public boolean mediate(MessageContext synCtx, ContinuationState contState) {
    SynapseLog synLog = getLog(synCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Aggregate mediator : Mediating from ContinuationState");
    }

    boolean result;

    SequenceMediator onCompleteSequence = getOnCompleteSequence();
    RuntimeStatisticCollector.openLogForContinuation(
        synCtx, onCompleteSequence.getSequenceNameForStatistics(synCtx));
    if (!contState.hasChild()) {
      result = onCompleteSequence.mediate(synCtx, contState.getPosition() + 1);
    } else {
      FlowContinuableMediator mediator =
          (FlowContinuableMediator) onCompleteSequence.getChild(contState.getPosition());
      RuntimeStatisticCollector.openLogForContinuation(
          synCtx, ((Mediator) mediator).getMediatorName());

      result = mediator.mediate(synCtx, contState.getChildContState());

      ((Mediator) mediator).reportStatistic(synCtx, null, false);
    }
    onCompleteSequence.reportStatistic(synCtx, null, false);
    return result;
  }
 protected SendMediator getSendMediator(SequenceMediator sequence) {
   SendMediator sendMediator = null;
   int size = sequence.getList().size();
   if (size > 0 && sequence.getList().get(size - 1) instanceof SendMediator) {
     sendMediator = (SendMediator) sequence.getList().get(size - 1);
   } else {
     sendMediator = new SendMediator();
     sequence.addChild(sendMediator);
   }
   return sendMediator;
 }
 protected CallMediator getCallMediator(SequenceMediator sequence) {
   CallMediator callMediator = null;
   int size = sequence.getList().size();
   if (size > 0 && sequence.getList().get(size - 1) instanceof CallMediator) {
     callMediator = (CallMediator) sequence.getList().get(size - 1);
   } else {
     callMediator = new CallMediator();
     sequence.addChild(callMediator);
   }
   return callMediator;
 }
 protected boolean injectMessage(InputStream in, String contentType) {
   try {
     org.apache.synapse.MessageContext msgCtx = createMessageContext();
     if (log.isDebugEnabled()) {
       log.debug("Processed Custom inbound EP Message of Content-type : " + contentType);
     }
     MessageContext axis2MsgCtx =
         ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx).getAxis2MessageContext();
     // Determine the message builder to use
     Builder builder;
     if (contentType == null) {
       log.debug("No content type specified. Using SOAP builder.");
       builder = new SOAPBuilder();
     } else {
       int index = contentType.indexOf(';');
       String type = index > 0 ? contentType.substring(0, index) : contentType;
       builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx);
       if (builder == null) {
         if (log.isDebugEnabled()) {
           log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
         }
         builder = new SOAPBuilder();
       }
     }
     OMElement documentElement = builder.processDocument(in, contentType, axis2MsgCtx);
     // Inject the message to the sequence.
     msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));
     if (injectingSeq == null || injectingSeq.equals("")) {
       log.error("Sequence name not specified. Sequence : " + injectingSeq);
       return false;
     }
     SequenceMediator seq =
         (SequenceMediator) synapseEnvironment.getSynapseConfiguration().getSequence(injectingSeq);
     if (seq != null) {
       if (log.isDebugEnabled()) {
         log.debug("injecting message to sequence : " + injectingSeq);
       }
       seq.setErrorHandler(onErrorSeq);
       if (!seq.isInitialized()) {
         seq.init(synapseEnvironment);
       }
       if (!synapseEnvironment.injectInbound(msgCtx, seq, sequential)) {
         return false;
       }
     } else {
       log.error("Sequence: " + injectingSeq + " not found");
     }
   } catch (Exception e) {
     log.error("Error while processing the Custom Inbound EP Message.");
   }
   return true;
 }
  public void init(SynapseEnvironment se) {
    synapseEnv = se;
    if (onCompleteSequence != null) {
      onCompleteSequence.init(se);
    } else if (onCompleteSequenceRef != null) {
      SequenceMediator referredOnCompleteSeq =
          (SequenceMediator) se.getSynapseConfiguration().getSequence(onCompleteSequenceRef);

      if (referredOnCompleteSeq == null || referredOnCompleteSeq.isDynamic()) {
        se.addUnavailableArtifactRef(onCompleteSequenceRef);
      }
    }
  }
  public void destroy() {
    if (onCompleteSequence != null) {
      onCompleteSequence.destroy();
    } else if (onCompleteSequenceRef != null) {
      SequenceMediator referredOnCompleteSeq =
          (SequenceMediator)
              synapseEnv.getSynapseConfiguration().getSequence(onCompleteSequenceRef);

      if (referredOnCompleteSeq == null || referredOnCompleteSeq.isDynamic()) {
        synapseEnv.removeUnavailableArtifactRef(onCompleteSequenceRef);
      }
    }
  }
 protected void setEndpointToSendOrCallMediator(SequenceMediator sequence, Endpoint synapseEP) {
   int size = sequence.getList().size();
   Object mediator = null;
   if (size > 0) {
     mediator = sequence.getList().get(size - 1);
   }
   if (mediator instanceof SendMediator) {
     SendMediator sendMediator = getSendMediator(sequence);
     sendMediator.setEndpoint(synapseEP);
   } else if (mediator instanceof CallMediator) {
     CallMediator callMediator = getCallMediator(sequence);
     callMediator.setEndpoint(synapseEP);
   }
 }
  /**
   * Deserialize a sequence
   *
   * @param mediatorFlow
   * @param sequence
   * @param connector
   * @param reversed
   * @throws DeserializerException
   */
  protected void deserializeSequence(
      IGraphicalEditPart part,
      SequenceMediator sequenceMediator,
      EsbConnector connector,
      boolean reversed)
      throws DeserializerException {
    LinkedList<EsbNode> nodeList = new LinkedList<>();
    LinkedList<CommentMediator> commentMediatorList = new LinkedList<>();
    SequenceMediator sequence = EditorUtils.stripUnsupportedMediators(sequenceMediator);

    TransactionalEditingDomain domain = part.getEditingDomain();

    if (connector instanceof OutputConnector) {
      int mediatorsCount = sequence.getList().size();
      boolean lastMediator = false;
      for (int i = 0; i < mediatorsCount; ++i) {
        AbstractMediator mediator = (AbstractMediator) sequence.getList().get(i);
        if (mediatorsCount == (i + 1)) {
          lastMediator = true;
        }
        if (reversedNodes.contains(connector.eContainer())) {
          executeMediatorDeserializer(
              part, nodeList, domain, mediator, true, commentMediatorList, lastMediator);
          reversedNodes.addAll(nodeList);
        } else {
          executeMediatorDeserializer(
              part, nodeList, domain, mediator, reversed, commentMediatorList, lastMediator);
          if (reversed) {
            reversedNodes.addAll(nodeList);
          }
        }
      }
      connectionFlowMap.put(connector, nodeList);
    } else if (connector instanceof InputConnector) {
      int mediatorsCount = sequence.getList().size();
      boolean lastMediator = false;
      for (int i = mediatorsCount - 1; i >= 0; --i) {
        if (i == 0) {
          lastMediator = true;
        }
        AbstractMediator mediator = (AbstractMediator) sequence.getList().get(i);
        executeMediatorDeserializer(
            part, nodeList, domain, mediator, true, commentMediatorList, lastMediator);
      }
      connectionFlowMap.put(connector, nodeList);
      reversedNodes.addAll(nodeList);
    }
  }
  public void transformWithinSequence(
      TransformationInfo information, EsbNode subject, SequenceMediator sequence) throws Exception {

    sequence.addChild(createValidateMediator(subject, information));
    doTransformWithinSequence(
        information, ((ValidateMediator) subject).getOutputConnector().getOutgoingLink(), sequence);
  }
Example #10
0
  public void destroy() {

    for (Target target : targets) {
      ManagedLifecycle seq = target.getSequence();
      if (seq != null) {
        seq.destroy();
      } else if (target.getSequenceRef() != null) {
        SequenceMediator targetSequence =
            (SequenceMediator)
                synapseEnv.getSynapseConfiguration().getSequence(target.getSequenceRef());

        if (targetSequence == null || targetSequence.isDynamic()) {
          synapseEnv.removeUnavailableArtifactRef(target.getSequenceRef());
        }
      }
      Endpoint endpoint = target.getEndpoint();
      if (endpoint != null) {
        endpoint.destroy();
      }
    }
  }
Example #11
0
  public void init(SynapseEnvironment se) {

    synapseEnv = se;
    for (Target target : targets) {
      ManagedLifecycle seq = target.getSequence();
      if (seq != null) {
        seq.init(se);
      } else if (target.getSequenceRef() != null) {
        SequenceMediator targetSequence =
            (SequenceMediator) se.getSynapseConfiguration().getSequence(target.getSequenceRef());

        if (targetSequence == null || targetSequence.isDynamic()) {
          se.addUnavailableArtifactRef(target.getSequenceRef());
        }
      }
      Endpoint endpoint = target.getEndpoint();
      if (endpoint != null) {
        endpoint.init(se);
      }
    }
  }
 public void transformWithinSequence(
     TransformationInfo information, EsbNode subject, SequenceMediator sequence) throws Exception {
   org.apache.synapse.mediators.builtin.CallMediator callMediator = createCallMediator(subject);
   if (callMediator != null) {
     sequence.addChild(callMediator);
   }
   if (((CallMediator) subject).getEndpointType() == CallMediatorEndpointType.INLINE) {
     // to transform the mediators inside the mediator
     doTransformWithinSequence(
         information,
         ((CallMediator) subject).getEndpointOutputConnector().getOutgoingLink(),
         sequence);
   }
   // to go in normal flow
   doTransformWithinSequence(
       information, ((CallMediator) subject).getOutputConnector().getOutgoingLink(), sequence);
 }
  /**
   * Create the file system for holding the synapse configuration for a new tanent.
   *
   * @param synapseConfigDir configuration directory where synapse configuration is created
   * @param tenantDomain name of the tenent
   */
  @SuppressWarnings({"ResultOfMethodCallIgnored"})
  private void createTenantSynapseConfigHierarchy(File synapseConfigDir, String tenantDomain) {

    if (!synapseConfigDir.mkdir()) {
      log.fatal(
          "Couldn't create the synapse-config root on the file system "
              + "for the tenant domain : "
              + tenantDomain);
      return;
    }

    File sequencesDir = new File(synapseConfigDir, MultiXMLConfigurationBuilder.SEQUENCES_DIR);
    File endpointsDir = new File(synapseConfigDir, MultiXMLConfigurationBuilder.ENDPOINTS_DIR);
    File entriesDir = new File(synapseConfigDir, MultiXMLConfigurationBuilder.LOCAL_ENTRY_DIR);
    File proxyServicesDir =
        new File(synapseConfigDir, MultiXMLConfigurationBuilder.PROXY_SERVICES_DIR);
    File eventSourcesDir = new File(synapseConfigDir, MultiXMLConfigurationBuilder.EVENTS_DIR);
    File tasksDir = new File(synapseConfigDir, MultiXMLConfigurationBuilder.TASKS_DIR);
    File executorsDir = new File(synapseConfigDir, MultiXMLConfigurationBuilder.EXECUTORS_DIR);

    if (!sequencesDir.mkdir()) {
      log.warn("Could not create " + sequencesDir);
    }
    if (!endpointsDir.mkdir()) {
      log.warn("Could not create " + endpointsDir);
    }
    if (!entriesDir.mkdir()) {
      log.warn("Could not create " + entriesDir);
    }
    if (!proxyServicesDir.mkdir()) {
      log.warn("Could not create " + proxyServicesDir);
    }
    if (!eventSourcesDir.mkdir()) {
      log.warn("Could not create " + eventSourcesDir);
    }
    if (!tasksDir.mkdir()) {
      log.warn("Could not create " + tasksDir);
    }
    if (!executorsDir.mkdir()) {
      log.warn("Could not create " + executorsDir);
    }

    SynapseConfiguration initialSynCfg = SynapseConfigurationBuilder.getDefaultConfiguration();
    SequenceMediator mainSequence = (SequenceMediator) initialSynCfg.getMainSequence();
    SequenceMediator faultSequence = (SequenceMediator) initialSynCfg.getFaultSequence();
    mainSequence.setFileName(SynapseConstants.MAIN_SEQUENCE_KEY + ".xml");
    faultSequence.setFileName(SynapseConstants.FAULT_SEQUENCE_KEY + ".xml");
    Registry registry = new WSO2Registry();
    initialSynCfg.setRegistry(registry);

    MultiXMLConfigurationSerializer serializer =
        new MultiXMLConfigurationSerializer(synapseConfigDir.getAbsolutePath());
    try {
      serializer.serializeSequence(mainSequence, initialSynCfg, null);
      serializer.serializeSequence(faultSequence, initialSynCfg, null);
      serializer.serializeSynapseRegistry(registry, initialSynCfg, null);
    } catch (Exception e) {
      handleException(
          "Couldn't serialise the initial synapse configuration "
              + "for the domain : "
              + tenantDomain,
          e);
    }
  }
  /**
   * Create the file system for holding the synapse configuration for a new tanent.
   *
   * @param synapseConfigDir configuration directory where synapse configuration is created
   * @param tenantDomain name of the tenent
   */
  @SuppressWarnings({"ResultOfMethodCallIgnored"})
  private void createTenantSynapseConfigHierarchy(File synapseConfigDir, String tenantDomain) {
    synapseConfigDir.mkdir();
    File sequencesDir = new File(synapseConfigDir, MultiXMLConfigurationBuilder.SEQUENCES_DIR);

    if (!sequencesDir.mkdir()) {
      log.warn("Could not create " + sequencesDir);
    }

    SynapseConfiguration initialSynCfg = SynapseConfigurationBuilder.getDefaultConfiguration();

    // SequenceMediator mainSequence = (SequenceMediator) initialSynCfg.getMainSequence();
    // SequenceMediator faultSequence = (SequenceMediator) initialSynCfg.getFaultSequence();
    InputStream in = null;
    StAXOMBuilder builder = null;
    SequenceMediatorFactory factory = new SequenceMediatorFactory();
    try {
      if (authFailureHandlerSequence == null) {
        in =
            FileUtils.openInputStream(
                new File(synapseConfigRootPath + authFailureHandlerSequenceName + ".xml"));
        builder = new StAXOMBuilder(in);
        authFailureHandlerSequence =
            (SequenceMediator)
                factory.createMediator(builder.getDocumentElement(), new Properties());
        authFailureHandlerSequence.setFileName(authFailureHandlerSequenceName + ".xml");
      }
      if (resourceMisMatchSequence == null) {
        in =
            FileUtils.openInputStream(
                new File(synapseConfigRootPath + resourceMisMatchSequenceName + ".xml"));
        builder = new StAXOMBuilder(in);
        resourceMisMatchSequence =
            (SequenceMediator)
                factory.createMediator(builder.getDocumentElement(), new Properties());
        resourceMisMatchSequence.setFileName(resourceMisMatchSequenceName + ".xml");
      }
      if (throttleOutSequence == null) {
        in =
            FileUtils.openInputStream(
                new File(synapseConfigRootPath + throttleOutSequenceName + ".xml"));
        builder = new StAXOMBuilder(in);
        throttleOutSequence =
            (SequenceMediator)
                factory.createMediator(builder.getDocumentElement(), new Properties());
        throttleOutSequence.setFileName(throttleOutSequenceName + ".xml");
      }
      //            if (buildSequence == null) {
      //                in = FileUtils.openInputStream(new File(synapseConfigRootPath +
      // buildSequenceName + ".xml"));
      //                builder = new StAXOMBuilder(in);
      //                buildSequence = (SequenceMediator)
      // factory.createMediator(builder.getDocumentElement(), new Properties());
      //                buildSequence.setFileName(buildSequenceName + ".xml");
      //            }
      if (sandboxKeyErrorSequence == null) {
        in =
            FileUtils.openInputStream(
                new File(synapseConfigRootPath + sandboxKeyErrorSequenceName + ".xml"));
        builder = new StAXOMBuilder(in);
        sandboxKeyErrorSequence =
            (SequenceMediator)
                factory.createMediator(builder.getDocumentElement(), new Properties());
        sandboxKeyErrorSequence.setFileName(sandboxKeyErrorSequenceName + ".xml");
      }
      if (productionKeyErrorSequence == null) {
        in =
            FileUtils.openInputStream(
                new File(synapseConfigRootPath + productionKeyErrorSequenceName + ".xml"));
        builder = new StAXOMBuilder(in);
        productionKeyErrorSequence =
            (SequenceMediator)
                factory.createMediator(builder.getDocumentElement(), new Properties());
        productionKeyErrorSequence.setFileName(productionKeyErrorSequenceName + ".xml");
      }
      FileUtils.copyFile(
          new File(synapseConfigRootPath + mainSequenceName + ".xml"),
          new File(
              synapseConfigDir.getAbsolutePath()
                  + File.separator
                  + "sequences"
                  + File.separator
                  + mainSequenceName
                  + ".xml"));

      FileUtils.copyFile(
          new File(synapseConfigRootPath + faultSequenceName + ".xml"),
          new File(
              synapseConfigDir.getAbsolutePath()
                  + File.separator
                  + "sequences"
                  + File.separator
                  + faultSequenceName
                  + ".xml"));
      FileUtils.copyFile(
          new File(synapseConfigRootPath + saml2SequenceName + ".xml"),
          new File(
              synapseConfigDir.getAbsolutePath()
                  + File.separator
                  + "sequences"
                  + File.separator
                  + saml2SequenceName
                  + ".xml"));

    } catch (IOException e) {
      log.error("Error while reading WebApp manager specific synapse sequences" + e);

    } catch (XMLStreamException e) {
      log.error("Error while parsing WebApp manager specific synapse sequences" + e);
    } finally {
      IOUtils.closeQuietly(in);
    }

    Registry registry = new WSO2Registry();
    initialSynCfg.setRegistry(registry);
    MultiXMLConfigurationSerializer serializer =
        new MultiXMLConfigurationSerializer(synapseConfigDir.getAbsolutePath());
    try {
      serializer.serializeSequence(authFailureHandlerSequence, initialSynCfg, null);
      serializer.serializeSequence(sandboxKeyErrorSequence, initialSynCfg, null);
      serializer.serializeSequence(productionKeyErrorSequence, initialSynCfg, null);
      //            serializer.serializeSequence(buildSequence, initialSynCfg, null);
      serializer.serializeSequence(throttleOutSequence, initialSynCfg, null);
      serializer.serializeSequence(resourceMisMatchSequence, initialSynCfg, null);
      serializer.serializeSynapseRegistry(registry, initialSynCfg, null);
    } catch (Exception e) {
      handleException(
          "Couldn't serialise the initial synapse configuration "
              + "for the domain : "
              + tenantDomain,
          e);
    }
  }
  /**
   * Invoked by the Aggregate objects that are timed out, to signal timeout/completion of itself
   *
   * @param aggregate the timed out Aggregate that holds collected messages and properties
   */
  public boolean completeAggregate(Aggregate aggregate) {

    boolean markedCompletedNow = false;
    boolean wasComplete = aggregate.isCompleted();
    if (wasComplete) {
      return false;
    }

    if (log.isDebugEnabled()) {
      log.debug("Aggregation completed or timed out");
    }

    // cancel the timer
    synchronized (this) {
      if (!aggregate.isCompleted()) {
        aggregate.cancel();
        aggregate.setCompleted(true);
        markedCompletedNow = true;
      }
    }

    if (!markedCompletedNow) {
      return false;
    }

    MessageContext newSynCtx = getAggregatedMessage(aggregate);

    if (newSynCtx == null) {
      log.warn("An aggregation of messages timed out with no aggregated messages", null);
      return false;
    } else {
      // Get the aggregated message to the next mediator placed after the aggregate mediator
      // in the sequence
      if (newSynCtx.isContinuationEnabled()) {
        try {
          aggregate
              .getLastMessage()
              .setEnvelope(MessageHelper.cloneSOAPEnvelope(newSynCtx.getEnvelope()));
        } catch (AxisFault axisFault) {
          log.warn(
              "Error occurred while assigning aggregated message"
                  + " back to the last received message context");
        }
      }
    }

    aggregate.clear();
    activeAggregates.remove(aggregate.getCorrelation());

    if ((correlateExpression != null
            && !correlateExpression.toString().equals(aggregate.getCorrelation()))
        || correlateExpression == null) {

      if (onCompleteSequence != null) {

        ContinuationStackManager.addReliantContinuationState(newSynCtx, 0, getMediatorPosition());
        boolean result = onCompleteSequence.mediate(newSynCtx);
        if (result) {
          ContinuationStackManager.removeReliantContinuationState(newSynCtx);
        }
        return result;

      } else if (onCompleteSequenceRef != null
          && newSynCtx.getSequence(onCompleteSequenceRef) != null) {

        ContinuationStackManager.updateSeqContinuationState(newSynCtx, getMediatorPosition());
        return newSynCtx.getSequence(onCompleteSequenceRef).mediate(newSynCtx);

      } else {
        handleException(
            "Unable to find the sequence for the mediation " + "of the aggregated message",
            newSynCtx);
      }
    }
    return false;
  }
  /** Invoke the mediation logic for the passed message */
  public boolean invoke(Object object, String name) throws SynapseException {

    Message msg = (Message) object;
    try {
      org.apache.synapse.MessageContext msgCtx = createMessageContext();
      msgCtx.setProperty("inbound.endpoint.name", name);
      InboundEndpoint inboundEndpoint = msgCtx.getConfiguration().getInboundEndpoint(name);
      CustomLogSetter.getInstance().setLogAppender(inboundEndpoint.getArtifactContainerName());
      String contentType = msg.getJMSType();

      if (contentType == null || contentType.trim().equals("")) {
        String contentTypeProperty = jmsProperties.getProperty(JMSConstants.CONTENT_TYPE_PROPERTY);
        if (contentTypeProperty != null) {
          contentType = msg.getStringProperty(contentTypeProperty);
        }
      } else {
        msgCtx.setProperty(JMSConstants.JMS_MESSAGE_TYPE, contentType);
      }

      if (contentType == null || contentType.trim().equals("")) {
        contentType = jmsProperties.getProperty(JMSConstants.CONTENT_TYPE);
      }
      if (log.isDebugEnabled()) {
        log.debug("Processed JMS Message of Content-type : " + contentType);
      }
      MessageContext axis2MsgCtx =
          ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx).getAxis2MessageContext();
      // set the JMS Message ID as the Message ID of the MessageContext
      try {
        msgCtx.setMessageID(msg.getJMSMessageID());
        String jmsCorrelationID = msg.getJMSCorrelationID();
        if (jmsCorrelationID != null && !jmsCorrelationID.isEmpty()) {
          msgCtx.setProperty(JMSConstants.JMS_COORELATION_ID, jmsCorrelationID);
        } else {
          msgCtx.setProperty(JMSConstants.JMS_COORELATION_ID, msg.getJMSMessageID());
        }
      } catch (JMSException ignore) {
        log.warn("Error getting the COORELATION ID from the message.");
      }

      // Handle dual channel
      Destination replyTo = msg.getJMSReplyTo();
      if (replyTo != null) {
        msgCtx.setProperty(SynapseConstants.IS_INBOUND, true);
        // Create the cachedJMSConnectionFactory with the existing
        // connection
        CachedJMSConnectionFactory cachedJMSConnectionFactory =
            new CachedJMSConnectionFactory(jmsProperties, connection);
        String strUserName = jmsProperties.getProperty(JMSConstants.PARAM_JMS_USERNAME);
        String strPassword = jmsProperties.getProperty(JMSConstants.PARAM_JMS_PASSWORD);
        JMSReplySender jmsReplySender =
            new JMSReplySender(replyTo, cachedJMSConnectionFactory, strUserName, strPassword);
        msgCtx.setProperty(
            InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, jmsReplySender);
      } else if (replyDestination != null) {
        msgCtx.setProperty(SynapseConstants.IS_INBOUND, true);
        // Create the cachedJMSConnectionFactory with the existing
        // connection
        CachedJMSConnectionFactory cachedJMSConnectionFactory =
            new CachedJMSConnectionFactory(jmsProperties, connection);
        String strUserName = jmsProperties.getProperty(JMSConstants.PARAM_JMS_USERNAME);
        String strPassword = jmsProperties.getProperty(JMSConstants.PARAM_JMS_PASSWORD);
        JMSReplySender jmsReplySender =
            new JMSReplySender(
                replyDestination, cachedJMSConnectionFactory, strUserName, strPassword);
        msgCtx.setProperty(
            InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, jmsReplySender);
      }

      // Determine the message builder to use
      Builder builder;
      if (contentType == null) {
        log.debug("No content type specified. Using SOAP builder.");
        builder = new SOAPBuilder();
      } else {
        int index = contentType.indexOf(';');
        String type = index > 0 ? contentType.substring(0, index) : contentType;
        builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx);
        if (builder == null) {
          if (log.isDebugEnabled()) {
            log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
          }
          builder = new SOAPBuilder();
        }
      }
      OMElement documentElement = null;
      // set the message payload to the message context
      if (msg instanceof TextMessage) {
        String message = ((TextMessage) msg).getText();
        InputStream in = new AutoCloseInputStream(new ByteArrayInputStream(message.getBytes()));
        documentElement = builder.processDocument(in, contentType, axis2MsgCtx);
      } else if (msg instanceof BytesMessage) {
        if (builder instanceof DataSourceMessageBuilder) {
          documentElement =
              ((DataSourceMessageBuilder) builder)
                  .processDocument(
                      new BytesMessageDataSource((BytesMessage) msg), contentType, axis2MsgCtx);
        } else {
          documentElement =
              builder.processDocument(
                  new BytesMessageInputStream((BytesMessage) msg), contentType, axis2MsgCtx);
        }
      } else if (msg instanceof MapMessage) {
        documentElement = convertJMSMapToXML((MapMessage) msg);
      }

      // Inject the message to the sequence.
      msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));
      if (injectingSeq == null || injectingSeq.equals("")) {
        log.error("Sequence name not specified. Sequence : " + injectingSeq);
        return false;
      }
      SequenceMediator seq =
          (SequenceMediator) synapseEnvironment.getSynapseConfiguration().getSequence(injectingSeq);
      if (seq != null) {
        if (log.isDebugEnabled()) {
          log.debug("injecting message to sequence : " + injectingSeq);
        }
        seq.setErrorHandler(onErrorSeq);
        if (!synapseEnvironment.injectInbound(msgCtx, seq, sequential)) {
          return false;
        }
      } else {
        log.error("Sequence: " + injectingSeq + " not found");
      }

      Object o = msgCtx.getProperty(JMSConstants.SET_ROLLBACK_ONLY);
      if (o != null) {
        if ((o instanceof Boolean && ((Boolean) o))
            || (o instanceof String && Boolean.valueOf((String) o))) {
          return false;
        }
      }
    } catch (SynapseException se) {
      throw se;
    } catch (Exception e) {
      log.error("Error while processing the JMS Message", e);
      throw new SynapseException("Error while processing the JMS Message", e);
    }
    return true;
  }
  private org.apache.synapse.mediators.builtin.ValidateMediator createValidateMediator(
      EsbNode subject, TransformationInfo information) throws TransformerException, JaxenException {

    /*
     * Check subject.
     */
    Assert.isTrue(subject instanceof ValidateMediator, "Invalid subject.");
    ValidateMediator visualValidateMediator = (ValidateMediator) subject;
    /*
     * Configure Validate mediator.
     */

    org.apache.synapse.mediators.builtin.ValidateMediator validateMediator =
        new org.apache.synapse.mediators.builtin.ValidateMediator();
    setCommonProperties(validateMediator, visualValidateMediator);

    NamespacedProperty sourceXPath = visualValidateMediator.getSourceXpath();
    if (sourceXPath.getPropertyValue() != null && !sourceXPath.getPropertyValue().equals("")) {
      SynapseXPath synapseXPath = new SynapseXPath(sourceXPath.getPropertyValue());
      for (Entry<String, String> entry : sourceXPath.getNamespaces().entrySet()) {
        synapseXPath.addNamespace(entry.getKey(), entry.getValue());
      }
      validateMediator.setSource(synapseXPath);
    }

    List<Value> valueList = new ArrayList<Value>();
    for (ValidateSchema schema : visualValidateMediator.getSchemas()) {

      if (schema.getValidateSchemaKeyType().getLiteral().equals(KeyType.STATIC.getLiteral())) {

        if (schema.getValidateStaticSchemaKey() != null
            && schema.getValidateStaticSchemaKey().getKeyValue() != null) {
          Value val = new Value(schema.getValidateStaticSchemaKey().getKeyValue());
          valueList.add(val);
        }

      } else {

        NamespacedProperty dynamicSchemaKey = schema.getValidateDynamicSchemaKey();
        if (dynamicSchemaKey != null && dynamicSchemaKey.getPropertyValue() != null) {
          SynapseXPath xpath = new SynapseXPath(dynamicSchemaKey.getPropertyValue());
          for (Entry<String, String> entry : dynamicSchemaKey.getNamespaces().entrySet()) {
            xpath.addNamespace(entry.getKey(), entry.getValue());
          }
          Value val = new Value(xpath);
          valueList.add(val);
        }
      }
    }
    validateMediator.setSchemaKeys(valueList);

    // ListMediator onFailMediatorList = new AnonymousListMediator();
    SequenceMediator onFailMediatorList = new SequenceMediator();
    TransformationInfo newOnFailInfo = new TransformationInfo();
    newOnFailInfo.setTraversalDirection(information.getTraversalDirection());
    newOnFailInfo.setSynapseConfiguration(information.getSynapseConfiguration());
    newOnFailInfo.setOriginInSequence(information.getOriginInSequence());
    newOnFailInfo.setOriginOutSequence(information.getOriginOutSequence());
    newOnFailInfo.setCurrentProxy(information.getCurrentProxy());
    newOnFailInfo.setParentSequence(onFailMediatorList);
    doTransform(newOnFailInfo, visualValidateMediator.getOnFailOutputConnector());
    validateMediator.addAll(onFailMediatorList.getList());

    for (ValidateFeature feature : visualValidateMediator.getFeatures()) {
      try {
        validateMediator.addFeature(feature.getFeatureName(), feature.isFeatureEnabled());
      } catch (Exception e) {
        log.error(e);
      }
    }

    if (!visualValidateMediator.getResources().isEmpty()) {

      ResourceMap rMap = new ResourceMap();

      for (ValidateResource resource : visualValidateMediator.getResources()) {

        if (resource.getLocation() != null && resource.getKey() != null) {

          rMap.addResource(resource.getLocation(), resource.getKey().getKeyValue());
        }
      }

      validateMediator.setResourceMap(rMap);
    }

    return validateMediator;
  }