Package com.comcast.cmb.common.util

Examples of com.comcast.cmb.common.util.CMBException


    String userId = user.getUserId();
      String subscriptionArn = request.getParameter("SubscriptionArn");
     
      if ((userId == null) || (subscriptionArn == null) ) {
        logger.error("event=cns_get_subscription_attributes error_code=InvalidParameters subscription_arn=" + subscriptionArn + " user_id=" + userId);
      throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"missing parameters");
     
     
      CNSSubscriptionAttributes attr = PersistenceFactory.getCNSAttributePersistence().getSubscriptionAttributes(subscriptionArn);
      CNSSubscription sub = PersistenceFactory.getSubscriptionPersistence().getSubscription(subscriptionArn);
      String out = CNSAttributePopulator.getGetSubscriptionAttributesResponse(sub, attr);
View Full Code Here


      String protocol = request.getParameter("Protocol");
      String topicArn = request.getParameter("TopicArn");
     
      if ((endpoint == null) || (protocol == null) || (userId == null) || (topicArn == null)) {
        logger.error("event=cns_subscribe error_code=InvalidParameters user_id="+userId+ " topic_arn=" + topicArn +" endpoint=" + endpoint + " protocol=" + protocol);
      throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"request parameter does not comply with the associated constraints.");
    }
     
      if (!Util.isValidTopicArn(topicArn)) {
        logger.error("event=cns_subscribe error_code=InvalidParameters problem=invalid_arn user_id="+userId+ " topic_arn=" + topicArn +" endpoint=" + endpoint + " protocol=" + protocol);
        throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"request parameter does not comply with the associated constraints.");
      }
      CNSSubscription.CnsSubscriptionProtocol subProtocol = null;
     
      if (protocol.equals("email-json")) {
        subProtocol = CNSSubscription.CnsSubscriptionProtocol.email_json;
      } else {
        try {
          subProtocol = CNSSubscription.CnsSubscriptionProtocol.valueOf(protocol);
        } catch (IllegalArgumentException iae) {
            logger.error("event=cns_subscribe error_code=InvalidParameters problem=unknown_protocol user_id="+userId+ " topic_arn=" + topicArn +" endpoint=" + endpoint + " protocol=" + protocol);
            throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"request parameter does not comply with the associated constraints.");
        }
      }
      logger.debug("event=cns_subscribe endpoint=" + endpoint + " protocol=" + protocol + " user_id=" + userId + " topic_arn=" + topicArn);
   
     
      if (!subProtocol.isValidEnpoint(endpoint)) {
        logger.error("event=cns_subscribe error_code=InvalidParameters problem=invalidEndpoint user_id="+userId+ " topic_arn=" + topicArn +" endpoint=" + endpoint + " protocol=" + protocol);
      throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"request parameter does not comply with the associated constraints.");
      }
     
      CNSSubscription sub = PersistenceFactory.getSubscriptionPersistence().subscribe(endpoint, subProtocol, topicArn, userId);
      String subscriptionArn = null;
     
      if (sub.isConfirmed()) {
        subscriptionArn = sub.getArn();
      } else {
        subscriptionArn = "pending confirmation";
        String messageId = UUID.randomUUID().toString();
        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());
          } else {
            throw new CMBException(CNSErrorCodes.CNS_InvalidParameter, "Invalid parameter: Unreachable endpoint " + endpoint);
          }
        }
       
        logger.info("event=cns_subscribe_confirmation_request_sent endpoint=" + endpoint + " protocol=" + protocol + " user_id=" + userId + " topic_arn=" + topicArn + " token=" + sub.getToken());
      }
View Full Code Here

      String topicArn = request.getParameter("TopicArn");
     
      if ((topicArn == null) ) {
        logger.error("event=cns_add_permission error_code=missing_parameter_topic_arn");
      throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"Missing parameter TopicArn");
      }
     
      CNSTopic topic = PersistenceFactory.getTopicPersistence().getTopic(topicArn);
     
      if (topic == null) {
        logger.error("event=cns_add_permission error_code=invalid_parameter_topic_arn");
      throw new CMBException(CNSErrorCodes.CNS_NotFound,"Resource not found.");
      }
     
        String label = request.getParameter(CQSConstants.LABEL);
       
        if (label == null) {
          throw new CMBException(CMBErrorCodes.ValidationError, "Validation error detected: Value null at 'label' failed to satisfy constraint: Member must not be null");
        }

        if (!Util.isValidId(label)) {
            throw new CMBException(CQSErrorCodes.InvalidBatchEntryId, "Label " + label + " is invalid. Only alphanumeric, hyphen, and underscore are allowed. It can be at most " + CMBProperties.getInstance().getCQSMaxMessageSuppliedIdLength() + " letters long.");
        }
       
        List<String> userList = new ArrayList<String>();
        int index = 1;
       
        String userId = request.getParameter(CQSConstants.AWS_ACCOUNT_ID + ".member." + index);

        IUserPersistence userHandler = PersistenceFactory.getUserPersistence();
       
        while (userId != null) {

          if (userId.equals("*") || userHandler.getUserById(userId) != null) { // only add user if they exist
                userList.add(userId);
            }
           
          index++;
            userId = request.getParameter(CQSConstants.AWS_ACCOUNT_ID + ".member." + index);
        }
       
        if (userList.size() == 0) {
            throw new CMBException(CMBErrorCodes.NotFound, "AWSAccountId is required");
        }

        List<String> actionList = new ArrayList<String>();
        index = 1;
        String action = request.getParameter(CQSConstants.ACTION_NAME + ".member." + index);

        while (action != null) {
         
          if (action.equals("")) {
          throw new CMBException(CMBErrorCodes.ValidationError, "Blank action parameter is invalid");
          }
         
          if (!CMBPolicy.CNS_ACTIONS.contains(action) && !action.equals("*")) {
          throw new CMBException(CNSErrorCodes.CNS_InvalidParameter, "Invalid action parameter " + action);
          }
         
          actionList.add(action);
            index++;
            action = request.getParameter(CQSConstants.ACTION_NAME + ".member." + index);
        }
       
        if (actionList.size() == 0) {
            throw new CMBException(CMBErrorCodes.NotFound, "ActionName is required");
        }
       
        CMBPolicy policy = null;
    CNSTopicAttributes attributes = CNSCache.getTopicAttributes(topicArn);

        // validate policy string
       
        if (attributes.getPolicy() != null) {
          policy = new CMBPolicy(attributes.getPolicy());
        } else {
          policy = new CMBPolicy();
        }

        if (policy.addStatement(CMBPolicy.SERVICE.CNS, label, "Allow", userList, actionList, topicArn, null)) {
          attributes.setPolicy(policy.toString());
          PersistenceFactory.getCNSAttributePersistence().setTopicAttributes(attributes, topicArn);
        } else {
          throw new CMBException(CMBErrorCodes.InvalidParameterValue, "Value " + label + " for parameter Label is invalid. Reason: Already exists.");
        }

        String out = CNSAttributePopulator.getAddPermissionResponse();
        writeResponse(out, response);

View Full Code Here

     
      logger.debug("event=cns_set_subscription_attributes attribute_name=" + attributeName + " attribute_value=" + attributeValue + " subscription_arn=" + subscriptionArn + " user_id=" + userId);
     
      if ((userId == null) || (subscriptionArn == null) || (attributeName == null) || (attributeValue == null)) {
        logger.error("event=cns_set_subscription_attributes error_code=InvalidParameters attribute_name=" + attributeName + " attribute_value=" + attributeValue + " subscription_arn=" + subscriptionArn + " user_id=" + userId);
      throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"missing parameters");
     
     
      CNSSubscriptionAttributes subscriptionAttributes = new CNSSubscriptionAttributes();
     
      if (attributeName.equals("DeliveryPolicy")) {     
        JSONObject json = new JSONObject(attributeValue);      
        CNSSubscriptionDeliveryPolicy deliveryPolicy = new CNSSubscriptionDeliveryPolicy(json);
        subscriptionAttributes.setDeliveryPolicy(deliveryPolicy);
      } else if (attributeName.equals("RawMessageDelivery")){
        Boolean rawMessageDelivery = Boolean.parseBoolean(attributeValue);
        PersistenceFactory.getSubscriptionPersistence().setRawMessageDelivery(subscriptionArn, rawMessageDelivery);
      }
      else {
        logger.error("event=cns_set_subscription_attributes error_code=InvalidParameters attribute_name=" + attributeName + " attribute_value=" + attributeValue + " subscription_arn=" + subscriptionArn + " user_id=" + userId);
      throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"AttributeName: " + attributeName + " is not a valid value");
      }
     
      PersistenceFactory.getCNSAttributePersistence().setSubscriptionAttributes(subscriptionAttributes, subscriptionArn);
     
      String out = CNSAttributePopulator.getSetSubscriptionAttributesResponse();
View Full Code Here

      String token = request.getParameter("Token");
      String topicArn = request.getParameter("TopicArn");
     
      if ((topicArn == null) || (token == null)) {
        logger.error("event=cns_confirmsubscription error_code=InvalidParameters token=" + token + " topic_arn=" + topicArn + " authenticate_on_unsubscribe=" + authOnUnsubscribeStr);
      throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"request parameter does not comply with the associated constraints.");
      }
     
      if (!Util.isValidTopicArn(topicArn)) {
        logger.error("event=cns_confirmsubscription error_code=InvalidParameters token=" + token + " topic_arn=" + topicArn + " authenticate_on_unsubscribe=" + authOnUnsubscribeStr);
      throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"request parameter does not comply with the associated constraints.");
      }
     
      boolean authenticateOnUnsubscribe = false;
   
      if (authOnUnsubscribeStr != null) {
      if (!(authOnUnsubscribeStr.equals("true") || (authOnUnsubscribeStr.equals("false")))) {
        logger.error("event=cns_confirmsubscription error_code=InvalidParameters token=" + token + " topic_arn=" + topicArn + " authenticate_on_unsubscribe=" + authOnUnsubscribeStr);
        throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"request parameter does not comply with the associated constraints.");
      } else
        authenticateOnUnsubscribe = (authOnUnsubscribeStr.equals("true"));
      }
    }
     
View Full Code Here

      String userId = user.getUserId();
      logger.debug("event=cns_topic_delete arn=" + arn + " userid=" + userId);
     
    if ((arn == null) || (userId == null)) {
      logger.error("event=cns_topic_delete errro_code=InvalidParameters topic_arn=" + arn + " user_id=" + userId);
      throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"request parameter does not comply with the associated constraints.");
    }
   
    PersistenceFactory.getTopicPersistence().deleteTopic(arn);     
    String out = CNSTopicPopulator.getDeleteTopicResponse();
        writeResponse(out, response);
View Full Code Here

   
    String task = request.getParameter("Task");

    if (task == null || task.equals("")) {
      logger.error("event=cns_manage_service error_code=missing_parameter_task");
      throw new CMBException(CNSErrorCodes.MissingParameter,"Request parameter Task missing.");
    }

    String host = request.getParameter("Host");
    //for some task, Host is mandatory. Check it.
    if (!task.equals("ClearAPIStats") && (!task.equals("StartWorker")) && (!task.equals("StopWorker")) && (host == null || host.equals(""))) {
      logger.error("event=cns_manage_service error_code=missing_parameter_host");
      throw new CMBException(CNSErrorCodes.MissingParameter,"Request parameter Host missing.");
    }

    AbstractDurablePersistence cassandraHandler = DurablePersistenceFactory.getInstance();

    if (task.equals("ClearWorkerQueues")) {

      List<CmbRow<String, String, String>> rows = cassandraHandler.readAllRows(AbstractDurablePersistence.CNS_KEYSPACE, CNS_WORKERS, 1000, 10, CMB_SERIALIZER.STRING_SERIALIZER, CMB_SERIALIZER.STRING_SERIALIZER, CMB_SERIALIZER.STRING_SERIALIZER);
      List<CNSWorkerStats> statsList = new ArrayList<CNSWorkerStats>();

      if (rows != null) {

        for (CmbRow<String, String, String> row : rows) {

          CNSWorkerStats stats = new CNSWorkerStats();
          stats.setIpAddress(row.getKey());

          if (row.getColumnSlice().getColumnByName("producerTimestamp") != null) {
            stats.setProducerTimestamp(Long.parseLong(row.getColumnSlice().getColumnByName("producerTimestamp").getValue()));
          }

          if (row.getColumnSlice().getColumnByName("consumerTimestamp") != null) {
            stats.setConsumerTimestamp(Long.parseLong(row.getColumnSlice().getColumnByName("consumerTimestamp").getValue()));
          }

          if (row.getColumnSlice().getColumnByName("jmxport") != null) {
            stats.setJmxPort(Long.parseLong(row.getColumnSlice().getColumnByName("jmxport").getValue()));
          }

          if (row.getColumnSlice().getColumnByName("mode") != null) {
            stats.setMode(row.getColumnSlice().getColumnByName("mode").getValue());
          }

          statsList.add(stats);
        }
      }

      for (CNSWorkerStats stats : statsList) {

        if (stats.getIpAddress().equals(host) && stats.getJmxPort() > 0) {

          JMXConnector jmxConnector = null;
          String url = null;

          try {

            long port = stats.getJmxPort();
            url = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";

            JMXServiceURL serviceUrl = new JMXServiceURL(url);
            jmxConnector = JMXConnectorFactory.connect(serviceUrl, null);

            MBeanServerConnection mbeanConn = jmxConnector.getMBeanServerConnection();
            ObjectName cnsWorkerMonitor = new ObjectName("com.comcast.cns.tools:type=CNSWorkerMonitorMBean");
            CNSWorkerMonitorMBean mbeanProxy = JMX.newMBeanProxy(mbeanConn, cnsWorkerMonitor,  CNSWorkerMonitorMBean.class, false);

            mbeanProxy.clearWorkerQueues();

            String res = CNSWorkerStatsPopulator.getGetManageWorkerResponse()
            response.getWriter().println(res);

            return true;

          } finally {

            if (jmxConnector != null) {
              jmxConnector.close();
            }
          }
        }
      }

      throw new CMBException(CMBErrorCodes.NotFound, "Cannot clear worker queues: Host " + host + " not found.");

    } else if (task.equals("RemoveWorkerRecord")) {
     
      cassandraHandler.delete(AbstractDurablePersistence.CNS_KEYSPACE, CNS_WORKERS, host, null, CMB_SERIALIZER.STRING_SERIALIZER, CMB_SERIALIZER.STRING_SERIALIZER);
      String out = CNSPopulator.getResponseMetadata();
          writeResponse(out, response);
      return true;
     
    } else if (task.equals("ClearAPIStats")) {
     
            CMBControllerServlet.initStats();
            String out = CNSPopulator.getResponseMetadata();
          writeResponse(out, response);
        return true;

    } else if (task.equals("RemoveRecord")) {
     
      cassandraHandler.delete(AbstractDurablePersistence.CNS_KEYSPACE, CNS_API_SERVERS, host, null, CMB_SERIALIZER.STRING_SERIALIZER, CMB_SERIALIZER.STRING_SERIALIZER);
      String out = CNSPopulator.getResponseMetadata();
          writeResponse(out, response);
      return true;
     
    } else if (task.equals("StartWorker")||task.equals("StopWorker")) {
      String dataCenter = request.getParameter("DataCenter");
      if(task.equals("StartWorker")){
        CNSWorkerStatWrapper.startWorkers(dataCenter);
      } else {
        CNSWorkerStatWrapper.stopWorkers(dataCenter);
      }
      String out = CNSPopulator.getResponseMetadata();
          writeResponse(out, response);
      return true;
     
    } else {
      logger.error("event=cns_manage_service error_code=invalid_task_parameter valid_values=ClearWorkerQueues,RemoveWorkerRecord,RemoveRecord,ClearAPIStats");
      throw new CMBException(CNSErrorCodes.InvalidParameterValue,"Request parameter Task missing is invalid. Valid values are ClearWorkerQueues, RemoveWorkerRecord, RemoveRecord, ClearAPIStats.");
    }
  }
View Full Code Here

        HttpServletResponse response = (HttpServletResponse)asyncContext.getResponse();
   
      String topicArn = request.getParameter("TopicArn");
     
      if (topicArn == null) {
      throw new CMBException(CNSErrorCodes.CNS_InvalidParameter, "Missing parameters TopicArn");
      }
     
      //CNSTopicAttributes attr = PersistenceFactory.getCNSAttributePersistence().getTopicAttributes(topicArn);
      CNSTopicAttributes attr = CNSCache.getTopicAttributes(topicArn);
     
      if (attr == null) {
        throw new CMBException(CNSErrorCodes.InternalError, "Unknown topic with arn " + topicArn);
      }
     
      String out = CNSAttributePopulator.getGetTopicAttributesResponse(attr);
     
        writeResponse(out, response);
View Full Code Here

    String topicArn = request.getParameter("TopicArn");
     
      if ((topicArn == null) ) {
        logger.error("event=cns_add_permission error_code=missing_parameter_topic_arn");
      throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,"Missing parameter TopicArn");
      }
     
      CNSTopic topic = PersistenceFactory.getTopicPersistence().getTopic(topicArn);
     
      if (topic == null) {
        logger.error("event=cns_add_permission error_code=invalid_parameter_topic_arn topic_arn=" + topicArn);
      throw new CMBException(CNSErrorCodes.CNS_NotFound,"Resource not found.");
      }
     
        String label = request.getParameter(CQSConstants.LABEL);

        if (!Util.isValidId(label)) {
            throw new CMBException(CQSErrorCodes.InvalidBatchEntryId, "Label " + label + " is invalid. Only alphanumeric, hyphen, and underscore are allowed. It can be at most " + CMBProperties.getInstance().getCQSMaxMessageSuppliedIdLength() + " letters long.");
        }
       
        CMBPolicy policy = null;

    CNSTopicAttributes attributes = CNSCache.getTopicAttributes(topicArn);
View Full Code Here

    List<CNSSubscription> subscriptions = null;
   
    try {
      subscriptions = PersistenceFactory.getSubscriptionPersistence().listSubscriptions(nextToken, null, userId);
    } catch (SubscriberNotFoundException ex) {
      throw new CMBException(CMBErrorCodes.InvalidParameterValue, "Invalid parameter nextToken");
    }
   
    if (subscriptions.size() >= 100) {
     
      //Check if there are more
View Full Code Here

TOP

Related Classes of com.comcast.cmb.common.util.CMBException

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.