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:net.jadler.JadlerMockingIntegrationTest.java

@Test
public void havingParameterPOST() throws Exception {
    final String body = "p1=p1v1&p2=p2v1&p2=p2v2&p3=&p4&url%20encoded=url%20encoded";

    final PostMethod method = new PostMethod("http://localhost:" + port() + "?p2=p2v3");
    method.setRequestEntity(new StringRequestEntity(body, "application/x-www-form-urlencoded", "UTF-8"));

    client.executeMethod(method);//from w w  w  .  j av a  2s. c  om

    verifyThatRequest().havingParameter("p1").havingParameter("p1", hasSize(1))
            .havingParameter("p1", everyItem(not(isEmptyOrNullString())))
            .havingParameter("p1", contains("p1v1")).havingParameterEqualTo("p1", "p1v1").havingParameter("p2")
            .havingParameter("p2", hasSize(3)).havingParameter("p2", hasItems("p2v1", "p2v2", "p2v3"))
            .havingParameterEqualTo("p2", "p2v1").havingParameterEqualTo("p2", "p2v2")
            .havingParameterEqualTo("p2", "p2v3").havingParameters("p1", "p2").havingParameter("p3")
            .havingParameter("p3", contains("")).havingParameterEqualTo("p3", "").havingParameter("p4")
            .havingParameter("p4", contains("")).havingParameterEqualTo("p4", "")
            .havingParameter("p5", nullValue()).havingParameter("url%20encoded", contains("url%20encoded"))
            .havingBodyEqualTo(body).receivedOnce();
}

From source file:net.bpelunit.framework.control.run.TestCaseRunner.java

/**
 * /*from ww w  .  j a  v a2  s  .  c om*/
 * Sends a synchronous message, waits for the result, and returns the
 * result. This method blocks until either a result has been retrieved, a
 * send error has occurred, or the thread was interrupted.
 * 
 * @param message
 *            the message to be sent
 * @return the resulting incoming message
 * @throws SynchronousSendException
 * @throws InterruptedException
 */
public IncomingMessage sendMessageSynchronous(OutgoingMessage message)
        throws SynchronousSendException, InterruptedException {
    PostMethod method = new PostMethod(message.getTargetURL());

    // Set parameters:
    // -> Do not retry
    // -> Socket timeout to default timeout value.
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, Integer.valueOf(BPELUnitRunner.getTimeout()));

    method.addRequestHeader("SOAPAction", "\"" + message.getSOAPHTTPAction() + "\"");
    RequestEntity entity;
    try {
        entity = new StringRequestEntity(message.getMessageAsString(), BPELUnitConstants.TEXT_XML_CONTENT_TYPE,
                BPELUnitConstants.DEFAULT_HTTP_CHARSET);
    } catch (UnsupportedEncodingException e) {
        // cannot happen since we use the default HTTP Encoding.
        throw new SynchronousSendException("Unsupported encoding when trying to post message to web service.",
                e);
    }

    for (String option : message.getProtocolOptionNames()) {
        method.addRequestHeader(option, message.getProtocolOption(option));
    }
    method.setRequestEntity(entity);

    try {
        // Execute the method.

        int statusCode = fClient.executeMethod(method);
        InputStream in = method.getResponseBodyAsStream();

        IncomingMessage returnMsg = new IncomingMessage();
        returnMsg.setStatusCode(statusCode);
        returnMsg.setMessage(in);

        return returnMsg;

    } catch (Exception e) {
        if (isAborting()) {
            throw new InterruptedException();
        } else {
            throw new SynchronousSendException(e);
        }
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

}

From source file:com.twinsoft.convertigo.beans.steps.SequenceStep.java

protected void prepareForRequestable(Context javascriptContext, Scriptable scope)
        throws MalformedURLException, EngineException {
    Sequence targetSequence = getTargetSequence();

    if (Engine.isStudioMode()) {
        if (targetSequence != null) {
            if (sequence.getOriginal().equals(targetSequence.getOriginal())) {
                throw new EngineException("Execution of recursive sequence is not allowed in Studio mode!");
            }/*from  w w  w  .jav a  2 s .co m*/
        }
    }

    String ctxName = getContextName(javascriptContext, scope);
    boolean useSequenceJSession = sequence.useSameJSessionForSteps();
    boolean maintainContext = useSequenceJSession && !ctxName.startsWith("Container-");
    boolean maintainSession = useSequenceJSession;

    boolean inheritContex = inheritTransactionCtx && sequence.equals(getTransactionContextMaintainer());
    String inheritedCxtName = sequence.getInheritedContextName();
    inheritedCxtName = (inheritContex && (inheritedCxtName == null)) ? sequence.getContextName()
            : inheritedCxtName;
    inheritedCxtName = (inheritedCxtName == null) ? "" : inheritedCxtName;

    if (isInternalInvoke()) {
        request.put(Parameter.Project.getName(), new String[] { projectName });
        request.put(Parameter.MotherSequenceContext.getName(), new String[] { sequence.context.contextID });
        request.put(Parameter.Sequence.getName(), new String[] { targetSequence.getName() });
        request.put(Parameter.Context.getName(), new String[] { sequence.addStepContextName(ctxName) });
        request.put(Parameter.SequenceInheritedTransactionContext.getName(),
                inheritContex ? new String[] { inheritedCxtName } : new String[] { "" });
        if (!maintainContext)
            request.put(Parameter.RemoveContext.getName(), new String[] { "" });
        if (!maintainSession)
            request.put(Parameter.RemoveSession.getName(), new String[] { "" });
        getPostQuery(scope);
    } else {
        targetUrl = EnginePropertiesManager.getProperty(PropertyName.APPLICATION_SERVER_CONVERTIGO_URL);
        targetUrl += "/projects/" + projectName + "/.xml?";

        URL url = new URL(targetUrl);
        String host = url.getHost();
        int port = url.getPort();

        Engine.logBeans.trace("(SequenceStep) Host: " + host + ":" + port);
        hostConfiguration.setHost(host, port);

        // Retrieves new HttpState!!
        // This will force a new http session on convertigo server : new context for sequence
        httpState = sequence.getNewHttpState();

        method = new PostMethod(targetUrl);
        method.setRequestHeader("Content-Type", MimeType.WwwForm.value());

        // Set transaction sessionId from context maintainer
        String sessionId = getTransactionSessionId();
        if (useSequenceJSession) {
            Engine.logBeans.trace("(SequenceStep) JSESSIONID required : " + sessionId);
            if (sessionId != null) {
                method.setRequestHeader("Cookie", "JSESSIONID=" + sessionId + ";");
                Engine.logBeans.trace("(SequenceStep) JSESSIONID used : " + sessionId);
            } else {
                Engine.logBeans.trace("(SequenceStep) JSESSIONID is null");
            }
        } else {
            if (sessionId != null) {
                method.addRequestHeader("Transaction-JSessionId", sessionId);
                Engine.logBeans.trace("(SequenceStep) Transaction JSESSIONID used : " + sessionId);
            } else {
                Engine.logBeans.trace("(SequenceStep) Transaction JSESSIONID is null");
            }
        }

        String postQuery = getPostQuery(scope);
        if (!maintainContext && (postQuery.indexOf(Parameter.RemoveContext.getName()) == -1))
            postQuery = addParamToPostQuery(Parameter.RemoveContext.getName(), "", postQuery);
        if (!maintainSession && (postQuery.indexOf(Parameter.RemoveSession.getName()) == -1))
            postQuery = addParamToPostQuery(Parameter.RemoveSession.getName(), "", postQuery);
        if (postQuery.indexOf(Parameter.SequenceInheritedTransactionContext.getName()) == -1)
            postQuery = addParamToPostQuery(Parameter.SequenceInheritedTransactionContext.getName(),
                    inheritContex ? inheritedCxtName : "", postQuery);
        if (postQuery.indexOf(Parameter.Sequence.getName()) == -1)
            postQuery = addParamToPostQuery(Parameter.Sequence.getName(), targetSequence.getName(), postQuery);
        if (postQuery.indexOf(Parameter.Context.getName()) == -1)
            postQuery = addParamToPostQuery(Parameter.Context.getName(), sequence.addStepContextName(ctxName),
                    postQuery);
        if (postQuery.indexOf(Parameter.MotherSequenceContext.getName()) == -1)
            postQuery = addParamToPostQuery(Parameter.MotherSequenceContext.getName(),
                    sequence.context.contextID, postQuery);

        if (Engine.logBeans.isTraceEnabled())
            Engine.logBeans.trace(
                    "(SequenceStep) postQuery :" + Visibility.Logs.replaceVariables(getVariables(), postQuery));

        try {
            method.setRequestEntity(new StringRequestEntity(postQuery, null, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new EngineException("Encoding error", e);
        }
    }
}

From source file:com.adobe.people.jedelson.aemslack.impl.Notifier.java

private void sendMessage(SlackMessage msg) throws HttpException, IOException {
    PostMethod pm = new PostMethod(url);
    pm.setRequestEntity(new StringRequestEntity(msg.toJsonString(), "application/json", "UTF-8"));
    httpClient.executeMethod(pm);//from w  w w .  ja  v a 2  s . co m
}

From source file:cuanto.api.CuantoConnector.java

/**
 * Creates a new TestOutcome for the specified TestRun on the Cuanto server using the details provided.  The ID value on
 * the testOutcome argument will be set upon successful creation.
 *
 * @param testOutcome The TestOutcome to be created on the Cuanto server.
 * @param testRun     The TestRun to which the TestOutcome should be added.
 * @return The server-assigned ID of the TestOutcome.
 *//*from w ww. j a  v  a2  s.c  o  m*/
public Long addTestOutcome(TestOutcome testOutcome, TestRun testRun) {
    PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, getCuantoUrl() + "/api/addTestOutcome");
    try {
        testOutcome.setTestRun(testRun);
        testOutcome.setProjectKey(this.projectKey);
        post.setRequestEntity(new StringRequestEntity(testOutcome.toJSON(), "application/json", null));
        int httpStatus = getHttpClient().executeMethod(post);
        if (httpStatus == HttpStatus.SC_CREATED) {
            TestOutcome fetchedOutcome = TestOutcome.fromJSON(getResponseBodyAsString(post));
            testOutcome.setId(fetchedOutcome.getId());
            testOutcome.getTestCase().setId(fetchedOutcome.getTestCase().getId());
            return fetchedOutcome.getId();
        } else {
            throw new RuntimeException("Adding the TestOutcome failed with HTTP status code " + httpStatus
                    + ": \n" + getResponseBodyAsString(post));
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ParseException e) {
        throw new RuntimeException("Error parsing server response", e);
    }
}

From source file:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java

/**
 *
 * @param endpoint// ww  w  .ja v  a  2 s  .  c om
 *            the url to the service to call
 * @param xml
 *            the BioMOBY input message
 * @return EndpointReference the EPR returned by the service
 * @throws MobyException
 */
private static EndpointReference launchCgiAsyncService(String endpoint, String xml) throws MobyException {
    // construct the Httpclient
    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "jMoby/Taverna2");
    // create the post method
    PostMethod method = new PostMethod(endpoint);

    // put our data in the request
    RequestEntity entity;
    try {
        entity = new StringRequestEntity(xml, "text/xml", null);
    } catch (UnsupportedEncodingException e) {
        throw new MobyException("Problem posting data to webservice", e);
    }
    method.setRequestEntity(entity);

    // retry up to 10 times
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(10, true));

    // call the method
    try {
        int result = client.executeMethod(method);
        if (result != HttpStatus.SC_OK)
            throw new MobyException(
                    "Async HTTP POST service returned code: " + result + "\n" + method.getStatusLine());
        return EndpointReference.createFromXML(method.getResponseHeader("moby-wsrf").getValue());
    } catch (IOException e) {
        throw new MobyException("Problem reading response from webservice", e);
    } finally {
        // Release current connection to the connection pool once you are
        // done
        method.releaseConnection();
    }
}

From source file:it.geosolutions.geonetwork.util.HTTPUtils.java

/**
 * POSTs a String to the given URL./*  w  ww.  ja  va  2 s  .co m*/
 *
 * @param url       The URL where to connect to.
 * @param content   The content to be sent as a String.
 * @param contentType The content-type to advert in the POST.
 * @return          The HTTP response as a String if the HTTP response code was 200 (OK).
 * @throws MalformedURLException
 * @return the HTTP response or <TT>null</TT> on errors.
 */
public String post(String url, String content, String contentType) {
    try {
        return post(url, new StringRequestEntity(content, contentType, null));
    } catch (UnsupportedEncodingException ex) {
        LOGGER.error("Cannot POST " + url, ex);
        return null;
    }
}

From source file:ch.gadp.alfresco.OAuthSSOAuthenticationFilter.java

protected String saveUser(String username, GoogleProfileInfo userInfo, String adminTicket, boolean newUser)
        throws IOException {
    logger.warn("saveUser " + username);
    EntityEnclosingMethod saveUserMethod;
    if (newUser) {
        saveUserMethod = new PostMethod(getAPIUri(REPOSITORY_API_PEOPLE));
    } else {/*from www  .  j a v a2  s.co m*/
        saveUserMethod = new PutMethod(getAPIUri(REPOSITORY_API_PEOPLE) + "/" + username);
    }

    this.addTicketParameter(saveUserMethod, adminTicket);

    String input = "{ " + (newUser ? "\"userName\" : \"" + username + "\", " : "") + "\"firstName\" : \""
            + userInfo.getGiven_name() + "\", " + "\"lastName\" : \"" + userInfo.getFamily_name() + "\", "
            + "\"email\" : \"" + userInfo.getEmail() + "\", "
            + (newUser ? "\"password\" : \"" + getConfigurationValue(USER_PASSWORD) + "\"" : "") + " }";

    saveUserMethod.setRequestEntity(new StringRequestEntity(input, "application/json", "utf-8"));
    HttpClient client = new HttpClient();

    return client.executeMethod(saveUserMethod) == HttpStatus.SC_OK ? username : null;
}

From source file:com.salesmanager.core.module.impl.integration.payment.AuthorizeNetTransactionImpl.java

private GatewayTransactionVO makeTransaction(String type, IntegrationKeys ik, IntegrationProperties props,
        MerchantStore store, Order order, Customer customer, CoreModuleService cis)
        throws TransactionException {

    PostMethod httppost = null;//from  w w w.  j ava  2  s. c om
    try {

        String host = cis.getCoreModuleServiceProdDomain();
        String protocol = cis.getCoreModuleServiceProdProtocol();
        String port = cis.getCoreModuleServiceProdPort();
        String url = cis.getCoreModuleServiceProdEnv();
        if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) {
            host = cis.getCoreModuleServiceDevDomain();
            protocol = cis.getCoreModuleServiceDevProtocol();
            port = cis.getCoreModuleServiceDevPort();
            url = cis.getCoreModuleServiceDevEnv();
        }

        // sb builds the nv pair to authorize net
        StringBuffer sb = new StringBuffer();

        // mandatory name/value pairs for all AIM CC transactions
        // as well as some "good to have" values
        sb.append("x_login=").append(ik.getUserid()).append("&"); // replace
        // with
        // your
        // own
        sb.append("x_tran_key=").append(ik.getTransactionKey()).append("&"); // replace
        // with
        // your
        // own
        sb.append("x_version=3.1&");// set to required in the specs

        // if dev
        if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) {
            sb.append("x_test_request=TRUE&"); // for testing
        }

        sb.append("x_method=CC&");// required, CC or ECHECK
        sb.append("x_type=").append(type).append("&");

        // need ccard number
        sb.append("x_card_num=").append(order.getCcNumber()).append("&");
        sb.append("x_exp_date=").append(order.getCcExpires()).append("&");
        sb.append("x_amount=").append(order.getTotal()).append("&");
        if (props.getProperties3().equals("2")) {
            sb.append("x_card_code=").append(order.getCcCvv()).append("&");
        }

        sb.append("x_delim_data=TRUE&");
        sb.append("x_delim_char=|&");
        sb.append("x_relay_response=FALSE&");

        // sx builds the xml for persisting local
        StringBuffer sx = new StringBuffer();

        sx.append("<transaction>");

        sx.append("<x_login>").append(ik.getUserid()).append("</x_login>"); // replace
        // with
        // your
        // own
        sx.append("<x_tran_key>").append(ik.getTransactionKey()).append("</x_tran_key>"); // replace with your own
        sx.append("<x_version>3.1</x_version>");// set to required in the
        // specs

        // if dev
        if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) {
            sx.append("<x_test_request>TRUE</x_test_request>"); // for
            // testing
        }

        sx.append("<x_method>CC</x_method>");// required, CC or ECHECK
        sx.append("<x_type>AUTH_ONLY</x_type>");

        // need ccard number
        sx.append("<x_card_num>").append(order.getCcNumber()).append("</x_card_num>");// at least 4 last card digit
        sx.append("<x_exp_date>").append(order.getCcExpires()).append("</x_exp_date>");
        sx.append("<x_amount>").append(order.getTotal()).append("</x_amount>");
        if (props.getProperties3().equals("2")) {
            sx.append("<x_card_code>").append(order.getCcCvv()).append("</x_card_code>");
        }

        sx.append("<x_delim_data>TRUE</x_delim_data>");
        sx.append("<x_delim_char>|</x_delim_char>");
        sx.append("<x_relay_response>FALSE</x_relay_response>");

        sx.append("</transaction>");

        /** debug **/
        // sb builds the nv pair to authorize net
        StringBuffer sblog = new StringBuffer();
        sblog.append("x_login=").append(ik.getUserid()).append("&"); // replace
        // with
        // your
        // own
        sblog.append("x_tran_key=").append(ik.getTransactionKey()).append("&"); // replace                                                   // own
        sblog.append("x_version=3.1&");// set to required in the specs
        if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) {
            sblog.append("x_test_request=TRUE&"); // for testing
        }

        sblog.append("x_method=CC&");// required, CC or ECHECK
        sblog.append("x_type=").append(type).append("&");
        sblog.append("x_card_num=").append(CreditCardUtil.maskCardNumber(order.getCcNumber())).append("&");
        sblog.append("x_exp_date=").append(order.getCcExpires()).append("&");
        sblog.append("x_amount=").append(order.getTotal()).append("&");
        if (props.getProperties3().equals("2")) {
            sblog.append("x_card_code=").append(order.getCcCvv()).append("&");
        }
        sblog.append("x_delim_data=TRUE&");
        sblog.append("x_delim_char=|&");
        sblog.append("x_relay_response=FALSE&");

        log.debug("Transaction sent -> " + sblog.toString());
        /**
         * log
         */

        HttpClient client = new HttpClient();

        httppost = new PostMethod(protocol + "://" + host + ":" + port + url);
        RequestEntity entity = new StringRequestEntity(sb.toString(), "text/plain", "UTF-8");
        httppost.setRequestEntity(entity);

        String stringresult = null;

        int result = client.executeMethod(httppost);
        if (result != 200) {
            log.error("Communication Error with Authorizenet " + protocol + "://" + host + ":" + port + url);
            throw new Exception(
                    "Communication Error with Authorizenet " + protocol + "://" + host + ":" + port + url);
        }

        // stringresult = httppost.getResponseBodyAsString();
        // log.debug("AuthorizeNet response " +stringresult);

        stringresult = httppost.getResponseBodyAsString();
        log.debug("AuthorizeNet response " + stringresult);

        StringBuffer appendresult = new StringBuffer().append(order.getTotal()).append("|")
                .append(stringresult);

        // Format to xml
        //
        String finalresult = this.readresponse("|", appendresult.toString());

        AuthorizeNetParsedElements pe = new AuthorizeNetParsedElements();
        Digester digester = new Digester();
        digester.push(pe);

        digester.addCallMethod("transaction/transactionid", "setTransactionId", 0);
        digester.addCallMethod("transaction/approvalcode", "setApprovalCode", 0);
        digester.addCallMethod("transaction/responsecode", "setResponseCode", 0);
        digester.addCallMethod("transaction/amount", "setTransactionAmount", 0);
        digester.addCallMethod("transaction/reasontext", "setReasontext", 0);
        digester.addCallMethod("transaction/reasoncode", "setReasonCode", 0);

        Reader reader = new StringReader(finalresult);

        digester.parse(reader);

        // check if you need it
        // pe.setTransactionId(trx.getTransactionDetails().getMerchantPaymentGwOrderid());//BECAUSE
        // NOT RETURNED FROM AUTHORIZE NET !!!!

        if (type.equals("AUTH_CAPTURE")) {

            return this.parseResponse(PaymentConstants.SALE, sx.toString(), finalresult, pe, order,
                    order.getTotal());

        } else {// AUTH_ONLY

            return this.parseResponse(PaymentConstants.PREAUTH, sx.toString(), finalresult, pe, order,
                    order.getTotal());

        }

    } catch (Exception e) {
        if (e instanceof TransactionException) {
            throw (TransactionException) e;
        }
        log.error(e);

        TransactionException te = new TransactionException("AuthorizeNet Gateway error ", e);
        throw te;
    } finally {
        if (httppost != null) {
            httppost.releaseConnection();
        }
    }

}

From source file:com.evolveum.midpoint.model.impl.bulkmodify.PostXML.java

/**
 * This method takes emailAddress as a search value and returns user's oid with the given emailAddress
 *
 * @param emailAddress/*from  w  w w. j ava2  s .  co  m*/
 * @return user object's oid if the given username exists. Empty String if the emailAddress does not exist.
 * @throws Exception
 *
 * This method
 */
public String searchByEmailPostMethod(String emailAddress) throws Exception {
    String returnOid = "";

    // Get target URL
    String strURL = "http://localhost:8080/midpoint/ws/rest/users/search";

    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);

    //AUTHENTICATION
    String userPass = this.getUsername() + ":" + this.getPassword();
    String basicAuth = "Basic "
            + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8"));
    post.addRequestHeader("Authorization", basicAuth);

    //construct searching string. place "name" attribute into <values> tags.
    String sendingXml = XML_TEMPLATE_SEARCH_BYEMAIL;

    sendingXml = sendingXml.replace("<value></value>", "<value>" + emailAddress + "</value>");

    RequestEntity userSearchEntity = new StringRequestEntity(sendingXml, "application/xml", "UTF-8");
    post.setRequestEntity(userSearchEntity);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {
        int result = httpclient.executeMethod(post);
        // Display status code
        //System.out.println("Response status code: " + result);
        // Display response
        //System.out.println("Response body: ");
        // System.out.println(post.getResponseBodyAsString());
        String sbf = new String(post.getResponseBodyAsString());
        //System.out.println(sbf);

        //find oid
        if (sbf.contains("oid")) {
            int begin = sbf.indexOf("oid");
            returnOid = (sbf.substring(begin + 5, begin + 41));
        }

    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }

    return returnOid;
}