Package com.comcast.cns.model

Examples of com.comcast.cns.model.CNSMessage


        String json =  Util.generateConfirmationJson(topicArn, sub.getToken(), messageId);
        String ownerUserId = PersistenceFactory.getTopicPersistence().getTopic(topicArn).getUserId();
        User topicOwner = PersistenceFactory.getUserPersistence().getUserById(ownerUserId);      
       
        try {
          CNSMessage message = new CNSMessage();
          message.setMessage(json);
          message.setSubscriptionArn(sub.getArn());
          message.setTopicArn(topicArn);
          message.setUserId(topicOwner.getUserId());
          message.setMessageType(CNSMessageType.SubscriptionConfirmation);
          message.setTimestamp(new Date());
          CommunicationUtils.sendMessage(topicOwner, subProtocol, endpoint, message, messageId, topicArn, sub.getArn(), false);
        } catch (Exception ex) {
          PersistenceFactory.getSubscriptionPersistence().unsubscribe(sub.getArn());
          if (ex instanceof CMBException) {
            throw new CMBException(CNSErrorCodes.CNS_InvalidParameter, "Invalid parameter: " + ex.getMessage());
View Full Code Here


           
            if (!CMBProperties.getInstance().isCQSLongPollEnabled()) {
              processingDelayMillis = 10;
            }
           
              CNSMessage publishMessage = CNSMessage.parseInstance(msg.getBody());
             
              int messageExpirationSeconds = CMBProperties.getInstance().getCNSMessageExpirationSeconds();
             
              if (messageExpirationSeconds != 0 && System.currentTimeMillis() - publishMessage.getTimestamp().getTime() > messageExpirationSeconds*1000) {
                  logger.error("event=deleting_publish_job reason=message_too_old topic_arn=" + publishMessage.getTopicArn());
                  CQSHandler.deleteMessage(queueUrl, msg.getReceiptHandle());
                  CMBControllerServlet.valueAccumulator.deleteAllCounters();
                  return true; // return true to avoid backoff
              }
             
              List<CNSEndpointPublishJob.CNSEndpointSubscriptionInfo> subscriptions = null;
              long t1=System.currentTimeMillis();
              try {
                  subscriptions = getSubscriptionsForTopic(publishMessage.getTopicArn());
              } catch (TopicNotFoundException e) {

                //delete this message/job since the topic was deleted.
                 
                logger.error("event=deleting_publish_job reason=topic_not_found topic_arn=" + publishMessage.getTopicArn());
                  CQSHandler.deleteMessage(queueUrl, msg.getReceiptHandle());
                  CMBControllerServlet.valueAccumulator.deleteAllCounters();
                  return true; // return true to avoid backoff
             
              } catch (Exception ex) {
View Full Code Here

                    AtomicInteger endpointPublishJobCount = new AtomicInteger(subs.size());               
                   
                    for (CNSEndpointSubscriptionInfo sub : subs) {            
                       
                      Runnable publishJob = null;
                      CNSMessage message = endpointPublishJob.getMessage();
                      message.setSubscriptionArn(sub.subArn);
                       
                        if (CMBProperties.getInstance().getCNSIOMode() == IO_MODE.SYNC) {
                          publishJob = new CNSPublishJob(message, pubUser, sub.protocol, sub.endpoint, sub.subArn, sub.rawDelivery, queueUrl, msg.getReceiptHandle(), endpointPublishJobCount);
                        } else {
                          publishJob = new CNSAsyncPublishJob(message, pubUser, sub.protocol, sub.endpoint, sub.subArn, sub.rawDelivery, queueUrl, msg.getReceiptHandle(), endpointPublishJobCount);
View Full Code Here

      String topicArn = request.getParameter("TopicArn");

      String messageStructure = null;
      String subject = null;
     
      CNSMessage cnsMessage = new CNSMessage();
      cnsMessage.generateMessageId();
      cnsMessage.setTimestamp(new Date());
      cnsMessage.setMessage(message);
     
      //TODO: optional shortcut
     
      if (request.getParameter("MessageStructure") != null) {
       
        messageStructure = request.getParameter("MessageStructure");    
       
        if (!messageStructure.equals("json")) {
          logger.error("event=cns_publish error_code=InvalidParameters message=" + message + " message_structure=" + messageStructure + " topic_arn=" + topicArn + " user_id=" + userId);
          throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"Invalid parameter: Invalid Message Structure parameter: " + messageStructure);
        }
       
        cnsMessage.setMessageStructure(CNSMessage.CNSMessageStructure.valueOf(messageStructure));
    }
     
      if (request.getParameter("Subject") != null) {
        subject = request.getParameter("Subject");
        cnsMessage.setSubject(subject);
    }
     
      if ((userId == null) || (message == null)) {
        logger.error("event=cns_publish error_code=InvalidParameters message=" + message + " topic_arn=" + topicArn + " user_id=" + userId);
      throw new CMBException(CNSErrorCodes.CNS_ValidationError,"1 validation error detected: Value null at 'message' failed to satisfy constraint: Member must not be null");
      }
     
    if ((topicArn == null) || !Util.isValidTopicArn(topicArn)) {
      logger.error("event=cns_publish error_code=InvalidParameters message=" + message + " topic_arn=" + topicArn + " user_id=" + userId);
      throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"TopicArn");
      }
   
    CNSTopic topic = CNSCache.getTopic(topicArn);
   
      if (topic == null) {
        logger.error("event=cns_publish error_code=NotFound message=" + message + " topic_arn=" + topicArn + " user_id=" + userId);
      throw new CMBException(CNSErrorCodes.CNS_NotFound,"Resource not found.");
      }
   
      cnsMessage.setUserId(topic.getUserId());
      cnsMessage.setTopicArn(topicArn);
      cnsMessage.setMessageType(CNSMessageType.Notification);
     
      cnsMessage.checkIsValid();
     
      CNSTopicAttributes topicAttributes = CNSCache.getTopicAttributes(topicArn);
      List<String> receiptHandles = new ArrayList<String>();
     
      boolean success = true;
     
      if (topicAttributes != null && topicAttributes.getSubscriptionsConfirmed() == 0) {
       
        // optimization: don't do anything if there are no confirmed subscribers
       
        logger.warn("event=no_confirmed_subscribers action=publish topic_arn=" + topicArn);
     
      } else if (CMBProperties.getInstance().isCNSBypassPublishJobQueueForSmallTopics() && topicAttributes != null && topicAttributes.getSubscriptionsConfirmed() <= CMBProperties.getInstance().getCNSMaxSubscriptionsPerEndpointPublishJob()) {
       
        // optimization: if there's only one chunk due to few subscribers, write directly into endpoint publish queue bypassing the publish job queue
       
        logger.debug("event=using_job_queue_overpass");
       
        List<CNSEndpointPublishJob.CNSEndpointSubscriptionInfo> subscriptions = CNSEndpointPublisherJobProducer.getSubscriptionsForTopic(topicArn);
       
            if (subscriptions != null && subscriptions.size() > 0) {
             
                List<CNSEndpointPublishJob> epPublishJobs = CNSEndpointPublisherJobProducer.createEndpointPublishJobs(cnsMessage, subscriptions);
               
                if (epPublishJobs.size() != 1) {
                  logger.warn("event=unexpected_number_of_endpoint_publish_jobs count=" + epPublishJobs.size());
                }
               
                for (CNSEndpointPublishJob epPublishJob: epPublishJobs) {
                String handle = sendMessageOnRandomShardAndCreateQueueIfAbsent(CNS_ENDPOINT_QUEUE_NAME_PREFIX, CMBProperties.getInstance().getCNSNumEndpointPublishJobQueues(), epPublishJob.serialize(), cnsInternalUser.getUserId());
                if (handle != null && !handle.equals("")) {
                  receiptHandles.add(handle);
                } else {
                  success = false;
                }
                }
            }
       
      } else {
     
        // otherwise pick publish job queue

        logger.debug("event=going_through_job_queue_town_center");
       
        String handle = sendMessageOnRandomShardAndCreateQueueIfAbsent(CNS_PUBLISH_QUEUE_NAME_PREFIX, CMBProperties.getInstance().getCNSNumPublishJobQueues(), cnsMessage.serialize(), cnsInternalUser.getUserId());
        if (handle != null && !handle.equals("")) {
          receiptHandles.add(handle);
        } else {
          success = false;
        }
View Full Code Here

        CMBProperties.getInstance().setCNSUseSubInfoCache(false);
    }

    @Test
    public void testEqualsEPJob() {
        CNSMessage p1 = CNSMessageTest.getMessage("test", null, "test", "test-arn", "test-pub-userId");
        CNSEndpointPublishJob.CNSEndpointSubscriptionInfo subInfo = new CNSEndpointPublishJob.CNSEndpointSubscriptionInfo(CnsSubscriptionProtocol.cqs, "test-endpoint1", "test-sub-arn", false);
        CNSEndpointPublishJob j1 = new CNSEndpointPublishJob(p1, Arrays.asList(subInfo));
        if (!j1.equals(j1)) {
            fail("CNSEndpointPublishJob not equal to itself");
        }
View Full Code Here

   
    @Test
    public void serializeDeserializeEPJob() {
       
      try {
        CNSMessage p1 = CNSMessageTest.getMessage("test", null, "test", "test-arn", "test-pub-userId");
          CNSEndpointPublishJob.CNSEndpointSubscriptionInfo subInfo = new CNSEndpointPublishJob.CNSEndpointSubscriptionInfo(CnsSubscriptionProtocol.cqs, "test-endpoint1", "test-sub-arn", false);
          CNSEndpointPublishJob j1 = new CNSEndpointPublishJob(p1, Arrays.asList(subInfo));
 
          String str = j1.serialize();
          CNSEndpointPublishJob rec = CNSEndpointPublishJob.parseInstance(str);
View Full Code Here

      }
    }
   
    @Test
    public void serializeSize() {
        CNSMessage p1 = CNSMessageTest.getMessage("test", null, "test", "test-arn", "test-pub-userId");
        LinkedList<CNSEndpointPublishJob.CNSEndpointSubscriptionInfo> subInfos = new LinkedList<CNSEndpointPublishJob.CNSEndpointSubscriptionInfo>();
        for (int i = 0; i < 500; i++) {
            subInfos.add(new CNSEndpointPublishJob.CNSEndpointSubscriptionInfo(CnsSubscriptionProtocol.cqs, CMBTestingConstants.HTTP_ENDPOINT_BASE_URL + "info/1234" + i, "27daac76-34dd-47df-bd01-1f6e873584a0" + i, false));   
        }
       
View Full Code Here

        logger.info("size of serialized=" + str.length());
    }
       
    @Test
    public void serializeDeserializeNoSubUsingCache() throws CMBException {
        CNSMessage p1 = CNSMessageTest.getMessage("test", null, "test", "test-arn", "test-pub-userId");
        CNSCachedEndpointPublishJob job = new CNSCachedEndpointPublishJob(p1, Collections.EMPTY_LIST);
       
        String str = job.serialize();
        logger.debug("serializedFOrm=" + str);
       
View Full Code Here

                sb.append("\n");
            }
            sb.append(arr[j]);
        }
       
        CNSMessage message = null;

        try {
            message = CNSMessage.parseInstance(sb.toString());
        } catch(Exception e) {
            logger.error("event=parse_publish_job cnsmessage_serialized=" + sb.toString(), e);
View Full Code Here

  }

  @Test
  public void testMessage() {

    CNSMessage msg = new CNSMessage();
    msg.generateMessageId();
        msg.setTimestamp(new Date());
    msg.setUserId("test");

    try {
      msg.checkIsValid();
      fail("Should have thrown an invalid message exception");
    } catch(Exception e) {
    }

    msg.setMessage("test message");

    try {
      msg.checkIsValid();
      fail("Should have thrown and invalid message expection");
    } catch(Exception e) {
    }

    msg.setTopicArn("test-topic-arn");
   
    try {
      msg.checkIsValid();           
    } catch (Exception e) {
      fail("Should NOT have thrown and invalid message expection: " + e.getMessage());
    }
   
    if (!msg.equals(msg)) {
      fail("Equals not reflexive for message");
    }

    msg.setMessage("test message");

    msg.setMessageStructure(CNSMessageStructure.json);
   
    try {
      msg.checkIsValid();
      fail("Should have thrown expection since message is not JSON");
    } catch (Exception e) {
     
    }

    msg.setMessage("{\"bogus\":\"val\"}");
   
    try {
      msg.checkIsValid();
      fail("Should have thrown expection since message is not JSON");
    } catch (Exception e) {
    }

    msg.setMessage("{\"email\"}:\"val\"}");

    try {
      msg.checkIsValid();
      fail("Should have thrown expection since message default is not specified");
    } catch (Exception e) {
    }

    msg.setMessage("{\"default\":\"send please\",\"email-json\":\"send in json\",\"email\":\"send in email\"}");
   
    try {
      msg.checkIsValid();           
    } catch(Exception e){
      fail("Should NOT have thrown expection: " + e.getMessage());
    }
   
    log.info(msg);

    StringBuffer sb = new StringBuffer();
   
    for (int i = 0; i < 100; i++) {
      sb.append('a');
    }
   
    msg.setSubject(sb.toString());
   
    try {
      msg.checkIsValid();
      fail("Should have thrown expection since message subject is too long");
    } catch(Exception e) {
    }
  }
View Full Code Here

TOP

Related Classes of com.comcast.cns.model.CNSMessage

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.