@Override
  public void undeploySynapseArtifact(String artifactName) {

    if (log.isDebugEnabled()) {
      log.debug("Endpoint Undeployment of the endpoint named : " + artifactName + " : Started");
    }

    try {
      Endpoint ep = getSynapseConfiguration().getDefinedEndpoints().get(artifactName);
      if (ep != null) {

        CustomLogSetter.getInstance()
            .setLogAppender((ep != null) ? ep.getArtifactContainerName() : "");

        getSynapseConfiguration().removeEndpoint(artifactName);
        if (log.isDebugEnabled()) {
          log.debug("Destroying the endpoint named : " + artifactName);
        }
        ep.destroy();
        if (log.isDebugEnabled()) {
          log.debug(
              "Endpoint Undeployment of the endpoint named : " + artifactName + " : Completed");
        }
        log.info("Endpoint named '" + ep.getName() + "' has been undeployed");
      } else if (log.isDebugEnabled()) {
        log.debug("Endpoint " + artifactName + " has already been undeployed");
      }
    } catch (Exception e) {
      handleSynapseArtifactDeploymentError(
          "Endpoint Undeployement of endpoint named : " + artifactName + " : Failed", e);
    }
  }
Example #2
0
  /**
   * Make sure that the endpoints created by the factory has a name
   *
   * @param epConfig OMElement containing the endpoint configuration.
   * @param anonymousEndpoint false if the endpoint has a name. true otherwise.
   * @param properties bag of properties to pass in any information to the factory
   * @return Endpoint implementation for the given configuration.
   */
  private Endpoint createEndpointWithName(
      OMElement epConfig, boolean anonymousEndpoint, Properties properties) {

    Endpoint ep = createEndpoint(epConfig, anonymousEndpoint, properties);
    OMElement descriptionElem = epConfig.getFirstChildWithName(DESCRIPTION_Q);
    if (descriptionElem != null) {
      ep.setDescription(descriptionElem.getText());
    }

    // if the endpoint doesn't have a name we will generate a unique name.
    if (anonymousEndpoint && ep.getName() == null) {
      String uuid = UIDGenerator.generateUID();
      uuid = uuid.replace(':', '_');
      ep.setName(ENDPOINT_NAME_PREFIX + uuid);
      if (ep instanceof AbstractEndpoint) {
        ((AbstractEndpoint) ep).setAnonymous(true);
      }
    }

    OMAttribute onFaultAtt = epConfig.getAttribute(ON_FAULT_Q);
    if (onFaultAtt != null) {
      ep.setErrorHandler(onFaultAtt.getAttributeValue());
    }
    return ep;
  }
  @Override
  public void restoreSynapseArtifact(String artifactName) {

    if (log.isDebugEnabled()) {
      log.debug("Restoring the Endpoint with name : " + artifactName + " : Started");
    }

    try {
      Endpoint ep = getSynapseConfiguration().getDefinedEndpoints().get(artifactName);

      CustomLogSetter.getInstance()
          .setLogAppender((ep != null) ? ep.getArtifactContainerName() : "");

      OMElement epElem = EndpointSerializer.getElementFromEndpoint(ep);
      if (ep.getFileName() != null) {
        String fileName =
            getServerConfigurationInformation().getSynapseXMLLocation()
                + File.separator
                + MultiXMLConfigurationBuilder.ENDPOINTS_DIR
                + File.separator
                + ep.getFileName();
        writeToFile(epElem, fileName);
        if (log.isDebugEnabled()) {
          log.debug("Restoring the Endpoint with name : " + artifactName + " : Completed");
        }
        log.info("Endpoint named '" + artifactName + "' has been restored");
      } else {
        handleSynapseArtifactDeploymentError(
            "Couldn't restore the endpoint named '" + artifactName + "', filename cannot be found");
      }
    } catch (Exception e) {
      handleSynapseArtifactDeploymentError(
          "Restoring of the endpoint named '" + artifactName + "' has failed", e);
    }
  }
Example #4
0
  public void init(SynapseEnvironment synapseEnvironment) {
    this.synapseEnv = synapseEnvironment;

    if (endpoint != null) {
      endpoint.init(synapseEnvironment);
    }

    if (blocking) {
      try {
        configCtx =
            ConfigurationContextFactory.createConfigurationContextFromFileSystem(
                DEFAULT_CLIENT_REPO, DEFAULT_AXIS2_XML);
        blockingMsgSender = new BlockingMsgSender();
        blockingMsgSender.setConfigurationContext(configCtx);
        blockingMsgSender.init();

      } catch (AxisFault axisFault) {
        String msg = "Error while initializing the Call mediator";
        log.error(msg, axisFault);
        throw new SynapseException(msg, axisFault);
      }
    } else {
      synapseEnvironment.updateCallMediatorCount(true);
    }
  }
Example #5
0
  /**
   * This will call the send method on the messages with implicit message parameters or else if
   * there is an endpoint, with that endpoint parameters
   *
   * @param synCtx the current message to be sent
   * @return false always as this is a leaf mediator
   */
  public boolean mediate(SynapseMessageContext synCtx) {

    log.debug("Start : Send mediator");
    if (log.isTraceEnabled()) {
      log.trace("Message : " + synCtx.getEnvelope());
    }

    // if no endpoints are defined, send where implicitly stated
    if (endpoint == null) {

      if (log.isDebugEnabled()) {
        StringBuffer sb = new StringBuffer();
        sb.append("Sending ")
            .append(synCtx.isResponse() ? "response" : "request")
            .append(" message using implicit message properties..");
        sb.append("\nSending To: ")
            .append(synCtx.getTo() != null ? synCtx.getTo().getAddress() : "null");
        sb.append("\nSOAPAction: ")
            .append(synCtx.getWSAAction() != null ? synCtx.getWSAAction() : "null");
        log.debug(sb.toString());
      }

      if (log.isTraceEnabled()) {
        log.trace("Envelope : " + synCtx.getEnvelope());
      }
      synCtx.getEnvironment().send(null, synCtx);

    } else {
      endpoint.send(synCtx);
    }

    log.debug("End : Send mediator");

    return true;
  }
Example #6
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);
      }
    }
  }
Example #7
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();
      }
    }
  }
  @Override
  public String deploySynapseArtifact(
      OMElement artifactConfig, String fileName, Properties properties) {

    if (log.isDebugEnabled()) {
      log.debug("Endpoint Deployment from file : " + fileName + " : Started");
    }

    CustomLogSetter.getInstance().setLogAppender(customLogContent);

    try {
      Endpoint ep = EndpointFactory.getEndpointFromElement(artifactConfig, false, properties);

      // Set the car name
      ep.setArtifactContainerName(customLogContent);
      if (ep != null) {
        ep.setFileName((new File(fileName)).getName());
        if (log.isDebugEnabled()) {
          log.debug(
              "Endpoint named '" + ep.getName() + "' has been built from the file " + fileName);
        }
        ep.init(getSynapseEnvironment());
        if (log.isDebugEnabled()) {
          log.debug("Initialized the endpoint : " + ep.getName());
        }
        getSynapseConfiguration().addEndpoint(ep.getName(), ep);
        if (log.isDebugEnabled()) {
          log.debug("Endpoint Deployment from file : " + fileName + " : Completed");
        }
        log.info("Endpoint named '" + ep.getName() + "' has been deployed from file : " + fileName);
        return ep.getName();
      } else {
        handleSynapseArtifactDeploymentError(
            "Endpoint Deployment Failed. The artifact "
                + "described in the file "
                + fileName
                + " is not an Endpoint");
      }
    } catch (Exception e) {
      handleSynapseArtifactDeploymentError(
          "Endpoint Deployment from the file : " + fileName + " : Failed.", e);
    }

    return null;
  }
Example #9
0
  /**
   * Helper method to construct children endpoints
   *
   * @param listEndpointElement OMElement representing the children endpoints
   * @param parent Parent endpoint
   * @param properties bag of properties to pass in any information to the factory
   * @return List of children endpoints
   */
  protected ArrayList<Endpoint> getEndpoints(
      OMElement listEndpointElement, Endpoint parent, Properties properties) {

    ArrayList<Endpoint> endpoints = new ArrayList<Endpoint>();
    ArrayList<String> keys = new ArrayList<String>();
    Iterator iter = listEndpointElement.getChildrenWithName(XMLConfigConstants.ENDPOINT_ELT);
    while (iter.hasNext()) {
      OMElement endptElem = (OMElement) iter.next();
      Endpoint endpoint = EndpointFactory.getEndpointFromElement(endptElem, true, properties);
      if (endpoint instanceof IndirectEndpoint) {
        String key = ((IndirectEndpoint) endpoint).getKey();
        if (!keys.contains(key)) {
          keys.add(key);
        } else {
          handleException("Same endpoint definition cannot be used with in the siblings");
        }
      }
      endpoint.setParentEndpoint(parent);
      endpoints.add(endpoint);
    }

    return endpoints;
  }
Example #10
0
  @Override
  public void setComponentStatisticsId(ArtifactHolder holder) {
    if (getAspectConfiguration() == null) {
      configure(new AspectConfiguration(getMediatorName()));
    }
    String cloneId =
        StatisticIdentityGenerator.getIdForComponent(
            getMediatorName(), ComponentType.MEDIATOR, holder);
    getAspectConfiguration().setUniqueId(cloneId);

    if (endpoint != null) {
      endpoint.setComponentStatisticsId(holder);
    }
    StatisticIdentityGenerator.reportingEndEvent(cloneId, ComponentType.MEDIATOR, holder);
  }
  /**
   * Handle the response or error (during a failed send) message received for an outgoing request
   *
   * @param messageID Request message ID
   * @param response the Axis2 MessageContext that has been received and has to be handled
   * @param synapseOutMsgCtx the corresponding (outgoing) Synapse MessageContext for the above Axis2
   *     MC, that holds Synapse specific information such as the error handler stack and local
   *     properties etc.
   * @throws AxisFault if the message cannot be processed
   */
  private void handleMessage(
      String messageID,
      MessageContext response,
      org.apache.synapse.MessageContext synapseOutMsgCtx,
      AsyncCallback callback)
      throws AxisFault {
    // apply the tenant information to the out message context
    TenantInfoConfigurator configurator =
        synapseOutMsgCtx.getEnvironment().getTenantInfoConfigurator();
    if (configurator != null) {
      configurator.applyTenantInfo(synapseOutMsgCtx);
    }
    Object o = response.getProperty(SynapseConstants.SENDING_FAULT);
    if (o != null && Boolean.TRUE.equals(o)) {

      StatisticsReporter.reportFaultForAll(
          synapseOutMsgCtx, ErrorLogFactory.createErrorLog(response));
      // there is a sending fault. propagate the fault to fault handlers.

      Stack faultStack = synapseOutMsgCtx.getFaultStack();
      if (faultStack != null && !faultStack.isEmpty()) {

        // if we have access to the full synapseOutMsgCtx.getEnvelope(), then let
        // it flow with the error details. Else, replace its envelope with the
        // fault envelope
        try {
          synapseOutMsgCtx.getEnvelope().build();
        } catch (OMException x) {
          synapseOutMsgCtx.setEnvelope(response.getEnvelope());
        }

        Exception e = (Exception) response.getProperty(SynapseConstants.ERROR_EXCEPTION);

        synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
        synapseOutMsgCtx.setProperty(
            SynapseConstants.ERROR_CODE, response.getProperty(SynapseConstants.ERROR_CODE));
        synapseOutMsgCtx.setProperty(
            SynapseConstants.ERROR_MESSAGE, response.getProperty(SynapseConstants.ERROR_MESSAGE));
        synapseOutMsgCtx.setProperty(
            SynapseConstants.ERROR_DETAIL, response.getProperty(SynapseConstants.ERROR_DETAIL));
        synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, e);

        if (log.isDebugEnabled()) {
          log.debug(
              "[Failed Request Message ID : "
                  + messageID
                  + "]"
                  + " [New to be Retried Request Message ID : "
                  + synapseOutMsgCtx.getMessageID()
                  + "]");
        }

        int errorCode = (Integer) response.getProperty(SynapseConstants.ERROR_CODE);

        // If a timeout has occured and the timeout action of the callback is to discard the message
        if (errorCode == SynapseConstants.NHTTP_CONNECTION_TIMEOUT
            && callback.getTimeOutAction() == SynapseConstants.DISCARD) {
          // Do not execute any fault sequences. Discard message
          if (log.isWarnEnabled()) {
            log.warn(
                "Synapse timed out for the request with Message ID : "
                    + messageID
                    + ". Ignoring fault handlers since the timeout action is DISCARD");
          }
          faultStack.removeAllElements();
        } else {
          ((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx, null);
        }
      }

    } else {

      // there can always be only one instance of an Endpoint in the faultStack of a message
      // if the send was successful, so remove it before we proceed any further
      Stack faultStack = synapseOutMsgCtx.getFaultStack();

      Endpoint successfulEndpoint = null;
      if (faultStack != null && !faultStack.isEmpty() && faultStack.peek() instanceof Endpoint) {
        successfulEndpoint = (Endpoint) faultStack.pop();
      }

      if (log.isDebugEnabled()) {
        log.debug("Synapse received an asynchronous response message");
        log.debug(
            "Received To: " + (response.getTo() != null ? response.getTo().getAddress() : "null"));
        log.debug(
            "SOAPAction: "
                + (response.getSoapAction() != null ? response.getSoapAction() : "null"));
        log.debug(
            "WSA-Action: " + (response.getWSAAction() != null ? response.getWSAAction() : "null"));
        String[] cids = response.getAttachmentMap().getAllContentIDs();
        if (cids != null && cids.length > 0) {
          for (String cid : cids) {
            log.debug("Attachment : " + cid);
          }
        }
        log.debug("Body : \n" + response.getEnvelope());
      }
      MessageContext axisOutMsgCtx =
          ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();

      // Processes 'Accept-Encoding'
      ResponseAcceptEncodingProcessor.process(response, axisOutMsgCtx);

      response.setServiceContext(null);
      response.setOperationContext(axisOutMsgCtx.getOperationContext());
      response.setAxisMessage(
          axisOutMsgCtx.getAxisOperation().getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE));

      // set properties on response
      response.setServerSide(true);
      response.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
      response.setProperty(
          MessageContext.TRANSPORT_OUT, axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
      response.setProperty(
          org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
          axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
      response.setTransportIn(axisOutMsgCtx.getTransportIn());
      response.setTransportOut(axisOutMsgCtx.getTransportOut());

      // If request is REST assume that the response is REST too
      response.setDoingREST(axisOutMsgCtx.isDoingREST());
      if (axisOutMsgCtx.isDoingMTOM()) {
        response.setDoingMTOM(true);
        response.setProperty(
            org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
            org.apache.axis2.Constants.VALUE_TRUE);
      }
      if (axisOutMsgCtx.isDoingSwA()) {
        response.setDoingSwA(true);
        response.setProperty(
            org.apache.axis2.Constants.Configuration.ENABLE_SWA,
            org.apache.axis2.Constants.VALUE_TRUE);
      }

      // when axis2 receives a soap message without addressing headers it users
      // DISABLE_ADDRESSING_FOR_OUT_MESSAGES property to keep it and hence avoid addressing
      // headers on the response. this causes a problem for synapse if the original message
      // it receivs (from client) has addressing and the synaspse service invocation has not
      // engage addressing. in this case when synapse receives the response from the server
      // addessing In handler dissable addressing since that response does not have addressing
      // headers. synapse sends the response to its orignal client using the same message
      // context. Then this response does not have addressing headers since it already
      // disable. to avoid this we need to set the DISABLE_ADDRESSING_FOR_OUT_MESSAGES
      // property state to original state.
      if (axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES)
          != null) {

        response.setProperty(
            AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES,
            axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES));
      } else {
        response.removeProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
      }

      Object messageType =
          axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
      if (!HTTPConstants.MEDIA_TYPE_X_WWW_FORM.equals(messageType)) {
        // copy the message type property that's used by the out message to the
        // response message
        response.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, messageType);
      }

      // compare original received message (axisOutMsgCtx) soap version with the response
      // if they are different change to original version
      if (axisOutMsgCtx.isSOAP11() != response.isSOAP11()) {
        if (axisOutMsgCtx.isSOAP11()) {
          SOAPUtils.convertSOAP12toSOAP11(response);
        } else {
          SOAPUtils.convertSOAP11toSOAP12(response);
        }
      }

      if (axisOutMsgCtx.getMessageID() != null) {
        response.setRelationships(new RelatesTo[] {new RelatesTo(axisOutMsgCtx.getMessageID())});
      }

      response.setReplyTo(axisOutMsgCtx.getReplyTo());
      response.setFaultTo(axisOutMsgCtx.getFaultTo());

      if (axisOutMsgCtx.isPropertyTrue(NhttpConstants.IGNORE_SC_ACCEPTED)) {
        response.setProperty(NhttpConstants.FORCE_SC_ACCEPTED, Constants.VALUE_TRUE);
      }

      // create the synapse message context for the response
      Axis2MessageContext synapseInMessageContext =
          new Axis2MessageContext(
              response, synapseOutMsgCtx.getConfiguration(), synapseOutMsgCtx.getEnvironment());
      synapseInMessageContext.setResponse(true);

      Object obj = synapseOutMsgCtx.getProperty(SynapseConstants.FORCE_ERROR_PROPERTY);
      String errorOnSOAPFault = (String) obj;

      if (Constants.VALUE_TRUE.equals(errorOnSOAPFault) && successfulEndpoint != null) {

        if (log.isDebugEnabled()) {
          log.debug("FORCE_ERROR_ON_SOAP_FAULT is true, checking for SOAPFault");
        }

        try {
          RelayUtils.buildMessage(
              ((Axis2MessageContext) synapseInMessageContext).getAxis2MessageContext(), true);
        } catch (Exception e) {
          // handleException("Error while building message", e, synapseInMessageContext);
        }

        if ((synapseInMessageContext.getEnvelope() != null)
            && synapseInMessageContext.getEnvelope().hasFault()) {

          if (log.isDebugEnabled()) {
            log.debug(
                "SOAPFault found in response message, forcing endpoint "
                    + successfulEndpoint.getName()
                    + " to fail");
          }

          // setup new pipe configuration..if failure happens (this will be setup as the source
          // writer and during the TargetContext
          // clean up operation the writer will be reset and pull to the buffer
          MessageContext axis2OUTMC =
              ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
          NHttpServerConnection conn =
              (NHttpServerConnection) axis2OUTMC.getProperty("pass-through.Source-Connection");
          if (conn != null) {
            SourceConfiguration sourceConfiguration =
                (SourceConfiguration) axis2OUTMC.getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
            Pipe pipe =
                new Pipe(
                    conn,
                    sourceConfiguration.getBufferFactory().getBuffer(),
                    "source",
                    sourceConfiguration);
            axis2OUTMC.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
          }

          StatisticsReporter.reportFaultForAll(
              synapseOutMsgCtx, ErrorLogFactory.createErrorLog(response));
          synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
          synapseOutMsgCtx.setProperty(
              SynapseConstants.ERROR_CODE, SynapseConstants.ENDPOINT_CUSTOM_ERROR);
          ((FaultHandler) successfulEndpoint).handleFault(synapseOutMsgCtx, null);
          return;
        } else {
          successfulEndpoint.onSuccess();
        }

      } else if (successfulEndpoint != null) {
        successfulEndpoint.onSuccess();
      }

      synapseInMessageContext.setTo(
          new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));
      synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState());

      // set the properties of the original MC to the new MC

      for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
        synapseInMessageContext.setProperty(
            (String) key, synapseOutMsgCtx.getProperty((String) key));
      }

      // Copy SequenceCallStack from original MC to the new MC
      if (synapseOutMsgCtx.isContinuationEnabled()) {

        // Set the message direction
        if (!synapseOutMsgCtx.isResponse()) {
          synapseInMessageContext.setResponse(false);
        }

        Stack<ContinuationState> seqContinuationStates =
            synapseOutMsgCtx.getContinuationStateStack();
        for (int i = 0; i < seqContinuationStates.size(); i++) {
          synapseInMessageContext.pushContinuationState(seqContinuationStates.get(i));
        }
      }

      // If this response is related to session affinity endpoints -Server initiated session
      Dispatcher dispatcher =
          (Dispatcher)
              synapseOutMsgCtx.getProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER);
      if (dispatcher != null && dispatcher.isServerInitiatedSession()) {
        dispatcher.updateSession(synapseInMessageContext);
      }

      StatisticsReporter.reportForAllOnResponseReceived(synapseInMessageContext);

      // send the response message through the synapse mediation flow
      try {
        synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext);
      } catch (SynapseException syne) {
        Stack stack = synapseInMessageContext.getFaultStack();
        if (stack != null && !stack.isEmpty()) {
          ((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne);
        } else {
          log.error(
              "Synapse encountered an exception, "
                  + "No error handlers found - [Message Dropped]\n"
                  + syne.getMessage());
        }
      }
    }
  }
  public void receive(org.apache.axis2.context.MessageContext mc) throws AxisFault {

    boolean traceOn = proxy.getAspectConfiguration().isTracingEnabled();
    boolean traceOrDebugOn = traceOn || log.isDebugEnabled();

    CustomLogSetter.getInstance().setLogAppender(proxy.getArtifactContainerName());

    String remoteAddr =
        (String) mc.getProperty(org.apache.axis2.context.MessageContext.REMOTE_ADDR);

    if (traceOrDebugOn) {
      traceOrDebug(
          traceOn,
          "Proxy Service "
              + name
              + " received a new message"
              + (remoteAddr != null ? " from : " + remoteAddr : "..."));
      traceOrDebug(
          traceOn, ("Message To: " + (mc.getTo() != null ? mc.getTo().getAddress() : "null")));
      traceOrDebug(
          traceOn, ("SOAPAction: " + (mc.getSoapAction() != null ? mc.getSoapAction() : "null")));
      traceOrDebug(
          traceOn, ("WSA-Action: " + (mc.getWSAAction() != null ? mc.getWSAAction() : "null")));

      if (traceOn && trace.isTraceEnabled()) {
        String[] cids = mc.getAttachmentMap().getAllContentIDs();
        if (cids != null && cids.length > 0) {
          for (String cid : cids) {
            trace.trace("With attachment content ID : " + cid);
          }
        }
        trace.trace("Envelope : " + mc.getEnvelope());
      }
    }

    MessageContext synCtx = MessageContextCreatorForAxis2.getSynapseMessageContext(mc);
    Integer statisticReportingIndex = null;
    // Statistic reporting
    boolean isStatisticsEnabled = RuntimeStatisticCollector.isStatisticsEnabled();
    if (isStatisticsEnabled) {
      statisticReportingIndex =
          OpenEventCollector.reportEntryEvent(
              synCtx, this.name, proxy.getAspectConfiguration(), ComponentType.PROXYSERVICE);
    }

    Object inboundServiceParam =
        proxy.getParameterMap().get(SynapseConstants.INBOUND_PROXY_SERVICE_PARAM);
    Object inboundMsgCtxParam = mc.getProperty(SynapseConstants.IS_INBOUND);

    // check whether the message is from Inbound EP
    if (inboundMsgCtxParam == null || !(boolean) inboundMsgCtxParam) {
      // check whether service parameter is set to true or null, then block this request
      if (inboundServiceParam != null && (Boolean.valueOf((String) inboundServiceParam))) {
        /*
        return because same proxy is exposed via InboundEP and service parameter(inbound.only) is set to
        true, which disable normal http transport proxy
        */
        if (!synCtx.getFaultStack().isEmpty()) {
          if (log.isDebugEnabled()) {
            log.debug(
                "Executing fault handler - message discarded due to the proxy is allowed only via InboundEP");
          }
          (synCtx.getFaultStack().pop())
              .handleFault(
                  synCtx,
                  new Exception(
                      "Proxy Service "
                          + name
                          + " message discarded due to the proxy is allowed only via InboundEP"));
        } else {
          if (log.isDebugEnabled()) {
            log.debug(
                "Proxy Service "
                    + name
                    + " message discarded due to the proxy is "
                    + "allowed only via InboundEP");
          }
        }
        return;
      }
    }

    TenantInfoConfigurator configurator = synCtx.getEnvironment().getTenantInfoConfigurator();
    if (configurator != null) {
      configurator.extractTenantInfo(synCtx);
    }
    TransportInDescription trpInDesc = mc.getTransportIn();
    if (trpInDesc != null) {
      synCtx.setProperty(SynapseConstants.TRANSPORT_IN_NAME, trpInDesc.getName());
    }

    // get service log for this message and attach to the message context also set proxy name
    Log serviceLog = LogFactory.getLog(SynapseConstants.SERVICE_LOGGER_PREFIX + name);
    ((Axis2MessageContext) synCtx).setServiceLog(serviceLog);

    synCtx.setProperty(SynapseConstants.PROXY_SERVICE, name);
    //        synCtx.setTracingState(proxy.getTraceState());

    synCtx.setProperty(SynapseConstants.IS_CLIENT_DOING_REST, mc.isDoingREST());
    synCtx.setProperty(SynapseConstants.IS_CLIENT_DOING_SOAP11, mc.isSOAP11());

    try {
      if (synCtx.getEnvironment().isDebuggerEnabled()) {
        SynapseDebugManager debugManager = synCtx.getEnvironment().getSynapseDebugManager();
        debugManager.acquireMediationFlowLock();
        debugManager.advertiseMediationFlowStartPoint(synCtx);
        if (!synCtx.isResponse()) {
          SynapseWireLogHolder wireLogHolder =
              (SynapseWireLogHolder)
                  ((Axis2MessageContext) synCtx)
                      .getAxis2MessageContext()
                      .getProperty(SynapseDebugInfoHolder.SYNAPSE_WIRE_LOG_HOLDER_PROPERTY);
          if (wireLogHolder == null) {
            wireLogHolder = new SynapseWireLogHolder();
          }
          if (synCtx.getProperty(SynapseConstants.PROXY_SERVICE) != null
              && !synCtx.getProperty(SynapseConstants.PROXY_SERVICE).toString().isEmpty()) {
            wireLogHolder.setProxyName(
                synCtx.getProperty(SynapseConstants.PROXY_SERVICE).toString());
          }
          ((Axis2MessageContext) synCtx)
              .getAxis2MessageContext()
              .setProperty(SynapseDebugInfoHolder.SYNAPSE_WIRE_LOG_HOLDER_PROPERTY, wireLogHolder);
        }
      }
      synCtx.setProperty(SynapseConstants.RESPONSE_STATE, new ResponseState());
      List handlers = synCtx.getEnvironment().getSynapseHandlers();
      Iterator<SynapseHandler> iterator = handlers.iterator();
      while (iterator.hasNext()) {
        SynapseHandler handler = iterator.next();
        if (!handler.handleRequestInFlow(synCtx)) {
          return;
        }
      }

      Mediator mandatorySeq = synCtx.getConfiguration().getMandatorySequence();
      if (mandatorySeq != null) {
        if (log.isDebugEnabled()) {
          log.debug(
              "Start mediating the message in the "
                  + "pre-mediate state using the mandatory sequence");
        }

        if (!mandatorySeq.mediate(synCtx)) {
          if (log.isDebugEnabled()) {
            log.debug(
                "Request message for the proxy service "
                    + name
                    + " dropped in "
                    + "the pre-mediation state by the mandatory sequence : \n"
                    + synCtx);
          }
          return;
        }
      }

      // setup fault sequence - i.e. what happens when something goes wrong with this message
      proxy.registerFaultHandler(synCtx);

      boolean inSequenceResult = true;

      // Using inSequence for the incoming message mediation
      if (proxy.getTargetInSequence() != null) {

        Mediator inSequence = synCtx.getSequence(proxy.getTargetInSequence());
        if (inSequence != null) {
          traceOrDebug(
              traceOn,
              "Using sequence named : "
                  + proxy.getTargetInSequence()
                  + " for incoming message mediation");
          inSequenceResult = inSequence.mediate(synCtx);

        } else {
          handleException("Unable to find in-sequence : " + proxy.getTargetInSequence(), synCtx);
        }

      } else if (proxy.getTargetInLineInSequence() != null) {
        traceOrDebug(
            traceOn, "Using the anonymous " + "in-sequence of the proxy service for mediation");
        inSequenceResult = proxy.getTargetInLineInSequence().mediate(synCtx);
      }

      // if inSequence returns true, forward message to endpoint
      if (inSequenceResult) {
        if (proxy.getTargetEndpoint() != null) {
          Endpoint endpoint = synCtx.getEndpoint(proxy.getTargetEndpoint());

          if (endpoint != null) {
            traceOrDebug(
                traceOn, "Forwarding message to the endpoint : " + proxy.getTargetEndpoint());
            endpoint.send(synCtx);

          } else {
            handleException(
                "Unable to find the endpoint specified : " + proxy.getTargetEndpoint(), synCtx);
          }

        } else if (proxy.getTargetInLineEndpoint() != null) {
          traceOrDebug(
              traceOn,
              "Forwarding the message to the anonymous " + "endpoint of the proxy service");
          proxy.getTargetInLineEndpoint().send(synCtx);
        }
      }

    } catch (SynapseException syne) {

      if (!synCtx.getFaultStack().isEmpty()) {
        warn(traceOn, "Executing fault handler due to exception encountered", synCtx);
        ((FaultHandler) synCtx.getFaultStack().pop()).handleFault(synCtx, syne);

      } else {
        warn(
            traceOn,
            "Exception encountered but no fault handler found - " + "message dropped",
            synCtx);
      }
    } finally {
      // Statistic reporting
      if (isStatisticsEnabled) {
        CloseEventCollector.tryEndFlow(
            synCtx, this.name, ComponentType.PROXYSERVICE, statisticReportingIndex, true);
      }
      if (synCtx.getEnvironment().isDebuggerEnabled()) {
        SynapseDebugManager debugManager = synCtx.getEnvironment().getSynapseDebugManager();
        debugManager.advertiseMediationFlowTerminatePoint(synCtx);
        debugManager.releaseMediationFlowLock();
      }
    }
  }
  @Override
  public String updateSynapseArtifact(
      OMElement artifactConfig,
      String fileName,
      String existingArtifactName,
      Properties properties) {

    Endpoint ep = EndpointFactory.getEndpointFromElement(artifactConfig, false, properties);

    CustomLogSetter.getInstance().setLogAppender((ep != null) ? ep.getArtifactContainerName() : "");

    if (log.isDebugEnabled()) {
      log.debug("Endpoint update from file : " + fileName + " has started");
    }

    try {
      if (ep == null) {
        handleSynapseArtifactDeploymentError(
            "Endpoint update failed. The artifact "
                + "defined in the file: "
                + fileName
                + " is not a valid endpoint.");
        return null;
      }
      ep.setFileName(new File(fileName).getName());

      if (log.isDebugEnabled()) {
        log.debug("Endpoint: " + ep.getName() + " has been built from the file: " + fileName);
      }

      ep.init(getSynapseEnvironment());
      Endpoint existingEp =
          getSynapseConfiguration().getDefinedEndpoints().get(existingArtifactName);
      if (existingArtifactName.equals(ep.getName())) {
        getSynapseConfiguration().updateEndpoint(existingArtifactName, ep);
      } else {
        // The user has changed the name of the endpoint
        // We should add the updated endpoint as a new endpoint and remove the old one
        getSynapseConfiguration().addEndpoint(ep.getName(), ep);
        getSynapseConfiguration().removeEndpoint(existingArtifactName);
        log.info("Endpoint: " + existingArtifactName + " has been undeployed");
      }

      log.info("Endpoint: " + ep.getName() + " has been updated from the file: " + fileName);

      waitForCompletion();
      existingEp.destroy();
      if (existingArtifactName.equals(ep.getName())) {
        // If the endpoint name was same as the old one, above method call (destroy)
        // will unregister the endpoint MBean - So we should register it again.
        MBeanRegistrar.getInstance().registerMBean(ep.getMetricsMBean(), "Endpoint", ep.getName());
      }
      return ep.getName();

    } catch (DeploymentException e) {
      handleSynapseArtifactDeploymentError(
          "Error while updating the endpoint from the " + "file: " + fileName);
    }

    return null;
  }
Example #14
0
 public void destroy() {
   if (endpoint != null) {
     endpoint.destroy();
   }
 }
Example #15
0
  /**
   * Send request in non-blocking manner
   *
   * @param synInCtx message context
   * @return continue the mediation flow or not
   */
  private boolean handleNonBlockingCall(MessageContext synInCtx) {
    SynapseLog synLog = getLog(synInCtx);

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("Start : Call mediator - Non Blocking Call");
      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Message : " + synInCtx.getEnvelope());
      }
    }

    // clear the message context properties related to endpoint in last service invocation
    Set keySet = synInCtx.getPropertyKeySet();
    if (keySet != null) {
      keySet.remove(SynapseConstants.RECEIVING_SEQUENCE);
      keySet.remove(EndpointDefinition.DYNAMIC_URL_VALUE);
    }

    boolean outOnlyMessage = "true".equals(synInCtx.getProperty(SynapseConstants.OUT_ONLY));

    // Prepare the outgoing message context
    MessageContext synOutCtx = null;
    if (outOnlyMessage) {
      try {
        synOutCtx = MessageHelper.cloneMessageContext(synInCtx);
      } catch (AxisFault axisFault) {
        handleException("Error occurred while cloning msg context", axisFault, synInCtx);
      }
    } else {
      synOutCtx = synInCtx;
    }

    synOutCtx.setProperty(SynapseConstants.CONTINUATION_CALL, true);
    ContinuationStackManager.updateSeqContinuationState(synOutCtx, getMediatorPosition());

    // If no endpoints are defined, send where implicitly stated
    if (endpoint == null) {

      if (synLog.isTraceOrDebugEnabled()) {
        StringBuffer sb = new StringBuffer();
        sb.append("Calling ")
            .append(synOutCtx.isResponse() ? "response" : "request")
            .append(" message using implicit message properties..");
        sb.append("\nCalling To: ")
            .append(synOutCtx.getTo() != null ? synOutCtx.getTo().getAddress() : "null");
        sb.append("\nSOAPAction: ")
            .append(synOutCtx.getWSAAction() != null ? synOutCtx.getWSAAction() : "null");
        synLog.traceOrDebug(sb.toString());
      }

      if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Envelope : " + synOutCtx.getEnvelope());
      }
      synOutCtx.getEnvironment().send(null, synOutCtx);

    } else {
      endpoint.send(synOutCtx);
    }

    if (synLog.isTraceOrDebugEnabled()) {
      synLog.traceOrDebug("End : Call mediator - Non Blocking Call");
    }

    if (outOnlyMessage) {
      // For out only invocations request flow should continue
      // otherwise flow should stop from here
      return true;
    }
    return false;
  }
  public boolean dispatch(MessageContext messageContext) {

    if (log.isDebugEnabled()) {
      log.debug(
          "Sending the message to client with message processor ["
              + messageProcessor.getName()
              + "]");
    }

    // The below code is just for keeping the backward compatibility with the old code.
    if (targetEndpoint == null) {
      targetEndpoint =
          (String) messageContext.getProperty(ForwardingProcessorConstants.TARGET_ENDPOINT);
    }

    MessageContext outCtx = null;
    SOAPEnvelope originalEnvelop = messageContext.getEnvelope();

    if (targetEndpoint != null) {
      Endpoint ep = messageContext.getEndpoint(targetEndpoint);

      try {

        // Send message to the client
        while (!isSuccessful && !isTerminated) {
          try {
            // For each retry we need to have a fresh copy of the actual message. otherwise retry
            // may not
            // work as expected.
            messageContext.setEnvelope(MessageHelper.cloneSOAPEnvelope(originalEnvelop));
            OMElement firstChild = null; //
            org.apache.axis2.context.MessageContext origAxis2Ctx =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();
            if (JsonUtil.hasAJsonPayload(origAxis2Ctx)) {
              firstChild = origAxis2Ctx.getEnvelope().getBody().getFirstElement();
            } // Had to do this because MessageHelper#cloneSOAPEnvelope does not clone
            // OMSourcedElemImpl correctly.
            if (JsonUtil.hasAJsonPayload(firstChild)) { //
              OMElement clonedFirstElement =
                  messageContext.getEnvelope().getBody().getFirstElement();
              if (clonedFirstElement != null) {
                clonedFirstElement.detach();
                messageContext.getEnvelope().getBody().addChild(firstChild);
              }
            } // Had to do this because MessageHelper#cloneSOAPEnvelope does not clone
            // OMSourcedElemImpl correctly.
            origAxis2Ctx.setProperty(
                HTTPConstants.NON_ERROR_HTTP_STATUS_CODES, getNonRetryStatusCodes());
            outCtx = sender.send(ep, messageContext);
            isSuccessful = true;

          } catch (Exception e) {

            // this means send has failed due to some reason so we have to retry it
            if (e instanceof SynapseException) {
              isSuccessful = isNonRetryErrorCode(e.getCause().getMessage());
            }
            if (!isSuccessful) {
              log.error(
                  "BlockingMessageSender of message processor ["
                      + this.messageProcessor.getName()
                      + "] failed to send message to the endpoint");
            }
          }

          if (isSuccessful) {
            if (outCtx != null) {
              if ("true"
                  .equals(outCtx.getProperty(ForwardingProcessorConstants.BLOCKING_SENDER_ERROR))) {

                // this means send has failed due to some reason so we have to retry it
                isSuccessful =
                    isNonRetryErrorCode(
                        (String) outCtx.getProperty(SynapseConstants.ERROR_MESSAGE));

                if (isSuccessful) {
                  sendThroughReplySeq(outCtx);
                } else {
                  // This means some error has occurred so must try to send down the fault sequence.
                  log.error(
                      "BlockingMessageSender of message processor ["
                          + this.messageProcessor.getName()
                          + "] failed to send message to the endpoint");
                  sendThroughFaultSeq(outCtx);
                }
              } else {
                // Send the message down the reply sequence if there is one
                sendThroughReplySeq(outCtx);
                messageConsumer.ack();
                attemptCount = 0;
                isSuccessful = true;

                if (log.isDebugEnabled()) {
                  log.debug(
                      "Successfully sent the message to endpoint ["
                          + ep.getName()
                          + "]"
                          + " with message processor ["
                          + messageProcessor.getName()
                          + "]");
                }
              }
            } else {
              // This Means we have invoked an out only operation
              // remove the message and reset the count
              messageConsumer.ack();
              attemptCount = 0;
              isSuccessful = true;

              if (log.isDebugEnabled()) {
                log.debug(
                    "Successfully sent the message to endpoint ["
                        + ep.getName()
                        + "]"
                        + " with message processor ["
                        + messageProcessor.getName()
                        + "]");
              }
            }
          }

          if (!isSuccessful) {
            // Then we have to retry sending the message to the client.
            prepareToRetry();
          } else {
            if (messageProcessor.isPaused()) {
              this.messageProcessor.resumeService();
              log.info(
                  "Resuming the service of message processor [" + messageProcessor.getName() + "]");
            }
          }
        }
      } catch (Exception e) {
        log.error(
            "Message processor ["
                + messageProcessor.getName()
                + "] failed to send the message to"
                + " client",
            e);
      }
    } else {
      // No Target Endpoint defined for the Message
      // So we do not have a place to deliver.
      // Here we log a warning and remove the message
      // todo: we can improve this by implementing a target inferring mechanism

      log.warn(
          "Property "
              + ForwardingProcessorConstants.TARGET_ENDPOINT
              + " not found in the message context , Hence removing the message ");

      messageConsumer.ack();
    }

    return true;
  }
Example #17
0
 public void init(SynapseEnvironment synapseEnvironment) {
   if (endpoint != null) {
     endpoint.init(synapseEnvironment);
   }
   initialized = true;
 }
Example #18
0
 public void destroy() {
   if (endpoint != null) {
     endpoint.destroy();
   }
   synapseEnv.updateCallMediatorCount(false);
 }