Java Code Examples for org.apache.synapse.MessageContext#setTo()

The following examples show how to use org.apache.synapse.MessageContext#setTo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ODataPassThroughHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleRequestInFlow(MessageContext messageContext) {
    try {
        org.apache.axis2.context.MessageContext axis2MessageContext =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();
        Object isODataService = axis2MessageContext.getProperty("IsODataService");
        // In this if block we are skipping proxy services, inbound related message contexts & api.
        if (axis2MessageContext.getProperty("TransportInURL") != null && isODataService != null) {
            RelayUtils.buildMessage(axis2MessageContext);
            ODataServletRequest request = new ODataServletRequest(axis2MessageContext);
            ODataServletResponse response = new ODataServletResponse(axis2MessageContext);
            ODataEndpoint.process(request, response);
            setContent(axis2MessageContext, response);
            setHeaders(axis2MessageContext, response);
            messageContext.setTo(null);
            messageContext.setResponse(true);
            Axis2Sender.sendBack(messageContext);
        }
        return true;
    } catch (Exception e) {
        this.handleException("Error occurred in integrator handler.", e, messageContext);
        return true;
    }
}
 
Example 2
Source File: SecurityHandlerAdapterTest.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a handler configuration similar to the following with no resources defined.
 * <p>
 * <handler name="SampleInternalApiHandlerWithNoResources"
 *          class="internal.http.api.SampleInternalApiHandlerWithNoResources"/>
 */
@Test
public void testHandledWithNoResource() {

    //set message context
    MessageContext messageContext = new TestMessageContext();
    EndpointReference endpointReference = new EndpointReference();
    endpointReference.setAddress("/sectest/resource1");
    messageContext.setTo(endpointReference);

    TestSecurityHandler internalAPIHandler = new TestSecurityHandler("/sectest");

    //test with no resources
    internalAPIHandler.setResources(new ArrayList<>());
    internalAPIHandler.invoke(messageContext);
    Assert.assertTrue("Handler should be engaged when no resources are explictely defined, but it was not engaged.",
                      internalAPIHandler.isHandleTriggered());
}
 
Example 3
Source File: SecurityHandlerAdapterTest.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a handler configuration similar to the following.
 *
 * <handler name="SampleInternalApiHandlerWithAllResources"
 *          class="internal.http.api.SampleInternalApiHandlerWithAllResources">
 *  <resources>
 *      <resource>/</resource>
 *  </resources>
 *</handler>
 */
@Test
public void testHandledWithAllResources() {

    //Create test message context
    MessageContext messageContext = new TestMessageContext();
    EndpointReference endpointReference = new EndpointReference();
    messageContext.setTo(endpointReference);

    TestSecurityHandler internalAPIHandler = new TestSecurityHandler("/sectest");
    List<String> resources = new ArrayList<>();
    resources.add("/");
    internalAPIHandler.setResources(resources);

    //set message context with matching resource
    endpointReference.setAddress("/sectest/resource1");
    internalAPIHandler.invoke(messageContext);
    Assert.assertTrue("Handler should be engaged since all resources are defined, but it was not engaged.",
                      internalAPIHandler.isHandleTriggered());
}
 
Example 4
Source File: Utils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public static void sendFault(MessageContext messageContext, int status) {
    org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).
            getAxis2MessageContext();

    axis2MC.setProperty(NhttpConstants.HTTP_SC, status);
    messageContext.setResponse(true);
    messageContext.setProperty("RESPONSE", "true");
    messageContext.setTo(null);        
    axis2MC.removeProperty("NO_ENTITY_BODY");

    // Always remove the ContentType - Let the formatter do its thing
    axis2MC.removeProperty(Constants.Configuration.CONTENT_TYPE);
    Map headers = (Map) axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    if (headers != null) {
        headers.remove(HttpHeaders.AUTHORIZATION);

        headers.remove(HttpHeaders.HOST);
    }
    Axis2Sender.sendBack(messageContext);
}
 
Example 5
Source File: RESTBasicAuthHandler.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleRequest(MessageContext messageContext) {
    org.apache.axis2.context.MessageContext axis2MessageContext
            = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    Object headers = axis2MessageContext.getProperty(
            org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);



    if (headers != null && headers instanceof Map) {
        Map headersMap = (Map) headers;
        if (headersMap.get(HTTPConstants.HEADER_AUTHORIZATION) == null) {
            headersMap.clear();
            axis2MessageContext.setProperty(BasicAuthConstants.HTTP_STATUS_CODE, BasicAuthConstants.SC_UNAUTHORIZED);
            headersMap.put(BasicAuthConstants.WWW_AUTHENTICATE, BasicAuthConstants.WWW_AUTH_METHOD);
            axis2MessageContext.setProperty(BasicAuthConstants.NO_ENTITY_BODY, true);
            messageContext.setProperty(BasicAuthConstants.RESPONSE, BasicAuthConstants.TRUE);
            messageContext.setTo(null);
            Axis2Sender.sendBack(messageContext);
            return false;


        } else {
            String authHeader = (String) headersMap.get(HTTPConstants.HEADER_AUTHORIZATION);
            String credentials = authHeader.substring(6).trim();
            if (processSecurity(credentials)) {
                return true;
            } else {
                headersMap.clear();
                axis2MessageContext.setProperty(BasicAuthConstants.HTTP_STATUS_CODE, BasicAuthConstants.SC_FORBIDDEN);
                axis2MessageContext.setProperty(BasicAuthConstants.NO_ENTITY_BODY, true);
                messageContext.setProperty(BasicAuthConstants.RESPONSE, BasicAuthConstants.TRUE);
                messageContext.setTo(null);
                Axis2Sender.sendBack(messageContext);
                return false;
            }
        }
    }
    return false;
}
 
Example 6
Source File: SecurityUtils.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the provided status code for the response.
 *
 * @param messageContext Synapse message context
 * @param statusCode     status code
 */
public static void setStatusCode(MessageContext messageContext, int statusCode) {

    org.apache.axis2.context.MessageContext axis2MessageContext
            = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    axis2MessageContext.setProperty(AuthConstants.HTTP_STATUS_CODE, statusCode);
    axis2MessageContext.setProperty(AuthConstants.NO_ENTITY_BODY, true);
    messageContext.setProperty(AuthConstants.RESPONSE, AuthConstants.TRUE);
    messageContext.setTo(null);
}
 
Example 7
Source File: SecurityHandlerAdapterTest.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Tests a handler configuration similar to the following.
 * <p>
 * <handler name="SampleInternalApiHandlerWithCustomResources"
 *          class="internal.http.api.SampleInternalApiHandlerWithCustomResources">
 *  <resources>
 *      <resource>/resource1</resource>
 *      <resource>/resource2</resource>
 *  </resources>
 *</handler>
 */
@Test
public void testHandledWithCustomResources() {

    //Create test message context
    MessageContext messageContext = new TestMessageContext();
    EndpointReference endpointReference = new EndpointReference();
    messageContext.setTo(endpointReference);

    TestSecurityHandler internalAPIHandler = new TestSecurityHandler("/sectest");
    List<String> resources = new ArrayList<>();
    resources.add("/resource1");
    resources.add("/resource2");
    internalAPIHandler.setResources(resources);

    //set message context with matching resource
    endpointReference.setAddress("/sectest/resource1");
    internalAPIHandler.invoke(messageContext);
    Assert.assertTrue("Handler should be engaged since resource 1 was defined, but it was not engaged.",
                      internalAPIHandler.isHandleTriggered());

    //set message context with matching resource
    endpointReference.setAddress("/sectest/resource2");
    internalAPIHandler.invoke(messageContext);
    Assert.assertTrue("Handler should be engaged since resource 2 was defined, but it was not engaged.",
                      internalAPIHandler.isHandleTriggered());

    //set message context with matching resource but containing a sub resource
    endpointReference.setAddress("/sectest/resource2/resource22");
    internalAPIHandler.invoke(messageContext);
    Assert.assertTrue("Handler should be engaged since resource 2 was defined, but it was not engaged.",
                      internalAPIHandler.isHandleTriggered());

    //set message context with a resource that is not matching
    endpointReference.setAddress("/sectest/resource3");
    internalAPIHandler.invoke(messageContext);
    Assert.assertFalse("Handler should not be engaged since resource 3 was not defined, but it was engaged.",
                       internalAPIHandler.isHandleTriggered());

}
 
Example 8
Source File: Utils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public static void setSOAPFault(MessageContext messageContext, String code, 
                                String reason, String detail) {
    SOAPFactory factory = (messageContext.isSOAP11() ?
            OMAbstractFactory.getSOAP11Factory() : OMAbstractFactory.getSOAP12Factory());

    OMDocument soapFaultDocument = factory.createOMDocument();
    SOAPEnvelope faultEnvelope = factory.getDefaultFaultEnvelope();
    soapFaultDocument.addChild(faultEnvelope);

    SOAPFault fault = faultEnvelope.getBody().getFault();
    if (fault == null) {
        fault = factory.createSOAPFault();
    }

    SOAPFaultCode faultCode = factory.createSOAPFaultCode();
    if (messageContext.isSOAP11()) {
        faultCode.setText(new QName(fault.getNamespace().getNamespaceURI(), code));
    } else {
        SOAPFaultValue value = factory.createSOAPFaultValue(faultCode);
        value.setText(new QName(fault.getNamespace().getNamespaceURI(), code));            
    }
    fault.setCode(faultCode);

    SOAPFaultReason faultReason = factory.createSOAPFaultReason();
    if (messageContext.isSOAP11()) {
        faultReason.setText(reason);
    } else {
        SOAPFaultText text = factory.createSOAPFaultText();
        text.setText(reason);
        text.setLang("en");
        faultReason.addSOAPText(text);            
    }
    fault.setReason(faultReason);

    SOAPFaultDetail soapFaultDetail = factory.createSOAPFaultDetail();
    soapFaultDetail.setText(detail);
    fault.setDetail(soapFaultDetail);
    
    // set the all headers of original SOAP Envelope to the Fault Envelope
    if (messageContext.getEnvelope() != null) {
        SOAPHeader soapHeader = messageContext.getEnvelope().getHeader();
        if (soapHeader != null) {
            for (Iterator iterator = soapHeader.examineAllHeaderBlocks(); iterator.hasNext();) {
                Object o = iterator.next();
                if (o instanceof SOAPHeaderBlock) {
                    SOAPHeaderBlock header = (SOAPHeaderBlock) o;
                    faultEnvelope.getHeader().addChild(header);
                } else if (o instanceof OMElement) {
                    faultEnvelope.getHeader().addChild((OMElement) o);
                }
            }
        }
    }

    try {
        messageContext.setEnvelope(faultEnvelope);
    } catch (AxisFault af) {
        log.error("Error while setting SOAP fault as payload", af);
        return;
    }

    if (messageContext.getFaultTo() != null) {
        messageContext.setTo(messageContext.getFaultTo());
    } else if (messageContext.getReplyTo() != null) {
        messageContext.setTo(messageContext.getReplyTo());
    } else {
        messageContext.setTo(null);
    }

    // set original messageID as relatesTo
    if (messageContext.getMessageID() != null) {
        RelatesTo relatesTo = new RelatesTo(messageContext.getMessageID());
        messageContext.setRelatesTo(new RelatesTo[] { relatesTo });
    }
}
 
Example 9
Source File: Utils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method used to send the response back from the request.
 *
 * @param messageContext messageContext of the request
 * @param status         HTTP Status to return from the response
 */
public static void send(MessageContext messageContext, int status) {
    org.apache.axis2.context.MessageContext axis2MC =
            ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    axis2MC.setProperty(NhttpConstants.HTTP_SC, status);
    messageContext.setResponse(true);
    messageContext.setProperty(SynapseConstants.RESPONSE, "true");
    messageContext.setTo(null);
    axis2MC.removeProperty(Constants.Configuration.CONTENT_TYPE);
    Axis2Sender.sendBack(messageContext);
}
 
Example 10
Source File: CacheMediator.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * This method returns the existing cached response.
 * @param synCtx Message context.
 * @param synLog Synapse log.
 * @param msgCtx Axis2 contex.
 * @param cachedResponse Cached response.
 */
private void replaceEnvelopeWithCachedResponse(MessageContext synCtx, SynapseLog synLog,
                                               org.apache.axis2.context.MessageContext msgCtx, CachableResponse cachedResponse) {
    Map<String, Object> headerProperties;
    try {
        if (cachedResponse.isJson()) {
            byte[] payload = cachedResponse.getResponsePayload();
            OMElement response = JsonUtil.getNewJsonPayload(msgCtx, payload, 0,
                    payload.length, false, false);
            if (msgCtx.getEnvelope().getBody().getFirstElement() != null) {
                msgCtx.getEnvelope().getBody().getFirstElement().detach();
            }
            msgCtx.getEnvelope().getBody().addChild(response);

        } else {
            msgCtx.setEnvelope(MessageHelper.cloneSOAPEnvelope(cachedResponse.getResponseEnvelope()));
        }
    } catch (AxisFault e) {
        handleException("Error creating response OM from cache : " + id, synCtx);
    }
    if (CachingConstants.HTTP_PROTOCOL_TYPE.equals(getProtocolType())) {
        if (cachedResponse.getStatusCode() != null) {
            msgCtx.setProperty(NhttpConstants.HTTP_SC,
                    Integer.parseInt(cachedResponse.getStatusCode()));
        }
        if (cachedResponse.getStatusReason() != null) {
            msgCtx.setProperty(PassThroughConstants.HTTP_SC_DESC, cachedResponse.getStatusReason());
        }
        //Set Age header to the cached response.
        if (cachedResponse.isAddAgeHeaderEnabled()) {
            HttpCachingFilter.setAgeHeader(cachedResponse, msgCtx);
        }
    }
    if (msgCtx.isDoingREST()) {

        msgCtx.removeProperty(PassThroughConstants.NO_ENTITY_BODY);
        msgCtx.removeProperty(Constants.Configuration.CONTENT_TYPE);
    }
    if ((headerProperties = cachedResponse.getHeaderProperties()) != null) {

        msgCtx.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS,
                headerProperties);
        msgCtx.setProperty(Constants.Configuration.MESSAGE_TYPE,
                headerProperties.get(Constants.Configuration.MESSAGE_TYPE));
    }

    // take specified action on cache hit
    if (onCacheHitSequence != null) {
        // if there is an onCacheHit use that for the mediation
        synLog.traceOrDebug("Delegating message to the onCacheHit "
                + "Anonymous sequence");
        ContinuationStackManager.addReliantContinuationState(synCtx, 0, getMediatorPosition());
        if (onCacheHitSequence.mediate(synCtx)) {
            ContinuationStackManager.removeReliantContinuationState(synCtx);
        }

    } else if (onCacheHitRef != null) {
        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("Delegating message to the onCacheHit "
                    + "sequence : " + onCacheHitRef);
        }
        ContinuationStackManager.updateSeqContinuationState(synCtx, getMediatorPosition());
        synCtx.getSequence(onCacheHitRef).mediate(synCtx);

    } else {

        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("Request message " + synCtx.getMessageID() +
                    " was served from the cache");
        }
        // send the response back if there is not onCacheHit is specified
        synCtx.setTo(null);
        //Todo continueExecution if needed
        Axis2Sender.sendBack(synCtx);

    }
}
 
Example 11
Source File: TenantAwareLoadBalanceEndpoint.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
protected void sendToApplicationMember(MessageContext synCtx,
                                       org.apache.axis2.clustering.Member currentMember,
                                       DynamicLoadbalanceFaultHandler faultHandler,
                                       boolean newSession) {
    //Rewriting the URL
    org.apache.axis2.context.MessageContext axis2MsgCtx =
            ((Axis2MessageContext) synCtx).getAxis2MessageContext();

    //Removing the REST_URL_POSTFIX - this is a hack.
    //In this load balance endpoint we create an endpoint per request by setting the complete url as the address.
    //If a REST message comes Axis2FlexibleMEPClient append the REST_URL_POSTFIX to the address. Hence endpoint fails
    //do send the request. e.g.  http://localhost:8080/example/index.html/example/index.html
    axis2MsgCtx.removeProperty(NhttpConstants.REST_URL_POSTFIX);

    String transport = axis2MsgCtx.getTransportIn().getName();
    EndpointReference to = getEndpointReferenceAfterURLRewrite(synCtx, currentMember, transport);
    synCtx.setTo(to);

    Endpoint endpoint = getEndpoint(to, currentMember, synCtx);

    // Push fault handler to manage statistics and fail-over logic
    faultHandler.setTo(to);
    faultHandler.setCurrentMember(currentMember);
    faultHandler.setCurrentEp(endpoint);
    synCtx.pushFaultHandler(faultHandler);
    synCtx.getEnvelope().build();

    if (isSessionAffinityBasedLB()) {
        synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_DEFAULT_SESSION_TIMEOUT, getSessionTimeout());
        synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER, dispatcher);

        if (newSession) {
            prepareEndPointSequence(synCtx, endpoint);
            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER, currentMember);
            // we should also indicate that this is the first message in the session. so that
            // onFault(...) method can resend only the failed attempts for the first message.
            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_FIRST_MESSAGE_IN_SESSION,
                    Boolean.TRUE);
        }
    }

    Map<String, String> memberHosts;
    if ((memberHosts = (Map<String, String>) currentMember.getProperties().get(HttpSessionDispatcher.HOSTS)) == null) {
        currentMember.getProperties().put(HttpSessionDispatcher.HOSTS,
                memberHosts = new HashMap<String, String>());
    }
    memberHosts.put(extractTargetHost(synCtx), "true");
    setupTransportHeaders(synCtx);
    setupLoadBalancerContextProperties(synCtx, currentMember);

    try {
        if (log.isDebugEnabled()) {
            log.debug(String.format("Sending request %s to endpoint: %s", synCtx.getMessageID(), to.getAddress()));
        }
        endpoint.send(synCtx);

        // Increment in-flight request count
        incrementInFlightRequestCount(synCtx);
    } catch (Exception e) {
        if (e.getMessage().toLowerCase().contains("io reactor shutdown")) {
            log.fatal("System cannot continue normal operation. Restarting", e);
            System.exit(121); // restart
        } else {
            throw new SynapseException(e);
        }
    }
}
 
Example 12
Source File: TenantAwareLoadBalanceEndpoint.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Override
public void onFault(MessageContext synCtx) {
    if (log.isWarnEnabled()) {
        log.warn(String.format("A fault detected in message sent to: %s ", (to != null) ? to.getAddress() : "address not found"));
    }

    // Decrement in-flight request count
    decrementInFlightRequestCount(synCtx);

    if (isFailover()) {
        if (log.isDebugEnabled()) {
            log.debug("Fail-over enabled, trying to send the message to the next available member");
        }

        // Cleanup endpoint if exists
        if (currentEp != null) {
            currentEp.destroy();
        }
        if (currentMember == null) {
            if (log.isErrorEnabled()) {
                log.error("Current member is null, could not fail-over");
            }
            return;
        }

        // Add current member to faulty members
        faultyMemberIds.put(currentMember.getProperties().getProperty(LoadBalancerConstants.MEMBER_ID), true);

        currentMember = findNextMember(synCtx);
        if (currentMember == null) {
            String msg = String.format("No members available to serve the request %s", (to != null) ? to.getAddress() : "address not found");
            if (log.isErrorEnabled()) {
                log.error(msg);
            }
            throwSynapseException(synCtx, 404, msg);
        }
        if (faultyMemberIds.containsKey(currentMember.getProperties().getProperty(LoadBalancerConstants.MEMBER_ID))) {
            // This member has been identified as faulty previously. It implies that
            // this request could not be served by any of the members in the cluster.
            throwSynapseException(synCtx, 404, String.format("Requested resource could not be found"));
        }

        synCtx.setTo(to);
        if (isSessionAffinityBasedLB()) {
            //We are sending the this message on a new session,
            // hence we need to remove previous session information
            Set<?> pros = synCtx.getPropertyKeySet();
            if (pros != null) {
                pros.remove(SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);
            }
        }
        sendToApplicationMember(synCtx, currentMember, this, true);
    }
}