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());
}
String out = CNSSubscriptionPopulator.getSubscribeResponse(subscriptionArn);
writeResponse(out, response);
return true;