Search in sources :

Example 86 with URL

use of org.apache.axis2.util.URL 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 87 with URL

use of org.apache.axis2.util.URL 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 88 with URL

use of org.apache.axis2.util.URL 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)

Example 89 with URL

use of org.apache.axis2.util.URL in project wso2-synapse by wso2.

the class APIDeployerTest method testDeploy.

/**
 * Testing the deployment of an API
 *
 * @throws Exception
 */
@Test
public void testDeploy() throws Exception {
    String inputXML = "<api name=\"TestAPI\" context=\"/order\" xmlns=\"http://ws.apache.org/ns/synapse\">" + "<resource url-mapping=\"/list\" inSequence=\"seq1\" outSequence=\"seq2\" xmlns=\"http://ws.apache.org/ns/synapse\"/>" + "</api>";
    OMElement inputElement = AXIOMUtil.stringToOM(inputXML);
    APIDeployer apiDeployer = new APIDeployer();
    SynapseConfiguration synapseConfiguration = new SynapseConfiguration();
    AxisConfiguration axisConfiguration = synapseConfiguration.getAxisConfiguration();
    ConfigurationContext cfgCtx = new ConfigurationContext(axisConfiguration);
    SynapseEnvironment synapseEnvironment = new Axis2SynapseEnvironment(cfgCtx, synapseConfiguration);
    axisConfiguration.addParameter(new Parameter(SynapseConstants.SYNAPSE_ENV, synapseEnvironment));
    axisConfiguration.addParameter(new Parameter(SynapseConstants.SYNAPSE_CONFIG, synapseConfiguration));
    cfgCtx.setAxisConfiguration(axisConfiguration);
    apiDeployer.init(cfgCtx);
    String response = apiDeployer.deploySynapseArtifact(inputElement, "sampleFile", new Properties());
    Assert.assertEquals("API not deployed!", "TestAPI", response);
}
Also used : AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) Axis2SynapseEnvironment(org.apache.synapse.core.axis2.Axis2SynapseEnvironment) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) Axis2SynapseEnvironment(org.apache.synapse.core.axis2.Axis2SynapseEnvironment) Parameter(org.apache.axis2.description.Parameter) OMElement(org.apache.axiom.om.OMElement) SynapseConfiguration(org.apache.synapse.config.SynapseConfiguration) Properties(java.util.Properties) Test(org.junit.Test)

Example 90 with URL

use of org.apache.axis2.util.URL in project wso2-synapse by wso2.

the class APIDeployerTest method testUndeploy.

/**
 * Test undeploying an API
 *
 * @throws Exception
 */
@Test
public void testUndeploy() throws Exception {
    String inputXML = "<api name=\"TestAPI\" context=\"/order\" xmlns=\"http://ws.apache.org/ns/synapse\">" + "<resource url-mapping=\"/list\" inSequence=\"seq1\" outSequence=\"seq2\" xmlns=\"http://ws.apache.org/ns/synapse\"/>" + "</api>";
    OMElement inputElement = AXIOMUtil.stringToOM(inputXML);
    APIDeployer apiDeployer = new APIDeployer();
    SynapseConfiguration synapseConfiguration = new SynapseConfiguration();
    AxisConfiguration axisConfiguration = synapseConfiguration.getAxisConfiguration();
    ConfigurationContext cfgCtx = new ConfigurationContext(axisConfiguration);
    SynapseEnvironment synapseEnvironment = new Axis2SynapseEnvironment(cfgCtx, synapseConfiguration);
    axisConfiguration.addParameter(new Parameter(SynapseConstants.SYNAPSE_ENV, synapseEnvironment));
    axisConfiguration.addParameter(new Parameter(SynapseConstants.SYNAPSE_CONFIG, synapseConfiguration));
    cfgCtx.setAxisConfiguration(axisConfiguration);
    apiDeployer.init(cfgCtx);
    apiDeployer.deploySynapseArtifact(inputElement, "sampleFile", new Properties());
    Assert.assertNotNull("API not deployed!", synapseConfiguration.getAPI("TestAPI"));
    apiDeployer.undeploySynapseArtifact("TestAPI");
    Assert.assertNull("Api cannot be undeployed!", synapseConfiguration.getAPI("TestAPI"));
}
Also used : AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) Axis2SynapseEnvironment(org.apache.synapse.core.axis2.Axis2SynapseEnvironment) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) Axis2SynapseEnvironment(org.apache.synapse.core.axis2.Axis2SynapseEnvironment) Parameter(org.apache.axis2.description.Parameter) OMElement(org.apache.axiom.om.OMElement) SynapseConfiguration(org.apache.synapse.config.SynapseConfiguration) Properties(java.util.Properties) Test(org.junit.Test)

Aggregations

IOException (java.io.IOException)31 EndpointReference (org.apache.axis2.addressing.EndpointReference)29 AxisFault (org.apache.axis2.AxisFault)27 URL (java.net.URL)21 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)19 URL (org.apache.axis2.util.URL)19 HttpClient (org.apache.http.client.HttpClient)19 Options (org.apache.axis2.client.Options)18 MalformedURLException (java.net.MalformedURLException)17 OMElement (org.apache.axiom.om.OMElement)17 MessageContext (org.apache.axis2.context.MessageContext)16 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)16 ServiceClient (org.apache.axis2.client.ServiceClient)13 SynapseException (org.apache.synapse.SynapseException)13 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)12 AxisService (org.apache.axis2.description.AxisService)10 StringEntity (org.apache.http.entity.StringEntity)9 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)9 Map (java.util.Map)7 JSONObject (org.json.JSONObject)7