Package org.serviceconnector.scmp

Examples of org.serviceconnector.scmp.SCMPMessage


  }

  /** {@inheritDoc} */
  @Override
  public void run(IRequest request, IResponse response, IResponderCallback responderCallback) throws Exception {
    SCMPMessage reqMessage = request.getMessage();
    String serviceName = reqMessage.getServiceName();

    // check service is present and enabled
    Service abstractService = this.getService(serviceName);
    if (abstractService.isEnabled() == false) {
      SCMPCommandException scmpCommandException = new SCMPCommandException(SCMPError.SERVICE_DISABLED, "service="
          + abstractService.getName() + " is disabled");
      scmpCommandException.setMessageType(getKey());
      throw scmpCommandException;
    }

    // enhance ipAddressList
    String ipAddressList = reqMessage.getHeader(SCMPHeaderAttributeKey.IP_ADDRESS_LIST);
    ipAddressList = ipAddressList + Constants.SLASH + request.getRemoteSocketAddress().getAddress().getHostAddress();
    reqMessage.setHeader(SCMPHeaderAttributeKey.IP_ADDRESS_LIST, ipAddressList);

    int oti = reqMessage.getHeaderInt(SCMPHeaderAttributeKey.OPERATION_TIMEOUT);
    // create temporary Subscription for cascaded SC
    String sessionInfo = reqMessage.getHeader(SCMPHeaderAttributeKey.SESSION_INFO);
    int noiSecs = reqMessage.getHeaderInt(SCMPHeaderAttributeKey.NO_DATA_INTERVAL);
    int noiInMillis = noiSecs * Constants.SEC_TO_MILLISEC_FACTOR;
    String cscSCMaskString = reqMessage.getHeader(SCMPHeaderAttributeKey.CASCADED_MASK);
    String cascSubscriptionId = reqMessage.getHeader(SCMPHeaderAttributeKey.CASCADED_SUBSCRIPTION_ID);
    Subscription cscSubscription = this.subscriptionRegistry.getSubscription(cascSubscriptionId);
    SubscriptionMask cscMask = new SubscriptionMask(cscSCMaskString);
    Subscription tmpCascSCSubscription = new Subscription(cscMask, sessionInfo, ipAddressList, noiInMillis, AppContext
        .getBasicConfiguration().getSubscriptionTimeoutMillis(), true);
    tmpCascSCSubscription.setService(abstractService);

    switch (abstractService.getType()) {
    case CASCADED_PUBLISH_SERVICE:
      // publish service is cascaded
      CascadedPublishService cascadedPublishService = (CascadedPublishService) abstractService;
      CascadedSC cascadedSC = cascadedPublishService.getCascadedSC();
      // add server to subscription
      tmpCascSCSubscription.setServer(cascadedSC);

      ISubscriptionCallback callback = null;
      if (cscSubscription == null) {
        // cascaded SC not subscribed yet
        callback = new SubscribeCommandCallback(request, response, responderCallback, tmpCascSCSubscription);
      } else {
        // subscribe is made by an active cascaded SC
        callback = new CscChangeSubscriptionCallbackForCasc(request, response, responderCallback, cscSubscription,
            cscSCMaskString);
      }
      cascadedSC.cascadedSCSubscribe(cascadedPublishService.getCascClient(), reqMessage, callback, oti);
      return;
    default:
      // code for other types of services is below
      break;
    }
    // modify message only if it goes to server
    reqMessage.removeHeader(SCMPHeaderAttributeKey.NO_DATA_INTERVAL);
    reqMessage.removeHeader(SCMPHeaderAttributeKey.CASCADED_MASK);
    reqMessage.removeHeader(SCMPHeaderAttributeKey.CASCADED_SUBSCRIPTION_ID);
    // check service is present
    PublishService service = this.validatePublishService(abstractService);
    int otiOnSCMillis = (int) (oti * basicConf.getOperationTimeoutMultiplier());
    int tries = (otiOnSCMillis / Constants.WAIT_FOR_FREE_CONNECTION_INTERVAL_MILLIS);
    int i = 0;
    // Following loop implements the wait mechanism in case of a busy connection pool
    do {
      // reset ipList&msgType, might have been modified in below operation try
      reqMessage.setHeader(SCMPHeaderAttributeKey.IP_ADDRESS_LIST, ipAddressList);
      reqMessage.setMessageType(this.getKey());
      try {
        if (cscSubscription != null) {
          // cascaded subscribe made by an active cascaded SC
          CscChangeSubscriptionCallbackForCasc cascCallback = new CscChangeSubscriptionCallbackForCasc(request, response,
              responderCallback, cscSubscription, cscSCMaskString);
          ((StatefulServer) cscSubscription.getServer()).subscribe(reqMessage, cascCallback, otiOnSCMillis);
          break;
        }
        // cascaded subscribe made by an inactive cascaded SC - forward client subscribe to server
        SubscribeCommandCallback callback = new SubscribeCommandCallback(request, response, responderCallback,
            tmpCascSCSubscription);
        service.allocateServerAndSubscribe(reqMessage, callback, tmpCascSCSubscription, otiOnSCMillis
            - (i * Constants.WAIT_FOR_FREE_CONNECTION_INTERVAL_MILLIS));
        // no exception has been thrown - get out of wait loop
        break;
      } catch (NoFreeServerException ex) {
        LOGGER.debug("NoFreeServerException caught in wait mec of subscribe, tries left=" + tries);
        if (i >= (tries - 1)) {
          // only one loop outstanding - don't continue throw current exception
          throw ex;
        }
      } catch (ConnectionPoolBusyException ex) {
        LOGGER.debug("ConnectionPoolBusyException caught in wait mec of subscribe, tries left=" + tries);
        if (i >= (tries - 1)) {
          // only one loop outstanding - don't continue throw current exception
          LOGGER.warn(SCMPError.NO_FREE_CONNECTION.getErrorText("service=" + reqMessage.getServiceName()));
          SCMPCommandException scmpCommandException = new SCMPCommandException(SCMPError.NO_FREE_CONNECTION, "service="
              + reqMessage.getServiceName());
          scmpCommandException.setMessageType(this.getKey());
          throw scmpCommandException;
        }
      }
      // sleep for a while and then try again
View Full Code Here


  }

  /** {@inheritDoc} */
  @Override
  public void validate(IRequest request) throws Exception {
    SCMPMessage message = request.getMessage();

    try {
      // scVersion mandatory
      String scVersion = message.getHeader(SCMPHeaderAttributeKey.SC_VERSION);
      SCMPMessage.SC_VERSION.isSupported(scVersion);
      // msgSequenceNr mandatory
      String msgSequenceNr = message.getMessageSequenceNr();
      ValidatorUtility.validateLong(1, msgSequenceNr, SCMPError.HV_WRONG_MESSAGE_SEQUENCE_NR);
      // serviceName mandatory
      String serviceName = message.getServiceName();
      ValidatorUtility.validateStringLengthTrim(1, serviceName, Constants.MAX_LENGTH_SERVICENAME,
          SCMPError.HV_WRONG_SERVICE_NAME);
      // operation timeout mandatory
      String otiValue = message.getHeader(SCMPHeaderAttributeKey.OPERATION_TIMEOUT);
      ValidatorUtility.validateInt(Constants.MIN_OTI_VALUE_CSC, otiValue, Constants.MAX_OTI_VALUE,
          SCMPError.HV_WRONG_OPERATION_TIMEOUT);
      // ipAddressList mandatory
      String ipAddressList = message.getHeader(SCMPHeaderAttributeKey.IP_ADDRESS_LIST);
      ValidatorUtility.validateIpAddressList(ipAddressList);
      // sessionId mandatory
      String sessionId = message.getSessionId();
      ValidatorUtility.validateStringLengthTrim(1, sessionId, Constants.MAX_STRING_LENGTH_256, SCMPError.HV_WRONG_SESSION_ID);
      // mask mandatory
      String mask = message.getHeader(SCMPHeaderAttributeKey.MASK);
      ValidatorUtility.validateStringLength(1, mask, Constants.MAX_STRING_LENGTH_256, SCMPError.HV_WRONG_MASK);
      // noDataInterval mandatory
      String noDataIntervalValue = message.getHeader(SCMPHeaderAttributeKey.NO_DATA_INTERVAL);
      ValidatorUtility.validateInt(Constants.MIN_NOI_VALUE, noDataIntervalValue, Constants.MAX_NOI_VALUE,
          SCMPError.HV_WRONG_NODATA_INTERVAL);
      // sessionInfo is optional
      String sessionInfo = message.getHeader(SCMPHeaderAttributeKey.SESSION_INFO);
      ValidatorUtility.validateStringLengthIgnoreNull(1, sessionInfo, Constants.MAX_STRING_LENGTH_256,
          SCMPError.HV_WRONG_SESSION_INFO);
      // cascadedMask
      String cascadedMask = message.getHeader(SCMPHeaderAttributeKey.CASCADED_MASK);
      ValidatorUtility.validateStringLengthTrim(1, cascadedMask, Constants.MAX_STRING_LENGTH_256, SCMPError.HV_WRONG_MASK);
    } catch (HasFaultResponseException ex) {
      // needs to set message type at this point
      ex.setMessageType(getKey());
      throw ex;
View Full Code Here

    LOGGER.trace("timeout receivePublicationTimeout");
    String subscriptionId = null;
    Subscription subscription = null;
    try {
      // extracting subscriptionId from request message
      SCMPMessage reqMsg = request.getMessage();
      // set up subscription timeout
      subscriptionId = reqMsg.getSessionId();

      LOGGER.trace("timeout receive publication timer datapointer subscriptionId " + subscriptionId);
      subscription = subscriptionRegistry.getSubscription(subscriptionId);
      if (subscription == null) {
        LOGGER.trace("subscription not found - already deleted subscriptionId=" + subscriptionId);
        // subscription has already been deleted
        SCMPMessageFault fault = new SCMPMessageFault(SCMPError.SUBSCRIPTION_NOT_FOUND, subscriptionId);
        fault.setMessageType(reqMsg.getMessageType());
        response.setSCMP(fault);
      } else {
        // tries polling from queue
        SCMPMessage message = this.publishMessageQueue.getMessage(subscriptionId);
        if (message == null) {
          LOGGER.trace("no message found on queue - subscription timeout set up no data message subscriptionId="
              + subscriptionId);
          // no message found on queue - subscription timeout set up no data message
          reqMsg.setHeaderFlag(SCMPHeaderAttributeKey.NO_DATA);
          reqMsg.setIsReply(true);
          this.response.setSCMP(reqMsg);
        } else {
          LOGGER.trace("message found on queue - subscription timeout set up reply message subscriptionId="
              + subscriptionId);
          // set up reply
          SCMPMessage reply = null;
          if (message.isPart()) {
            // message from queue is of type part - outgoing must be part too, no poll request
            reply = new SCMPPart(false);
          } else {
            reply = new SCMPMessage();
          }
          reply.setServiceName(reqMsg.getHeader(SCMPHeaderAttributeKey.SERVICE_NAME));
          reply.setSessionId(subscriptionId);
          reply.setMessageType(reqMsg.getMessageType());
          reply.setIsReply(true);

          // message polling successful
          reply.setBody(message.getBody());
          reply.setHeader(SCMPHeaderAttributeKey.MESSAGE_SEQUENCE_NR, message.getMessageSequenceNr());
          String messageInfo = message.getHeader(SCMPHeaderAttributeKey.MSG_INFO);
          if (messageInfo != null) {
            reply.setHeader(SCMPHeaderAttributeKey.MSG_INFO, messageInfo);
          }
          reply.setHeader(SCMPHeaderAttributeKey.MASK, message.getHeader(SCMPHeaderAttributeKey.MASK));
          reply.setBody(message.getBody());
          this.response.setSCMP(reply);
        }
      }
    } catch (Exception ex) {
      LOGGER.warn("timeout expired procedure failed, " + ex.getMessage());
View Full Code Here

      try {
        registerServerCall.invoke(callback, Constants.DEFAULT_OPERATION_TIMEOUT_SECONDS * Constants.SEC_TO_MILLISEC_FACTOR);
      } catch (Exception e) {
        throw new SCServiceException("Register server failed. ", e);
      }
      SCMPMessage reply = callback.getMessageSync(Constants.DEFAULT_OPERATION_TIMEOUT_SECONDS
          * Constants.SEC_TO_MILLISEC_FACTOR);
      if (reply.isFault()) {
        SCServiceException ex = new SCServiceException("Register server failed.");
        ex.setSCErrorCode(reply.getHeaderInt(SCMPHeaderAttributeKey.SC_ERROR_CODE));
        ex.setSCErrorText(reply.getHeader(SCMPHeaderAttributeKey.SC_ERROR_TEXT));
        throw ex;
      }
      AppContext.attachedCommunicators.incrementAndGet();
    }
    // set up server timeout thread
View Full Code Here

          deRegisterServerCall.invoke(callback, Constants.DEFAULT_OPERATION_TIMEOUT_SECONDS
              * Constants.SEC_TO_MILLISEC_FACTOR);
        } catch (Exception e) {
          throw new SCServiceException("Deregister server failed. ", e);
        }
        SCMPMessage reply = callback.getMessageSync(Constants.DEFAULT_OPERATION_TIMEOUT_SECONDS
            * Constants.SEC_TO_MILLISEC_FACTOR);
        if (reply.isFault()) {
          SCServiceException ex = new SCServiceException("Deregister server failed.");
          ex.setSCErrorCode(reply.getHeaderInt(SCMPHeaderAttributeKey.SC_ERROR_CODE));
          ex.setSCErrorText(reply.getHeader(SCMPHeaderAttributeKey.SC_ERROR_TEXT));
          throw ex;
        }
      } finally {
        this.registered = false;
        AppContext.attachedCommunicators.decrementAndGet();
View Full Code Here

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    IEncoderDecoder encoderDecoder = null;
    SCMPMessage scReply = null;
    SCMPMessage reqMessage = null;
    try {
      byte[] buffer = new byte[request.getContentLength()];
      request.getInputStream().read(buffer);
      Statistics.getInstance().incrementTotalMessages(buffer.length);
      if (ConnectionLogger.isEnabledFull()) {
        ConnectionLogger.logReadBuffer(this.getClass().getSimpleName(), request.getServerName(), request.getServerPort(),
            buffer, 0, buffer.length);
      }
      ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
      encoderDecoder = AppContext.getEncoderDecoderFactory().createEncoderDecoder(buffer);
      reqMessage = (SCMPMessage) encoderDecoder.decode(bais);

      if (reqMessage.isKeepAlive() == true) {
        // keep alive received, just reply nothing more to do.
        reqMessage.setIsReply(true);
        // write reply to servlet output stream
        this.writeResponse(reqMessage, scReply, response);
        return;
      }

      String sessionId = reqMessage.getSessionId();
      if (reqMessage.isFault()) {
        SCBaseServlet.compositeRegistry.removeSCMPLargeResponse(sessionId);
        SCBaseServlet.compositeRegistry.removeSCMPLargeRequest(sessionId);
        // fault received nothing to to return - delete largeRequest/largeResponse
        SCMPMessageFault scmpFault = new SCMPMessageFault(SCMPError.BAD_REQUEST, "messagType="
            + reqMessage.getMessageType());
        scmpFault.setMessageType(reqMessage.getMessageType());
        scmpFault.setLocalDateTime();
        // write reply to servlet output stream
        this.writeResponse(reqMessage, scReply, response);
        return;
      }

      if (this.handleLargeResponse(request, response, reqMessage)) {
        // large message and response has been handled no need to continue
        return;
      }

      if (this.handleLargeRequestNeeded(request, response, reqMessage)) {
        SCMPMessage message = this.handleLargeRequest(request, response, reqMessage);
        if (message == null) {
          // reply inside
          return;
        }
        reqMessage = message;
View Full Code Here

    IEncoderDecoder encoderDecoder;
    try {
      if (responseMessage.isLargeMessage()) {
        // response is large create a large response for reply
        SCMPCompositeSender largeResponse = new SCMPCompositeSender(responseMessage);
        SCMPMessage firstSCMP = largeResponse.getFirst();
        SCMPMessageSequenceNr messageSequenceNr = this.requester.getSCMPMsgSequenceNr();
        firstSCMP.setHeader(SCMPHeaderAttributeKey.MESSAGE_SEQUENCE_NR, messageSequenceNr.incrementAndGetMsgSequenceNr());
        int oti = requestMessage.getHeaderInt(SCMPHeaderAttributeKey.OPERATION_TIMEOUT);
        // adding compositeReceiver to the composite registry
        SCBaseServlet.compositeRegistry.addSCMPLargeResponse(requestMessage.getSessionId(), largeResponse, oti);
        responseMessage = firstSCMP;
      }
View Full Code Here

    if (largeResponse != null && scmpReq.isPart()) {
      // sending of a large response has already been started and incoming SCMP is a pull request
      if (largeResponse.hasNext()) {
        // there are still parts to send to complete request
        SCMPMessage nextSCMP = largeResponse.getNext();
        // handling msgSequenceNr
        SCMPMessageSequenceNr msgSequenceNr = this.requester.getSCMPMsgSequenceNr();
        nextSCMP.setHeader(SCMPHeaderAttributeKey.MESSAGE_SEQUENCE_NR, msgSequenceNr.incrementAndGetMsgSequenceNr());
        this.writeResponse(scmpReq, nextSCMP, response);
        return true;
      }
      SCBaseServlet.compositeRegistry.removeSCMPLargeResponse(sessionId);
    }
View Full Code Here

  private SCMPMessage handleLargeRequest(HttpServletRequest request, HttpServletResponse response, SCMPMessage scmpReq) {
    String sessionId = scmpReq.getSessionId();
    // gets the large request or creates a new one if necessary
    SCMPCompositeReceiver largeRequest = SCBaseServlet.compositeRegistry.getSCMPLargeRequest(sessionId);
    SCMPMessageSequenceNr msgSequenceNr = this.requester.getSCMPMsgSequenceNr();
    SCMPMessage scmpReply = null;
    if (scmpReq.isPart()) {
      // received message part - request not complete yet
      largeRequest.incomplete();
      // set up poll response
      scmpReply = new SCMPPart(true);
      scmpReply.setHeader(SCMPHeaderAttributeKey.MESSAGE_SEQUENCE_NR, msgSequenceNr.incrementAndGetMsgSequenceNr());
      scmpReply.setIsReply(true);
      scmpReply.setMessageType(scmpReq.getMessageType());
    } else {
      // last message of a chunk message received - request complete now
      largeRequest.complete();
      largeRequest.setHeader(SCMPHeaderAttributeKey.MESSAGE_SEQUENCE_NR, msgSequenceNr.incrementAndGetMsgSequenceNr());
      scmpReply = largeRequest;
View Full Code Here

      }
      CacheLogger.tryGetMessageFromCache(reqCacheKey, sessionId, reqPartNr);
      // meta entry exists
      if (metaEntry.isLoaded() == true) {
        // message already loaded - return message
        SCMPMessage cachedMessage = dataCache.get(metaEntry.getCacheKey() + Constants.SLASH + reqPartNr);
        if (cachedMessage != null) {
          // message found adapt header fields for requester
          cachedMessage.setServiceName(serviceName);
          cachedMessage.setMessageType(reqMessage.getMessageType());
          cachedMessage.setHeader(SCMPHeaderAttributeKey.MESSAGE_SEQUENCE_NR, reqMessage.getMessageSequenceNr());
          cachedMessage.setSessionId(sessionId);
          if (CacheLogger.isEnabled()) {
            CacheLogger.gotMessageFromCache(reqCacheKey, sessionId, cachedMessage.getBodyLength());
          }
        } else {
          LOGGER.error("Cache error, data-cache and meta-cache are not consistent. cacheKey=" + reqCacheKey
              + Constants.SLASH + reqPartNr);
        }
View Full Code Here

TOP

Related Classes of org.serviceconnector.scmp.SCMPMessage

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.