org.apache.axis2.client.ServiceClient - java examples

Here are the examples of the java api org.apache.axis2.client.ServiceClient taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

155 Examples 7

19 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
/**
 * Send place order request
 *
 * @param trpUrl transport url
 * @param addUrl address url
 * @param symbol symbol
 * @throws AxisFault if error occurs when sending request
 */
public void sendPlaceOrderRequest(String trpUrl, String addUrl, String symbol) throws AxisFault {
    double price = getRandom(100, 0.9, true);
    int quanreplacedy = (int) getRandom(10000, 1.0, true);
    ServiceClient serviceClient = getServiceClient(trpUrl, addUrl, "placeOrder");
    try {
        serviceClient.fireAndForget(createPlaceOrderRequest(price, quanreplacedy, symbol));
    } finally {
        serviceClient.cleanupTransport();
    }
}

18 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement sendMultipleQuoteRequest(String trpUrl, String addUrl, String symbol, int n) throws AxisFault {
    ServiceClient serviceClient = getServiceClient(trpUrl, addUrl);
    try {
        return buildResponse(serviceClient.sendReceive(createMultipleQuoteRequest(symbol, n)));
    } finally {
        serviceClient.cleanupTransport();
    }
}

18 View Complete Implementation : TcpClient.java
Copyright Apache License 2.0
Author : wso2
public clreplaced TcpClient {

    private static final Log log = LogFactory.getLog(TcpClient.clreplaced);

    private ConfigurationContext cfgCtx;

    private ServiceClient serviceClient;

    public final String CONTENT_TYPE_TEXT_XML = "text/xml";

    public final String CONTENT_TYPE_APPLICATIONS_SOAP_XML = "application/soap+xml";

    public TcpClient() {
        String repositoryPath = /*ProductConstant.getModuleClientPath()*/
        FrameworkPathUtil.getSystemResourceLocation() + File.separator + "client";
        File repository = new File(repositoryPath);
        try {
            cfgCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(repository.getCanonicalPath(), /*ProductConstant.getResourceLocations(ProductConstant.ESB_SERVER_NAME)*/
            FrameworkPathUtil.getSystemResourceLocation() + File.separator + "artifacts" + File.separator + "ESB" + File.separator + "tcp" + File.separator + "transport" + File.separator + "client_axis2.xml");
            serviceClient = new ServiceClient(cfgCtx, null);
        } catch (Exception e) {
            log.error(e);
        }
    }

    public OMElement send12(String trpUrl, String action, OMElement payload, String contentType) throws AxisFault {
        Options options = new Options();
        options.setTo(new EndpointReference(trpUrl));
        options.setTransportInProtocol(Constants.TRANSPORT_TCP);
        options.setAction("urn:" + action);
        options.setProperty(Constants.Configuration.MESSAGE_TYPE, contentType);
        options.setSoapVersionURI(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);
        serviceClient.engageModule(Constants.MODULE_ADDRESSING);
        serviceClient.setOptions(options);
        OMElement result = serviceClient.sendReceive(payload);
        return result;
    }

    public OMElement sendSimpleStockQuote12(String trpUrl, String symbol, String contentType) throws AxisFault {
        return send12(trpUrl, "getQuote", createStandardRequest(symbol), contentType);
    }

    private OMElement createStandardRequest(String symbol) {
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMNamespace omNs = fac.createOMNamespace("http://services.samples", "ns");
        OMElement method = fac.createOMElement("getQuote", omNs);
        OMElement value1 = fac.createOMElement("request", omNs);
        OMElement value2 = fac.createOMElement("symbol", omNs);
        value2.addChild(fac.createOMText(value1, symbol));
        value1.addChild(value2);
        method.addChild(value1);
        return method;
    }
}

18 View Complete Implementation : LoadBalanceSessionFullClient.java
Copyright Apache License 2.0
Author : wso2
/**
 * Load balance failover client with session affinity
 */
public clreplaced LoadBalanceSessionFullClient {

    protected static final Log log = LogFactory.getLog(LoadBalanceSessionFullClient.clreplaced);

    private final static String DEFAULT_CLIENT_REPO = "client_repo";

    private final static String COOKIE = "Cookie";

    private final static String SET_COOKIE = "Set-Cookie";

    protected ServiceClient serviceClient;

    private SOAPEnvelope[] envelopes = null;

    private long sleepTime = -1;

    public LoadBalanceSessionFullClient() throws IOException {
        init();
        buildSoapEnvelopesWithClientSession();
    }

    private void init() throws IOException {
        String repositoryPath = System.getProperty(ESBTestConstant.CARBON_HOME) + File.separator + "samples" + File.separator + "axis2Client" + File.separator + DEFAULT_CLIENT_REPO;
        File repository = new File(repositoryPath);
        if (log.isDebugEnabled()) {
            log.debug("Axis2 repository path: " + repository.getAbsolutePath());
        }
        ConfigurationContext configurationContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(repository.getCanonicalPath(), null);
        serviceClient = new ServiceClient(configurationContext, null);
        log.info("LoadBalanceSessionFullClient initialized successfully...");
    }

    private void buildSoapEnvelopesWithClientSession() {
        Date date = new Date();
        SOAPEnvelope env1 = buildSoapEnvelope("" + (date.getTime() + 10), "v1");
        SOAPEnvelope env2 = buildSoapEnvelope("" + (date.getTime() + 20), "v1");
        SOAPEnvelope env3 = buildSoapEnvelope("" + (date.getTime() + 30), "v1");
        envelopes = new SOAPEnvelope[] { env1, env2, env3 };
    }

    /**
     * Send load balance request
     *
     * @param trpUrl     transport URL
     * @param addUrl     address URL
     * @param prxUrl     proxy URL
     * @param iterations number of requests
     * @return list of ResponseData
     * @throws org.apache.axis2.AxisFault if error occurs when sending request
     */
    public List<ResponseData> sendLoadBalanceRequest(String trpUrl, String addUrl, String prxUrl, int iterations) throws AxisFault {
        updateServiceClientOptions(trpUrl, addUrl, prxUrl);
        return makeRequest(null, iterations, sleepTime, envelopes, serviceClient);
    }

    /**
     * Send load balance request
     *
     * @param trpUrl     transport URL
     * @param addUrl     address URL
     * @param prxUrl     proxy URL
     * @param session    session
     * @param iterations number of requests
     * @return list of ResponseData
     * @throws org.apache.axis2.AxisFault if error occurs when sending request
     */
    public List<ResponseData> sendLoadBalanceRequest(String trpUrl, String addUrl, String prxUrl, String session, int iterations) throws AxisFault {
        updateServiceClientOptions(trpUrl, addUrl, prxUrl);
        return makeRequest(session, iterations, sleepTime, envelopes, serviceClient);
    }

    /**
     * Send load balance request
     *
     * @param trpUrl     transport URL
     * @param addUrl     address URL
     * @param prxUrl     proxy URL
     * @param session    session
     * @param iterations number of requests
     * @param sleepTime  sleep time
     * @return list of ResponseData
     * @throws org.apache.axis2.AxisFault if error occurs when sending request
     */
    public List<ResponseData> sendLoadBalanceRequest(String trpUrl, String addUrl, String prxUrl, String session, int iterations, long sleepTime) throws AxisFault {
        updateServiceClientOptions(trpUrl, addUrl, prxUrl);
        return makeRequest(session, iterations, sleepTime, envelopes, serviceClient);
    }

    private void updateServiceClientOptions(String trpUrl, String addUrl, String prxUrl) throws AxisFault {
        Options options = new Options();
        options.setTo(new EndpointReference(trpUrl));
        options.setAction("urn:sampleOperation");
        options.setTimeOutInMilliSeconds(10000000);
        // 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);
        } else {
            serviceClient.engageModule("addressing");
        }
        serviceClient.engageModule("addressing");
        if (prxUrl != null && !"null".equals(prxUrl)) {
            HttpTransportProperties.ProxyProperties proxyProperties = new HttpTransportProperties.ProxyProperties();
            try {
                URL url = new URL(prxUrl);
                proxyProperties.setProxyName(url.getHost());
                proxyProperties.setProxyPort(url.getPort());
                proxyProperties.setUserName("");
                proxyProperties.setPreplacedWord("");
                proxyProperties.setDomain("");
                options.setProperty(HTTPConstants.PROXY, proxyProperties);
            } catch (MalformedURLException e) {
                String msg = "Error while creating proxy URL";
                log.error(msg, e);
                throw new AxisFault(msg, e);
            }
        }
        serviceClient.setOptions(options);
    }

    private List<ResponseData> makeRequest(String session, int iterations, long sleepTime, SOAPEnvelope[] envelopes, ServiceClient client) throws AxisFault {
        List<ResponseData> responseList = new ArrayList<ResponseData>();
        int i = 0;
        int sessionNumber;
        String[] cookies = new String[3];
        boolean httpSession = session != null && "http".equals(session);
        int cookieNumber;
        while (i < iterations) {
            i++;
            if (sleepTime != -1) {
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException ignored) {
                }
            }
            MessageContext messageContext = new MessageContext();
            sessionNumber = getSessionTurn(envelopes.length);
            messageContext.setEnvelope(envelopes[sessionNumber]);
            cookieNumber = getSessionTurn(cookies.length);
            String cookie = cookies[cookieNumber];
            if (httpSession) {
                setSessionID(messageContext, cookie);
            }
            try {
                OperationClient op = client.createClient(ServiceClient.ANON_OUT_IN_OP);
                op.addMessageContext(messageContext);
                op.execute(true);
                MessageContext responseContext = op.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
                String receivedCookie = extractSessionID(responseContext);
                String receivedSetCookie = getSetCookieHeader(responseContext);
                if (httpSession) {
                    if (receivedSetCookie != null && !"".equals(receivedSetCookie)) {
                        cookies[cookieNumber] = receivedCookie;
                    }
                }
                SOAPEnvelope responseEnvelope = responseContext.getEnvelope();
                OMElement vElement = responseEnvelope.getBody().getFirstChildWithName(new QName("Value"));
                if (log.isDebugEnabled()) {
                    log.debug("Request: " + i + " with Session ID: " + (httpSession ? cookie : sessionNumber) + " ---- " + "Response : with  " + (httpSession && receivedCookie != null ? (receivedSetCookie != null ? receivedSetCookie : receivedCookie) : " ") + " " + vElement.getText());
                }
                responseList.add(new ResponseData(true, "" + (httpSession ? cookie : sessionNumber), vElement.getText()));
            } catch (AxisFault axisFault) {
                if (log.isDebugEnabled()) {
                    log.debug("Request with session id " + (httpSession ? cookie : sessionNumber), axisFault);
                }
                responseList.add(new ResponseData(false, "" + (httpSession ? cookie : sessionNumber), axisFault.getMessage()));
            }
        }
        return responseList;
    }

    private int getSessionTurn(int max) {
        Random random = new Random();
        return random.nextInt(max);
    }

    protected String extractSessionID(MessageContext axis2MessageContext) {
        Object o = axis2MessageContext.getProperty(MessageContext.TRANSPORT_HEADERS);
        if (o instanceof Map) {
            Map headerMap = (Map) o;
            String cookie = (String) headerMap.get(SET_COOKIE);
            if (cookie == null) {
                cookie = (String) headerMap.get(COOKIE);
            } else {
                cookie = cookie.split(";")[0];
            }
            return cookie;
        }
        return null;
    }

    protected String getSetCookieHeader(MessageContext axis2MessageContext) {
        Object o = axis2MessageContext.getProperty(MessageContext.TRANSPORT_HEADERS);
        if (o instanceof Map) {
            Map headerMap = (Map) o;
            return (String) headerMap.get(SET_COOKIE);
        }
        return null;
    }

    protected void setSessionID(MessageContext axis2MessageContext, String value) {
        if (value == null) {
            return;
        }
        Map map = (Map) axis2MessageContext.getProperty(HTTPConstants.HTTP_HEADERS);
        if (map == null) {
            map = new HashMap();
            axis2MessageContext.setProperty(HTTPConstants.HTTP_HEADERS, map);
        }
        map.put(COOKIE, value);
    }

    private SOAPEnvelope buildSoapEnvelope(String clientID, String value) {
        SOAPFactory soapFactory = OMAbstractFactory.getSOAP12Factory();
        SOAPEnvelope envelope = soapFactory.createSOAPEnvelope();
        SOAPHeader header = soapFactory.createSOAPHeader();
        envelope.addChild(header);
        OMNamespace synNamespace = soapFactory.createOMNamespace("http://ws.apache.org/ns/synapse", "syn");
        OMElement clientIDElement = soapFactory.createOMElement("ClientID", synNamespace);
        clientIDElement.setText(clientID);
        header.addChild(clientIDElement);
        SOAPBody body = soapFactory.createSOAPBody();
        envelope.addChild(body);
        OMElement valueElement = soapFactory.createOMElement("Value", null);
        valueElement.setText(value);
        body.addChild(valueElement);
        return envelope;
    }
}

18 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement sendMultipleQuoteRequestREST(String trpUrl, String addUrl, String symbol, int n) throws AxisFault {
    ServiceClient serviceClient = getRESTEnabledServiceClient(trpUrl, addUrl);
    try {
        return buildResponse(serviceClient.sendReceive(createMultipleQuoteRequest(symbol, n)));
    } finally {
        serviceClient.cleanupTransport();
    }
}

18 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement sendMultipleCustomQuoteRequest(String trpUrl, String addUrl, String symbol, int n) throws AxisFault {
    ServiceClient serviceClient = getServiceClient(trpUrl, addUrl);
    try {
        return buildResponse(serviceClient.sendReceive(createMultipleCustomQuoteRequest(symbol, n)));
    } finally {
        serviceClient.cleanupTransport();
    }
}

18 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement sendSimpleQuoteRequestREST(String trpUrl, String addUrl, String symbol) throws AxisFault {
    ServiceClient serviceClient = getRESTEnabledServiceClient(trpUrl, addUrl, "getSimpleQuote");
    try {
        return buildResponse(serviceClient.sendReceive(createStandardSimpleRequest(symbol)));
    } finally {
        serviceClient.cleanupTransport();
    }
}

18 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement sendCustomQuoteRequestREST(String trpUrl, String addUrl, String symbol) throws AxisFault {
    ServiceClient serviceClient = getRESTEnabledServiceClient(trpUrl, addUrl);
    try {
        return buildResponse(serviceClient.sendReceive(createCustomQuoteRequest(symbol)));
    } finally {
        serviceClient.cleanupTransport();
    }
}

18 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement sendSimpleStockQuoteRequest(String trpUrl, String addUrl, String symbol) throws AxisFault {
    ServiceClient sc;
    sc = getServiceClient(trpUrl, addUrl);
    try {
        return buildResponse(sc.sendReceive(createStandardRequest(symbol)));
    } finally {
        sc.cleanupTransport();
    }
}

18 View Complete Implementation : ServiceInvoker.java
Copyright Apache License 2.0
Author : wso2
public clreplaced ServiceInvoker extends Thread {

    private String invokerName = "anonymous";

    private String operation = null;

    private ServiceClient client = null;

    private OMElement msg = null;

    private long iterations = 10;

    private boolean statefull = false;

    private OMFactory fac = null;

    private long runningTime = 0;

    public ServiceInvoker(String epr, String operation) {
        this.operation = operation;
        Options options = new Options();
        options.setTo(new EndpointReference(epr));
        options.setAction(operation);
        try {
            ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem("client_repo", null);
            client = new ServiceClient(configContext, null);
            options.setTimeOutInMilliSeconds(10000000);
            client.setOptions(options);
            client.engageModule("addressing");
        } catch (AxisFault axisFault) {
            axisFault.printStackTrace();
        }
        fac = OMAbstractFactory.getOMFactory();
        msg = fac.createOMElement("SampleMsg", null);
        OMElement load = fac.createOMElement("load", null);
        load.setText("1000");
        msg.addChild(load);
    }

    public String getInvokerName() {
        return invokerName;
    }

    public void setInvokerName(String invokerName) {
        this.invokerName = invokerName;
        if (statefull) {
            client.getOptions().setManageSession(true);
            client.getOptions().setAction("setClientName");
            OMElement cName = fac.createOMElement("cName", null);
            cName.setText(invokerName);
            try {
                OMElement response = client.sendReceive(cName);
                System.out.println(response.getText());
            } catch (AxisFault axisFault) {
                axisFault.printStackTrace();
            }
        }
    }

    public long getRunningTime() {
        return runningTime;
    }

    public void setLoad(String load) {
        OMElement loadElement = msg.getFirstChildWithName(new QName("load"));
        loadElement.setText(load);
    }

    public void addDummyElements(long numElements) {
        OMElement dummies = fac.createOMElement("Dummies", null);
        msg.addChild(dummies);
        for (long i = 0; i < numElements; i++) {
            OMElement dummy = fac.createOMElement("Dummy", null);
            dummy.setText("This is the dummy element " + i);
            dummies.addChild(dummy);
        }
    }

    public void setClientSessionID(String id) {
        SOAPFactory soapFactory = OMAbstractFactory.getSOAP12Factory();
        OMNamespace synNamespace = soapFactory.createOMNamespace("http://ws.apache.org/namespaces/synapse", "syn");
        SOAPHeaderBlock header = soapFactory.createSOAPHeaderBlock("ClientID", synNamespace);
        header.setText(id);
        client.addHeader(header);
    }

    public void sereplacederations(long i) {
        iterations = i;
    }

    public void setStatefull(boolean state) {
        this.statefull = state;
    }

    public void run() {
        client.getOptions().setAction(operation);
        try {
            long t1 = System.currentTimeMillis();
            for (long i = 0; i < iterations; i++) {
                OMElement response2 = client.sendReceive(msg);
                OMElement loadElement = response2.getFirstChildWithName(new QName("load"));
                System.out.println(invokerName + ": " + loadElement.toString());
            }
            long t2 = System.currentTimeMillis();
            System.out.println("================================================================");
            System.out.println(invokerName + " completed requests.");
            System.out.println("================================================================");
            runningTime = t2 - t1;
        } catch (AxisFault axisFault) {
            System.out.println(axisFault.getMessage());
        }
    }
}

18 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement sendSimpleQuoteRequest(String trpUrl, String addUrl, String symbol) throws AxisFault {
    ServiceClient sc = getServiceClient(trpUrl, addUrl, "getSimpleQuote");
    try {
        return buildResponse(sc.sendReceive(createStandardSimpleRequest(symbol)));
    } finally {
        sc.cleanupTransport();
    }
}

18 View Complete Implementation : ServiceInvoker.java
Copyright Apache License 2.0
Author : wso2
public clreplaced ServiceInvoker extends Thread {

    private String invokerName = "anonymous";

    private String operation = null;

    private ServiceClient client = null;

    private OMElement msg = null;

    private long iterations = 10;

    private boolean statefull = false;

    private OMFactory fac = null;

    private long runningTime = 0;

    public ServiceInvoker(String epr, String operation) {
        this.operation = operation;
        Options options = new Options();
        options.setTo(new EndpointReference(epr));
        options.setAction(operation);
        try {
            ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem("client_repo", null);
            client = new ServiceClient(configContext, null);
            options.setTimeOutInMilliSeconds(10000000);
            client.setOptions(options);
            client.engageModule("addressing");
        } catch (AxisFault axisFault) {
            axisFault.printStackTrace();
        }
        fac = OMAbstractFactory.getOMFactory();
        msg = fac.createOMElement("SampleMsg", null);
        OMElement load = fac.createOMElement("load", null);
        load.setText("1000");
        msg.addChild(load);
    }

    public String getInvokerName() {
        return invokerName;
    }

    public void setInvokerName(String invokerName) {
        this.invokerName = invokerName;
        if (statefull) {
            client.getOptions().setManageSession(true);
            client.getOptions().setAction("setClientName");
            OMElement cName = fac.createOMElement("cName", null);
            cName.setText(invokerName);
            try {
                OMElement response = client.sendReceive(cName);
                System.out.println(response.getText());
            } catch (AxisFault axisFault) {
                axisFault.printStackTrace();
            }
        }
    }

    public long getRunningTime() {
        return runningTime;
    }

    public void setLoad(String load) {
        OMElement loadElement = msg.getFirstChildWithName(new QName("load"));
        loadElement.setText(load);
    }

    public void addDummyElements(long numElements) {
        OMElement dummies = fac.createOMElement("Dummies", null);
        msg.addChild(dummies);
        for (long i = 0; i < numElements; i++) {
            OMElement dummy = fac.createOMElement("Dummy", null);
            dummy.setText("This is the dummy element " + i);
            dummies.addChild(dummy);
        }
    }

    public void setClientSessionID(String id) {
        SOAPFactory soapFactory = OMAbstractFactory.getSOAP12Factory();
        OMNamespace synNamespace = soapFactory.createOMNamespace("http://ws.apache.org/namespaces/synapse", "syn");
        SOAPHeaderBlock header = soapFactory.createSOAPHeaderBlock("ClientID", synNamespace);
        header.setText(id);
        client.addHeader(header);
    }

    public void sereplacederations(long i) {
        iterations = i;
    }

    public void setStatefull(boolean state) {
        this.statefull = state;
    }

    public void run() {
        client.getOptions().setAction(operation);
        try {
            long t1 = System.currentTimeMillis();
            for (long i = 0; i < iterations; i++) {
                OMElement response2 = client.sendReceive(msg);
                OMElement loadElement = response2.getFirstChildWithName(new QName("load"));
                System.out.println(invokerName + ": " + loadElement.toString());
            }
            long t2 = System.currentTimeMillis();
            System.out.println("================================================================");
            System.out.println(invokerName + " completed requests.");
            System.out.println("================================================================");
            runningTime = t2 - t1;
        } catch (AxisFault axisFault) {
            System.out.println(axisFault.getMessage());
        }
    }
}

18 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
private ServiceClient getRESTEnabledServiceClient(String trpUrl, String addUrl, String operation) throws AxisFault {
    ServiceClient serviceClient = getServiceClient(trpUrl, addUrl, operation);
    serviceClient.getOptions().setProperty("enableREST", "true");
    return serviceClient;
}

18 View Complete Implementation : ParallelRequestHelper.java
Copyright Apache License 2.0
Author : wso2
/**
 * helper clreplaced to send parallel boxcarring requests to the backend
 */
public clreplaced ParallelRequestHelper extends Thread {

    private ServiceClient sender;

    private OMElement payload;

    /**
     * constructor for parallel request helper
     * we can use this for the initial begin boxcarring request as well.(sending sessionCookie null)
     *
     * @param sessionCookie
     * @param operation
     * @param payload
     * @param serviceEndPoint
     * @throws org.apache.axis2.AxisFault
     */
    public ParallelRequestHelper(String sessionCookie, String operation, OMElement payload, String serviceEndPoint) throws AxisFault {
        this.payload = payload;
        sender = new ServiceClient();
        Options options = new Options();
        options.setTo(new EndpointReference(serviceEndPoint));
        options.setProperty("__CHUNKED__", Boolean.FALSE);
        options.setTimeOutInMilliSeconds(45000L);
        options.setAction("urn:" + operation);
        sender.setOptions(options);
        if (sessionCookie != null && !sessionCookie.isEmpty()) {
            Header header = new Header("Cookie", sessionCookie);
            ArrayList headers = new ArrayList();
            headers.add(header);
            sender.getOptions().setProperty(HTTPConstants.HTTP_HEADERS, headers);
        }
    }

    @Override
    public void run() {
        try {
            sender.sendRobust(payload);
            LockHolder.getInstance().updateRequests();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * helper method to send begin boxcar request and return the session
     *
     * @return cookie
     * @throws org.apache.axis2.AxisFault
     */
    public String beginBoxcarReturningSession() throws AxisFault {
        sender.sendReceive(payload);
        MessageContext msgCtx = sender.getLastOperationContext().getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
        CommonsTransportHeaders commonsTransportHeaders = (CommonsTransportHeaders) msgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
        String cookie = (String) commonsTransportHeaders.get("Set-Cookie");
        return cookie;
    }

    /**
     * helper method to send request and return the result
     *
     * @return response
     * @throws org.apache.axis2.AxisFault
     */
    public OMElement sendRequestAndReceiveResult() throws AxisFault {
        OMElement response = sender.sendReceive(payload);
        return response;
    }
}

18 View Complete Implementation : LoadbalanceFailoverClient.java
Copyright Apache License 2.0
Author : wso2
public clreplaced LoadbalanceFailoverClient {

    private static final Log log = LogFactory.getLog(LoadbalanceFailoverClient.clreplaced);

    private final static String COOKIE = "Cookie";

    private final static String SET_COOKIE = "Set-Cookie";

    private final static String DEFAULT_CLIENT_REPO = "client_repo";

    private ConfigurationContext cfgCtx;

    private ServiceClient serviceClient;

    public LoadbalanceFailoverClient() {
        String repositoryPath = System.getProperty(ESBTestConstant.CARBON_HOME) + File.separator + "samples" + File.separator + "axis2Client" + File.separator + "client_repo";
        File repository = new File(repositoryPath);
        log.info("Using the Axis2 repository path: " + repository.getAbsolutePath());
        try {
            cfgCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(repository.getCanonicalPath(), null);
            serviceClient = new ServiceClient(cfgCtx, null);
            log.info("Sample clients initialized successfully...");
        } catch (Exception e) {
            log.error("Error while initializing the StockQuoteClient", e);
        }
    }

    private static String getProperty(String name, String def) {
        String result = System.getProperty(name);
        if (result == null || result.length() == 0) {
            result = def;
        }
        return result;
    }

    public void sendLoadBalanceRequests() throws Exception {
        new LoadbalanceFailoverClient().sessionlessClient();
    }

    public String sessionlessClient() throws AxisFault {
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMElement value = fac.createOMElement("Value", null);
        value.setText("Sample string");
        Options options = new Options();
        options.setTo(new EndpointReference("http://localhost:8480/services/LBService1"));
        options.setAction("urn:sampleOperation");
        long timeout = Integer.parseInt(getProperty("timeout", "10000000"));
        System.out.println("timeout=" + timeout);
        options.setTimeOutInMilliSeconds(timeout);
        // set addressing, transport and proxy url
        serviceClient.engageModule("addressing");
        options.setTo(new EndpointReference("http://localhost:8480"));
        serviceClient.setOptions(options);
        String testString = "";
        long i = 0;
        while (i < 100) {
            serviceClient.getOptions().setManageSession(true);
            OMElement responseElement = serviceClient.sendReceive(value);
            String response = responseElement.getText();
            i++;
            System.out.println("Request: " + i + " ==> " + response);
            testString = testString.concat(":" + i + ">" + response + ":");
        }
        return testString;
    }

    /**
     * This method is used to send a single request to the load balancing service
     *
     * @param proxyURL   will be the location where load balancing proxy or sequence is defined.
     * @param serviceURL will be the URL for LBService
     * @return the response
     * @throws org.apache.axis2.AxisFault
     */
    public String sendLoadBalanceRequest(String proxyURL, String serviceURL) throws AxisFault {
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMElement value = fac.createOMElement("Value", null);
        value.setText("Sample string");
        Options options = new Options();
        if (proxyURL != null && !"null".equals(proxyURL)) {
            options.setTo(new EndpointReference(proxyURL));
        }
        options.setAction("urn:sampleOperation");
        long timeout = Integer.parseInt(getProperty("timeout", "10000000"));
        System.out.println("timeout=" + timeout);
        options.setTimeOutInMilliSeconds(timeout);
        if (serviceURL != null && !"null".equals(serviceURL)) {
            // set addressing, transport and proxy url
            serviceClient.engageModule("addressing");
            options.setTo(new EndpointReference(serviceURL));
        }
        serviceClient.setOptions(options);
        serviceClient.getOptions().setManageSession(true);
        OMElement responseElement = serviceClient.sendReceive(value);
        String response = responseElement.getText();
        return response;
    }

    /**
     * This method is used to send a single request to the load balancing service
     *
     * @param proxyURL   will be the location where load balancing proxy or sequence is defined.
     * @param serviceURL will be the URL for LBService
     * @return the response
     * @throws org.apache.axis2.AxisFault
     */
    public String sendLoadBalanceRequest(String proxyURL, String serviceURL, String clientTimeoutInMilliSeconds) throws AxisFault {
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMElement value = fac.createOMElement("Value", null);
        value.setText("Sample string");
        Options options = new Options();
        if (proxyURL != null && !"null".equals(proxyURL)) {
            options.setTo(new EndpointReference(proxyURL));
        }
        options.setAction("urn:sampleOperation");
        long timeout = Integer.parseInt(getProperty("timeout", clientTimeoutInMilliSeconds));
        System.out.println("timeout=" + timeout);
        options.setTimeOutInMilliSeconds(timeout);
        if (serviceURL != null && !"null".equals(serviceURL)) {
            // set addressing, transport and proxy url
            serviceClient.engageModule("addressing");
            options.setTo(new EndpointReference(serviceURL));
        }
        serviceClient.setOptions(options);
        serviceClient.getOptions().setManageSession(true);
        OMElement responseElement = serviceClient.sendReceive(value);
        String response = responseElement.getText();
        return response;
    }

    /**
     * This method is used to send a single request to the load balancing service which will invoke a sleep in the service
     *
     * @param proxyURL                    will be the location where load balancing proxy or sequence is defined.
     * @param sleepTimeInMilliSeconds
     * @param clientTimeoutInMilliSeconds
     * @return
     * @throws org.apache.axis2.AxisFault
     */
    public String sendSleepRequest(String proxyURL, String sleepTimeInMilliSeconds, String clientTimeoutInMilliSeconds) throws AxisFault {
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMNamespace omNs = fac.createOMNamespace("http://services.samples", "ns");
        OMElement sleepOperation = fac.createOMElement("sleepOperation", omNs);
        OMElement load = fac.createOMElement("load", null);
        load.setText(sleepTimeInMilliSeconds);
        sleepOperation.addChild(load);
        Options options = new Options();
        if (proxyURL != null && !"null".equals(proxyURL)) {
            options.setTo(new EndpointReference(proxyURL));
        }
        options.setAction("urn:sleepOperation");
        long timeout = Integer.parseInt(getProperty("timeout", clientTimeoutInMilliSeconds));
        System.out.println("timeout=" + timeout);
        options.setTimeOutInMilliSeconds(timeout);
        serviceClient.setOptions(options);
        serviceClient.getOptions().setManageSession(true);
        OMElement responseElement = serviceClient.sendReceive(sleepOperation);
        String response = responseElement.getText();
        return response;
    }

    /**
     * This method is used to send a single request to the load balancing service. No service endpoint is needed
     *
     * @param URL will be the location where load balancing proxy or sequence is defined.     *
     * @return the response
     * @throws org.apache.axis2.AxisFault
     */
    public String sendLoadBalanceFailoverRequest(String URL) throws AxisFault {
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMElement value = fac.createOMElement("Value", null);
        value.setText("Sample string");
        Options options = new Options();
        options.setTo(new EndpointReference(URL));
        options.setAction("urn:sampleOperation");
        long timeout = Integer.parseInt(getProperty("timeout", "10000000"));
        System.out.println("timeout=" + timeout);
        options.setTimeOutInMilliSeconds(timeout);
        // set addressing, transport and proxy url
        serviceClient.engageModule("addressing");
        options.setTo(new EndpointReference("http://localhost:8280"));
        serviceClient.setOptions(options);
        serviceClient.getOptions().setManageSession(true);
        serviceClient.getOptions().setTo(new EndpointReference(URL));
        OMElement responseElement = serviceClient.sendReceive(value);
        String response = responseElement.getText();
        return response;
    }

    /**
     * This method creates 3 soap envelopes for 3 different clients based sessions. Then it randomly
     * choose one envelope for each iteration and send it to the ESB. ESB should be configured with
     * session affinity load balancer and the SampleClientInitiatedSession dispatcher. This will
     * output request number, session number and the server ID for each iteration. So it can be
     * observed that one session number always replacedociated with one server ID.
     */
    private void sessionfullClient() {
        String synapsePort = "8480";
        int iterations = 100;
        boolean infinite = true;
        String pPort = getProperty("port", synapsePort);
        String pIterations = getProperty("i", null);
        String addUrl = getProperty("addurl", null);
        String trpUrl = getProperty("trpurl", null);
        String prxUrl = getProperty("prxurl", null);
        String sleep = getProperty("sleep", null);
        String session = getProperty("session", null);
        long sleepTime = -1;
        if (sleep != null) {
            try {
                sleepTime = Long.parseLong(sleep);
            } catch (NumberFormatException ignored) {
            }
        }
        if (pPort != null) {
            try {
                Integer.parseInt(pPort);
                synapsePort = pPort;
            } catch (NumberFormatException e) {
            // run with default value
            }
        }
        if (pIterations != null) {
            try {
                iterations = Integer.parseInt(pIterations);
                if (iterations != -1) {
                    infinite = false;
                }
            } catch (NumberFormatException e) {
            // run with default values
            }
        }
        Options options = new Options();
        options.setTo(new EndpointReference("http://localhost:" + synapsePort + "/services/LBService1"));
        options.setAction("urn:sampleOperation");
        options.setTimeOutInMilliSeconds(10000000);
        try {
            SOAPEnvelope env1 = buildSoapEnvelope("c1", "v1");
            SOAPEnvelope env2 = buildSoapEnvelope("c2", "v1");
            SOAPEnvelope env3 = buildSoapEnvelope("c3", "v1");
            SOAPEnvelope[] envelopes = { env1, env2, env3 };
            String repoLocationProperty = System.getProperty("repository");
            String repo = repoLocationProperty != null ? repoLocationProperty : DEFAULT_CLIENT_REPO;
            ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(repo, repo + File.separator + "conf" + File.separator + "axis2.xml");
            ServiceClient client = new ServiceClient(configContext, null);
            // set addressing, transport and proxy url
            if (addUrl != null && !"null".equals(addUrl)) {
                client.engageModule("addressing");
                options.setTo(new EndpointReference(addUrl));
            }
            if (trpUrl != null && !"null".equals(trpUrl)) {
                options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl);
            } else {
                client.engageModule("addressing");
            }
            if (prxUrl != null && !"null".equals(prxUrl)) {
                HttpTransportProperties.ProxyProperties proxyProperties = new HttpTransportProperties.ProxyProperties();
                try {
                    URL url = new URL(prxUrl);
                    proxyProperties.setProxyName(url.getHost());
                    proxyProperties.setProxyPort(url.getPort());
                    proxyProperties.setUserName("");
                    proxyProperties.setPreplacedWord("");
                    proxyProperties.setDomain("");
                    options.setProperty(HTTPConstants.PROXY, proxyProperties);
                } catch (MalformedURLException e) {
                    throw new AxisFault("Error creating proxy URL", e);
                }
            }
            client.setOptions(options);
            int i = 0;
            int sessionNumber;
            String[] cookies = new String[3];
            boolean httpSession = session != null && "http".equals(session);
            int cookieNumber;
            while (i < iterations || infinite) {
                i++;
                if (sleepTime != -1) {
                    try {
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException ignored) {
                    }
                }
                MessageContext messageContext = new MessageContext();
                sessionNumber = getSessionTurn(envelopes.length);
                messageContext.setEnvelope(envelopes[sessionNumber]);
                cookieNumber = getSessionTurn(cookies.length);
                String cookie = cookies[cookieNumber];
                if (httpSession) {
                    setSessionID(messageContext, cookie);
                }
                try {
                    OperationClient op = client.createClient(ServiceClient.ANON_OUT_IN_OP);
                    op.addMessageContext(messageContext);
                    op.execute(true);
                    MessageContext responseContext = op.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
                    String receivedCookie = extractSessionID(responseContext);
                    String receivedSetCookie = getSetCookieHeader(responseContext);
                    if (httpSession) {
                        if (receivedSetCookie != null && !"".equals(receivedSetCookie)) {
                            cookies[cookieNumber] = receivedCookie;
                        }
                    }
                    SOAPEnvelope responseEnvelope = responseContext.getEnvelope();
                    OMElement vElement = responseEnvelope.getBody().getFirstChildWithName(new QName("Value"));
                    System.out.println("Request: " + i + " with Session ID: " + (httpSession ? cookie : sessionNumber) + " ---- " + "Response : with  " + (httpSession && receivedCookie != null ? (receivedSetCookie != null ? receivedSetCookie : receivedCookie) : " ") + " " + vElement.getText());
                } catch (AxisFault axisFault) {
                    System.out.println("Request with session id " + (httpSession ? cookie : sessionNumber) + " " + "- Get a Fault : " + axisFault.getMessage());
                }
            }
        } catch (AxisFault axisFault) {
            System.out.println(axisFault.getMessage());
        }
    }

    private int getSessionTurn(int max) {
        Random random = new Random();
        return random.nextInt(max);
    }

    protected String extractSessionID(MessageContext axis2MessageContext) {
        Object o = axis2MessageContext.getProperty(MessageContext.TRANSPORT_HEADERS);
        if (o != null && o instanceof Map) {
            Map headerMap = (Map) o;
            String cookie = (String) headerMap.get(SET_COOKIE);
            if (cookie == null) {
                cookie = (String) headerMap.get(COOKIE);
            } else {
                cookie = cookie.split(";")[0];
            }
            return cookie;
        }
        return null;
    }

    protected String getSetCookieHeader(MessageContext axis2MessageContext) {
        Object o = axis2MessageContext.getProperty(MessageContext.TRANSPORT_HEADERS);
        if (o != null && o instanceof Map) {
            Map headerMap = (Map) o;
            return (String) headerMap.get(SET_COOKIE);
        }
        return null;
    }

    protected void setSessionID(MessageContext axis2MessageContext, String value) {
        if (value == null) {
            return;
        }
        Map map = (Map) axis2MessageContext.getProperty(HTTPConstants.HTTP_HEADERS);
        if (map == null) {
            map = new HashMap();
            axis2MessageContext.setProperty(HTTPConstants.HTTP_HEADERS, map);
        }
        map.put(COOKIE, value);
    }

    private SOAPEnvelope buildSoapEnvelope(String clientID, String value) {
        SOAPFactory soapFactory = OMAbstractFactory.getSOAP12Factory();
        SOAPEnvelope envelope = soapFactory.createSOAPEnvelope();
        SOAPHeader header = soapFactory.createSOAPHeader();
        envelope.addChild(header);
        OMNamespace synNamespace = soapFactory.createOMNamespace("http://ws.apache.org/ns/synapse", "syn");
        OMElement clientIDElement = soapFactory.createOMElement("ClientID", synNamespace);
        clientIDElement.setText(clientID);
        header.addChild(clientIDElement);
        SOAPBody body = soapFactory.createSOAPBody();
        envelope.addChild(body);
        OMElement valueElement = soapFactory.createOMElement("Value", null);
        valueElement.setText(value);
        body.addChild(valueElement);
        return envelope;
    }
}

18 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
private ServiceClient getRESTEnabledServiceClient(String trpUrl, String addUrl) throws AxisFault {
    ServiceClient serviceClient = getServiceClient(trpUrl, addUrl);
    serviceClient.getOptions().setProperty("enableREST", "true");
    return serviceClient;
}

18 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement sendSimpleStockQuoteRequestREST(String trpUrl, String addUrl, String symbol) throws AxisFault {
    ServiceClient sc = getRESTEnabledServiceClient(trpUrl, addUrl);
    try {
        return buildResponse(sc.sendReceive(createStandardRequest(symbol)));
    } finally {
        sc.cleanupTransport();
    }
}

18 View Complete Implementation : FIXClient.java
Copyright Apache License 2.0
Author : wso2
public clreplaced FIXClient {

    private String addUrl = null;

    private String trpUrl = null;

    private String prxyUrl = null;

    private String symbol;

    private String mode;

    private String qty;

    private String repo;

    private Options options;

    private ServiceClient serviceClient;

    private ConfigurationContext configContext = null;

    private String pathToRepo;

    public FIXClient() throws IOException {
        options = new Options();
        repo = FrameworkPathUtil.getSystemResourceLocation() + File.separator + "clients";
        pathToRepo = (new File(repo)).getCanonicalPath();
    }

    // send the request and get the response as a string
    public String send(String symbol, String mode, String qty, String addUrl, String trpUrl, String prxUrl) throws Exception {
        setSymbol(symbol);
        setMode(mode);
        setQty(qty);
        setAddUrl(addUrl);
        setTrpUrl(trpUrl);
        setPrxyUrl(prxUrl);
        String side = "1";
        if (getMode().equals("sell")) {
            side = "2";
        }
        if (pathToRepo != null && !"null".equals(pathToRepo)) {
            configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(pathToRepo, null);
            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, getSymbol(), side, getQty()));
        message.addChild(factory.createOMElement("trailer", null));
        // set addressing, transport and proxy url
        if (getAddUrl() != null && !"null".equals(getAddUrl())) {
            serviceClient.engageModule("addressing");
            options.setTo(new EndpointReference(getAddUrl()));
        }
        if (getTrpUrl() != null && !"null".equals(getTrpUrl())) {
            options.setProperty(Constants.Configuration.TRANSPORT_URL, getTrpUrl());
        }
        if (getPrxyUrl() != null && !"null".equals(getPrxyUrl())) {
            HttpTransportProperties.ProxyProperties proxyProperties = new HttpTransportProperties.ProxyProperties();
            URL url = new URL(getPrxyUrl());
            proxyProperties.setProxyName(url.getHost());
            proxyProperties.setProxyPort(url.getPort());
            proxyProperties.setUserName("");
            proxyProperties.setPreplacedWord("");
            proxyProperties.setDomain("");
            options.setProperty(HTTPConstants.PROXY, proxyProperties);
        }
        options.setAction("urn:mediate");
        serviceClient.setOptions(options);
        OMElement response = serviceClient.sendReceive(message);
        Thread.sleep(5000);
        try {
            if (configContext != null) {
                configContext.terminate();
            }
        } catch (Exception ignore) {
        }
        return response.toString();
    }

    private OMElement getHeader(OMFactory factory) {
        OMElement header = factory.createOMElement("header", null);
        OMElement msgType = factory.createOMElement("field", null);
        msgType.addAttribute(factory.createOMAttribute("id", null, "35"));
        factory.createOMText(msgType, "D");
        header.addChild(msgType);
        OMElement sendingTime = factory.createOMElement("field", null);
        sendingTime.addAttribute(factory.createOMAttribute("id", null, "52"));
        factory.createOMText(sendingTime, new Date().toString());
        header.addChild(sendingTime);
        return header;
    }

    private OMElement getBody(OMFactory factory, String text, String mode, String qtyValue) {
        OMElement body = factory.createOMElement("body", null);
        OMElement clordID = factory.createOMElement("field", null);
        clordID.addAttribute(factory.createOMAttribute("id", null, "11"));
        factory.createOMText(clordID, "122333");
        body.addChild(clordID);
        OMElement handleIns = factory.createOMElement("field", null);
        handleIns.addAttribute(factory.createOMAttribute("id", null, "21"));
        factory.createOMText(handleIns, "1");
        body.addChild(handleIns);
        OMElement qty = factory.createOMElement("field", null);
        qty.addAttribute(factory.createOMAttribute("id", null, "38"));
        factory.createOMText(qty, qtyValue);
        body.addChild(qty);
        OMElement ordType = factory.createOMElement("field", null);
        ordType.addAttribute(factory.createOMAttribute("id", null, "40"));
        factory.createOMText(ordType, "1");
        body.addChild(ordType);
        OMElement side = factory.createOMElement("field", null);
        side.addAttribute(factory.createOMAttribute("id", null, "54"));
        factory.createOMText(side, mode);
        body.addChild(side);
        OMElement symbol = factory.createOMElement("field", null);
        symbol.addAttribute(factory.createOMAttribute("id", null, "55"));
        factory.createOMText(symbol, text);
        body.addChild(symbol);
        OMElement timeInForce = factory.createOMElement("field", null);
        timeInForce.addAttribute(factory.createOMAttribute("id", null, "59"));
        factory.createOMText(timeInForce, "0");
        body.addChild(timeInForce);
        return body;
    }

    public String getAddUrl() {
        return addUrl;
    }

    public void setAddUrl(String addUrl) {
        this.addUrl = addUrl;
    }

    public String getTrpUrl() {
        return trpUrl;
    }

    public void setTrpUrl(String trpUrl) {
        this.trpUrl = trpUrl;
    }

    public String getSymbol() {
        return symbol;
    }

    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }

    public String getMode() {
        return mode;
    }

    public void setMode(String mode) {
        this.mode = mode;
    }

    public String getQty() {
        return qty;
    }

    public void setQty(String qty) {
        this.qty = qty;
    }

    public String getPrxyUrl() {
        return prxyUrl;
    }

    public void setPrxyUrl(String prxyUrl) {
        this.prxyUrl = prxyUrl;
    }
}

18 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement sendCustomQuoteRequest(String trpUrl, String addUrl, String symbol) throws AxisFault {
    ServiceClient serviceClient = getServiceClient(trpUrl, addUrl);
    try {
        return buildResponse(serviceClient.sendReceive(createCustomQuoteRequest(symbol)));
    } finally {
        serviceClient.cleanupTransport();
    }
}

17 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement sendSimpleStockQuoteRequestREST(String trpUrl, String addUrl, OMElement payload) throws AxisFault {
    ServiceClient serviceClient = getRESTEnabledServiceClient(trpUrl, addUrl);
    try {
        return buildResponse(serviceClient.sendReceive(payload));
    } finally {
        serviceClient.cleanupTransport();
    }
}

17 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
/**
 * Send dual quote request
 *
 * @param trpUrl transport url
 * @param addUrl address url
 * @param symbol symbol
 * @throws AxisFault if error occurs when sending request
 */
public void sendDualQuoteRequest(String trpUrl, String addUrl, String symbol) throws AxisFault {
    ServiceClient serviceClient = getServiceClient(trpUrl, addUrl);
    serviceClient.getOptions().setUseSeparateListener(true);
    try {
        serviceClient.sendReceiveNonBlocking(createStandardRequest(symbol), new AxisCallback() {

            @Override
            public void onMessage(MessageContext messageContext) {
                log.info("Response received to the callback");
            }

            @Override
            public void onFault(MessageContext messageContext) {
                log.info("Fault received to the callback : " + messageContext.getEnvelope().getBody().getFault());
            }

            @Override
            public void onError(Exception e) {
                log.error("Error inside callback", e);
            }

            @Override
            public void onComplete() {
                log.info("OnComplete called....");
            }
        });
    } finally {
        serviceClient.cleanupTransport();
    }
}

17 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement sendSimpleStockQuoteSoap12(String trpUrl, String addUrl, String symbol) throws AxisFault {
    ServiceClient serviceClient = getServiceClient(trpUrl, addUrl);
    serviceClient.getOptions().setSoapVersionURI(org.apache.axiom.soap.SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    try {
        return buildResponse(serviceClient.sendReceive(createStandardRequest(symbol)));
    } finally {
        serviceClient.cleanupTransport();
    }
}

17 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement sendSimpleStockQuoteRequest(String trpUrl, String addUrl, OMElement payload) throws AxisFault {
    ServiceClient serviceClient = getServiceClient(trpUrl, addUrl);
    try {
        return buildResponse(serviceClient.sendReceive(payload));
    } finally {
        serviceClient.cleanupTransport();
    }
}

17 View Complete Implementation : AxisOperationClient.java
Copyright Apache License 2.0
Author : wso2
public clreplaced AxisOperationClient {

    private static final Log log = LogFactory.getLog(AxisOperationClient.clreplaced);

    private MessageContext outMsgCtx;

    private ConfigurationContext cfgCtx;

    private ServiceClient serviceClient;

    private OperationClient operationClient;

    private SOAPFactory fac;

    private SOAPEnvelope envelope;

    public AxisOperationClient() {
        String repositoryPath = System.getProperty(ServerConstants.CARBON_HOME) + File.separator + "samples" + File.separator + "axis2Server" + File.separator + "repository";
        File repository = new File(repositoryPath);
        log.info("Using the Axis2 repository path: " + repository.getAbsolutePath());
        try {
            cfgCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(repository.getCanonicalPath(), null);
            serviceClient = new ServiceClient(cfgCtx, null);
            log.info("Sample clients initialized successfully...");
        } catch (Exception e) {
            log.error("Error while initializing the Operational Client", e);
        }
    }

    /**
     * @param trpUrl
     * @param addUrl
     * @param symbol
     * @param iterations
     * @return
     * @throws java.io.IOException
     */
    public OMElement sendMultipleQuoteRequest(String trpUrl, String addUrl, String symbol, int iterations) throws IOException {
        return createMultipleQuoteRequest(trpUrl, addUrl, symbol, iterations);
    }

    /**
     * @param trpUrl
     * @param addUrl
     * @param payload
     * @param action
     * @return soap envelop
     * @throws org.apache.axis2.AxisFault
     */
    public OMElement send(String trpUrl, String addUrl, OMElement payload, String action) throws AxisFault {
        operationClient = serviceClient.createClient(ServiceClient.ANON_OUT_IN_OP);
        setMessageContext(addUrl, trpUrl, action);
        outMsgCtx.setEnvelope(createSOAPEnvelope(payload));
        operationClient.addMessageContext(outMsgCtx);
        operationClient.execute(true);
        MessageContext inMsgtCtx = operationClient.getMessageContext("In");
        SOAPEnvelope response = inMsgtCtx.getEnvelope();
        return response;
    }

    /**
     * Creating the multiple quote request body
     *
     * @param symbol
     * @param iterations
     * @return
     */
    private OMElement createMultipleQuoteRequestBody(String symbol, int iterations) {
        OMNamespace omNs = fac.createOMNamespace("http://services.samples", "ns");
        OMElement method = fac.createOMElement("getQuote", omNs);
        for (int i = 0; i < iterations; i++) {
            OMElement value1 = fac.createOMElement("request", omNs);
            OMElement value2 = fac.createOMElement("symbol", omNs);
            value2.addChild(fac.createOMText(value1, symbol));
            value1.addChild(value2);
            method.addChild(value1);
        }
        return method;
    }

    /**
     * Creating the multiple quote request
     *
     * @param trpUrl
     * @param addUrl
     * @param symbol
     * @param iterations
     * @return
     * @throws java.io.IOException
     */
    private OMElement createMultipleQuoteRequest(String trpUrl, String addUrl, String symbol, int iterations) throws IOException {
        operationClient = serviceClient.createClient(ServiceClient.ANON_OUT_IN_OP);
        setMessageContext(addUrl, trpUrl, null);
        outMsgCtx.setEnvelope(createSOAPEnvelope(symbol, iterations));
        operationClient.addMessageContext(outMsgCtx);
        operationClient.execute(true);
        MessageContext inMsgtCtx = operationClient.getMessageContext("In");
        SOAPEnvelope response = inMsgtCtx.getEnvelope();
        return response;
    }

    /**
     * creating the message context of the soap message
     *
     * @param addUrl
     * @param trpUrl
     * @param action
     */
    private void setMessageContext(String addUrl, String trpUrl, String action) {
        outMsgCtx = new MessageContext();
        // replacedigning message context’s option object into instance variable
        Options options = outMsgCtx.getOptions();
        // setting properties into option
        if (trpUrl != null && !"null".equals(trpUrl)) {
            options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl);
        }
        if (addUrl != null && !"null".equals(addUrl)) {
            options.setTo(new EndpointReference(addUrl));
        }
        if (action != null && !"null".equals(action)) {
            options.setAction(action);
        }
    }

    /**
     * Create the soap envelop
     *
     * @param symbol
     * @param iterations
     * @return
     */
    private SOAPEnvelope createSOAPEnvelope(String symbol, int iterations) {
        fac = OMAbstractFactory.getSOAP11Factory();
        envelope = fac.getDefaultEnvelope();
        envelope.getBody().addChild(createMultipleQuoteRequestBody(symbol, iterations));
        return envelope;
    }

    /**
     * @param payload
     * @return
     */
    private SOAPEnvelope createSOAPEnvelope(OMElement payload) {
        fac = OMAbstractFactory.getSOAP11Factory();
        envelope = fac.getDefaultEnvelope();
        envelope.getBody().addChild(payload);
        return envelope;
    }

    /**
     * Destroy objects
     */
    public void destroy() {
        try {
            serviceClient.cleanup();
            cfgCtx.cleanupContexts();
            cfgCtx.terminate();
        } catch (AxisFault axisFault) {
            log.error("Error while cleaning up the service clients", axisFault);
        }
        outMsgCtx = null;
        serviceClient = null;
        operationClient = null;
        cfgCtx = null;
        envelope = null;
        fac = null;
    }
}

17 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement send(String trpUrl, String addUrl, String action, OMElement payload) throws AxisFault {
    ServiceClient serviceClient = getServiceClient(trpUrl, addUrl, action);
    try {
        return buildResponse(serviceClient.sendReceive(payload));
    } finally {
        serviceClient.cleanupTransport();
    }
}

17 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
public OMElement sendSimpleStockQuoteSoap11(String trpUrl, String addUrl, String symbol) throws AxisFault {
    ServiceClient serviceClient = getServiceClient(trpUrl, addUrl);
    serviceClient.getOptions().setSoapVersionURI(org.apache.axiom.soap.SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    try {
        return buildResponse(serviceClient.sendReceive(createStandardRequest(symbol)));
    } finally {
        serviceClient.cleanupTransport();
    }
}

17 View Complete Implementation : TopicAdminClient.java
Copyright Apache License 2.0
Author : wso2
private void configureCookie(ServiceClient client) throws AxisFault {
    if (SessionCookie != null) {
        Options option = client.getOptions();
        option.setManageSession(true);
        option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, SessionCookie);
    }
}

17 View Complete Implementation : StockQuoteClient.java
Copyright Apache License 2.0
Author : wso2
/**
 * This method utilises serviceClient's sendRobust() method
 *
 * @param trpUrl  transport url
 * @param addUrl  address url
 * @param action  action
 * @param payload payload
 * @throws AxisFault if error occurs in sending the request
 */
public void sendRobust(String trpUrl, String addUrl, String action, OMElement payload) throws AxisFault {
    ServiceClient serviceClient = getServiceClient(trpUrl, addUrl, action);
    try {
        serviceClient.sendRobust(payload);
    } finally {
        serviceClient.cleanupTransport();
    }
}

15 View Complete Implementation : EntitlementServiceStubFactory.java
Copyright Apache License 2.0
Author : wso2
@Override
public Object makeObject() throws Exception {
    EnreplacedlementServiceStub stub = new EnreplacedlementServiceStub(configurationContext, targetEndpoint);
    ServiceClient client = stub._getServiceClient();
    Options options = client.getOptions();
    options.setManageSession(true);
    options.setProperty(HTTPConstants.AUTHENTICATE, authenticator);
    return stub;
}

15 View Complete Implementation : ESBJAVA2262ContentEncodingGzipTestCase.java
Copyright Apache License 2.0
Author : wso2
private ServiceClient getServiceClient(String trpUrl) throws AxisFault {
    ServiceClient serviceClient;
    Options options = new Options();
    serviceClient = new ServiceClient();
    if (trpUrl != null && !"null".equals(trpUrl)) {
        options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl);
    }
    options.setAction("urn:getQuote");
    serviceClient.setOptions(options);
    return serviceClient;
}

15 View Complete Implementation : XdsTest.java
Copyright Apache License 2.0
Author : jembi
/**
 * Submit one doreplacedent to support ProvideAndRegisterDoreplacedentSet-b (ITI-41)
 *
 * @return XDSDoreplacedentEntry.uuid
 * @throws
 * @throws Exception
 */
protected String submitOneDoreplacedent(String patientId) throws Exception {
    String message = IOUtils.toString(ProvideAndRegisterDoreplacedentSetTest.clreplaced.getResourcereplacedtream("/data/submit_doreplacedent.xml"));
    String doreplacedent = IOUtils.toString(ProvideAndRegisterDoreplacedentSetTest.clreplaced.getResourcereplacedtream("/data/referral_summary.xml"));
    // replace doreplacedent and submission set uniqueId variables with actual uniqueIds.
    message = message.replace("$XDSDoreplacedentEntry.uniqueId", "2.16.840.1.113883.3.65.2." + System.currentTimeMillis());
    message = message.replace("$XDSSubmissionSet.uniqueId", "1.3.6.1.4.1.21367.2009.1.2.108." + System.currentTimeMillis());
    // replace the doreplacedent uuid.
    String uuid = "urn:uuid:" + UUID.randomUUID().toString();
    message = message.replace("$doc1", uuid);
    // replace the patient id
    if (patientId != null)
        message = message.replace("$patientId", patientId);
    ServiceClient sender = getRepositoryServiceClient();
    OMElement request = OMUtil.xmlStringToOM(message);
    // Add a doreplacedent
    request = addOneDoreplacedent(request, doreplacedent, uuid);
    System.out.println("Request:\n" + request);
    OMElement response = sender.sendReceive(request);
    replacedertNotNull(response);
    OMAttribute status = response.getAttribute(new QName("status"));
    replacedertEquals("urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success", status.getAttributeValue());
    String result = response.toString();
    System.out.println("Result:\n" + result);
    return uuid;
}

15 View Complete Implementation : AuthenticateStubUtil.java
Copyright Apache License 2.0
Author : wso2
/**
 * Stub authentication method
 *
 * @param stub          valid stub
 * @param sessionCookie session cookie
 */
public static void authenticateStub(String sessionCookie, Stub stub) {
    // Three minutes
    long soTimeout = 5 * 60 * 1000;
    ServiceClient client = stub._getServiceClient();
    Options option = client.getOptions();
    option.setManageSession(true);
    option.setTimeOutInMilliSeconds(soTimeout);
    option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, sessionCookie);
    if (log.isDebugEnabled()) {
        log.debug("AuthenticateStub : Stub created with session " + sessionCookie);
    }
}

15 View Complete Implementation : XdsTest.java
Copyright Apache License 2.0
Author : jembi
/**
 * Submits doreplacedent to the SubmisstionSet And Folder.
 * @param patientId
 * @return doreplacedent UUID
 * @throws Exception
 */
protected String submitDoreplacedent2SubmissionSet(String patientId) throws Exception {
    String message = IOUtils.toString(ProvideAndRegisterDoreplacedentSetTest.clreplaced.getResourcereplacedtream("/data/add_doreplacedent2_folder.xml"));
    String doreplacedent1 = IOUtils.toString(ProvideAndRegisterDoreplacedentSetTest.clreplaced.getResourcereplacedtream("/data/referral_summary.xml"));
    // replace doreplacedent , submission set and folder uniqueId variables with actual uniqueIds.
    message = message.replace("$XDSDoreplacedentEntry.uniqueId", "2.16.840.1.113883.3.65.2." + System.currentTimeMillis());
    String subUniqueId = "1.3.6.1.4.1.21367.2009.1.2.108." + System.currentTimeMillis();
    message = message.replace("$XDSSubmissionSet.uniqueId", subUniqueId);
    String folderUniqueId = "2.16.840.1.113883.3.65.3." + System.currentTimeMillis();
    message = message.replace("$folder_uniqueid", folderUniqueId);
    // replace the doreplacedentId doc1 with an UUID
    String uuid = "urn:uuid:" + UUID.randomUUID().toString();
    message = message.replace("doc1", uuid);
    // replace the patient id
    message = message.replace("$patientId", patientId);
    ServiceClient sender = getRepositoryServiceClient();
    OMElement request = OMUtil.xmlStringToOM(message);
    // Add a referral summary doreplacedent
    request = addOneDoreplacedent(request, doreplacedent1, uuid);
    System.out.println("Request:\n" + request);
    OMElement response = sender.sendReceive(request);
    replacedertNotNull(response);
    OMAttribute status = response.getAttribute(new QName("status"));
    replacedertEquals("urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success", status.getAttributeValue());
    String result = response.toString();
    System.out.println("Result:\n" + result);
    return subUniqueId;
}

15 View Complete Implementation : XdsTest.java
Copyright Apache License 2.0
Author : jembi
/**
 * Submits new doreplacedent and replaces the doreplacedent
 *
 * @param patientId
 * @return Doreplacedent UUID
 * @throws Exception
 */
public String replaceDoreplacedent(String patientId) throws Exception {
    // First submit a doreplacedent
    String doc_uuid = submitOneDoreplacedent(patientId);
    // Then add a replacement doc
    String message = IOUtils.toString(ProvideAndRegisterDoreplacedentSetTest.clreplaced.getResourcereplacedtream("/data/doreplacedent_replacement.xml"));
    String doreplacedent1 = IOUtils.toString(ProvideAndRegisterDoreplacedentSetTest.clreplaced.getResourcereplacedtream("/data/medical_summary.xml"));
    // replace doreplacedent and submission set variables with actual uniqueIds.
    message = message.replace("$XDSDoreplacedentEntry.uniqueId", "2.16.840.1.113883.3.65.2." + System.currentTimeMillis());
    message = message.replace("$XDSSubmissionSet.uniqueId", "1.3.6.1.4.1.21367.2009.1.2.108." + System.currentTimeMillis());
    message = message.replace("$patientId", patientId);
    // populate the doreplacedent uuid to be replaced.
    message = message.replace("$rplc_doc_uuid", doc_uuid);
    ServiceClient sender = getRepositoryServiceClient();
    OMElement request = OMUtil.xmlStringToOM(message);
    // Add a medical summary doreplacedent
    request = addOneDoreplacedent(request, doreplacedent1, "doc1");
    System.out.println("Request:\n" + request);
    OMElement response = sender.sendReceive(request);
    replacedertNotNull(response);
    OMAttribute status = response.getAttribute(new QName("status"));
    replacedertEquals("urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success", status.getAttributeValue());
    String result = response.toString();
    System.out.println("Result:\n" + result);
    return doc_uuid;
}

15 View Complete Implementation : XdsTest.java
Copyright Apache License 2.0
Author : jembi
public String submitMultipleDoreplacedents(String patientId) throws Exception {
    String message = IOUtils.toString(ProvideAndRegisterDoreplacedentSetTest.clreplaced.getResourcereplacedtream("/data/submit_multiple_doreplacedents.xml"));
    String doreplacedent1 = IOUtils.toString(ProvideAndRegisterDoreplacedentSetTest.clreplaced.getResourcereplacedtream("/data/referral_summary.xml"));
    String doreplacedent2 = IOUtils.toString(ProvideAndRegisterDoreplacedentSetTest.clreplaced.getResourcereplacedtream("/data/medical_summary.xml"));
    // replace doreplacedent and submission set uniqueId variables with actual uniqueIds.
    message = message.replace("$XDSDoreplacedentEntry.uniqueId", "2.16.840.1.113883.3.65.2." + System.currentTimeMillis());
    message = message.replace("$XDSDoreplacedentEntry.uniqueId1", "2.16.840.1.113883.3.65.2." + System.currentTimeMillis());
    message = message.replace("$XDSSubmissionSet.uniqueId", "1.3.6.1.4.1.21367.2009.1.2.108." + System.currentTimeMillis());
    // replace the doreplacedent uuid.
    String uuid1 = getUUID();
    message = message.replace("$doc1", uuid1);
    String uuid2 = getUUID();
    message = message.replace("$doc2", uuid2);
    // replace the patient id
    if (patientId != null)
        message = message.replace("$patientId", patientId);
    ServiceClient sender = getRepositoryServiceClient();
    OMElement request = OMUtil.xmlStringToOM(message);
    // Add a referral summary doreplacedent
    request = addOneDoreplacedent(request, doreplacedent1, uuid1);
    // Add a Discharge summary doreplacedents
    request = addOneDoreplacedent(request, doreplacedent2, uuid2);
    System.out.println("Request:\n" + request);
    OMElement response = sender.sendReceive(request);
    replacedertNotNull(response);
    OMAttribute status = response.getAttribute(new QName("status"));
    replacedertEquals("urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success", status.getAttributeValue());
    String result = response.toString();
    System.out.println("Result:\n" + result);
    String uuids = uuid1 + "','" + uuid2;
    return uuids;
}

15 View Complete Implementation : SecureAxisServiceClient.java
Copyright Apache License 2.0
Author : wso2
/**
 * This will send request by getting keyStore wso2carbon.jks
 *
 * @param userName
 * @param preplacedword
 * @param endpointReference
 * @param operation
 * @param payload
 * @param securityScenarioNo
 * @throws Exception
 */
public void sendRobust(String userName, String preplacedword, String endpointReference, String operation, OMElement payload, int securityScenarioNo) throws Exception {
    if (securityScenarioNo == 1) {
        replacedert.replacedertTrue(endpointReference.startsWith("https:"), "Endpoint reference should be https");
    }
    String keyPath = FrameworkPathUtil.getSystemResourceLocation() + File.separator + "keystores" + File.separator + "products";
    String securityPolicyPath = FrameworkPathUtil.getSystemResourceLocation() + File.separator + "security" + File.separator + "policies" + "scenario" + securityScenarioNo + "-policy.xml";
    ServiceClient sc = getServiceClient(userName, preplacedword, endpointReference, operation, securityPolicyPath, "wso2carbon", "wso2carbon", keyPath, "wso2carbon");
    try {
        sc.sendRobust(payload);
        log.info("Request Sent");
    } catch (AxisFault axisFault) {
        log.error("AxisFault : " + axisFault.getMessage());
        throw axisFault;
    } finally {
        sc.cleanupTransport();
    }
}

15 View Complete Implementation : XdsTest.java
Copyright Apache License 2.0
Author : jembi
/**
 * Submits doreplacedent to the folder.
 * @param patientId
 * @return doreplacedent UUID
 * @throws Exception
 */
protected String submitDoreplacedent2Folder(String patientId) throws Exception {
    String message = IOUtils.toString(ProvideAndRegisterDoreplacedentSetTest.clreplaced.getResourcereplacedtream("/data/add_doreplacedent2_folder.xml"));
    String doreplacedent1 = IOUtils.toString(ProvideAndRegisterDoreplacedentSetTest.clreplaced.getResourcereplacedtream("/data/referral_summary.xml"));
    // replace doreplacedent , submission set and folder uniqueId variables with actual uniqueIds.
    message = message.replace("$XDSDoreplacedentEntry.uniqueId", "2.16.840.1.113883.3.65.2." + System.currentTimeMillis());
    message = message.replace("$XDSSubmissionSet.uniqueId", "1.3.6.1.4.1.21367.2009.1.2.108." + System.currentTimeMillis());
    String folderUniqueId = "2.16.840.1.113883.3.65.3." + System.currentTimeMillis();
    message = message.replace("$folder_uniqueid", folderUniqueId);
    // replace the doreplacedentId doc1 with an UUID
    String uuid = "urn:uuid:" + UUID.randomUUID().toString();
    message = message.replace("doc1", uuid);
    // replace the patient id
    message = message.replace("$patientId", patientId);
    ServiceClient sender = getRepositoryServiceClient();
    OMElement request = OMUtil.xmlStringToOM(message);
    // Add a referral summary doreplacedent
    request = addOneDoreplacedent(request, doreplacedent1, uuid);
    System.out.println("Request:\n" + request);
    OMElement response = sender.sendReceive(request);
    replacedertNotNull(response);
    OMAttribute status = response.getAttribute(new QName("status"));
    replacedertEquals("urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success", status.getAttributeValue());
    String result = response.toString();
    System.out.println("Result:\n" + result);
    return uuid;
}

15 View Complete Implementation : MicroIntegratorBaseUtils.java
Copyright Apache License 2.0
Author : wso2
/**
 * This is a utility method which can be used to set security headers in a service client. This method
 * will create authorization header according to basic security protocol. i.e. encodeBase64(username:preplacedword)
 * and put it in a HTTP header with name "Authorization".
 *
 * @param userName      User calling the service.
 * @param preplacedword      Preplacedword of the user.
 * @param rememberMe    <code>true</code> if UI asks to persist remember me cookie.
 * @param serviceClient The service client used in the communication.
 */
public static void setBasicAccessSecurityHeaders(String userName, String preplacedword, boolean rememberMe, ServiceClient serviceClient) {
    String userNamePreplacedword = userName + ":" + preplacedword;
    String encodedString = Base64Utils.encode(userNamePreplacedword.getBytes());
    String authorizationHeader = "Basic " + encodedString;
    List<Header> headers = new ArrayList<Header>();
    Header authHeader = new Header("Authorization", authorizationHeader);
    headers.add(authHeader);
    if (rememberMe) {
        Header rememberMeHeader = new Header("RememberMe", TRUE);
        headers.add(rememberMeHeader);
    }
    serviceClient.getOptions().setProperty(HTTPConstants.HTTP_HEADERS, headers);
}

15 View Complete Implementation : XdsTest.java
Copyright Apache License 2.0
Author : jembi
// return folder unique Id
protected String submitOneDoreplacedent2Folder(String patientId) throws Exception {
    String message = IOUtils.toString(ProvideAndRegisterDoreplacedentSetTest.clreplaced.getResourcereplacedtream("/data/add_doreplacedent2_folder.xml"));
    String doreplacedent1 = IOUtils.toString(ProvideAndRegisterDoreplacedentSetTest.clreplaced.getResourcereplacedtream("/data/referral_summary.xml"));
    // replace doreplacedent , submission set and folder uniqueId variables with actual uniqueIds.
    message = message.replace("$XDSDoreplacedentEntry.uniqueId", "2.16.840.1.113883.3.65.2." + System.currentTimeMillis());
    message = message.replace("$XDSSubmissionSet.uniqueId", "1.3.6.1.4.1.21367.2009.1.2.108." + System.currentTimeMillis());
    String folderUniqueId = "2.16.840.1.113883.3.65.3." + System.currentTimeMillis();
    message = message.replace("$folder_uniqueid", folderUniqueId);
    // replace the doreplacedentId doc1 with an UUID
    String uuid = "urn:uuid:" + UUID.randomUUID().toString();
    message = message.replace("doc1", uuid);
    // replace the patient id
    message = message.replace("$patientId", patientId);
    ServiceClient sender = getRepositoryServiceClient();
    OMElement request = OMUtil.xmlStringToOM(message);
    // Add a referral summary doreplacedent
    request = addOneDoreplacedent(request, doreplacedent1, uuid);
    System.out.println("Request:\n" + request);
    OMElement response = sender.sendReceive(request);
    replacedertNotNull(response);
    OMAttribute status = response.getAttribute(new QName("status"));
    replacedertEquals("urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Success", status.getAttributeValue());
    String result = response.toString();
    System.out.println("Result:\n" + result);
    return folderUniqueId;
}

15 View Complete Implementation : EventBrokerAdminClient.java
Copyright Apache License 2.0
Author : wso2
private void configureCookie(ServiceClient client) throws AxisFault {
    if (SessionCookie != null) {
        Options option = client.getOptions();
        option.setManageSession(true);
        option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, SessionCookie);
    }
}

14 View Complete Implementation : SecureAxisServiceClient.java
Copyright Apache License 2.0
Author : wso2
/**
 * @param userName
 * @param preplacedword
 * @param endpointReference
 * @param operation
 * @param payload
 * @param securityPolicyPath
 * @param userCertAlias
 * @param encryptionUser
 * @param keyStorePath
 * @param keyStorePreplacedword
 * @throws Exception
 */
public void sendRobust(String userName, String preplacedword, String endpointReference, String operation, OMElement payload, String securityPolicyPath, String userCertAlias, String encryptionUser, String keyStorePath, String keyStorePreplacedword) throws Exception {
    ServiceClient sc = getServiceClient(userName, preplacedword, endpointReference, operation, securityPolicyPath, userCertAlias, encryptionUser, keyStorePath, keyStorePreplacedword);
    if (log.isDebugEnabled()) {
        log.debug("payload :" + payload);
        log.debug("Security Policy Path :" + securityPolicyPath);
        log.debug("Operation :" + operation);
        log.debug("username :" + userName);
        log.debug("preplacedword :" + preplacedword);
    }
    log.info("Endpoint reference :" + endpointReference);
    try {
        sc.sendRobust(payload);
    } catch (AxisFault axisFault) {
        log.error("AxisFault : " + axisFault.getMessage());
        throw axisFault;
    } finally {
        sc.cleanupTransport();
    }
}

14 View Complete Implementation : SecureAxisServiceClient.java
Copyright Apache License 2.0
Author : wso2
/**
 * @param userName
 * @param preplacedword
 * @param endpointReference
 * @param operation
 * @param payload
 * @param securityPolicyPath
 * @param userCertAlias
 * @param encryptionUser
 * @param keyStorePath
 * @param keyStorePreplacedword
 * @return
 * @throws Exception
 */
public OMElement sendReceive(String userName, String preplacedword, String endpointReference, String operation, OMElement payload, String securityPolicyPath, String userCertAlias, String encryptionUser, String keyStorePath, String keyStorePreplacedword) throws Exception {
    ServiceClient sc = getServiceClient(userName, preplacedword, endpointReference, operation, securityPolicyPath, userCertAlias, encryptionUser, keyStorePath, keyStorePreplacedword);
    OMElement result;
    if (log.isDebugEnabled()) {
        log.debug("payload :" + payload);
        log.debug("Policy Path :" + securityPolicyPath);
        log.debug("Operation :" + operation);
        log.debug("username :" + userName);
        log.debug("preplacedword :" + preplacedword);
    }
    log.info("Endpoint reference :" + endpointReference);
    try {
        result = buildResponse(sc.sendReceive(payload));
        if (log.isDebugEnabled()) {
            log.debug("Response :" + result);
        }
    } catch (AxisFault axisFault) {
        log.error("AxisFault : " + axisFault.getMessage());
        throw axisFault;
    } finally {
        sc.cleanupTransport();
    }
    replacedert.replacedertNotNull(result);
    return result;
}

14 View Complete Implementation : RetrieveB.java
Copyright Apache License 2.0
Author : jembi
private OMElement call(OMElement metadata_ele, String endpoint) throws XdsWSException, XdsException, AxisFault {
    Options options = new Options();
    // this sets the location of MyService service
    options.setTo(new EndpointReference(endpoint));
    ServiceClient serviceClient = new ServiceClient();
    serviceClient.setOptions(options);
    OMElement result;
    Soap soap = new Soap();
    soap.setAsync(async);
    soap.soapCall(metadata_ele, // Protocol
    null, endpoint, // mtom
    true, // addressing
    true, // soap12
    soap12, getRequestAction(), getResponseAction());
    result = soap.getResult();
    return result;
}

13 View Complete Implementation : AuthenticateStub.java
Copyright Apache License 2.0
Author : wso2
/**
 * Stub authentication method
 *
 * @param stub          valid stub
 * @param sessionCookie session cookie
 */
public static void authenticateStub(String sessionCookie, Stub stub) {
    // Three minutes
    long soTimeout = 5 * 60 * 1000;
    ServiceClient client = stub._getServiceClient();
    Options option = client.getOptions();
    option.setManageSession(true);
    option.setTimeOutInMilliSeconds(soTimeout);
    option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, sessionCookie);
    if (log.isDebugEnabled()) {
        log.debug("AuthenticateStub : Stub created with session " + sessionCookie);
    }
}

13 View Complete Implementation : SetHeaderActionTestCase.java
Copyright Apache License 2.0
Author : wso2
private OMElement sendReceive(String trpUrl, String symbol) throws AxisFault {
    ServiceClient sender;
    Options options;
    OMElement response;
    sender = new ServiceClient();
    options = new Options();
    options.setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
    options.setAction("urn:getPrice123");
    if (trpUrl != null && !"null".equals(trpUrl)) {
        options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl);
    }
    sender.setOptions(options);
    response = sender.sendReceive(createStandardRequest(symbol));
    return response;
}

13 View Complete Implementation : AxisServiceClientUtils.java
Copyright Apache License 2.0
Author : wso2
public static void sendRequestOneWay(String payloadStr, EndpointReference targetEPR) throws XMLStreamException, AxisFault {
    OMElement payload = AXIOMUtil.stringToOM(payloadStr);
    Options options = new Options();
    options.setTo(targetEPR);
    // options.setAction("urn:" + operation); //since soapAction = ""
    // Blocking invocation
    ServiceClient sender = new ServiceClient();
    sender.setOptions(options);
    sender.fireAndForget(payload);
}

13 View Complete Implementation : SecurityVerificationTestCase.java
Copyright Apache License 2.0
Author : wso2
@Test(description = "Ensures that all Admin services are exposed only via HTTPS", enabled = false)
public void verifyAdminServiceSecurity() throws AxisFault, XPathExpressionException {
    ServiceClient client = new ServiceClient(null, null);
    Options opts = new Options();
    String serviceName = "SecurityVerifierService";
    EndpointReference epr = new EndpointReference(getServiceUrlHttp(serviceName));
    opts.setTo(epr);
    client.setOptions(opts);
    // robust send. Will get reply only if there is a fault
    client.sendRobust(createPayLoad());
    log.info("sent the message");
}

13 View Complete Implementation : XQueryReplaceEmptyMessageBody.java
Copyright Apache License 2.0
Author : wso2
private OMElement sendReceive(String endPointReference) throws AxisFault {
    ServiceClient sender;
    Options options;
    OMElement response;
    sender = new ServiceClient();
    options = new Options();
    options.setTo(new EndpointReference(endPointReference));
    options.setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
    options.setAction("urn:getQuote");
    sender.setOptions(options);
    response = sender.sendReceive(null);
    return response;
}

13 View Complete Implementation : PayloadFormatValueAndExpressionTestCase.java
Copyright Apache License 2.0
Author : wso2
@Test(groups = "wso2.esb", description = "invoke service - operation placeOrder")
public void invokeServiceFromXmlRequest() throws AxisFault {
    ServiceClient sender;
    Options options;
    sender = new ServiceClient();
    options = new Options();
    options.setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
    options.setAction("urn:placeOrder");
    options.setProperty(Constants.Configuration.TRANSPORT_URL, getProxyServiceURLHttps("PayloadFormatValueAndExpressionProxy"));
    sender.setOptions(options);
    sender.sendRobust(createPayload());
}

13 View Complete Implementation : Sample705TestCase.java
Copyright Apache License 2.0
Author : wso2
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = { "wso2.esb" }, description = "Test forwarding with load balancing")
public void loadBalancingTest() throws Exception {
    ServiceClient serviceClient = new ServiceClient();
    Options options = new Options();
    options.setTo(new EndpointReference(getProxyServiceURLHttp("Sample705StockQuoteProxy")));
    options.setAction("urn:placeOrder");
    serviceClient.setOptions(options);
    for (int i = 0; i < 100; i++) {
        serviceClient.sendRobust(createPayload());
    }
}