Search in sources :

Example 96 with EndpointReference

use of org.apache.axis2.addressing.EndpointReference in project wso2-synapse by wso2.

the class ServerWorker method handleRESTUrlPost.

/**
 * Method will setup the necessary parameters for the rest url post action
 *
 * @param
 * @return
 * @throws FactoryConfigurationError
 */
public SOAPEnvelope handleRESTUrlPost(String contentTypeHdr) throws FactoryConfigurationError {
    SOAPEnvelope soapEnvelope = null;
    String contentType = contentTypeHdr != null ? TransportUtils.getContentType(contentTypeHdr, msgContext) : null;
    // recipient should consider it as application/octet-stream (rfc2616)
    if (contentType == null || contentType.isEmpty()) {
        contentType = PassThroughConstants.APPLICATION_OCTET_STREAM;
        // Temp fix for https://github.com/wso2/product-ei/issues/2001
        if (HTTPConstants.HTTP_METHOD_GET.equals(msgContext.getProperty(HTTP_METHOD)) || "DELETE".equals(msgContext.getProperty(HTTP_METHOD))) {
            contentType = HTTPConstants.MEDIA_TYPE_X_WWW_FORM;
        }
    }
    if (HTTPConstants.MEDIA_TYPE_X_WWW_FORM.equals(contentType) || (PassThroughConstants.APPLICATION_OCTET_STREAM.equals(contentType) && contentTypeHdr == null)) {
        msgContext.setTo(new EndpointReference(request.getRequest().getRequestLine().getUri()));
        String charSetEncoding;
        if (contentTypeHdr != null) {
            msgContext.setProperty(Constants.Configuration.CONTENT_TYPE, contentTypeHdr);
            charSetEncoding = BuilderUtil.getCharSetEncoding(contentTypeHdr);
        } else {
            msgContext.setProperty(Constants.Configuration.CONTENT_TYPE, contentType);
            charSetEncoding = BuilderUtil.getCharSetEncoding(contentType);
        }
        msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEncoding);
        try {
            RESTUtil.dispatchAndVerify(msgContext);
        } catch (AxisFault e1) {
            log.error("Error while building message for REST_URL request", e1);
        }
        try {
            /**
             * This reverseProxyMode was introduce to avoid the LB exposing
             * it's own web service when REST call was initiated
             */
            boolean reverseProxyMode = PassThroughConfiguration.getInstance().isReverseProxyMode();
            AxisService axisService = null;
            if (!reverseProxyMode) {
                RequestURIBasedDispatcher requestDispatcher = new RequestURIBasedDispatcher();
                axisService = requestDispatcher.findService(msgContext);
            }
            // the logic determines which service dispatcher to get invoke,
            // this will be determine
            // based on parameter defines at disableRestServiceDispatching,
            // and if super tenant invoke, with isTenantRequest
            // identifies whether the request to be dispatch to custom REST
            // Dispatcher Service.
            boolean isCustomRESTDispatcher = false;
            String requestURI = request.getRequest().getRequestLine().getUri();
            if (requestURI.matches(PassThroughConfiguration.getInstance().getRestUriApiRegex()) || requestURI.matches(PassThroughConfiguration.getInstance().getRestUriProxyRegex())) {
                isCustomRESTDispatcher = true;
            }
            if (!isCustomRESTDispatcher) {
                if (axisService == null) {
                    String defaultSvcName = PassThroughConfiguration.getInstance().getPassThroughDefaultServiceName();
                    axisService = msgContext.getConfigurationContext().getAxisConfiguration().getService(defaultSvcName);
                    msgContext.setAxisService(axisService);
                }
            } else {
                String multiTenantDispatchService = PassThroughConfiguration.getInstance().getRESTDispatchService();
                axisService = msgContext.getConfigurationContext().getAxisConfiguration().getService(multiTenantDispatchService);
                msgContext.setAxisService(axisService);
            }
        } catch (AxisFault e) {
            handleException("Error processing " + request.getMethod() + " request for : " + request.getUri(), e);
        }
        try {
            soapEnvelope = TransportUtils.createSOAPMessage(msgContext, null, contentType);
        } catch (Exception e) {
            log.error("Error while building message for REST_URL request");
        }
        // msgContext.setProperty(Constants.Configuration.CONTENT_TYPE,"application/xml");
        msgContext.setProperty(Constants.Configuration.MESSAGE_TYPE, HTTPConstants.MEDIA_TYPE_APPLICATION_XML);
    }
    return soapEnvelope;
}
Also used : AxisFault(org.apache.axis2.AxisFault) RequestURIBasedDispatcher(org.apache.axis2.dispatchers.RequestURIBasedDispatcher) AxisService(org.apache.axis2.description.AxisService) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 97 with EndpointReference

use of org.apache.axis2.addressing.EndpointReference in project wso2-synapse by wso2.

the class ServerWorker method processHttpRequestUri.

/**
 * Get Uri of underlying SourceRequest and  calculate service prefix and add to message context
 * create response buffers for  HTTP GET, DELETE, OPTION and HEAD methods
 * @param msgContext Axis2MessageContext of the request
 * @param method HTTP Method of the request
 */
public void processHttpRequestUri(MessageContext msgContext, String method) {
    String servicePrefixIndex = "://";
    ConfigurationContext cfgCtx = sourceConfiguration.getConfigurationContext();
    msgContext.setProperty(Constants.Configuration.HTTP_METHOD, request.getMethod());
    // String uri = request.getUri();
    String oriUri = request.getUri();
    String restUrlPostfix = NhttpUtil.getRestUrlPostfix(oriUri, cfgCtx.getServicePath());
    String servicePrefix = oriUri.substring(0, oriUri.indexOf(restUrlPostfix));
    if (servicePrefix.indexOf(servicePrefixIndex) == -1) {
        HttpInetConnection inetConn = (HttpInetConnection) request.getConnection();
        InetAddress localAddr = inetConn.getLocalAddress();
        if (localAddr != null) {
            servicePrefix = sourceConfiguration.getScheme().getName() + servicePrefixIndex + localAddr.getHostAddress() + ":" + inetConn.getLocalPort() + servicePrefix;
        }
    }
    msgContext.setProperty(PassThroughConstants.SERVICE_PREFIX, servicePrefix);
    msgContext.setTo(new EndpointReference(restUrlPostfix));
    msgContext.setProperty(PassThroughConstants.REST_URL_POSTFIX, restUrlPostfix);
    if (PassThroughConstants.HTTP_GET.equals(method) || PassThroughConstants.HTTP_HEAD.equals(method) || PassThroughConstants.HTTP_OPTIONS.equals(method)) {
        HttpResponse response = sourceConfiguration.getResponseFactory().newHttpResponse(request.getVersion(), HttpStatus.SC_OK, request.getConnection().getContext());
        // create a basic HttpEntity using the source channel of the response pipe
        BasicHttpEntity entity = new BasicHttpEntity();
        if (request.getVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
            entity.setChunked(true);
        }
        response.setEntity(entity);
        httpGetRequestProcessor.process(request.getRequest(), response, msgContext, request.getConnection(), os, isRestDispatching);
    }
}
Also used : ConfigurationContext(org.apache.axis2.context.ConfigurationContext) HttpResponse(org.apache.http.HttpResponse) HttpInetConnection(org.apache.http.HttpInetConnection) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) InetAddress(java.net.InetAddress) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 98 with EndpointReference

use of org.apache.axis2.addressing.EndpointReference in project wso2-synapse by wso2.

the class ServerWorker method processNonEntityEnclosingRESTHandler.

public void processNonEntityEnclosingRESTHandler(SOAPEnvelope soapEnvelope, MessageContext msgContext, boolean injectToAxis2Engine) {
    String soapAction = request.getHeaders().get(SOAP_ACTION_HEADER);
    if ((soapAction != null) && soapAction.startsWith("\"") && soapAction.endsWith("\"")) {
        soapAction = soapAction.substring(1, soapAction.length() - 1);
    }
    msgContext.setSoapAction(soapAction);
    msgContext.setTo(new EndpointReference(request.getUri()));
    msgContext.setServerSide(true);
    msgContext.setDoingREST(true);
    if (!(request.isEntityEnclosing())) {
        msgContext.setProperty(PassThroughConstants.NO_ENTITY_BODY, Boolean.TRUE);
    }
    try {
        if (soapEnvelope == null) {
            msgContext.setEnvelope(new SOAP11Factory().getDefaultEnvelope());
        } else {
            msgContext.setEnvelope(soapEnvelope);
        }
        if (injectToAxis2Engine) {
            AxisEngine.receive(msgContext);
        }
    } catch (AxisFault axisFault) {
        handleException("Error processing " + request.getMethod() + " request for : " + request.getUri(), axisFault);
    } catch (Exception e) {
        String encodedURL = StringEscapeUtils.escapeHtml(request.getUri());
        handleException("Error processing " + request.getMethod() + " request for : " + encodedURL + ". ", e);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) SOAP11Factory(org.apache.axiom.soap.impl.llom.soap11.SOAP11Factory) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 99 with EndpointReference

use of org.apache.axis2.addressing.EndpointReference in project wso2-synapse by wso2.

the class HttpCoreNIOSender method sendAsyncRequest.

/**
 * Send the request message asynchronously to the given EPR
 * @param epr the destination EPR for the message
 * @param msgContext the message being sent
 * @throws AxisFault on error
 */
private void sendAsyncRequest(EndpointReference epr, MessageContext msgContext) throws AxisFault {
    try {
        URL url = new URL(epr.getAddress());
        String scheme = url.getProtocol() != null ? url.getProtocol() : "http";
        String hostname = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            // use default
            if ("http".equals(scheme)) {
                port = 80;
            } else if ("https".equals(scheme)) {
                port = 443;
            }
        }
        HttpHost target = new HttpHost(hostname, port, scheme);
        boolean secure = "https".equalsIgnoreCase(target.getSchemeName());
        HttpHost proxy = proxyConfig.selectProxy(target);
        msgContext.setProperty(NhttpConstants.PROXY_PROFILE_TARGET_HOST, target.getHostName());
        HttpRoute route;
        if (proxy != null) {
            route = new HttpRoute(target, null, proxy, secure);
        } else {
            route = new HttpRoute(target, null, secure);
        }
        Axis2HttpRequest axis2Req = new Axis2HttpRequest(epr, route, msgContext);
        Object timeout = msgContext.getProperty(NhttpConstants.SEND_TIMEOUT);
        if (timeout != null && timeout instanceof Long) {
            axis2Req.setTimeout((int) ((Long) timeout).longValue());
        }
        NHttpClientConnection conn = connpool.getConnection(route);
        // Ensure MessageContext has a ClientConnectionDebug attached before we start streaming
        ServerConnectionDebug scd = (ServerConnectionDebug) msgContext.getProperty(ServerHandler.SERVER_CONNECTION_DEBUG);
        ClientConnectionDebug ccd;
        if (scd != null) {
            ccd = scd.getClientConnectionDebug();
            if (ccd == null) {
                ccd = new ClientConnectionDebug(scd);
                scd.setClientConnectionDebug(ccd);
            }
            ccd.recordRequestStartTime(conn, axis2Req);
            msgContext.setProperty(ClientHandler.CLIENT_CONNECTION_DEBUG, ccd);
        }
        if (conn == null) {
            HttpHost host = route.getProxyHost() != null ? route.getProxyHost() : route.getTargetHost();
            ioReactor.connect(new InetSocketAddress(host.getHostName(), host.getPort()), null, axis2Req, sessionRequestCallback);
            if (log.isDebugEnabled()) {
                log.debug("A new connection established to : " + route);
            }
        } else {
            // reinitialize timeouts for the pooled connection
            conn.setSocketTimeout(socketTimeout);
            try {
                handler.submitRequest(conn, axis2Req);
                if (log.isDebugEnabled()) {
                    log.debug("An existing connection reused to : " + hostname + ":" + port);
                }
            } catch (ConnectionClosedException e) {
                ioReactor.connect(new InetSocketAddress(hostname, port), null, axis2Req, sessionRequestCallback);
                if (log.isDebugEnabled()) {
                    log.debug("A new connection established to : " + hostname + ":" + port);
                }
            }
        }
        try {
            axis2Req.streamMessageContents();
        } catch (AxisFault af) {
            throw af;
        }
    } catch (MalformedURLException e) {
        handleException("Malformed destination EPR : " + epr.getAddress(), e);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) MalformedURLException(java.net.MalformedURLException) ServerConnectionDebug(org.apache.synapse.transport.nhttp.debug.ServerConnectionDebug) InetSocketAddress(java.net.InetSocketAddress) ClientConnectionDebug(org.apache.synapse.transport.nhttp.debug.ClientConnectionDebug) ConnectionClosedException(org.apache.http.ConnectionClosedException) NHttpClientConnection(org.apache.http.nio.NHttpClientConnection) URL(java.net.URL) HttpRoute(org.apache.http.conn.routing.HttpRoute) HttpHost(org.apache.http.HttpHost)

Example 100 with EndpointReference

use of org.apache.axis2.addressing.EndpointReference in project wso2-synapse by wso2.

the class RESTUtil method prepareMessageContext.

/**
 * prepare message context prior to call axis2 RestUtils
 *
 * @param msgContext  The MessageContext of the Request Message
 * @param requestURI  The URL that the request came to
 * @param httpMethod  The http method of the request
 * @param out         The output stream of the response
 * @param contentType The content type of the request
 * @param dispatching weather we should do dispatching
 * @throws AxisFault Thrown in case a fault occurs
 */
private static void prepareMessageContext(MessageContext msgContext, String requestURI, String httpMethod, OutputStream out, String contentType, boolean dispatching) throws AxisFault {
    msgContext.setTo(new EndpointReference(requestURI));
    msgContext.setProperty(HTTPConstants.HTTP_METHOD, httpMethod);
    msgContext.setServerSide(true);
    msgContext.setDoingREST(true);
    msgContext.setProperty(MessageContext.TRANSPORT_OUT, out);
    msgContext.setProperty(NhttpConstants.REST_REQUEST_CONTENT_TYPE, contentType);
    // workaround to get REST working in the case of
    // 1) Based on the request URI , it is possible to find a service name and operation.
    // However, there is no actual service deployed in the synapse ( no  i.e proxy or other)
    // e.g  http://localhost:8280/services/StudentService/students where there  is no proxy
    // service with name StudentService.This is a senario where StudentService is in an external
    // server and it is needed to call it from synapse using the main sequence
    // 2) request is to be injected into  the main sequence  .i.e. http://localhost:8280
    // This method does not cause any performance issue ...
    // Proper fix should be refractoring axis2 RestUtil in a proper way
    /**
     * This reverseProxyMode was introduce to avoid the LB exposing it's own web service when REST call was initiated
     */
    boolean reverseProxyMode = Boolean.parseBoolean(System.getProperty("reverseProxyMode"));
    AxisService axisService = null;
    if (!reverseProxyMode) {
        axisService = requestDispatcher.findService(msgContext);
    }
    boolean isCustomRESTDispatcher = false;
    if (requestURI.matches(NHttpConfiguration.getInstance().getRestUriApiRegex()) || requestURI.matches(NHttpConfiguration.getInstance().getRestUriProxyRegex())) {
        isCustomRESTDispatcher = true;
    }
    if (dispatching || !isCustomRESTDispatcher) {
        if (axisService == null) {
            String defaultSvcName = NHttpConfiguration.getInstance().getStringValue("nhttp.default.service", "__SynapseService");
            axisService = msgContext.getConfigurationContext().getAxisConfiguration().getService(defaultSvcName);
        }
        msgContext.setAxisService(axisService);
        // When receiving rest request axis2 checks whether axis operation is set in the message context to build
        // the request message. Therefore we have to set axis operation before we handed over request to axis
        // engine. If axis operation is already set in the message context take it from there. If not take the
        // axis operation from axis service.
        setAxisOperation(msgContext, axisService);
    } else {
        String multiTenantDispatchService = NHttpConfiguration.getInstance().getRESTDispatchService();
        axisService = msgContext.getConfigurationContext().getAxisConfiguration().getService(multiTenantDispatchService);
        msgContext.setAxisService(axisService);
        setAxisOperation(msgContext, axisService);
    }
}
Also used : AxisService(org.apache.axis2.description.AxisService) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Aggregations

EndpointReference (org.apache.axis2.addressing.EndpointReference)126 Options (org.apache.axis2.client.Options)49 ServiceClient (org.apache.axis2.client.ServiceClient)29 OMElement (org.apache.axiom.om.OMElement)26 AxisFault (org.apache.axis2.AxisFault)26 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)25 MessageContext (org.apache.axis2.context.MessageContext)25 MessageContext (org.apache.synapse.MessageContext)25 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)25 Map (java.util.Map)20 Test (org.junit.Test)14 URL (java.net.URL)13 HttpTransportProperties (org.apache.axis2.transport.http.HttpTransportProperties)13 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)13 QName (javax.xml.namespace.QName)12 AxisService (org.apache.axis2.description.AxisService)12 SOAPEnvelope (org.apache.axiom.soap.SOAPEnvelope)11 MalformedURLException (java.net.MalformedURLException)10 ArrayList (java.util.ArrayList)10 HashMap (java.util.HashMap)10