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.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public void setUserStatus(Long userId, UserStatus status) {
    String resource = String.format(baseUrl + SET_STATUS, userId);
    PutMethod method = new PutMethod(resource);
    try {//  www  .  j a  v a  2  s .c o m
        ChangeUserStatusRequest request = new ChangeUserStatusRequest();
        request.setUserStatus(status);
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.inbravo.scribe.rest.service.crm.zd.ZDV2RESTCRMService.java

@Override
public final ScribeCommandObject updateObject(final ScribeCommandObject cADCommandObject) throws Exception {

    logger.debug("----Inside updateObject");
    PutMethod putMethod = null;//  ww  w  .  j a  v a2 s  .c  o m
    try {
        String serviceURL = null;
        String serviceProtocol = null;
        String userId = null;
        String password = null;
        String sessionId = null;
        String crmPort = "80";

        /* Get agent from session manager */
        final ScribeCacheObject cacheObject = zDCRMSessionManager
                .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId());

        /* Get CRM information from agent */
        serviceURL = cacheObject.getScribeMetaObject().getCrmServiceURL();
        serviceProtocol = cacheObject.getScribeMetaObject().getCrmServiceProtocol();
        userId = cacheObject.getScribeMetaObject().getCrmUserId();
        password = cacheObject.getScribeMetaObject().getCrmPassword();
        crmPort = cacheObject.getScribeMetaObject().getCrmPort();

        String crmObjectId = null;

        /* Check if response content in request, is not null */
        if (cADCommandObject.getObject() != null && cADCommandObject.getObject().length == 1) {

            /* Get Id of CRM object */
            crmObjectId = ZDCRMMessageFormatUtils.getNodeValue("ID", cADCommandObject.getObject()[0]);

            if (crmObjectId == null) {

                /* Inform user about invalid request */
                throw new ScribeException(
                        ScribeResponseCodes._1008 + "CRM object id is not present in request");
            }
        } else {
            /* Inform user about invalid request */
            throw new ScribeException(
                    ScribeResponseCodes._1008 + "CRM object information is not present in request");
        }

        /* Create Zen desk URL */
        final String zenDeskURL = serviceProtocol + "://" + serviceURL + zdAPISubPath
                + cADCommandObject.getObjectType().toLowerCase() + "s/" + crmObjectId + ".json";

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside updateObject zenDeskURL: " + zenDeskURL);
        }

        /* Instantiate put method */
        putMethod = new PutMethod(zenDeskURL);

        /* Set request content type */
        putMethod.addRequestHeader("Content-Type", "application/json");
        putMethod.addRequestHeader("accept", "application/json");

        /* Cookie is required to be set for session management */
        putMethod.addRequestHeader("Cookie", sessionId);

        /* Add request entity */
        final RequestEntity entity = new StringRequestEntity(
                ZDCRMMessageFormatUtils.getCreateRequestJSON(cADCommandObject), null, null);
        putMethod.setRequestEntity(entity);

        final HttpClient httpclient = new HttpClient();

        /* Set credentials */
        httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)),
                new UsernamePasswordCredentials(userId, password));

        /* Execute method */
        int result = httpclient.executeMethod(putMethod);

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside updateObject response code: " + result + " & body: "
                    + putMethod.getResponseBodyAsString());
        }

        /* Check if object is updated */
        if (result == HttpStatus.SC_OK || result == HttpStatus.SC_CREATED) {

            /* Return the response object */
            return this.createCreateResponse(putMethod.getResponseBodyAsString(),
                    cADCommandObject.getObjectType().toLowerCase());

        } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED
                || result == HttpStatus.SC_NOT_ACCEPTABLE || result == HttpStatus.SC_UNPROCESSABLE_ENTITY) {

            /* Throw user error with valid reasons for failure */
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : "
                    + ZDCRMMessageFormatUtils.getErrorFromResponse(putMethod.getResponseBodyAsStream()));
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {

            /* Throw user error with valid reasons for failure */
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {

            /* Throw user error with valid reasons for failure */
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM");
        } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {

            /* Throw user error with valid reasons for failure */
            throw new ScribeException(ScribeResponseCodes._1004
                    + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct");
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final JSONException e) {

        /* Throw user error */
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM",
                e);
    } catch (final ParserConfigurationException exception) {

        /* Throw user error */
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM",
                exception);
    } catch (final SAXException exception) {

        /* Throw user error */
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM",
                exception);
    } catch (final IOException exception) {

        /* Throw user error */
        throw new ScribeException(
                ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                exception);
    } finally {
        /* Release connection socket */
        if (putMethod != null) {
            putMethod.releaseConnection();
        }
    }
    return cADCommandObject;
}

From source file:com.cloudbees.jenkins.plugins.gogs.server.client.GogsServerAPIClient.java

private String postRequest(String path, String content) throws UnsupportedEncodingException {
    PostMethod httppost = new PostMethod(this.baseURL + path);
    httppost.setRequestEntity(new StringRequestEntity(content, "application/json", "UTF-8"));
    return postRequest(httppost);
}

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

public int modifyByOidPostMethod(String oid, String administrativeStatus) throws Exception {
    String returnString = "";
    int result = 0;
    // Get target URL
    String strURLBase = "http://localhost:8080/midpoint/ws/rest/users";
    String strURL = strURLBase + oid;

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

    //AUTHENTICATION BY GURER
    //String username = "administrator";
    //String password = "5ecr3t";
    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_MODIFY;

    sendingXml = sendingXml.replace("<oid></oid>", "<oid>" + oid + "</oid>");
    sendingXml = sendingXml.replace("<t:value></t:value>", "<t:value>" + administrativeStatus + "</t:value>");

    RequestEntity userSearchEntity = new StringRequestEntity(sendingXml, "application/xml", "UTF-8");
    post.setRequestEntity(userSearchEntity);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {/* ww w. ja  v  a 2s .  c  o  m*/
        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);

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

    return result;
}

From source file:cuanto.api.CuantoConnector.java

/**
 * Updates a TestOutcome on the Cuanto server with the details provided.
 *
 * @param testOutcome The new details that will replace the corresponding values of the existing TestOutcome.
 *///from ww w  .  j  a  v a  2  s  . c  o m
public void updateTestOutcome(TestOutcome testOutcome) {
    if (testOutcome.getId() == null) {
        throw new IllegalArgumentException(
                "The specified TestOutcome has no ID value. Any TestOutcome you wish to"
                        + " update should be fetched from the server first.");
    }
    PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, getCuantoUrl() + "/api/updateTestOutcome");
    try {
        post.setRequestEntity(new StringRequestEntity(testOutcome.toJSON(), "application/json", null));
        int httpStatus = getHttpClient().executeMethod(post);
        if (httpStatus != HttpStatus.SC_CREATED) {
            throw new RuntimeException("Adding 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);
    }
}

From source file:eu.eco2clouds.scheduler.accounting.client.AccountingClientHC.java

private String postMethod(String url, String payload, String bonfireUserId, String bonfireGroupId,
        Boolean exception) {/* w ww . jav a2 s  . c o m*/
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    PostMethod method = new PostMethod(url);
    setHeaders(method, bonfireGroupId, bonfireUserId);
    //method.addRequestHeader("Content-Type", SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    String response = "";

    try {
        // We set the payload
        StringRequestEntity payloadEntity = new StringRequestEntity(payload,
                SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML, "UTF-8");
        method.setRequestEntity(payloadEntity);

        // Execute the method.
        int statusCode = client.executeMethod(method);
        logger.debug("Status Code: " + statusCode);

        if (statusCode >= 200 && statusCode > 300) { //TODO test for this case... 
            logger.warn("Get host information of testbeds: " + url + " failed: " + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public AccountQueryResult listAccounts(ListAccountsRequest request) {
    String uri = baseUrl + ACCOUNTS;
    PutMethod method = new PutMethod(uri);
    try {//from  w ww  . j av a  2 s. c  o m
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, AccountQueryResult.class);

        } else {
            throw new RuntimeException(
                    "Failed to list accounts, RESPONSE CODE: " + statusCode + " url: " + uri);
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed listing accounts via url " + uri, e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.cloud.network.nicira.NiciraNvpApi.java

private <T> void executeUpdateObject(T newObject, String uri, Map<String, String> parameters)
        throws NiciraNvpApiException {
    String url;//from w  w  w .j  a  va 2 s .  c o  m
    try {
        url = new URL(_protocol, _host, uri).toString();
    } catch (MalformedURLException e) {
        s_logger.error("Unable to build Nicira API URL", e);
        throw new NiciraNvpApiException("Connection to NVP Failed");
    }

    Gson gson = new Gson();

    PutMethod pm = new PutMethod(url);
    pm.setRequestHeader("Content-Type", "application/json");
    try {
        pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), "application/json", null));
    } catch (UnsupportedEncodingException e) {
        throw new NiciraNvpApiException("Failed to encode json request body", e);
    }

    executeMethod(pm);

    if (pm.getStatusCode() != HttpStatus.SC_OK) {
        String errorMessage = responseToErrorMessage(pm);
        pm.releaseConnection();
        s_logger.error("Failed to update object : " + errorMessage);
        throw new NiciraNvpApiException("Failed to update object : " + errorMessage);
    }
    pm.releaseConnection();
}

From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public void updateUser(User user) {
    String resource = String.format(baseUrl + USER, user.getUserId());
    PutMethod method = new PutMethod(resource);
    try {/*from   w  w w. ja  v a  2 s  . c o  m*/
        String data = serialize(user);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java

public String registerNewClient(String clientName, String scope, String redirectUri) {
    PostMethod post = new PostMethod(baseOAuth20Uri + APPLICATION_ENDPOINT);
    String response = null;//from  w  ww  .ja v  a 2 s . c  o  m
    try {
        JSONObject json = new JSONObject();
        json.put("name", clientName);
        json.put("description", DEFAULT_DESCRIPTION);
        json.put("scope", scope);
        json.put("redirect_uri", redirectUri);

        String requestBody = json.toString();
        RequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8");
        post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        post.setRequestEntity(requestEntity);
        response = readResponse(post);
        log.info(response);
    } catch (IOException e) {
        log.error("cannot register new client app", e);
    } catch (JSONException e) {
        log.error("cannot register new client app", e);
    }
    return response;
}