Package org.serviceconnector.scmp

Examples of org.serviceconnector.scmp.SCMPMessage


    byte[] version = new byte[Constants.SCMP_VERSION_LENGTH_IN_HEADLINE];
    this.readBufferFromStream(is, version);
    SCMPMessage.SCMP_VERSION.isSupported(version);
    is.skip(1); // read LF

    SCMPMessage scmpMsg = null;
    // evaluating header key and creating corresponding SCMP type
    SCMPHeaderKey headerKey = SCMPHeaderKey.getKeyByHeadline(headline);
    switch (headerKey) {
    case KRS:
    case KRQ:
      scmpMsg = new SCMPKeepAlive();
      return scmpMsg;
    case PRQ:
    case PRS:
      // no poll request
      scmpMsg = new SCMPPart(false);
      break;
    case PAC:
      // poll request
      scmpMsg = new SCMPPart(true);
      break;
    case EXC:
      scmpMsg = new SCMPMessageFault();
      break;
    case UNDEF:
      throw new EncodingDecodingException("wrong protocol in message not possible to decode");
    default:
      scmpMsg = new SCMPMessage();
    }

    // parse headerSize & bodySize
    int scmpHeaderSize = SCMPFrameDecoder.parseHeaderSize(headline);
    int scmpBodySize = SCMPFrameDecoder.parseMessageSize(headline) - scmpHeaderSize;

    // storing header fields in meta map
    Map<String, String> metaMap = new HashMap<String, String>();
    byte[] header = new byte[scmpHeaderSize];
    int readBytes = this.readBufferFromStream(is, header);
    int keyOff = 0;
    // decoding header
    for (int index = 0; index < readBytes; index++) {
      // looping until <=> found, looking for key value pair
      if (header[index] == Constants.SCMP_EQUAL) {
        // <=> found
        for (int inLoopIndex = index; inLoopIndex < readBytes; inLoopIndex++) {
          // looping until <LF> got found
          if (header[inLoopIndex] == Constants.SCMP_LF) {
            // <LF> found
            metaMap.put(new String(header, keyOff, (index - keyOff), Constants.SC_CHARACTER_SET), new String(header,
                index + 1, (inLoopIndex - 1) - index, Constants.SC_CHARACTER_SET));
            // updating outer loop index
            index = inLoopIndex;
            // updating offset for next key, +1 for <LF>
            keyOff = inLoopIndex + 1;
            // key value pair found, stop inner loop
            break;
          }
        }
        // key value pair found, continue looking for next pair
        continue;
      }
      // looping until <LF> found, looking for header flag
      if (header[index] == Constants.SCMP_LF) {
        // <LF> found
        metaMap.put(new String(header, keyOff, (index - keyOff), Constants.SC_CHARACTER_SET), null);
        // updating offset for next key, +1 for <LF>
        keyOff = index + 1;
      }
    }

    scmpMsg.setHeader(metaMap);
    // message logging
    MessageLogger.logInputMessage(headerKey, scmpMsg);
    if (scmpBodySize <= 0) {
      // no body found stop decoding
      return scmpMsg;
    }
    // decoding body - depends on body type
    String scmpBodyTypeString = metaMap.get(SCMPHeaderAttributeKey.BODY_TYPE.getValue());
    SCMPBodyType scmpBodyType = SCMPBodyType.getBodyType(scmpBodyTypeString);
    try {
      byte[] body = new byte[scmpBodySize];
      int bodySize = this.readBufferFromStream(is, body);
      if (scmpMsg.getHeaderFlag(SCMPHeaderAttributeKey.COMPRESSION)) {
        if (AppContext.isScEnvironment() == false) {
          // message decompression required
          Inflater decompresser = new Inflater();
          decompresser.setInput(body, 0, bodySize);
          ByteArrayOutputStream bos = new ByteArrayOutputStream(Constants.MAX_MESSAGE_SIZE);
          byte[] buf = new byte[Constants.MAX_MESSAGE_SIZE];
          bodySize = 0;
          while (!decompresser.finished()) {
            int count = decompresser.inflate(buf);
            bodySize += count;
            bos.write(buf, 0, count);
          }
          bos.close();
          decompresser.end();
          body = bos.toByteArray();
        } else {
          // is an SC environment - body is compressed - below switch is irrelevant
          scmpMsg.setBody(body, 0, bodySize);
          return scmpMsg;
        }
      }

      switch (scmpBodyType) {
      case BINARY:
      case INPUT_STREAM:
      case UNDEFINED:
        scmpMsg.setBody(body, 0, bodySize);
        return scmpMsg;
      case TEXT:
        scmpMsg.setBody(new String(body, 0, bodySize));
        return scmpMsg;
      default:
        throw new EncodingDecodingException("unknown body type of SCMP type=" + scmpBodyTypeString);
      }
    } catch (Exception ex) {
View Full Code Here


  }

  /** {@inheritDoc} */
  @Override
  public void receive(Exception ex) {
    SCMPMessage reqMessage = this.request.getMessage();
    String sid = reqMessage.getSessionId();
    LOGGER.warn("receive exception sid=" + sid + " " + ex.toString());
    SCMPMessage fault = null;
    if (ex instanceof IdleTimeoutException) {
      // operation timeout handling
      fault = new SCMPMessageFault(SCMPError.OPERATION_TIMEOUT, "Operation timeout expired on SC sid=" + sid);
    } else if (ex instanceof IOException) {
      fault = new SCMPMessageFault(SCMPError.CONNECTION_EXCEPTION, "broken connection on SC sid=" + sid);
    } else if (ex instanceof InvalidMaskLengthException) {
      fault = new SCMPMessageFault(SCMPError.HV_WRONG_MASK, ex.getMessage() + " sid=" + sid);
    } else {
      fault = new SCMPMessageFault(SCMPError.SC_ERROR, "executing " + this.msgType + " failed sid=" + sid);
    }
    fault.setSessionId(this.request.getMessage().getSessionId());
    String serviceName = reqMessage.getServiceName();
    // forward server reply to client
    fault.setIsReply(true);
    fault.setServiceName(serviceName);
    fault.setMessageType(this.msgType);
    this.response.setSCMP(fault);
    this.responderCallback.responseCallback(request, response);
  }
View Full Code Here

  }

  /** {@inheritDoc} */
  @Override
  public void receive(Exception ex) {
    SCMPMessage reqMessage = this.request.getMessage();
    String sid = reqMessage.getSessionId();
    LOGGER.warn("receive exception sid=" + sid + " " + ex.toString());
    // release permit
    this.cascClient.getCascClientSemaphore().release();
    // forward reply to client
    this.commandCallback.receive(ex);
View Full Code Here

  /** {@inheritDoc} */
  @Override
  public void run(IRequest request, IResponse response, IResponderCallback responderCallback) throws Exception {
    InetSocketAddress socketAddress = request.getRemoteSocketAddress();

    SCMPMessage message = request.getMessage();
    String serviceName = message.getServiceName();
    // lookup service and checks properness
    StatefulService service = this.getStatefulService(serviceName);

    String serverKey = serviceName + "_" + socketAddress.getHostName() + Constants.SLASH + socketAddress.getPort();
    // controls that server not has been registered before for specific service
    this.getServerByKeyAndValidateNotRegistered(serverKey);

    int maxSessions = message.getHeaderInt(SCMPHeaderAttributeKey.MAX_SESSIONS);
    int maxConnections = message.getHeaderInt(SCMPHeaderAttributeKey.MAX_CONNECTIONS);
    int portNr = message.getHeaderInt(SCMPHeaderAttributeKey.PORT_NR);
    boolean immediateConnect = message.getHeaderFlag(SCMPHeaderAttributeKey.IMMEDIATE_CONNECT);
    int keepAliveIntervalSeconds = message.getHeaderInt(SCMPHeaderAttributeKey.KEEP_ALIVE_INTERVAL);
    int checkRegistrationIntervalSeconds = message.getHeaderInt(SCMPHeaderAttributeKey.CHECK_REGISTRATION_INTERVAL);
    String httpUrlFileQualifier = message.getHeader(SCMPHeaderAttributeKey.URL_PATH);

    if (httpUrlFileQualifier == null) {
      // httpUrlFileQualifier is an optional attribute
      httpUrlFileQualifier = Constants.SLASH;
    }

    ResponderRegistry responderRegistry = AppContext.getResponderRegistry();
    IResponder responder = responderRegistry.getCurrentResponder();
    ListenerConfiguration listenerConfig = responder.getListenerConfig();
    String connectionType = listenerConfig.getConnectionType();

    RemoteNodeConfiguration remoteNodeConfiguration = new RemoteNodeConfiguration(ServerType.STATEFUL_SERVER, serverKey,
        socketAddress.getHostName(), portNr, connectionType, keepAliveIntervalSeconds, checkRegistrationIntervalSeconds,
        maxConnections, maxSessions, httpUrlFileQualifier);
    // create new server
    StatefulServer server = new StatefulServer(remoteNodeConfiguration, serviceName, socketAddress);
    try {
      if (immediateConnect) {
        // server connections get connected immediately
        server.immediateConnect();
      }
    } catch (Exception ex) {
      LOGGER.error("immediate connect", ex);
      HasFaultResponseException communicationException = new SCMPCommunicationException(SCMPError.CONNECTION_EXCEPTION,
          "immediate connect to server=" + serverKey);
      communicationException.setMessageType(getKey());
      throw communicationException;
    }
    // add server to service
    service.addServer(server);
    // add service to server
    server.setService(service);
    // add server to server registry
    this.serverRegistry.addServer(serverKey, server);

    SCMPMessage scmpReply = new SCMPMessage();
    scmpReply.setIsReply(true);
    scmpReply.setMessageType(getKey());
    scmpReply.setHeader(SCMPHeaderAttributeKey.SERVICE_NAME, serviceName);
    scmpReply.setHeader(SCMPHeaderAttributeKey.LOCAL_DATE_TIME, DateTimeUtility.getCurrentTimeZoneMillis());
    response.setSCMP(scmpReply);
    responderCallback.responseCallback(request, response);
  }
View Full Code Here

  }

  /** {@inheritDoc} */
  @Override
  public void receive(Exception ex) {
    SCMPMessage reqMessage = this.request.getMessage();
    String sid = reqMessage.getSessionId();
    LOGGER.warn("receive exception sid=" + sid + " " + ex.toString());
    // release permit
    this.cascClient.getCascClientSemaphore().release();
    // forward reply to client
    this.commandCallback.receive(ex);
View Full Code Here

  }

  /** {@inheritDoc} */
  @Override
  public void validate(IRequest request) throws Exception {
    SCMPMessage message = request.getMessage();
    try {
      // serviceName mandatory
      String serviceName = message.getServiceName();
      ValidatorUtility.validateStringLengthTrim(1, serviceName, Constants.MAX_LENGTH_SERVICENAME,
          SCMPError.HV_WRONG_SERVICE_NAME);
      // scVersion mandatory
      String scVersion = message.getHeader(SCMPHeaderAttributeKey.SC_VERSION);
      SCMPMessage.SC_VERSION.isSupported(scVersion);
      // localDateTime mandatory
      ValidatorUtility.validateDateTime(message.getHeader(SCMPHeaderAttributeKey.LOCAL_DATE_TIME), SCMPError.HV_WRONG_LDT);
      // maxSessions - validate with lower limit 1 mandatory
      String maxSessionsValue = message.getHeader(SCMPHeaderAttributeKey.MAX_SESSIONS);
      ValidatorUtility.validateInt(1, maxSessionsValue, SCMPError.HV_WRONG_MAX_SESSIONS);
      int maxSessions = Integer.parseInt(maxSessionsValue);
      // maxConnections - validate with lower limit 1 & higher limit maxSessions mandatory
      String maxConnectionsValue = message.getHeader(SCMPHeaderAttributeKey.MAX_CONNECTIONS);
      ValidatorUtility.validateInt(1, maxConnectionsValue, maxSessions, SCMPError.HV_WRONG_MAX_CONNECTIONS);
      int maxConnections = Integer.parseInt(maxConnectionsValue);
      if (maxConnections == 1 && maxSessions != 1) {
        // invalid configuration
        throw new SCMPValidatorException(SCMPError.HV_WRONG_MAX_SESSIONS, "maxSessions must be 1 if maxConnections is 1");
      }
      // portNr - portNr >= 1 && portNr <= 0xFFFF mandatory
      String portNr = message.getHeader(SCMPHeaderAttributeKey.PORT_NR);
      ValidatorUtility.validateInt(Constants.MIN_PORT_VALUE, portNr, Constants.MAX_PORT_VALUE, SCMPError.HV_WRONG_PORTNR);
      // keepAliveInterval mandatory
      String kpi = message.getHeader(SCMPHeaderAttributeKey.KEEP_ALIVE_INTERVAL);
      ValidatorUtility.validateInt(Constants.MIN_KPI_VALUE, kpi, Constants.MAX_KPI_VALUE,
          SCMPError.HV_WRONG_KEEPALIVE_INTERVAL);
      // checkRegistrationInterval mandatory
      String cri = message.getHeader(SCMPHeaderAttributeKey.CHECK_REGISTRATION_INTERVAL);
      ValidatorUtility.validateInt(Constants.MIN_CRI_VALUE, cri, Constants.MAX_CRI_VALUE,
          SCMPError.HV_WRONG_CHECK_REGISTRATION_INTERVAL);
    } catch (HasFaultResponseException ex) {
      // needs to set message type at this point
      ex.setMessageType(getKey());
View Full Code Here

   * @param reply
   *            the reply {@inheritDoc}
   */
  @Override
  public void receive(SCMPMessage reply) {
    SCMPMessage reqMessage = request.getMessage();
    String serviceName = reqMessage.getServiceName();

    if (reply.isFault() == false && reply.getHeaderFlag(SCMPHeaderAttributeKey.REJECT_SESSION) == false) {
      if (cascSCSubscription.isCascaded() == true) {
        // update csc subscription id list for cascaded subscription
        cascSCSubscription.addCscSubscriptionId(reqMessage.getSessionId(),
            new SubscriptionMask(reqMessage.getHeader(SCMPHeaderAttributeKey.MASK)));
      }
      // change subscription for cascaded SC
      PublishMessageQueue<SCMPMessage> queue = ((IPublishService) cascSCSubscription.getService()).getMessageQueue();
      SubscriptionMask cascSCMask = new SubscriptionMask(cascSCMaskString);
      queue.changeSubscription(this.cascSCSubscription.getId(), cascSCMask);
View Full Code Here

  }

  /** {@inheritDoc} */
  @Override
  public void run(IRequest request, IResponse response, IResponderCallback responderCallback) throws Exception {
    SCMPMessage message = request.getMessage();
    String serviceName = message.getServiceName();
    // check service is present
    Service abstractService = this.getService(serviceName);
    int oti = message.getHeaderInt(SCMPHeaderAttributeKey.OPERATION_TIMEOUT);

    switch (abstractService.getType()) {
    case CASCADED_FILE_SERVICE:
      CascadedSC cascadedSC = ((CascadedFileService) abstractService).getCascadedSC();
      CommandCascCallback callback = new CommandCascCallback(request, response, responderCallback);
      cascadedSC.serverUploadFile(message, callback, oti);
      return;
    default:
      // code for other types of services is below
      break;
    }

    FileSession session = (FileSession) this.getSessionById(message.getSessionId());
    // reset session timeout to OTI+ECI - during wait for server reply
    int otiOnSCMillis = (int) (oti * basicConf.getOperationTimeoutMultiplier());
    double otiOnSCSeconds = (otiOnSCMillis / Constants.SEC_TO_MILLISEC_FACTOR);
    this.sessionRegistry.resetSessionTimeout(session, (otiOnSCSeconds + session.getSessionTimeoutMillis()));
    SCMPMessage reply = null;
    try {
      String remoteFileName = message.getHeader(SCMPHeaderAttributeKey.REMOTE_FILE_NAME);
      FileServer fileServer = session.getFileServer();
      reply = fileServer.serverUploadFile(session, message, remoteFileName, oti);
    } catch (Exception e) {
      SCMPCommandException scmpCommandException = new SCMPCommandException(SCMPError.FILE_UPLOAD_FAILED,
          "Error occured in file server on SC.");
      scmpCommandException.setMessageType(getKey());
      throw scmpCommandException;
    }
    reply.setIsReply(true);
    reply.setMessageType(getKey());
    response.setSCMP(reply);
    // reset session timeout to ECI
    this.sessionRegistry.resetSessionTimeout(session, session.getSessionTimeoutMillis());
    responderCallback.responseCallback(request, response);
  }
View Full Code Here

  /** {@inheritDoc} */
  @Override
  public void validate(IRequest request) throws Exception {
    try {
      SCMPMessage message = request.getMessage();
      // remoteFileName mandatory
      String remoteFileName = message.getHeader(SCMPHeaderAttributeKey.REMOTE_FILE_NAME);
      ValidatorUtility.validateStringLengthTrim(1, remoteFileName, Constants.MAX_STRING_LENGTH_256,
          SCMPError.HV_WRONG_REMOTE_FILE_NAME);
      // operation timeout mandatory
      String otiValue = message.getHeader(SCMPHeaderAttributeKey.OPERATION_TIMEOUT);
      ValidatorUtility.validateInt(Constants.MIN_OTI_VALUE_CLN, otiValue, Constants.MAX_OTI_VALUE,
          SCMPError.HV_WRONG_OPERATION_TIMEOUT);
      // serviceName mandatory
      String serviceName = message.getServiceName();
      ValidatorUtility.validateStringLengthTrim(1, serviceName, Constants.MAX_LENGTH_SERVICENAME,
          SCMPError.HV_WRONG_SERVICE_NAME);
      // sessionId mandatory
      String sessionId = message.getSessionId();
      ValidatorUtility.validateStringLengthTrim(1, sessionId, Constants.MAX_STRING_LENGTH_256, SCMPError.HV_WRONG_SESSION_ID);
    } catch (HasFaultResponseException ex) {
      // needs to set message type at this point
      ex.setMessageType(getKey());
      throw ex;
View Full Code Here

  }

  /** {@inheritDoc} */
  @Override
  public void receive(SCMPMessage reply) {
    SCMPMessage reqMessage = request.getMessage();
    // only if service cascaded update cascaded client with new subscription mask
    String newMask = reqMessage.getHeader(SCMPHeaderAttributeKey.CASCADED_MASK);
    this.cascClient.setSubscriptionMask(new SubscriptionMask(newMask));
    // only if service is cascaded - release permit
    this.cascClient.getCascClientSemaphore().release();
    try {
      this.commandCallback.receive(reply);
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.