Example usage for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity

List of usage examples for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity.

Prototype

public StringRequestEntity(String paramString1, String paramString2, String paramString3)
  throws UnsupportedEncodingException

Source Link

Usage

From source file:org.apache.kylin.jdbc.stub.KylinClient.java

@Override
public void connect() throws ConnectionException {
    PostMethod post = new PostMethod(conn.getConnectUrl());
    HttpClient httpClient = new HttpClient();

    if (conn.getConnectUrl().toLowerCase().startsWith("https://")) {
        registerSsl();//from   w  ww.  j a  v a  2s. c o m
    }
    addPostHeaders(post);

    try {
        StringRequestEntity requestEntity = new StringRequestEntity("{}", "application/json", "UTF-8");
        post.setRequestEntity(requestEntity);
        httpClient.executeMethod(post);

        if (post.getStatusCode() != 200 && post.getStatusCode() != 201) {
            logger.error("Connect failed with error code " + post.getStatusCode() + " and message:\n"
                    + post.getResponseBodyAsString());

            throw new ConnectionException("Connect failed, error code " + post.getStatusCode()
                    + " and message: " + post.getResponseBodyAsString());
        }
    } catch (HttpException e) {
        logger.error(e.getLocalizedMessage(), e);
        throw new ConnectionException(e.getLocalizedMessage());
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage(), e);
        throw new ConnectionException(e.getLocalizedMessage());
    }
}

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java

/**
 * create and initialize the http method.
 * Http Headers that may been passed in the params are not set in this method.
 * Headers will be automatically set by HttpClient.
 * See usages of HostParams.DEFAULT_HEADERS
 * See org.apache.commons.httpclient.HttpMethodDirector#executeMethod(org.apache.commons.httpclient.HttpMethod)
 *///from ww  w .  jav a 2s . c o m
protected HttpMethod prepareHttpMethod(BindingOperation opBinding, String verb, Map<String, Element> partValues,
        Map<String, Node> headers, final String rootUri, HttpParams params)
        throws UnsupportedEncodingException {
    if (log.isDebugEnabled())
        log.debug("Preparing http request...");
    // convenience variables...
    BindingInput bindingInput = opBinding.getBindingInput();
    HTTPOperation httpOperation = (HTTPOperation) WsdlUtils.getOperationExtension(opBinding);
    MIMEContent content = WsdlUtils.getMimeContent(bindingInput.getExtensibilityElements());
    String contentType = content == null ? null : content.getType();
    boolean useUrlEncoded = WsdlUtils.useUrlEncoded(bindingInput)
            || PostMethod.FORM_URL_ENCODED_CONTENT_TYPE.equalsIgnoreCase(contentType);
    boolean useUrlReplacement = WsdlUtils.useUrlReplacement(bindingInput);

    // the http method to be built and returned
    HttpMethod method = null;

    // the 4 elements the http method may be made of
    String relativeUri = httpOperation.getLocationURI();
    String queryPath = null;
    RequestEntity requestEntity;
    String encodedParams = null;

    // ODE supports uri template in both port and operation location.
    // so assemble the final url *before* replacement
    String completeUri = rootUri;
    if (StringUtils.isNotEmpty(relativeUri)) {
        completeUri = completeUri + (completeUri.endsWith("/") || relativeUri.startsWith("/") ? "" : "/")
                + relativeUri;
    }

    if (useUrlReplacement) {
        // insert part values in the url
        completeUri = new UrlReplacementTransformer().transform(completeUri, partValues);
    } else if (useUrlEncoded) {
        // encode part values
        encodedParams = new URLEncodedTransformer().transform(partValues);
    }

    // http-client api is not really neat
    // something similar to the following would save some if/else manipulations.
    // But we have to deal with it as-is.
    //
    //  method = new Method(verb);
    //  method.setRequestEnity(..)
    //  etc...
    if ("GET".equalsIgnoreCase(verb) || "DELETE".equalsIgnoreCase(verb)) {
        if ("GET".equalsIgnoreCase(verb)) {
            method = new GetMethod();
        } else if ("DELETE".equalsIgnoreCase(verb)) {
            method = new DeleteMethod();
        }
        method.getParams().setDefaults(params);
        if (useUrlEncoded) {
            queryPath = encodedParams;
        }

        // Let http-client manage the redirection
        // see org.apache.commons.httpclient.params.HttpClientParams.MAX_REDIRECTS
        // default is 100
        method.setFollowRedirects(true);
    } else if ("POST".equalsIgnoreCase(verb) || "PUT".equalsIgnoreCase(verb)) {

        if ("POST".equalsIgnoreCase(verb)) {
            method = new PostMethod();
        } else if ("PUT".equalsIgnoreCase(verb)) {
            method = new PutMethod();
        }
        method.getParams().setDefaults(params);
        // some body-building...
        final String contentCharset = method.getParams().getContentCharset();
        if (log.isDebugEnabled())
            log.debug("Content-Type [" + contentType + "] Charset [" + contentCharset + "]");
        if (useUrlEncoded) {
            requestEntity = new StringRequestEntity(encodedParams, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE,
                    contentCharset);
        } else {
            // get the part to be put in the body
            Part part = opBinding.getOperation().getInput().getMessage().getPart(content.getPart());
            Element partValue = partValues.get(part.getName());

            if (part.getElementName() == null) {
                String errMsg = "XML Types are not supported. Parts must use elements.";
                if (log.isErrorEnabled())
                    log.error(errMsg);
                throw new RuntimeException(errMsg);
            } else if (HttpUtils.isXml(contentType)) {
                if (log.isDebugEnabled())
                    log.debug("Content-Type [" + contentType + "] equivalent to 'text/xml'");
                // stringify the first element
                String xmlString = DOMUtils.domToString(DOMUtils.getFirstChildElement(partValue));
                requestEntity = new StringRequestEntity(xmlString, contentType, contentCharset);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Content-Type [" + contentType
                            + "] NOT equivalent to 'text/xml'. The text content of part value will be sent as text");
                // encoding conversion is managed by StringRequestEntity if necessary
                requestEntity = new StringRequestEntity(DOMUtils.getTextContent(partValue), contentType,
                        contentCharset);
            }
        }

        // cast safely, PUT and POST are subclasses of EntityEnclosingMethod
        final EntityEnclosingMethod enclosingMethod = (EntityEnclosingMethod) method;
        enclosingMethod.setRequestEntity(requestEntity);
        enclosingMethod
                .setContentChunked(params.getBooleanParameter(Properties.PROP_HTTP_REQUEST_CHUNK, false));

    } else {
        // should not happen because of HttpBindingValidator, but never say never
        throw new IllegalArgumentException("Unsupported HTTP method: " + verb);
    }

    method.setPath(completeUri); // assumes that the path is properly encoded (URL safe).
    method.setQueryString(queryPath);

    // set headers
    setHttpRequestHeaders(method, opBinding, partValues, headers, params);
    return method;
}

From source file:org.apache.oodt.cas.filemgr.catalog.solr.SolrClient.java

/**
 * Method to execute a POST request to the given URL.
 * @param url/* w w w .  j  av a2  s.  c  o  m*/
 * @param document
 * @return
 */
private String doPost(String url, String document, String mimeType) throws IOException, CatalogException {

    // build HTTP/POST request
    PostMethod method = new PostMethod(url);
    StringRequestEntity requestEntity = new StringRequestEntity(document, mimeType, "UTF-8");
    method.setRequestEntity(requestEntity);

    // send HTTP/POST request, return response
    return doHttp(method);

}

From source file:org.apache.sling.discovery.impl.topology.connector.TopologyConnectorClient.java

/** ping the server and pass the announcements between the two **/
void ping(final boolean force) {
    if (autoStopped) {
        // then we suppress any further pings!
        logger.debug("ping: autoStopped=true, hence suppressing any further pings.");
        return;/*from   w ww  .  j a va  2s  .  c  om*/
    }
    if (force) {
        backoffPeriodEnd = -1;
    } else if (backoffPeriodEnd > 0) {
        if (System.currentTimeMillis() < backoffPeriodEnd) {
            logger.debug("ping: not issueing a heartbeat due to backoff instruction from peer.");
            return;
        } else {
            logger.debug("ping: backoff period ended, issuing another ping now.");
        }
    }
    final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json";
    if (logger.isDebugEnabled()) {
        logger.debug("ping: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
    }
    HttpClient httpClient = new HttpClient();
    final PutMethod method = new PutMethod(uri);
    Announcement resultingAnnouncement = null;
    try {
        String userInfo = connectorUrl.getUserInfo();
        if (userInfo != null) {
            Credentials c = new UsernamePasswordCredentials(userInfo);
            httpClient.getState()
                    .setCredentials(new AuthScope(method.getURI().getHost(), method.getURI().getPort()), c);
        }

        Announcement topologyAnnouncement = new Announcement(clusterViewService.getSlingId());
        topologyAnnouncement.setServerInfo(serverInfo);
        final ClusterView clusterView = clusterViewService.getClusterView();
        topologyAnnouncement.setLocalCluster(clusterView);
        if (force) {
            logger.debug("ping: sending a resetBackoff");
            topologyAnnouncement.setResetBackoff(true);
        }
        announcementRegistry.addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() {

            public boolean accept(final String receivingSlingId, final Announcement announcement) {
                // filter out announcements that are of old cluster instances
                // which I dont really have in my cluster view at the moment
                final Iterator<InstanceDescription> it = clusterViewService.getClusterView().getInstances()
                        .iterator();
                while (it.hasNext()) {
                    final InstanceDescription instance = it.next();
                    if (instance.getSlingId().equals(receivingSlingId)) {
                        // then I have the receiving instance in my cluster view
                        // all fine then
                        return true;
                    }
                }
                // looks like I dont have the receiving instance in my cluster view
                // then I should also not propagate that announcement anywhere
                return false;
            }
        });
        final String p = requestValidator.encodeMessage(topologyAnnouncement.asJSON());

        if (logger.isDebugEnabled()) {
            logger.debug("ping: topologyAnnouncement json is: " + p);
        }
        requestValidator.trustMessage(method, p);
        if (config.isGzipConnectorRequestsEnabled()) {
            // tell the server that the content is gzipped:
            method.addRequestHeader("Content-Encoding", "gzip");
            // and gzip the body:
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
            gzipOut.write(p.getBytes("UTF-8"));
            gzipOut.close();
            final byte[] gzippedEncodedJson = baos.toByteArray();
            method.setRequestEntity(new ByteArrayRequestEntity(gzippedEncodedJson, "application/json"));
            lastRequestEncoding = "gzip";
        } else {
            // otherwise plaintext:
            method.setRequestEntity(new StringRequestEntity(p, "application/json", "UTF-8"));
            lastRequestEncoding = "plaintext";
        }
        // independent of request-gzipping, we do accept the response to be gzipped,
        // so indicate this to the server:
        method.addRequestHeader("Accept-Encoding", "gzip");
        DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false);
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);
        httpClient.getHttpConnectionManager().getParams()
                .setConnectionTimeout(1000 * config.getConnectionTimeout());
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(1000 * config.getSoTimeout());
        method.getParams().setSoTimeout(1000 * config.getSoTimeout());
        httpClient.executeMethod(method);
        if (logger.isDebugEnabled()) {
            logger.debug("ping: done. code=" + method.getStatusCode() + " - " + method.getStatusText());
        }
        lastStatusCode = method.getStatusCode();
        lastResponseEncoding = null;
        if (method.getStatusCode() == HttpServletResponse.SC_OK) {
            final Header contentEncoding = method.getResponseHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue() != null
                    && contentEncoding.getValue().contains("gzip")) {
                lastResponseEncoding = "gzip";
            } else {
                lastResponseEncoding = "plaintext";
            }
            String responseBody = requestValidator.decodeMessage(method); // limiting to 16MB, should be way enough
            if (logger.isDebugEnabled()) {
                logger.debug("ping: response body=" + responseBody);
            }
            if (responseBody != null && responseBody.length() > 0) {
                Announcement inheritedAnnouncement = Announcement.fromJSON(responseBody);
                final long backoffInterval = inheritedAnnouncement.getBackoffInterval();
                if (backoffInterval > 0) {
                    // then reset the backoffPeriodEnd:

                    /* minus 1 sec to avoid slipping the interval by a few millis */
                    this.backoffPeriodEnd = System.currentTimeMillis() + (1000 * backoffInterval) - 1000;
                    logger.debug("ping: servlet instructed to backoff: backoffInterval=" + backoffInterval
                            + ", resulting in period end of " + new Date(backoffPeriodEnd));
                } else {
                    logger.debug("ping: servlet did not instruct any backoff-ing at this stage");
                    this.backoffPeriodEnd = -1;
                }
                if (inheritedAnnouncement.isLoop()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "ping: connector response indicated a loop detected. not registering this announcement from "
                                        + inheritedAnnouncement.getOwnerId());
                    }
                    if (inheritedAnnouncement.getOwnerId().equals(clusterViewService.getSlingId())) {
                        // SLING-3316 : local-loop detected. Check config to see if we should stop this connector

                        if (config.isAutoStopLocalLoopEnabled()) {
                            inheritedAnnouncement = null; // results in connected -> false and representsloop -> true
                            autoStopped = true; // results in isAutoStopped -> true
                        }
                    }
                } else {
                    inheritedAnnouncement.setInherited(true);
                    if (announcementRegistry.registerAnnouncement(inheritedAnnouncement) == -1) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "ping: connector response is from an instance which I already see in my topology"
                                            + inheritedAnnouncement);
                        }
                        statusDetails = "receiving side is seeing me via another path (connector or cluster) already (loop)";
                        return;
                    }
                }
                resultingAnnouncement = inheritedAnnouncement;
                statusDetails = null;
            } else {
                statusDetails = "no response body received";
            }
        } else {
            statusDetails = "got HTTP Status-Code: " + lastStatusCode;
        }
        // SLING-2882 : reset suppressPingWarnings_ flag in success case
        suppressPingWarnings_ = false;
    } catch (URIException e) {
        logger.warn("ping: Got URIException: " + e + ", uri=" + uri);
        statusDetails = e.toString();
    } catch (IOException e) {
        // SLING-2882 : set/check the suppressPingWarnings_ flag
        if (suppressPingWarnings_) {
            if (logger.isDebugEnabled()) {
                logger.debug("ping: got IOException: " + e + ", uri=" + uri);
            }
        } else {
            suppressPingWarnings_ = true;
            logger.warn("ping: got IOException [suppressing further warns]: " + e + ", uri=" + uri);
        }
        statusDetails = e.toString();
    } catch (JSONException e) {
        logger.warn("ping: got JSONException: " + e);
        statusDetails = e.toString();
    } catch (RuntimeException re) {
        logger.warn("ping: got RuntimeException: " + re, re);
        statusDetails = re.toString();
    } finally {
        method.releaseConnection();
        lastInheritedAnnouncement = resultingAnnouncement;
        lastPingedAt = System.currentTimeMillis();
    }
}

From source file:org.apache.synapse.transport.nhttp.NHttpTransportListenerTest.java

/**
 * Test the Source Handler respond to client.
 * Send a message to http listener and get the same request message as a response using PassThroughHttpSender
 *///ww w . j a v a2 s.co m
@Test
public void testRequestAndResponse() throws Exception {
    RequestURIBasedDispatcher requestURIBasedDispatcher = Mockito.mock(RequestURIBasedDispatcher.class);
    Mockito.when(requestURIBasedDispatcher.findService(any(MessageContext.class)))
            .thenReturn(new AxisService("myservice"));
    PowerMockito.whenNew(RequestURIBasedDispatcher.class).withNoArguments()
            .thenReturn(requestURIBasedDispatcher);
    PowerMockito.mockStatic(AxisEngine.class);
    PowerMockito.doAnswer(new Answer<Void>() {
        public Void answer(InvocationOnMock invocation) throws Exception {
            MessageContext axis2MessageContext = invocation.getArgument(0);
            ServiceContext svcCtx = new ServiceContext();
            OperationContext opCtx = new OperationContext(new InOutAxisOperation(), svcCtx);
            axis2MessageContext.setServiceContext(svcCtx);
            axis2MessageContext.setOperationContext(opCtx);
            axis2MessageContext.getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN,
                    "SKIP");
            axis2MessageContext.setTo(null);
            axis2MessageContext.setProperty("synapse.isresponse", true);
            HttpCoreNIOSender sender = new HttpCoreNIOSender();
            ConfigurationContext cfgCtx = new ConfigurationContext(new AxisConfiguration());
            sender.init(cfgCtx, new TransportOutDescription("http"));
            sender.invoke(axis2MessageContext);
            return null;
        }
    }).when(AxisEngine.class, "receive", any(MessageContext.class));

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(ServiceUtils.getServiceEndpoint("myservice", HOST, PORT));
    method.setRequestHeader("Content-Type", "application/xml");
    StringRequestEntity stringRequestEntity = new StringRequestEntity("<msg>hello</msg>", "application/xml",
            "UTF-8");
    method.setRequestEntity(stringRequestEntity);
    int responseCode = client.executeMethod(method);
    Assert.assertEquals("Response code mismatched", 200, responseCode);
    String response = method.getResponseBodyAsString();
    Assert.assertEquals("Response", "<msg>hello</msg>", response);
}

From source file:org.apache.synapse.transport.nhttp.NHttpTransportListenerTest.java

/**
 * Test the Source Handler respond to client.
 * Send a message to http listener and get the response from backend server.
 *///from   w w w .ja  va 2  s .co  m
@Test
public void testBackendResponse() throws Exception {
    final SimpleHttpServer helloServer = new SimpleHttpServer();
    try {
        helloServer.start();
        RequestURIBasedDispatcher requestURIBasedDispatcher = Mockito.mock(RequestURIBasedDispatcher.class);
        Mockito.when(requestURIBasedDispatcher.findService(any(MessageContext.class)))
                .thenReturn(new AxisService("myservice"));
        PowerMockito.whenNew(RequestURIBasedDispatcher.class).withNoArguments()
                .thenReturn(requestURIBasedDispatcher);
        PowerMockito.mockStatic(AxisEngine.class);
        PowerMockito.doAnswer(new Answer<Void>() {
            public Void answer(InvocationOnMock invocation) throws Exception {
                MessageContext axis2MessageContext = invocation.getArgument(0);
                if (axis2MessageContext.getServiceContext() == null) {
                    //request path
                    ServiceContext svcCtx = new ServiceContext();
                    OperationContext opCtx = new OperationContext(new InOutAxisOperation(), svcCtx);
                    axis2MessageContext.setServiceContext(svcCtx);
                    axis2MessageContext.setOperationContext(opCtx);
                    axis2MessageContext.setProperty("TransportURL", helloServer.getServerUrl());
                    inMsgContext = axis2MessageContext;
                } else {
                    //response path
                    axis2MessageContext.setTo(null);
                    axis2MessageContext.setProperty("synapse.isresponse", true);
                    axis2MessageContext.removeProperty("TransportURL");
                    axis2MessageContext.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
                            inMsgContext.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
                    axis2MessageContext.getOperationContext()
                            .setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP");
                }
                HttpCoreNIOSender sender = new HttpCoreNIOSender();
                ConfigurationContext cfgCtx = new ConfigurationContext(new AxisConfiguration());
                sender.init(cfgCtx, new TransportOutDescription("http"));
                sender.invoke(axis2MessageContext);
                return null;
            }
        }).when(AxisEngine.class, "receive", any(MessageContext.class));

        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(ServiceUtils.getServiceEndpoint("myservice", HOST, PORT));
        method.setRequestHeader("Content-Type", "application/xml");
        StringRequestEntity stringRequestEntity = new StringRequestEntity("<msg>hello server</msg>",
                "application/xml", "UTF-8");
        method.setRequestEntity(stringRequestEntity);
        int responseCode = client.executeMethod(method);
        Assert.assertEquals("Response code mismatched", 200, responseCode);
        String response = method.getResponseBodyAsString();
        Assert.assertEquals("Response", "<msg>hello</msg>", response);
    } finally {
        helloServer.stop();
    }
}

From source file:org.apache.synapse.transport.passthru.RequestResponseTest.java

/**
 * Test the request ack when Source Handler received a request.
 *///from w ww .  j  a  va  2s .c  o m
@Test
public void testRequestAck() throws Exception {
    PowerMockito.mockStatic(AxisEngine.class);
    PowerMockito.doNothing().doThrow(new RuntimeException()).when(AxisEngine.class);

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(ServiceUtils.getServiceEndpoint("myservice", HOST, PORT));
    method.setRequestHeader("Content-Type", "application/xml");
    StringRequestEntity stringRequestEntity = new StringRequestEntity("<msg>hello</msg>", "application/xml",
            "UTF-8");
    method.setRequestEntity(stringRequestEntity);
    int responseCode = client.executeMethod(method);
    method.getResponseBodyAsString();
    Assert.assertEquals("Response code mismatched", 202, responseCode);
}

From source file:org.apache.synapse.transport.passthru.RequestResponseTest.java

/**
 * Test the Source Handler respond to client.
 * Send a message to http listener and get the same request message as a response using PassThroughHttpSender
 */// ww  w .  ja v a 2 s.c o  m
@Test
public void testRequestAndResponse() throws Exception {
    PowerMockito.mockStatic(AxisEngine.class);
    PowerMockito.doAnswer(new Answer<Void>() {
        public Void answer(InvocationOnMock invocation) throws Exception {
            MessageContext axis2MessageContext = invocation.getArgument(0);
            axis2MessageContext.setTo(null);
            if (axis2MessageContext.getServiceContext() == null) {
                ServiceContext svcCtx = new ServiceContext();
                OperationContext opCtx = new OperationContext(new InOutAxisOperation(), svcCtx);
                axis2MessageContext.setServiceContext(svcCtx);
                axis2MessageContext.setOperationContext(opCtx);
            }
            axis2MessageContext.getOperationContext().setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN,
                    "SKIP");
            ServiceUtils.receive(axis2MessageContext);
            return null;
        }
    }).when(AxisEngine.class, "receive", any(MessageContext.class));

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(ServiceUtils.getServiceEndpoint("myservice", HOST, PORT));
    method.setRequestHeader("Content-Type", "application/xml");
    StringRequestEntity stringRequestEntity = new StringRequestEntity("<msg>hello</msg>", "application/xml",
            "UTF-8");
    method.setRequestEntity(stringRequestEntity);
    int responseCode = client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    Assert.assertEquals("Response code mismatched", 200, responseCode);
    Assert.assertEquals("Response", "<msg>hello</msg>", response);
}

From source file:org.apache.synapse.transport.passthru.RequestResponseTest.java

/**
 * Test the Source Handler respond to client.
 * Send a message to http listener and get the response from backend server.
 *///from   ww  w .j a v  a 2  s .  com
@Test
public void testBackendResponse() throws Exception {
    final SimpleHttpServer helloServer = new SimpleHttpServer();
    try {
        helloServer.start();
        PowerMockito.mockStatic(AxisEngine.class);
        PowerMockito.doAnswer(new Answer<Void>() {
            public Void answer(InvocationOnMock invocation) throws Exception {
                MessageContext axis2MessageContext = invocation.getArgument(0);
                if (axis2MessageContext.getServiceContext() == null) {
                    //request path
                    axis2MessageContext.setProperty("TransportURL", helloServer.getServerUrl());
                    inMsgContext = axis2MessageContext;
                } else {
                    //response path
                    axis2MessageContext.removeProperty("TransportURL");
                    axis2MessageContext.setTo(null);
                    axis2MessageContext.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
                            inMsgContext.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
                    axis2MessageContext.getOperationContext()
                            .setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP");
                }
                ServiceUtils.receive(axis2MessageContext);
                return null;
            }
        }).when(AxisEngine.class, "receive", any(MessageContext.class));

        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(ServiceUtils.getServiceEndpoint("myservice", HOST, PORT));
        method.setRequestHeader("Content-Type", "application/xml");
        StringRequestEntity stringRequestEntity = new StringRequestEntity("<msg>hello Server</msg>",
                "application/xml", "UTF-8");
        method.setRequestEntity(stringRequestEntity);
        int responseCode = client.executeMethod(method);
        String response = method.getResponseBodyAsString();
        Assert.assertEquals("Response code mismatched", 200, responseCode);
        Assert.assertEquals("Response", "<msg>hello</msg>", response);
    } finally {
        helloServer.stop();
    }

}

From source file:org.apache.synapse.transport.passthru.SourceHandlerTest.java

/**
 * Test the Source Handler respond to client.
 * Send a message to http listener and get the same request message as a response using PassThroughHttpSender
 *///w w  w .ja  va 2 s . c  o m
@Test
public void testRequestAndResponse() throws Exception {
    PowerMockito.mockStatic(AxisEngine.class);
    PowerMockito.doAnswer(new Answer<Void>() {
        public Void answer(InvocationOnMock invocation) throws Exception {
            MessageContext axis2MessageContext = invocation.getArgument(0);
            ServiceUtils.receive(axis2MessageContext);
            return null;
        }
    }).when(AxisEngine.class, "receive", any(MessageContext.class));

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(ServiceUtils.getServiceEndpoint("myservice", HOST, PORT));
    method.setRequestHeader("Content-Type", "application/xml");
    StringRequestEntity stringRequestEntity = new StringRequestEntity("<msg>hello</msg>", "application/xml",
            "UTF-8");
    method.setRequestEntity(stringRequestEntity);
    int responseCode = client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    Assert.assertEquals("Response code mismatched", 200, responseCode);
    Assert.assertEquals("Response", "<msg>hello</msg>", response);
}