Search in sources :

Example 1 with NHttpServerConnection

use of org.apache.http.nio.NHttpServerConnection in project wso2-synapse by wso2.

the class MessageHelper method cloneAxis2MessageContext.

/**
 * This method will simulate cloning the message context and creating an exact copy of the
 * passed message. One should use this method with care; that is because, inside the new MC,
 * most of the attributes of the MC like opCtx and so on are still kept as references. Otherwise
 * there will be perf issues. But ..... this may reveal in some conflicts in the cloned message
 * if you try to do advanced mediations with the cloned message, in which case you should
 * manually get a clone of the changing part of the MC and set that cloned part to your MC.
 * Changing the MC after doing that will solve most of the issues. (Note: You don't have to worry
 * about the SOAPEnvelope, it is a cloned copy and not a reference from any other MC)
 *
 * @param mc - this will be cloned for getting an exact copy
 * @param cloneSoapEnvelope The flag to say whether to clone the SOAP envelope or not.
 * @return cloned MessageContext from the given mc
 * @throws AxisFault if there is a failure in copying the certain attributes of the
 *          provided message context
 */
public static org.apache.axis2.context.MessageContext cloneAxis2MessageContext(org.apache.axis2.context.MessageContext mc, boolean cloneSoapEnvelope) throws AxisFault {
    // empty buffer in PASS_THROUGH_PIPE without the message payload.
    try {
        RelayUtils.buildMessage(mc, false);
    } catch (IOException e) {
        handleException(e);
    } catch (XMLStreamException e) {
        handleException(e);
    }
    org.apache.axis2.context.MessageContext newMC = clonePartially(mc);
    if (cloneSoapEnvelope) {
        newMC.setEnvelope(cloneSOAPEnvelope(mc.getEnvelope()));
    }
    // XXX: always this section must come after the above step. ie. after applying Envelope.
    // That is to get the existing headers into the new envelope.
    JsonUtil.cloneJsonPayload(mc, newMC);
    newMC.setOptions(cloneOptions(mc.getOptions()));
    newMC.setServiceContext(mc.getServiceContext());
    newMC.setOperationContext(mc.getOperationContext());
    newMC.setAxisMessage(mc.getAxisMessage());
    if (newMC.getAxisMessage() != null) {
        newMC.getAxisMessage().setParent(mc.getAxisOperation());
    }
    newMC.setAxisService(mc.getAxisService());
    // copying transport related parts from the original
    newMC.setTransportIn(mc.getTransportIn());
    newMC.setTransportOut(mc.getTransportOut());
    newMC.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO, mc.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
    newMC.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, getClonedTransportHeaders(mc));
    if (newMC.getProperty(PassThroughConstants.PASS_THROUGH_PIPE) != null) {
        // clone passthrough pipe here..writer...
        // newMC.setProperty(PassThroughConstants.CLONE_PASS_THROUGH_PIPE_REQUEST,true);
        NHttpServerConnection conn = (NHttpServerConnection) newMC.getProperty("pass-through.Source-Connection");
        if (conn != null) {
            SourceConfiguration sourceConfiguration = (SourceConfiguration) newMC.getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
            Pipe pipe = new Pipe(conn, sourceConfiguration.getBufferFactory().getBuffer(), "source", sourceConfiguration);
            newMC.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
        } else {
            newMC.removeProperty(PassThroughConstants.PASS_THROUGH_PIPE);
        }
    }
    return newMC;
}
Also used : NHttpServerConnection(org.apache.http.nio.NHttpServerConnection) XMLStreamException(javax.xml.stream.XMLStreamException) SourceConfiguration(org.apache.synapse.transport.passthru.config.SourceConfiguration) IOException(java.io.IOException) Pipe(org.apache.synapse.transport.passthru.Pipe)

Example 2 with NHttpServerConnection

use of org.apache.http.nio.NHttpServerConnection in project wso2-synapse by wso2.

the class SynapseCallbackReceiver method handleMessage.

/**
 * 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);
    }
    Boolean isConcurrencyThrottleEnabled = (Boolean) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE);
    if (isConcurrencyThrottleEnabled != null && isConcurrencyThrottleEnabled) {
        ConcurrentAccessController concurrentAccessController = (ConcurrentAccessController) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_CONTROLLER);
        int available = concurrentAccessController.incrementAndGet();
        int concurrentLimit = concurrentAccessController.getLimit();
        if (log.isDebugEnabled()) {
            log.debug("Concurrency Throttle : Connection returned" + " :: " + available + " of available of " + concurrentLimit + " connections");
        }
        ConcurrentAccessReplicator concurrentAccessReplicator = (ConcurrentAccessReplicator) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_REPLICATOR);
        String throttleKey = (String) synapseOutMsgCtx.getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE_KEY);
        if (concurrentAccessReplicator != null) {
            concurrentAccessReplicator.replicate(throttleKey, true);
        }
    }
    // get the original message context that went through the OAuth Configured HTTP endpoint
    // this is used to retry the call when there is any oauth related issue
    org.apache.synapse.MessageContext originalMC = MessageCache.getInstance().removeMessageContext(synapseOutMsgCtx.getMessageID());
    Object o = response.getProperty(SynapseConstants.SENDING_FAULT);
    if (o != null && Boolean.TRUE.equals(o)) {
        // This path hits with a fault. Sequence mediator threads should not remove faultSequence.
        // SynapseCallbackReceiver thread should handle the faultStack.
        // We have to clone the message context to avoid Intermittently ConcurrentModificationException when request
        // burst on passthrough transport
        Axis2MessageContext axis2MC = (Axis2MessageContext) synapseOutMsgCtx;
        axis2MC.setAxis2MessageContext(MessageHelper.cloneAxis2MessageContext(((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext(), true, true, false));
        Pipe pipe = (Pipe) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
        SourceConfiguration sourceConfiguration = (SourceConfiguration) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
        if (pipe != null && pipe.isSerializationComplete() && sourceConfiguration != null) {
            NHttpServerConnection conn = (NHttpServerConnection) ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().getProperty("pass-through.Source-Connection");
            Pipe newPipe = new Pipe(conn, sourceConfiguration.getBufferFactory().getBuffer(), "source", sourceConfiguration);
            newPipe.setDiscardable(true);
            ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().setProperty(PassThroughConstants.PASS_THROUGH_PIPE, newPipe);
        }
        // there is a sending fault. propagate the fault to fault handlers.
        Stack faultStack = synapseOutMsgCtx.getFaultStack();
        if (faultStack != null && !faultStack.isEmpty()) {
            // fault envelope
            try {
                synapseOutMsgCtx.getEnvelope().build();
            } catch (Exception 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);
            /* Clear the NO_KEEPALIVE property to prevent closing response connection when going through
                   the fault sequence due to sender error. Since the axis2 message context used here
                   is the same axis2 message context used in request path and the intention of this property
                   is to Disable HTTP keep alive for outgoing requests only. If it is required this can be put
                   in fault sequence.
               */
            ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext().removeProperty(PassThroughConstants.NO_KEEPALIVE);
            if (synapseOutMsgCtx.getEnvironment().isContinuationEnabled()) {
                synapseOutMsgCtx.setContinuationEnabled(true);
            }
            if (log.isDebugEnabled()) {
                log.debug("[Failed Request Message ID : " + messageID + "]" + " [New to be Retried Request Message ID : " + synapseOutMsgCtx.getMessageID() + "]");
            }
            Integer 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 != null && 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 = null;
            try {
                cids = response.getAttachmentMap().getAllContentIDs();
            } catch (Exception ex) {
                // partially read stream could lead to corrupted attachment map and hence this exception
                // corrupted attachment map leads to inconsistent runtime exceptions and behavior
                // discard the attachment map for the fault handler invocation
                // ensure the successful completion for fault handler flow
                response.setAttachmentMap(null);
                log.error("Synapse encountered an exception when reading attachments from bytes stream. " + "Hence Attachments map is dropped from the message context.", ex);
            }
            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(CorrelationConstants.CORRELATION_ID, axisOutMsgCtx.getProperty(CorrelationConstants.CORRELATION_ID));
        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());
        // response.setDoingREST(axisOutMsgCtx.isDoingREST()); This information already present, hence removing
        if (axisOutMsgCtx.isDoingMTOM() && (axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM) == null || Boolean.getBoolean((String) axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM)) == true)) {
            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);
        }
        // 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);
        }
        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);
        }
        // axis2 client options still contains properties such as policy files used in
        // outgoing request. Need to remove those.
        removeUnwantedClientOptions(response);
        // 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;
        boolean failOver = isChildOfFailOverEP(successfulEndpoint);
        if (Constants.VALUE_TRUE.equals(errorOnSOAPFault) && successfulEndpoint != null) {
            if (log.isDebugEnabled()) {
                log.debug("FORCE_ERROR_ON_SOAP_FAULT is true, checking for SOAPFault");
            }
            try {
                org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) synapseInMessageContext).getAxis2MessageContext();
                MessageHandlerProvider.getMessageHandler(axis2MsgCtx).buildMessage(axis2MsgCtx, true);
            } catch (Exception e) {
            // handleException("Error while building message", e, synapseInMessageContext);
            }
            if ((synapseInMessageContext.getEnvelope() != null) && synapseInMessageContext.getEnvelope().hasFault()) {
                invokeHandlers(synapseInMessageContext);
                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");
                SourceConfiguration sourceConfiguration = (SourceConfiguration) axis2OUTMC.getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
                if (conn != null && sourceConfiguration != null) {
                    Pipe pipe = new Pipe(conn, sourceConfiguration.getBufferFactory().getBuffer(), "source", sourceConfiguration);
                    axis2OUTMC.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
                }
                synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
                synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE, SynapseConstants.ENDPOINT_CUSTOM_ERROR);
                for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
                    synapseInMessageContext.setProperty((String) key, synapseOutMsgCtx.getProperty((String) key));
                }
                if (failOver) {
                    // we may required to handle same message for failover cases only other than that
                    // should treat based on the incoming message
                    ((FaultHandler) successfulEndpoint).handleFault(synapseOutMsgCtx, null);
                } else {
                    faultStack = synapseOutMsgCtx.getFaultStack();
                    if (faultStack != null) {
                        synapseInMessageContext.getFaultStack().addAll(faultStack);
                        ((FaultHandler) successfulEndpoint).handleFault(synapseInMessageContext, null);
                    }
                }
                return;
            } else {
                successfulEndpoint.onSuccess();
                if (failOver) {
                    popFailOverEPFromFaultStack(synapseOutMsgCtx);
                }
            }
        } else if (successfulEndpoint != null) {
            successfulEndpoint.onSuccess();
            if (failOver) {
                popFailOverEPFromFaultStack(synapseOutMsgCtx);
            }
        }
        synapseInMessageContext.setTo(new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));
        synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState());
        synapseInMessageContext.setMessageFlowTracingState(synapseOutMsgCtx.getMessageFlowTracingState());
        for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
            synapseInMessageContext.setProperty((String) key, synapseOutMsgCtx.getProperty((String) key));
        }
        if (successfulEndpoint instanceof OAuthConfiguredHTTPEndpoint) {
            OAuthConfiguredHTTPEndpoint httpEndpoint = (OAuthConfiguredHTTPEndpoint) successfulEndpoint;
            if (originalMC != null && OAuthUtils.retryOnOAuthFailure(httpEndpoint, synapseInMessageContext, synapseOutMsgCtx)) {
                httpEndpoint.retryCallWithNewToken(originalMC);
                return;
            }
        }
        // Copy SequenceCallStack from original MC to the new MC
        Boolean isContinuationCall = (Boolean) synapseOutMsgCtx.getProperty(SynapseConstants.CONTINUATION_CALL);
        if (isContinuationCall != null && isContinuationCall) {
            // 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));
            }
            faultStack = synapseOutMsgCtx.getFaultStack();
            if (faultStack != null) {
                synapseInMessageContext.getFaultStack().addAll(faultStack);
            }
        }
        // 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);
        }
        // send the response message through the synapse mediation flow
        try {
            synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext);
        } catch (Exception syne) {
            // introduced to handle runtime exceptions which are occurred inside Synapse handlers
            // partially read stream could lead to corrupted attachment map and hence this exception
            // corrupted attachment map leads to inconsistent runtime exceptions and behavior
            // discard the attachment map for the fault handler invocation
            // ensure the successful completion for fault handler flow
            // even we drop attachment map for both cases messages which have attachment /
            // messages which do not have attachments it would still not be any impact.
            // However setting attachment map to null for messages which do not have attachments is not required.
            // introduced due to the fact conflicts between Axiom exceptions for attachment/ non attachments cases
            // and performance impact that could cause of regular expression matching of exceptional stack traces.
            Axis2MessageContext axis2smc = (Axis2MessageContext) synapseInMessageContext;
            org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
            // Set correct status code
            axis2MessageCtx.setProperty(PassThroughConstants.HTTP_SC, HttpStatus.SC_INTERNAL_SERVER_ERROR);
            axis2MessageCtx.setAttachmentMap(null);
            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());
            }
        }
    }
}
Also used : OAuthConfiguredHTTPEndpoint(org.apache.synapse.endpoints.OAuthConfiguredHTTPEndpoint) Dispatcher(org.apache.synapse.endpoints.dispatch.Dispatcher) RelatesTo(org.apache.axis2.addressing.RelatesTo) NHttpServerConnection(org.apache.http.nio.NHttpServerConnection) OAuthConfiguredHTTPEndpoint(org.apache.synapse.endpoints.OAuthConfiguredHTTPEndpoint) Endpoint(org.apache.synapse.endpoints.Endpoint) AbstractEndpoint(org.apache.synapse.endpoints.AbstractEndpoint) FailoverEndpoint(org.apache.synapse.endpoints.FailoverEndpoint) ConcurrentAccessController(org.apache.synapse.commons.throttle.core.ConcurrentAccessController) MessageContext(org.apache.axis2.context.MessageContext) FaultHandler(org.apache.synapse.FaultHandler) MediatorFaultHandler(org.apache.synapse.mediators.MediatorFaultHandler) Pipe(org.apache.synapse.transport.passthru.Pipe) OAuthConfiguredHTTPEndpoint(org.apache.synapse.endpoints.OAuthConfiguredHTTPEndpoint) Endpoint(org.apache.synapse.endpoints.Endpoint) AbstractEndpoint(org.apache.synapse.endpoints.AbstractEndpoint) FailoverEndpoint(org.apache.synapse.endpoints.FailoverEndpoint) ConcurrentAccessReplicator(org.apache.synapse.commons.throttle.core.ConcurrentAccessReplicator) Stack(java.util.Stack) EndpointReference(org.apache.axis2.addressing.EndpointReference) ContinuationState(org.apache.synapse.ContinuationState) TenantInfoConfigurator(org.apache.synapse.carbonext.TenantInfoConfigurator) SourceConfiguration(org.apache.synapse.transport.passthru.config.SourceConfiguration) MessageContext(org.apache.axis2.context.MessageContext)

Example 3 with NHttpServerConnection

use of org.apache.http.nio.NHttpServerConnection in project wso2-synapse by wso2.

the class PassThroughHttpSenderTest method testSubmitResponse.

/**
 * This method tests the submitting of response when the source request is null
 * @throws Exception
 */
@Test
public void testSubmitResponse() throws Exception {
    MockitoAnnotations.initMocks(this);
    MessageContext messageContext = new MessageContext();
    messageContext.setProperty(Constants.Configuration.TRANSPORT_URL, "http://sample.url");
    messageContext.setProperty(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH, true);
    messageContext.setProperty(PassThroughConstants.COPY_CONTENT_LENGTH_FROM_INCOMING, true);
    messageContext.setProperty(PassThroughConstants.ORGINAL_CONTEN_LENGTH, "1000");
    messageContext.setOperationContext(new OperationContext());
    IOSession session = PowerMockito.mock(IOSession.class);
    NHttpServerConnection conn = new DefaultNHttpServerConnection(session, 12);
    messageContext.setProperty(PassThroughConstants.PASS_THROUGH_SOURCE_CONNECTION, conn);
    messageContext.setProperty(PassThroughConstants.HTTP_ETAG_ENABLED, true);
    Map headers = new HashMap();
    headers.put("randomKey", "randomValue");
    messageContext.setProperty(MessageContext.TRANSPORT_HEADERS, headers);
    sender = PowerMockito.spy(sender);
    PowerMockito.when(digestGenerator.getDigest(any(MessageContext.class))).thenReturn("testString");
    sender.submitResponse(messageContext);
}
Also used : OperationContext(org.apache.axis2.context.OperationContext) NHttpServerConnection(org.apache.http.nio.NHttpServerConnection) DefaultNHttpServerConnection(org.apache.http.impl.nio.DefaultNHttpServerConnection) HashMap(java.util.HashMap) IOSession(org.apache.http.nio.reactor.IOSession) MessageContext(org.apache.axis2.context.MessageContext) HashMap(java.util.HashMap) Map(java.util.Map) DefaultNHttpServerConnection(org.apache.http.impl.nio.DefaultNHttpServerConnection) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 4 with NHttpServerConnection

use of org.apache.http.nio.NHttpServerConnection in project wso2-synapse by wso2.

the class ServerWorker method sendAck.

public void sendAck(MessageContext msgContext) {
    String respWritten = "";
    if (msgContext.getOperationContext() != null) {
        respWritten = (String) msgContext.getOperationContext().getProperty(Constants.RESPONSE_WRITTEN);
    }
    if (msgContext.getProperty(PassThroughConstants.FORCE_SOAP_FAULT) != null) {
        respWritten = "SKIP";
    }
    boolean respWillFollow = !Constants.VALUE_TRUE.equals(respWritten) && !"SKIP".equals(respWritten);
    boolean ack = (((RequestResponseTransport) msgContext.getProperty(RequestResponseTransport.TRANSPORT_CONTROL)).getStatus() == RequestResponseTransport.RequestResponseTransportStatus.ACKED);
    boolean forced = msgContext.isPropertyTrue(NhttpConstants.FORCE_SC_ACCEPTED);
    boolean nioAck = msgContext.isPropertyTrue("NIO-ACK-Requested", false);
    if (respWillFollow || ack || forced || nioAck) {
        NHttpServerConnection conn = request.getConnection();
        SourceResponse sourceResponse;
        if (!nioAck) {
            msgContext.removeProperty(MessageContext.TRANSPORT_HEADERS);
            sourceResponse = SourceResponseFactory.create(msgContext, request, sourceConfiguration);
            sourceResponse.setStatus(HttpStatus.SC_ACCEPTED);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Sending ACK response with status " + msgContext.getProperty(NhttpConstants.HTTP_SC) + ", for MessageID : " + msgContext.getMessageID());
            }
            sourceResponse = SourceResponseFactory.create(msgContext, request, sourceConfiguration);
            sourceResponse.setStatus(Integer.parseInt(msgContext.getProperty(NhttpConstants.HTTP_SC).toString()));
        }
        SourceContext.setResponse(conn, sourceResponse);
        ProtocolState state = SourceContext.getState(conn);
        if (state != null && state.compareTo(ProtocolState.REQUEST_DONE) <= 0) {
            conn.requestOutput();
        } else {
            SourceContext.updateState(conn, ProtocolState.CLOSED);
            sourceConfiguration.getSourceConnections().shutDownConnection(conn);
        }
    }
}
Also used : NHttpServerConnection(org.apache.http.nio.NHttpServerConnection) HttpCoreRequestResponseTransport(org.apache.synapse.transport.nhttp.HttpCoreRequestResponseTransport) RequestResponseTransport(org.apache.axis2.transport.RequestResponseTransport)

Example 5 with NHttpServerConnection

use of org.apache.http.nio.NHttpServerConnection in project wso2-synapse by wso2.

the class ServerWorker method createMessageContext.

/**
 * Create an Axis2 message context for the given http request. The request may be in the
 * process of being streamed
 *
 * @param request the http request to be used to create the corresponding Axis2 message context
 * @return the Axis2 message context created
 */
public MessageContext createMessageContext(MessageContext msgContext, SourceRequest request) {
    Map excessHeaders = request.getExcessHeaders();
    ConfigurationContext cfgCtx = sourceConfiguration.getConfigurationContext();
    NHttpServerConnection conn = request.getConnection();
    Object systemGeneratedCorrelationLog = conn.getContext().getAttribute(CorrelationConstants.SYSTEM_GENERATED_CORRELATION_ID);
    Object correlationId = conn.getContext().getAttribute(CorrelationConstants.CORRELATION_ID);
    if (msgContext == null) {
        msgContext = new MessageContext();
    }
    String messageId = null;
    if (systemGeneratedCorrelationLog instanceof Boolean && (Boolean) systemGeneratedCorrelationLog) {
        if (correlationId instanceof String && StringUtils.isNotEmpty((String) correlationId)) {
            messageId = "urn:uuid:" + correlationId;
        }
    }
    if (StringUtils.isEmpty(messageId)) {
        messageId = UIDGenerator.generateURNString();
    }
    msgContext.setMessageID(messageId);
    // Axis2 spawns a new threads to send a message if this is TRUE - and it has to
    // be the other way
    msgContext.setProperty(MessageContext.CLIENT_API_NON_BLOCKING, Boolean.FALSE);
    msgContext.setConfigurationContext(cfgCtx);
    // msgContext.setTransportOut(cfgCtx.getAxisConfiguration()
    // .getTransportOut(Constants.TRANSPORT_HTTP));
    // msgContext.setTransportIn(cfgCtx.getAxisConfiguration()
    // .getTransportIn(Constants.TRANSPORT_HTTP));
    // msgContext.setIncomingTransportName(Constants.TRANSPORT_HTTP);
    // msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, this);
    // propagate correlation logging related properties
    msgContext.setProperty(CorrelationConstants.CORRELATION_ID, correlationId);
    // propagate transaction property
    msgContext.setProperty(BaseConstants.INTERNAL_TRANSACTION_COUNTED, conn.getContext().getAttribute(BaseConstants.INTERNAL_TRANSACTION_COUNTED));
    if (sourceConfiguration.getScheme().isSSL()) {
        msgContext.setTransportOut(cfgCtx.getAxisConfiguration().getTransportOut(Constants.TRANSPORT_HTTPS));
        msgContext.setTransportIn(cfgCtx.getAxisConfiguration().getTransportIn(Constants.TRANSPORT_HTTPS));
        msgContext.setIncomingTransportName(sourceConfiguration.getInDescription() != null ? sourceConfiguration.getInDescription().getName() : Constants.TRANSPORT_HTTPS);
        SSLIOSession ssliosession = (SSLIOSession) (conn.getContext()).getAttribute(SSLIOSession.SESSION_KEY);
        // set SSL certificates to message context if SSLVerifyClient parameter is set
        if (ssliosession != null && msgContext.getTransportIn() != null && msgContext.getTransportIn().getParameter(NhttpConstants.SSL_VERIFY_CLIENT) != null) {
            try {
                msgContext.setProperty(NhttpConstants.SSL_CLIENT_AUTH_CERT_X509, ssliosession.getSSLSession().getPeerCertificateChain());
            } catch (SSLPeerUnverifiedException e) {
                // Peer Certificate Chain may not be available always.(in case of Mutual SSL is not enabled)
                if (log.isTraceEnabled()) {
                    log.trace("Peer certificate chain is not available for MsgContext " + msgContext.getMessageID());
                }
            }
        }
    } else {
        msgContext.setTransportOut(cfgCtx.getAxisConfiguration().getTransportOut(Constants.TRANSPORT_HTTP));
        msgContext.setTransportIn(cfgCtx.getAxisConfiguration().getTransportIn(Constants.TRANSPORT_HTTP));
        msgContext.setIncomingTransportName(sourceConfiguration.getInDescription() != null ? sourceConfiguration.getInDescription().getName() : Constants.TRANSPORT_HTTP);
    }
    msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, this);
    msgContext.setServerSide(true);
    msgContext.setProperty(Constants.Configuration.TRANSPORT_IN_URL, request.getUri());
    // http transport header names are case insensitive
    Map<String, String> headers = new TreeMap<String, String>(new Comparator<String>() {

        public int compare(String o1, String o2) {
            return o1.compareToIgnoreCase(o2);
        }
    });
    Set<Map.Entry<String, String>> entries = request.getHeaders().entrySet();
    for (Map.Entry<String, String> entry : entries) {
        headers.put(entry.getKey(), entry.getValue());
    }
    msgContext.setProperty(MessageContext.TRANSPORT_HEADERS, headers);
    msgContext.setProperty(NhttpConstants.EXCESS_TRANSPORT_HEADERS, excessHeaders);
    if (conn instanceof HttpInetConnection) {
        HttpInetConnection netConn = (HttpInetConnection) conn;
        InetAddress remoteAddress = netConn.getRemoteAddress();
        if (remoteAddress != null) {
            msgContext.setProperty(MessageContext.REMOTE_ADDR, remoteAddress.getHostAddress());
            msgContext.setProperty(NhttpConstants.REMOTE_HOST, NhttpUtil.getHostName(remoteAddress));
        }
    }
    msgContext.setProperty(RequestResponseTransport.TRANSPORT_CONTROL, new HttpCoreRequestResponseTransport(msgContext));
    msgContext.setProperty(PassThroughConstants.TRANSPORT_MESSAGE_HANDLER, new PassThroughMessageHandler());
    return msgContext;
}
Also used : PassThroughMessageHandler(org.apache.synapse.transport.util.PassThroughMessageHandler) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) HttpInetConnection(org.apache.http.HttpInetConnection) TreeMap(java.util.TreeMap) HttpCoreRequestResponseTransport(org.apache.synapse.transport.nhttp.HttpCoreRequestResponseTransport) NHttpServerConnection(org.apache.http.nio.NHttpServerConnection) SSLIOSession(org.apache.http.nio.reactor.ssl.SSLIOSession) MessageContext(org.apache.axis2.context.MessageContext) Map(java.util.Map) TreeMap(java.util.TreeMap) InetAddress(java.net.InetAddress)

Aggregations

NHttpServerConnection (org.apache.http.nio.NHttpServerConnection)12 MessageContext (org.apache.axis2.context.MessageContext)7 IOException (java.io.IOException)5 Map (java.util.Map)4 SourceConfiguration (org.apache.synapse.transport.passthru.config.SourceConfiguration)4 OutputStream (java.io.OutputStream)3 ConnectionClosedException (org.apache.http.ConnectionClosedException)3 HttpException (org.apache.http.HttpException)3 Pipe (org.apache.synapse.transport.passthru.Pipe)3 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)2 XMLStreamException (javax.xml.stream.XMLStreamException)2 OMOutputFormat (org.apache.axiom.om.OMOutputFormat)2 MessageFormatter (org.apache.axis2.transport.MessageFormatter)2 HttpResponse (org.apache.http.HttpResponse)2 HttpContext (org.apache.http.protocol.HttpContext)2 HttpCoreRequestResponseTransport (org.apache.synapse.transport.nhttp.HttpCoreRequestResponseTransport)2 InputStream (java.io.InputStream)1 InterruptedIOException (java.io.InterruptedIOException)1 InetAddress (java.net.InetAddress)1 MalformedURLException (java.net.MalformedURLException)1