Search in sources :

Example 96 with URL

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

the class StockQuoteClient method executeClient.

public static void executeClient() throws Exception {
    // defaults
    String symbol = getProperty("symbol", "IBM");
    String soapVer = getProperty("soapver", "soap11");
    String mode = getProperty("mode", "quote");
    String addUrl = getProperty("addurl", null);
    String trpUrl = getProperty("trpurl", null);
    String prxUrl = getProperty("prxurl", null);
    String repo = getProperty("repository", "client_repo");
    String svcPolicy = getProperty("policy", null);
    String rest = getProperty("rest", null);
    String wsrm = getProperty("wsrm", null);
    String wsrm11 = getProperty("wsrm11", null);
    String itr = getProperty("itr", "1");
    int iterations = 1;
    boolean infinite = false;
    String pIterations = getProperty("i", null);
    if (pIterations != null) {
        try {
            iterations = Integer.parseInt(pIterations);
            if (iterations != -1) {
                infinite = false;
            }
        } catch (NumberFormatException e) {
        // run with default values
        }
    }
    double price = 0;
    int quantity = 0;
    ConfigurationContext configContext = null;
    Options options = new Options();
    OMElement payload = null;
    ServiceClient serviceClient;
    if (repo != null && !"null".equals(repo)) {
        configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(repo, repo + File.separator + "conf" + File.separator + "axis2.xml");
        serviceClient = new ServiceClient(configContext, null);
    } else {
        serviceClient = new ServiceClient();
    }
    if ("customquote".equals(mode)) {
        payload = StockQuoteHandler.createCustomQuoteRequest(symbol);
        options.setAction("urn:getQuote");
    } else if ("fullquote".equals(mode)) {
        payload = StockQuoteHandler.createFullQuoteRequest(symbol);
        options.setAction("urn:getFullQuote");
    } else if ("placeorder".equals(mode)) {
        price = getRandom(100, 0.9, true);
        quantity = (int) getRandom(10000, 1.0, true);
        payload = StockQuoteHandler.createPlaceOrderRequest(price, quantity, symbol);
        options.setAction("urn:placeOrder");
    } else if ("marketactivity".equals(mode)) {
        payload = StockQuoteHandler.createMarketActivityRequest();
        options.setAction("urn:getMarketActivity");
    } else if ("quote".equals(mode) || "dualquote".equals(mode)) {
        payload = StockQuoteHandler.createStandardQuoteRequest(symbol, Integer.parseInt(itr));
        options.setAction("urn:getQuote");
        if ("dualquote".equals(mode)) {
            serviceClient.engageModule("addressing");
            options.setUseSeparateListener(true);
        }
    }
    // set addressing, transport and proxy url
    if (addUrl != null && !"null".equals(addUrl)) {
        serviceClient.engageModule("addressing");
        options.setTo(new EndpointReference(addUrl));
    }
    if (trpUrl != null && !"null".equals(trpUrl)) {
        options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl);
    }
    if (prxUrl != null && !"null".equals(prxUrl)) {
        HttpTransportProperties.ProxyProperties proxyProperties = new HttpTransportProperties.ProxyProperties();
        URL url = new URL(prxUrl);
        proxyProperties.setProxyName(url.getHost());
        proxyProperties.setProxyPort(url.getPort());
        proxyProperties.setUserName("");
        proxyProperties.setPassWord("");
        proxyProperties.setDomain("");
        options.setProperty(HTTPConstants.PROXY, proxyProperties);
    }
    // apply any service policies if any
    if (svcPolicy != null && !"null".equals(svcPolicy) && svcPolicy.length() > 0) {
        System.out.println("Using WS-Security");
        serviceClient.engageModule("addressing");
        serviceClient.engageModule("rampart");
        options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy(svcPolicy));
    }
    if (Boolean.parseBoolean(rest)) {
        System.out.println("Sending as REST");
        options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE);
    }
    if (Boolean.parseBoolean(wsrm) || Boolean.parseBoolean(wsrm11)) {
        System.out.println("Using WS-RM");
        serviceClient.engageModule("sandesha2");
        if (Boolean.parseBoolean(wsrm11)) {
            options.setProperty(SandeshaClientConstants.RM_SPEC_VERSION, Sandesha2Constants.SPEC_VERSIONS.v1_1);
        }
        options.setProperty(SandeshaClientConstants.LAST_MESSAGE, Constants.VALUE_TRUE);
        options.setProperty(SandeshaClientConstants.OFFERED_SEQUENCE_ID, UIDGenerator.generateURNString());
    }
    if ("soap12".equals(soapVer)) {
        options.setSoapVersionURI(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    }
    serviceClient.setOptions(options);
    InnerStruct.MODE = mode;
    InnerStruct.SYMBOL = symbol;
    InnerStruct.PRICE = price;
    InnerStruct.QUANTITY = quantity;
    if ("placeorder".equals(mode)) {
        serviceClient.fireAndForget(payload);
        Thread.sleep(5000);
    } else if ("dualquote".equals(mode)) {
        serviceClient.sendReceiveNonBlocking(payload, new StockQuoteCallback());
        printResult();
    } else {
        long i = 0;
        while (i < iterations || infinite) {
            InnerStruct.RESULT = serviceClient.sendReceive(payload);
            i++;
            printResult();
            if (Boolean.parseBoolean(wsrm) || Boolean.parseBoolean(wsrm11)) {
                // give some time for RM to terminate normally
                if (Boolean.parseBoolean(wsrm11)) {
                    SandeshaClient.terminateSequence(serviceClient);
                }
                Thread.sleep(5000);
                if (configContext != null) {
                    configContext.getListenerManager().stop();
                }
                serviceClient.cleanup();
            }
        }
    }
}
Also used : ConfigurationContext(org.apache.axis2.context.ConfigurationContext) Options(org.apache.axis2.client.Options) HttpTransportProperties(org.apache.axis2.transport.http.HttpTransportProperties) OMElement(org.apache.axiom.om.OMElement) URL(java.net.URL) EndpointReference(org.apache.axis2.addressing.EndpointReference) ServiceClient(org.apache.axis2.client.ServiceClient)

Example 97 with URL

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

the class EventSender method executeClient.

public static void executeClient() throws Exception {
    Options options = new Options();
    ServiceClient serviceClient;
    ConfigurationContext configContext = null;
    String addUrl = getProperty("addurl", "http://localhost:8280/services/EventingProxy");
    String repo = getProperty("repository", "client_repo");
    String symbol = getProperty("symbol", "GOOG");
    String price = getProperty("price", "10.10");
    String qty = getProperty("qty", "1000");
    String topic = getProperty("topic", "synapse/event/test");
    String action = getProperty("action", "urn:event");
    String topicns = getProperty("topicns", "http://apache.org/aip");
    if (repo != null && !"null".equals(repo)) {
        configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(repo, repo + File.separator + "conf" + File.separator + "axis2.xml");
        serviceClient = new ServiceClient(configContext, null);
    } else {
        serviceClient = new ServiceClient();
    }
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace nsaip = factory.createOMNamespace(topicns, "aip");
    // set the target topic
    OMElement topicOm = factory.createOMElement("Topic", nsaip);
    factory.createOMText(topicOm, topic);
    // set addressing, transport and proxy url
    serviceClient.engageModule("addressing");
    options.setTo(new EndpointReference(addUrl));
    options.setAction(action);
    options.setProperty(MessageContext.CLIENT_API_NON_BLOCKING, // set for fire and foget
    Boolean.FALSE);
    serviceClient.setOptions(options);
    serviceClient.addHeader(topicOm);
    OMElement payload = AXIOMUtil.stringToOM("<m:placeOrder xmlns:m=\"http://services.samples\">\n" + "    <m:order>\n" + "        <m:price>" + price + "</m:price>\n" + "        <m:quantity>" + qty + "</m:quantity>\n" + "        <m:symbol>" + symbol + "</m:symbol>\n" + "    </m:order>\n" + "</m:placeOrder>");
    System.out.println("Sending Event : \n" + payload.toString());
    serviceClient.fireAndForget(payload);
    System.out.println("Event sent to topic " + topic);
    Thread.sleep(1000);
    if (configContext != null) {
        configContext.terminate();
    }
}
Also used : OMFactory(org.apache.axiom.om.OMFactory) Options(org.apache.axis2.client.Options) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) OMNamespace(org.apache.axiom.om.OMNamespace) ServiceClient(org.apache.axis2.client.ServiceClient) OMElement(org.apache.axiom.om.OMElement) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 98 with URL

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

the class FIXClient method executeClient.

public static void executeClient() throws Exception {
    Options options = new Options();
    ServiceClient serviceClient;
    ConfigurationContext configContext = null;
    String symbol = getProperty("symbol", "IBM");
    String mode = getProperty("mode", "buy");
    String addUrl = getProperty("addurl", null);
    String trpUrl = getProperty("trpurl", null);
    String prxUrl = getProperty("prxurl", null);
    String repo = getProperty("repository", "client_repo");
    String qty = getProperty("qty", "1");
    String side = "1";
    if (mode.equals("sell")) {
        side = "2";
    }
    if (repo != null && !"null".equals(repo)) {
        configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(repo, repo + File.separator + "conf" + File.separator + "axis2.xml");
        serviceClient = new ServiceClient(configContext, null);
    } else {
        serviceClient = new ServiceClient();
    }
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMElement message = factory.createOMElement("message", null);
    message.addChild(getHeader(factory));
    message.addChild(getBody(factory, symbol, side, qty));
    message.addChild(factory.createOMElement("trailer", null));
    // set addressing, transport and proxy url
    if (addUrl != null && !"null".equals(addUrl)) {
        serviceClient.engageModule("addressing");
        options.setTo(new EndpointReference(addUrl));
    }
    if (trpUrl != null && !"null".equals(trpUrl)) {
        options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl);
    }
    if (prxUrl != null && !"null".equals(prxUrl)) {
        HttpTransportProperties.ProxyProperties proxyProperties = new HttpTransportProperties.ProxyProperties();
        URL url = new URL(prxUrl);
        proxyProperties.setProxyName(url.getHost());
        proxyProperties.setProxyPort(url.getPort());
        proxyProperties.setUserName("");
        proxyProperties.setPassWord("");
        proxyProperties.setDomain("");
        options.setProperty(HTTPConstants.PROXY, proxyProperties);
    }
    options.setAction("urn:mediate");
    serviceClient.setOptions(options);
    OMElement response = serviceClient.sendReceive(message);
    Thread.sleep(5000);
    System.out.println("Response Received: " + response.toString());
    try {
        if (configContext != null) {
            configContext.terminate();
        }
    } catch (Exception ignore) {
    }
}
Also used : OMFactory(org.apache.axiom.om.OMFactory) Options(org.apache.axis2.client.Options) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) HttpTransportProperties(org.apache.axis2.transport.http.HttpTransportProperties) ServiceClient(org.apache.axis2.client.ServiceClient) OMElement(org.apache.axiom.om.OMElement) URL(java.net.URL) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 99 with URL

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

the class Axis2FlexibleMEPClient method send.

/**
 * Based on the Axis2 client code. Sends the Axis2 Message context out and returns
 * the Axis2 message context for the response.
 * <p/>
 * Here Synapse works as a Client to the service. It would expect 200 ok, 202 ok and
 * 500 internal server error as possible responses.
 *
 * @param endpoint                 the endpoint being sent to, maybe null
 * @param synapseOutMessageContext the outgoing synapse message
 * @throws AxisFault on errors
 */
public static void send(EndpointDefinition endpoint, org.apache.synapse.MessageContext synapseOutMessageContext) throws AxisFault {
    if (synapseOutMessageContext.getProperty(SynapseConstants.BLOCKING_MSG_SENDER) != null) {
        BlockingMsgSender blockingMsgSender = (BlockingMsgSender) synapseOutMessageContext.getProperty(SynapseConstants.BLOCKING_MSG_SENDER);
        blockingMsgSender.send(endpoint, synapseOutMessageContext);
        return;
    }
    boolean separateListener = false;
    boolean wsSecurityEnabled = false;
    String wsSecPolicyKey = null;
    String inboundWsSecPolicyKey = null;
    String outboundWsSecPolicyKey = null;
    boolean wsRMEnabled = false;
    boolean wsAddressingEnabled = false;
    String wsAddressingVersion = null;
    if (endpoint != null) {
        separateListener = endpoint.isUseSeparateListener();
        wsSecurityEnabled = endpoint.isSecurityOn();
        wsSecPolicyKey = endpoint.getWsSecPolicyKey();
        inboundWsSecPolicyKey = endpoint.getInboundWsSecPolicyKey();
        outboundWsSecPolicyKey = endpoint.getOutboundWsSecPolicyKey();
        wsAddressingEnabled = endpoint.isAddressingOn();
        wsAddressingVersion = endpoint.getAddressingVersion();
    }
    if (log.isDebugEnabled()) {
        String to;
        if (endpoint != null && endpoint.getAddress() != null) {
            to = endpoint.getAddress(synapseOutMessageContext);
        } else {
            to = synapseOutMessageContext.getTo().toString();
        }
        log.debug("Sending [add = " + wsAddressingEnabled + "] [sec = " + wsSecurityEnabled + (endpoint != null ? "] [mtom = " + endpoint.isUseMTOM() + "] [swa = " + endpoint.isUseSwa() + "] [format = " + endpoint.getFormat() + "] [force soap11=" + endpoint.isForceSOAP11() + "] [force soap12=" + endpoint.isForceSOAP12() + "] [pox=" + endpoint.isForcePOX() + "] [get=" + endpoint.isForceGET() + "] [encoding=" + endpoint.getCharSetEncoding() : "") + "] [to=" + to + "]");
    }
    // save the original message context without altering it, so we can tie the response
    MessageContext originalInMsgCtx = ((Axis2MessageContext) synapseOutMessageContext).getAxis2MessageContext();
    // TODO Temp hack: ESB removes the session id from request in a random manner.
    Map headers = (Map) originalInMsgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
    String session = (String) synapseOutMessageContext.getProperty("LB_COOKIE_HEADER");
    if (session != null) {
        headers.put("Cookie", session);
    }
    if (originalInMsgCtx.getProperty(CorrelationConstants.CORRELATION_ID) == null) {
        originalInMsgCtx.setProperty(CorrelationConstants.CORRELATION_ID, UUID.randomUUID().toString());
    }
    if (headers == null) {
        headers = new HashMap();
        originalInMsgCtx.setProperty(MessageContext.TRANSPORT_HEADERS, headers);
    }
    Object status = originalInMsgCtx.getProperty(NhttpConstants.ACTIVITY_ID_STATUS);
    if ((status != null) && ((boolean) status)) {
        headers.put(PassThroughConfiguration.getInstance().getCorrelationHeaderName(), originalInMsgCtx.getProperty(CorrelationConstants.CORRELATION_ID).toString());
    }
    // create a new MessageContext to be sent out as this should not corrupt the original
    // we need to create the response to the original message later on
    String preserveAddressingProperty = (String) synapseOutMessageContext.getProperty(SynapseConstants.PRESERVE_WS_ADDRESSING);
    MessageContext axisOutMsgCtx = cloneForSend(originalInMsgCtx, preserveAddressingProperty);
    // set "INTERNAL_TRANSACTION_COUNTED" property in axisOutMsgCtx's message context.
    axisOutMsgCtx.setProperty(BaseConstants.INTERNAL_TRANSACTION_COUNTED, originalInMsgCtx.getProperty(BaseConstants.INTERNAL_TRANSACTION_COUNTED));
    Object TRIGGER_NAME;
    if ((TRIGGER_NAME = synapseOutMessageContext.getProperty(SynapseConstants.PROXY_SERVICE)) != null) {
        axisOutMsgCtx.setProperty(PassThroughConstants.INTERNAL_TRIGGER_TYPE, SynapseConstants.PROXY_SERVICE_TYPE);
        axisOutMsgCtx.setProperty(PassThroughConstants.INTERNAL_TRIGGER_NAME, TRIGGER_NAME.toString());
    } else if ((TRIGGER_NAME = synapseOutMessageContext.getProperty(RESTConstants.SYNAPSE_REST_API)) != null) {
        axisOutMsgCtx.setProperty(PassThroughConstants.INTERNAL_TRIGGER_TYPE, SynapseConstants.FAIL_SAFE_MODE_API);
        axisOutMsgCtx.setProperty(PassThroughConstants.INTERNAL_TRIGGER_NAME, TRIGGER_NAME.toString());
    } else if ((TRIGGER_NAME = synapseOutMessageContext.getProperty(SynapseConstants.INBOUND_ENDPOINT_NAME)) != null) {
        axisOutMsgCtx.setProperty(PassThroughConstants.INTERNAL_TRIGGER_TYPE, SynapseConstants.FAIL_SAFE_MODE_INBOUND_ENDPOINT);
        axisOutMsgCtx.setProperty(PassThroughConstants.INTERNAL_TRIGGER_NAME, TRIGGER_NAME.toString());
    } else {
        axisOutMsgCtx.setProperty(PassThroughConstants.INTERNAL_TRIGGER_TYPE, "anonymous");
        axisOutMsgCtx.setProperty(PassThroughConstants.INTERNAL_TRIGGER_NAME, "anonymous");
    }
    if (log.isDebugEnabled()) {
        log.debug("Message [Original Request Message ID : " + synapseOutMessageContext.getMessageID() + "]" + " [New Cloned Request Message ID : " + axisOutMsgCtx.getMessageID() + "]");
    }
    // so that we can use the original message context for resending through different endpoints
    if (endpoint != null) {
        // get the endpoint encoding attribute
        String strCharSetEncoding = "";
        if (endpoint.getCharSetEncoding() != null) {
            strCharSetEncoding = ";" + endpoint.getCharSetEncoding();
        }
        if (SynapseConstants.FORMAT_POX.equals(endpoint.getFormat())) {
            axisOutMsgCtx.setDoingREST(true);
            axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);
            axisOutMsgCtx.setProperty(Constants.Configuration.CONTENT_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);
            Object o = axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            Map _headers = (Map) o;
            if (_headers != null) {
                _headers.remove(HTTP.CONTENT_TYPE);
                _headers.put(HTTP.CONTENT_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML + strCharSetEncoding);
            }
        } else if (SynapseConstants.FORMAT_GET.equals(endpoint.getFormat())) {
            axisOutMsgCtx.setDoingREST(true);
            axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_GET);
            axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_X_WWW_FORM);
        } else if (SynapseConstants.FORMAT_SOAP11.equals(endpoint.getFormat())) {
            axisOutMsgCtx.setDoingREST(false);
            axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
            // We need to set this explicitly here in case the request was not a POST
            axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_POST);
            if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) {
                axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction());
            }
            // If the incoming is rest, then message need to be serialized prior to the conversion.
            if (originalInMsgCtx.isDoingREST()) {
                try {
                    MediatorPropertyUtils.serializeOMElement(synapseOutMessageContext);
                } catch (Exception e) {
                    handleException("Error while serializing the  message", e);
                }
            }
            if (!axisOutMsgCtx.isSOAP11()) {
                SOAPUtils.convertSOAP12toSOAP11(axisOutMsgCtx);
            }
            Object o = axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            Map transportHeaders = (Map) o;
            if (transportHeaders != null) {
                // Fix ESBJAVA-3645 Should not do this for multipart/related
                String trpContentType = (String) transportHeaders.get(HTTP.CONTENT_TYPE);
                // if content type is not found, setting the content type
                if (trpContentType == null) {
                    transportHeaders.put(HTTP.CONTENT_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_TEXT_XML + strCharSetEncoding);
                } else if (!trpContentType.contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) {
                    transportHeaders.remove(HTTP.CONTENT_TYPE);
                    try {
                        // ESBJAVA-3447, Appending charset, if exist in property
                        ContentType contentType = new ContentType(trpContentType);
                        if (contentType.getParameter(HTTPConstants.CHAR_SET_ENCODING) != null) {
                            strCharSetEncoding = "; charset=" + contentType.getParameter(HTTPConstants.CHAR_SET_ENCODING);
                        }
                    } catch (ParseException e) {
                        log.warn("Error occurred while parsing ContentType header, using default: " + HTTPConstants.MEDIA_TYPE_TEXT_XML);
                    }
                    transportHeaders.put(HTTP.CONTENT_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_TEXT_XML + strCharSetEncoding);
                }
            }
        } else if (SynapseConstants.FORMAT_SOAP12.equals(endpoint.getFormat())) {
            axisOutMsgCtx.setDoingREST(false);
            axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
            // We need to set this explicitly here in case the request was not a POST
            axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_POST);
            if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) {
                axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction());
            }
            if (axisOutMsgCtx.isSOAP11()) {
                SOAPUtils.convertSOAP11toSOAP12(axisOutMsgCtx);
            }
            Object o = axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            Map transportHeaders = (Map) o;
            if (transportHeaders != null) {
                // Fix ESBJAVA-3645 Should not do this for multipart/related
                String trpContentType = (String) transportHeaders.get(HTTP.CONTENT_TYPE);
                // if content type is not found, setting the content type
                if (trpContentType == null) {
                    transportHeaders.put(HTTP.CONTENT_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML + strCharSetEncoding);
                } else if (!trpContentType.contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) {
                    transportHeaders.remove(HTTP.CONTENT_TYPE);
                    try {
                        // ESBJAVA-3447, Appending charset, if exist in property
                        ContentType contentType = new ContentType(trpContentType);
                        if (contentType.getParameter(HTTPConstants.CHAR_SET_ENCODING) != null) {
                            strCharSetEncoding = "; charset=" + contentType.getParameter(HTTPConstants.CHAR_SET_ENCODING);
                        }
                    } catch (ParseException e) {
                        log.warn("Error occurred while parsing ContentType header in property, using default: " + HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML);
                    }
                    if (axisOutMsgCtx.getSoapAction() != null) {
                        String actionHeaderPrefix = ";action=\"";
                        String contentTypeWithAction = new StringBuilder(org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML.length() + axisOutMsgCtx.getSoapAction().length() + actionHeaderPrefix.length() + 1).append(org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML).append(actionHeaderPrefix).append(axisOutMsgCtx.getSoapAction()).append('\"').toString();
                        transportHeaders.put(HTTP.CONTENT_TYPE, contentTypeWithAction + strCharSetEncoding);
                    } else {
                        transportHeaders.put(HTTP.CONTENT_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML + strCharSetEncoding);
                    }
                }
            }
        } else if (SynapseConstants.FORMAT_REST.equals(endpoint.getFormat())) {
            /* Remove Message Type  for GET and DELETE Request */
            if (originalInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD) != null) {
                if (originalInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD).toString().equals(Constants.Configuration.HTTP_METHOD_GET) || originalInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD).toString().equals(Constants.Configuration.HTTP_METHOD_DELETE)) {
                    axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
                }
            }
            axisOutMsgCtx.setDoingREST(true);
        } else {
            processWSDL2RESTRequestMessageType(originalInMsgCtx, axisOutMsgCtx);
        }
        if (endpoint.isUseMTOM()) {
            axisOutMsgCtx.setDoingMTOM(true);
            // fix / workaround for AXIS2-1798
            axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM, org.apache.axis2.Constants.VALUE_TRUE);
            axisOutMsgCtx.setDoingMTOM(true);
            // Remove the Content-Type transport header if it is not multipart/related to honor the content
            // type extracted from the SOAPMessageFormatter
            Object trpHeaders = axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
            if (trpHeaders != null && trpHeaders instanceof Map && ((Map) trpHeaders).get(HTTPConstants.HEADER_CONTENT_TYPE) != null && !isMultipartContent(((Map) trpHeaders).get(HTTPConstants.HEADER_CONTENT_TYPE).toString())) {
                ((Map) trpHeaders).remove(HTTPConstants.HEADER_CONTENT_TYPE);
            }
        } else if (endpoint.isUseSwa()) {
            axisOutMsgCtx.setDoingSwA(true);
            // fix / workaround for AXIS2-1798
            axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_SWA, org.apache.axis2.Constants.VALUE_TRUE);
            axisOutMsgCtx.setDoingSwA(true);
        }
        if (endpoint.getCharSetEncoding() != null) {
            axisOutMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, endpoint.getCharSetEncoding());
        }
        // HTTP Endpoint : use the specified HTTP method and remove REST_URL_POSTFIX, it's not supported in HTTP Endpoint
        if (endpoint.isHTTPEndpoint()) {
            axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, synapseOutMessageContext.getProperty(Constants.Configuration.HTTP_METHOD));
            axisOutMsgCtx.removeProperty(NhttpConstants.REST_URL_POSTFIX);
        }
        // add rest request' suffix URI
        String restSuffix = (String) axisOutMsgCtx.getProperty(NhttpConstants.REST_URL_POSTFIX);
        boolean isRest = SynapseConstants.FORMAT_REST.equals(endpoint.getFormat());
        if (!isRest && !endpoint.isForceSOAP11() && !endpoint.isForceSOAP12()) {
            isRest = isRequestRest(originalInMsgCtx);
        }
        if (endpoint.getAddress() != null) {
            String address = endpoint.getAddress(synapseOutMessageContext);
            if (isRest && restSuffix != null && !"".equals(restSuffix)) {
                String url = "";
                if (!address.endsWith("/") && !restSuffix.startsWith("/") && !restSuffix.startsWith("?")) {
                    url = address + "/" + restSuffix;
                } else if (address.endsWith("/") && restSuffix.startsWith("/")) {
                    url = address + restSuffix.substring(1);
                } else if (address.endsWith("/") && restSuffix.startsWith("?")) {
                    url = address.substring(0, address.length() - 1) + restSuffix;
                } else {
                    if (!address.startsWith("jms")) {
                        url = address + restSuffix;
                    } else {
                        url = address;
                    }
                }
                axisOutMsgCtx.setTo(new EndpointReference(url));
            } else {
                axisOutMsgCtx.setTo(new EndpointReference(address));
            }
            axisOutMsgCtx.setProperty(NhttpConstants.ENDPOINT_PREFIX, address);
            synapseOutMessageContext.setProperty(SynapseConstants.ENDPOINT_PREFIX, address);
        } else {
            // Supporting RESTful invocation
            if (isRest && restSuffix != null && !"".equals(restSuffix)) {
                EndpointReference epr = axisOutMsgCtx.getTo();
                if (epr != null) {
                    String address = epr.getAddress();
                    String url;
                    if (!address.endsWith("/") && !restSuffix.startsWith("/") && !restSuffix.startsWith("?")) {
                        url = address + "/" + restSuffix;
                    } else {
                        url = address + restSuffix;
                    }
                    axisOutMsgCtx.setTo(new EndpointReference(url));
                }
            }
        }
        // Update To url if mock-service exists for unit test
        MediatorPropertyUtils.updateSendToUrlForMockServices(endpoint, synapseOutMessageContext, axisOutMsgCtx);
        if (endpoint.isUseSeparateListener()) {
            axisOutMsgCtx.getOptions().setUseSeparateListener(true);
        }
    } else {
        processWSDL2RESTRequestMessageType(originalInMsgCtx, axisOutMsgCtx);
    }
    // only put whttp:location for the REST (GET) requests, otherwise causes issues for POX messages
    if (axisOutMsgCtx.isDoingREST() && HTTPConstants.MEDIA_TYPE_X_WWW_FORM.equals(axisOutMsgCtx.getProperty(Constants.Configuration.MESSAGE_TYPE))) {
        if (axisOutMsgCtx.getProperty(WSDL2Constants.ATTR_WHTTP_LOCATION) == null && axisOutMsgCtx.getEnvelope().getBody().getFirstElement() != null) {
            axisOutMsgCtx.setProperty(WSDL2Constants.ATTR_WHTTP_LOCATION, axisOutMsgCtx.getEnvelope().getBody().getFirstElement().getQName().getLocalPart());
        }
    }
    if (wsAddressingEnabled) {
        if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_SUBMISSION.equals(wsAddressingVersion)) {
            axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Submission.WSA_NAMESPACE);
        } else if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_FINAL.equals(wsAddressingVersion)) {
            axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Final.WSA_NAMESPACE);
        }
        axisOutMsgCtx.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.FALSE);
    } else {
        axisOutMsgCtx.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE);
    }
    // remove the headers if we don't need to preserve them.
    // determine weather we need to preserve the processed headers
    String preserveHeaderProperty = (String) synapseOutMessageContext.getProperty(SynapseConstants.PRESERVE_PROCESSED_HEADERS);
    if (preserveHeaderProperty == null || !Boolean.parseBoolean(preserveHeaderProperty)) {
        // default behaviour is to remove the headers
        MessageHelper.removeProcessedHeaders(axisOutMsgCtx, (preserveAddressingProperty != null && Boolean.parseBoolean(preserveAddressingProperty)));
    }
    ConfigurationContext axisCfgCtx = axisOutMsgCtx.getConfigurationContext();
    AxisConfiguration axisCfg = axisCfgCtx.getAxisConfiguration();
    AxisService anoymousService = AnonymousServiceFactory.getAnonymousService(synapseOutMessageContext.getConfiguration(), axisCfg, wsAddressingEnabled, wsRMEnabled, wsSecurityEnabled);
    // mark the anon services created to be used in the client side of synapse as hidden
    // from the server side of synapse point of view
    anoymousService.getParent().addParameter(SynapseConstants.HIDDEN_SERVICE_PARAM, "true");
    ServiceGroupContext sgc = new ServiceGroupContext(axisCfgCtx, (AxisServiceGroup) anoymousService.getParent());
    ServiceContext serviceCtx = sgc.getServiceContext(anoymousService);
    boolean outOnlyMessage = "true".equals(synapseOutMessageContext.getProperty(SynapseConstants.OUT_ONLY));
    // get a reference to the DYNAMIC operation of the Anonymous Axis2 service
    AxisOperation axisAnonymousOperation = anoymousService.getOperation(outOnlyMessage ? new QName(AnonymousServiceFactory.OUT_ONLY_OPERATION) : new QName(AnonymousServiceFactory.OUT_IN_OPERATION));
    Options clientOptions = MessageHelper.cloneOptions(originalInMsgCtx.getOptions());
    clientOptions.setUseSeparateListener(separateListener);
    // if security is enabled,
    if (wsSecurityEnabled) {
        // if a WS-Sec policy is specified, use it
        if (wsSecPolicyKey != null) {
            if (endpoint.isDynamicPolicy()) {
                wsSecPolicyKey = endpoint.evaluateDynamicEndpointSecurityPolicy(synapseOutMessageContext);
            }
            clientOptions.setProperty(SynapseConstants.RAMPART_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, wsSecPolicyKey));
        } else {
            if (inboundWsSecPolicyKey != null) {
                clientOptions.setProperty(SynapseConstants.RAMPART_IN_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, inboundWsSecPolicyKey));
            }
            if (outboundWsSecPolicyKey != null) {
                clientOptions.setProperty(SynapseConstants.RAMPART_OUT_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, outboundWsSecPolicyKey));
            }
        }
        // temporary workaround for https://issues.apache.org/jira/browse/WSCOMMONS-197
        if (axisOutMsgCtx.getEnvelope().getHeader() == null) {
            SOAPFactory fac = axisOutMsgCtx.isSOAP11() ? OMAbstractFactory.getSOAP11Factory() : OMAbstractFactory.getSOAP12Factory();
            fac.createSOAPHeader(axisOutMsgCtx.getEnvelope());
        }
    }
    OperationClient mepClient = axisAnonymousOperation.createClient(serviceCtx, clientOptions);
    mepClient.addMessageContext(axisOutMsgCtx);
    axisOutMsgCtx.setAxisMessage(axisAnonymousOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE));
    // set the SEND_TIMEOUT for transport sender
    if (endpoint != null && endpoint.getEffectiveTimeout() > 0) {
        if (!endpoint.isDynamicTimeoutEndpoint()) {
            axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.getEffectiveTimeout());
        } else {
            axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.evaluateDynamicEndpointTimeout(synapseOutMessageContext));
        }
    }
    // always set a callback as we decide if the send it blocking or non blocking within
    // the MEP client. This does not cause an overhead, as we simply create a 'holder'
    // object with a reference to the outgoing synapse message context
    // synapseOutMessageContext
    AsyncCallback callback = new AsyncCallback(axisOutMsgCtx, synapseOutMessageContext);
    if (!outOnlyMessage) {
        if (endpoint != null) {
            // TimeoutHandler can detect timed out callbacks and take appropriate action.
            if (!endpoint.isDynamicTimeoutEndpoint()) {
                long endpointTimeout = endpoint.getEffectiveTimeout();
                callback.setTimeout(endpointTimeout);
                callback.setTimeOutAction(endpoint.getTimeoutAction());
                callback.setTimeoutType(endpoint.getEndpointTimeoutType());
                if (log.isDebugEnabled()) {
                    log.debug("Setting Timeout for endpoint : " + getEndpointLogMessage(synapseOutMessageContext, axisOutMsgCtx) + " to static timeout value : " + endpointTimeout);
                }
            } else {
                long endpointTimeout = endpoint.evaluateDynamicEndpointTimeout(synapseOutMessageContext);
                callback.setTimeout(endpointTimeout);
                callback.setTimeOutAction(endpoint.getTimeoutAction());
                callback.setTimeoutType(endpoint.getEndpointTimeoutType());
                if (log.isDebugEnabled()) {
                    log.debug("Setting Timeout for endpoint : " + getEndpointLogMessage(synapseOutMessageContext, axisOutMsgCtx) + " to dynamic timeout value : " + endpointTimeout);
                }
            }
        } else {
            long globalTimeout = synapseOutMessageContext.getEnvironment().getGlobalTimeout();
            callback.setTimeout(globalTimeout);
            callback.setTimeoutType(SynapseConstants.ENDPOINT_TIMEOUT_TYPE.GLOBAL_TIMEOUT);
            if (log.isDebugEnabled()) {
                log.debug("Setting timeout for implicit endpoint : " + getEndpointLogMessage(synapseOutMessageContext, axisOutMsgCtx) + " to global timeout value of " + globalTimeout);
            }
        }
    }
    mepClient.setCallback(callback);
    // HTTP 1.1 messages and HTTP 1.0 require the whole message to caculate the content length
    if (originalInMsgCtx.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0)) {
        synapseOutMessageContext.getEnvelope().toString();
    }
    // with the nio transport, this causes the listener not to write a 202
    // Accepted response, as this implies that Synapse does not yet know if
    // a 202 or 200 response would be written back.
    originalInMsgCtx.getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP");
    // if the transport out is explicitly set use it
    Object o = originalInMsgCtx.getProperty("TRANSPORT_OUT_DESCRIPTION");
    if (o != null && o instanceof TransportOutDescription) {
        axisOutMsgCtx.setTransportOut((TransportOutDescription) o);
        clientOptions.setTransportOut((TransportOutDescription) o);
        clientOptions.setProperty("TRANSPORT_OUT_DESCRIPTION", o);
    }
    // clear the message context properties related to endpoint in last service invocation
    Set keySet = synapseOutMessageContext.getPropertyKeySet();
    if (keySet != null) {
        keySet.remove(EndpointDefinition.DYNAMIC_URL_VALUE);
    }
    // throttling count for OUT_ONLY messages
    if (outOnlyMessage) {
        Boolean isConcurrencyThrottleEnabled = (Boolean) synapseOutMessageContext.getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE);
        if (isConcurrencyThrottleEnabled != null && isConcurrencyThrottleEnabled) {
            ConcurrentAccessController concurrentAccessController = (ConcurrentAccessController) synapseOutMessageContext.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) synapseOutMessageContext.getProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_REPLICATOR);
            String throttleKey = (String) synapseOutMessageContext.getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE_KEY);
            if (concurrentAccessReplicator != null) {
                concurrentAccessReplicator.replicate(throttleKey, true);
            }
        }
    }
    mepClient.execute(true);
}
Also used : AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) Options(org.apache.axis2.client.Options) Set(java.util.Set) ContentType(javax.mail.internet.ContentType) AxisOperation(org.apache.axis2.description.AxisOperation) HashMap(java.util.HashMap) AxisService(org.apache.axis2.description.AxisService) SOAPFactory(org.apache.axiom.soap.SOAPFactory) ConcurrentAccessController(org.apache.synapse.commons.throttle.core.ConcurrentAccessController) MessageContext(org.apache.axis2.context.MessageContext) TransportOutDescription(org.apache.axis2.description.TransportOutDescription) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) OperationClient(org.apache.axis2.client.OperationClient) ServiceContext(org.apache.axis2.context.ServiceContext) QName(javax.xml.namespace.QName) URISyntaxException(java.net.URISyntaxException) ParseException(javax.mail.internet.ParseException) SynapseException(org.apache.synapse.SynapseException) EndpointReference(org.apache.axis2.addressing.EndpointReference) ConcurrentAccessReplicator(org.apache.synapse.commons.throttle.core.ConcurrentAccessReplicator) BlockingMsgSender(org.apache.synapse.message.senders.blocking.BlockingMsgSender) ServiceGroupContext(org.apache.axis2.context.ServiceGroupContext) ParseException(javax.mail.internet.ParseException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 100 with URL

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

the class URLRewriteMediatorTest method testFullRewriteScenario1.

public void testFullRewriteScenario1() throws Exception {
    String xml = "<rewrite xmlns=\"http://ws.apache.org/ns/synapse\">\n" + "    <rewriterule>\n" + "        <condition>\n" + "            <and>\n" + "                <equal type=\"url\" source=\"protocol\" value=\"http\"/>\n" + "                <equal type=\"url\" source=\"host\" value=\"test.org\"/>\n" + "            </and>\n" + "        </condition>\n" + "        <action value=\"https\" fragment=\"protocol\"/>\n" + "        <action value=\"test.com\" fragment=\"host\"/>\n" + "        <action value=\"9443\" fragment=\"port\"/>\n" + "    </rewriterule>\n" + "    <rewriterule>\n" + "        <condition>\n" + "            <not>\n" + "                <match type=\"url\" source=\"path\" regex=\"/services/.*\"/>\n" + "            </not>\n" + "        </condition>\n" + "        <action value=\"/services\" type=\"prepend\" fragment=\"path\"/>\n" + "    </rewriterule>\n" + "    <rewriterule>\n" + "        <condition>\n" + "            <and>\n" + "               <match type=\"url\" source=\"path\" regex=\".*/MyService\"/>\n" + "               <equal type=\"property\" source=\"prop1\" value=\"value1\"/>\n" + "            </and>\n" + "        </condition>        \n" + "        <action fragment=\"path\" value=\"StockQuoteService\" regex=\"MyService\" type=\"replace\"/>\n" + "        <action fragment=\"ref\" value=\"id\"/>\n" + "    </rewriterule>\n" + "</rewrite>";
    OMElement element = AXIOMUtil.stringToOM(xml);
    URLRewriteMediator mediator = (URLRewriteMediator) new URLRewriteMediatorFactory().createMediator(element, new Properties());
    MessageContext msgCtx = TestUtils.createLightweightSynapseMessageContext("<empty/>");
    msgCtx.setTo(new EndpointReference("http://test.org:9763/MyService"));
    msgCtx.setProperty("prop1", "value1");
    mediator.mediate(msgCtx);
    assertEquals("https://test.com:9443/services/StockQuoteService#id", msgCtx.getTo().getAddress());
}
Also used : OMElement(org.apache.axiom.om.OMElement) MessageContext(org.apache.synapse.MessageContext) URLRewriteMediatorFactory(org.apache.synapse.config.xml.URLRewriteMediatorFactory) Properties(java.util.Properties) EndpointReference(org.apache.axis2.addressing.EndpointReference)

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