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:com.apifest.oauth20.tests.OAuth20BasicTest.java

public boolean revokeAccessToken(String token, String currentClientId, String currentClientSecret) {
    PostMethod post = new PostMethod(baseOAuth20Uri + TOKEN_REVOKE_ENDPOINT);
    String response = null;//from   w ww  .ja va  2 s. co  m
    boolean revoked = false;
    try {
        JSONObject reqJson = new JSONObject();
        reqJson.put(ACCESS_TOKEN_PARAM, token);
        reqJson.put(CLIENT_ID_PARAM, clientId);
        reqJson.put(CLIENT_SECRET_PARAM, clientSecret);
        String requestBody = reqJson.toString();
        RequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8");
        post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        //post.setRequestHeader(HttpHeaders.AUTHORIZATION, createBasicAuthorization(currentClientId, currentClientSecret));
        post.setRequestEntity(requestEntity);
        response = readResponse(post);
        log.info(response);
        if (response != null) {
            JSONObject json;
            try {
                json = new JSONObject(response);
                revoked = json.getBoolean("revoked");
            } catch (JSONException e) {
                log.error("cannot revoke access token", e);
            }
        }
    } catch (IOException e) {
        log.error("cannot revoke access token", e);
    } catch (JSONException e) {
        log.error("cannot revoke access token", e);
    }
    return revoked;
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation2() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation2";
    PostMethod method = new PostMethod(url);
    String param = "this is string parameter!";
    method.setRequestEntity(new StringRequestEntity(param, "application/xml", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);/*from w w  w  .j  a  v a2 s.c om*/
}

From source file:cuanto.api.CuantoConnector.java

/**
 * Gets all TestRuns that include the specified TestProperties. The properties can be a subset of a TestRun's
 * properties, but all of the specified properties must match for a TestRun to be returned.
 *
 * @param testProperties The properties for which to search. This is a Map with property names as the keys and the
 *                       property values as the values.
 * @return All TestRuns that contain the specified properties. A zero-length array is returned if no matching TestRuns
 *         are found./*w  w  w  .  j a va  2  s  .c o  m*/
 */
public List<TestRun> getTestRunsWithProperties(Map<String, String> testProperties) {
    PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, getCuantoUrl() + "/api/getTestRunsWithProperties");
    try {
        Map jsonMap = new HashMap();
        jsonMap.put("projectKey", getProjectKey());
        jsonMap.put("testProperties", JSONObject.fromObject(testProperties));
        JSONObject jsonToPost = JSONObject.fromObject(jsonMap);
        post.setRequestEntity(new StringRequestEntity(jsonToPost.toString(), "application/json", null));
        int httpStatus = getHttpClient().executeMethod(post);
        if (httpStatus == HttpStatus.SC_OK) {
            JSONObject jsonReturned = JSONObject.fromObject(getResponseBodyAsString(post));
            List<TestRun> testRuns = new ArrayList<TestRun>();
            if (jsonReturned.has("testRuns")) {
                JSONArray returnedRuns = jsonReturned.getJSONArray("testRuns");
                for (Object run : returnedRuns) {
                    JSONObject jsonRun = (JSONObject) run;
                    testRuns.add(TestRun.fromJSON(jsonRun));
                }
            } else {
                throw new RuntimeException("JSON response didn't have testRuns node");
            }
            return testRuns;
        } else {
            throw new RuntimeException("Getting the TestRun 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("Unable to parse JSON response: " + e.getMessage(), e);
    }
}

From source file:com.borhan.client.BorhanClientBase.java

private PostMethod addParams(PostMethod method, BorhanParams kparams) throws UnsupportedEncodingException {
    String content = kparams.toString();
    String contentType = "application/json";
    StringRequestEntity requestEntity = new StringRequestEntity(content, contentType, null);

    method.setRequestEntity(requestEntity);
    return method;
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation4() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation4";
    PostMethod method = new PostMethod(url);
    String param = "this is string parameter!";
    method.setRequestEntity(new StringRequestEntity(param, "application/xml", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK);
    byte[] responseBody = method.getResponseBody();
    String actualResponse = new String(responseBody);
    String expectedResponse = "this is string parameter!";
    assertEquals(expectedResponse, actualResponse);
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation5Xml() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation5Xml";
    PostMethod method = new PostMethod(url);
    String param = this.getXmlCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/xml", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);//from w  w  w  .  j a v  a 2  s. c om
}

From source file:com.vmware.aurora.vc.vcservice.VcService.java

/**
 * This sends a URL POST request to the Extension vService guest API to
 * register a new extension. Upon success, set vcExtensionRegistered to true.
 * Note that the extension will not be fully configured until we log in to VC
 * as this extension and make some VMODL calls to finish the job.
 *
 * Note also that we only need to do this once per CMS install, not once per
 * CMS startup, but it doesn't seem to hurt to do it every time.
 *
 * @synchronized for preventing concurrent call to register EVS.
 *///from  w w w .java  2  s  . c o  m
private static synchronized void registerExtensionVService() {
    if (vcExtensionRegistered) {
        return;
    }
    logger.debug("Register extension vService at: " + evsURL + " token=" + evsToken);
    Writer output = null;
    BufferedReader input = null;
    try {
        /**
         *  Initialize our own trust manager
         */
        ThumbprintTrustManager thumbprintTrustManager = new ThumbprintTrustManager();
        thumbprintTrustManager.add(vcThumbprint);

        TrustManager[] trustManagers = new TrustManager[] { thumbprintTrustManager };

        HttpClient httpClient = new HttpClient();

        TlsSocketFactory tlsSocketFactory = new TlsSocketFactory(trustManagers);

        Protocol.registerProtocol("https",
                new Protocol("https", (ProtocolSocketFactory) tlsSocketFactory, 443));

        PostMethod method = new PostMethod(evsURL);
        method.setRequestHeader("evs-token", evsToken);

        Certificate cert = CmsKeyStore.getCertificate(CmsKeyStore.VC_EXT_KEY);
        String evsSchema = "http://www.vmware.com/schema/vservice/ExtensionVService";
        String payload = "<RegisterExtension xmlns=\"" + evsSchema + "\">\n" + "  <Key>" + extKey + "</Key>\n"
                + "  <Certificate>\n" + CertificateToPem(cert) + "\n" + "  </Certificate>\n"
                + "</RegisterExtension>\n";

        RequestEntity requestEntity = new StringRequestEntity(payload, "text/plain", "UTF-8");
        method.setRequestEntity(requestEntity);
        int statusCode = httpClient.executeMethod(method);

        logger.info("status code: " + statusCode);
        for (Header e : method.getResponseHeaders()) {
            logger.debug("Response Header: " + e.getName() + " :" + e.getValue());
        }

        input = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        for (String str = input.readLine(); str != null; str = input.readLine()) {
            logger.debug("Response: " + str);
        }

        if (statusCode == 200) {
            vcExtensionRegistered = true;
            logger.info("Extension registration request sent successfully");
        } else {
            logger.error("Extension registration request sent error");
        }
    } catch (Exception e) {
        logger.error("Failed Extension registration to " + evsURL, e);
    } finally {
        Configuration.setBoolean(SERENGETI_EXTENSION_REGISTERED, true);
        Configuration.save();
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                logger.error("Failed to close output Writer", e);
            }
        }
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                logger.error("Failed to close input Reader", e);
            }
        }
    }
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation5Json() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation5Json";
    PostMethod method = new PostMethod(url);
    String param = this.getJsonCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/json", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);//from   w  w w . j a  va2  s.  c  o m
}

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

public GatewayTransactionVO refundTransaction(IntegrationKeys keys, IntegrationProperties props,
        MerchantStore store, Order order, GatewayTransactionVO trx, Customer customer, CoreModuleService cis,
        BigDecimal amount) throws TransactionException {

    PostMethod httppost = null;//from  w w  w . j  a  v  a  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();
        }

        // parse sent elements required
        AuthorizeNetParsedElements pe = null;
        pe = new AuthorizeNetParsedElements();
        Digester digester = new Digester();
        digester.push(pe);

        digester.addCallMethod("transaction/x_card_num", "setCardnumber", 0);
        digester.addCallMethod("transaction/approvalcode", "setApprovalCode", 0);
        digester.addCallMethod("transaction/x_exp_date", "setExpiration", 0);
        digester.addCallMethod("transaction/x_amount", "setTransactionAmount", 0);
        digester.addCallMethod("transaction/x_card_code", "setCvv", 0);

        Reader reader = new StringReader(trx.getTransactionDetails().getGatewaySentDecrypted().trim());

        digester.parse(reader);

        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(keys.getUserid()).append("&"); // replace
        // with
        // your
        // own
        sb.append("x_tran_key=").append(keys.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=CREDIT&");

        sb.append("x_card_num=").append(pe.getCardnumber()).append("&");// at
        // least
        // 4
        // last
        // card
        // digit
        sb.append("x_exp_date=").append(pe.getExpiration()).append("&");
        sb.append("x_amount=").append(amount.toString()).append("&");
        if (pe.getCvv() != null) {
            sb.append("x_card_code=").append(pe.getCvv()).append("&");
        }
        sb.append("x_delim_data=TRUE&");
        sb.append("x_delim_char=|&");
        sb.append("x_relay_response=FALSE&");
        sb.append("x_trans_id=").append(trx.getTransactionID()).append("&");

        /** debug **/
        StringBuffer sblog = new StringBuffer();

        // mandatory name/value pairs for all AIM CC transactions
        // as well as some "good to have" values
        sblog.append("x_login=").append(keys.getUserid()).append("&"); // replace
        // with
        // your
        // own
        sblog.append("x_tran_key=").append(keys.getTransactionKey()).append("&"); // replace                                                   // own
        sblog.append("x_version=3.1&");// set to required in the specs
        // if dev
        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=CREDIT&");
        sblog.append("x_card_num=").append(pe.getCardnumber()).append("&");// at
        // least
        // 4
        // last
        // card
        // digit
        sblog.append("x_exp_date=").append(pe.getExpiration()).append("&");
        sblog.append("x_amount=").append(amount.toString()).append("&");
        if (pe.getCvv() != null) {
            sblog.append("x_card_code=").append(pe.getCvv()).append("&");
        }
        sblog.append("x_delim_data=TRUE&");
        sblog.append("x_delim_char=|&");
        sblog.append("x_relay_response=FALSE&");
        sblog.append("x_trans_id=").append(trx.getTransactionID()).append("&");

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

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

        sx.append("<transaction>");
        sx.append("<x_login>").append(keys.getUserid()).append("</x_login>"); // replace
        // with
        // your
        // own
        sx.append("<x_tran_key>").append(keys.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>CREDIT</x_type>");

        // need ccard number
        sx.append("<x_card_num>").append(pe.getCardnumber()).append("</x_card_num>");// at least 4 last card digit
        sx.append("<x_exp_date>").append(pe.getExpiration()).append("</x_exp_date>");
        sx.append("<x_amount>").append(pe.getTransactionAmount()).append("</x_amount>");
        if (pe.getCvv() != null) {
            sx.append("<x_card_code>").append(pe.getCvv()).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("<x_trans_id>").append(trx.getTransactionID()).append("</x_trans_id>");
        sx.append("</transaction>");

        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);

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

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

        pe = new AuthorizeNetParsedElements();
        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 = new StringReader(finalresult);

        digester.parse(reader);

        pe.setTransactionId(trx.getTransactionDetails().getMerchantPaymentGwOrderid());// BECAUSE NOT RETURNED FROM
        // AUTHORIZE NET !!!!

        return this.parseResponse(PaymentConstants.REFUND, sx.toString(), finalresult, pe, order, amount);

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

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

}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation7Xml() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation7Xml";
    PostMethod method = new PostMethod(url);
    String param = this.getXmlCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/xml", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK);
    byte[] responseBody = method.getResponseBody();
    String xmlResponse = new String(responseBody);
    assertTrue(xmlResponse.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>") > -1);
    assertTrue(xmlResponse.indexOf("<title>My Track 1</title>") > -1);
}