Search in sources :

Example 36 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project rhsm-qe by RedHatQE.

the class CandlepinTasks method postResourceUsingRESTfulAPI.

public static String postResourceUsingRESTfulAPI(String authenticator, String password, String url, String path, String requestBody) throws Exception {
    PostMethod post = new PostMethod(url + path);
    if (requestBody != null) {
        post.setRequestEntity(new StringRequestEntity(requestBody, "application/json", null));
        post.addRequestHeader("accept", "application/json");
        post.addRequestHeader("content-type", "application/json");
    }
    // log the curl alternative to HTTP request
    // Example: curl --insecure --user testuser1:password --request PUT --data '{"autoheal":"false"}' --header 'accept: application/json' --header 'content-type: application/json' https://jsefler-onprem-62candlepin.usersys.redhat.com:8443/candlepin/consumers/e60d7786-1f61-4dec-ad19-bde068dd3c19
    String user = (authenticator.equals("")) ? "" : "--user " + authenticator + ":" + password + " ";
    String request = "--request " + post.getName() + " ";
    String data = (requestBody == null) ? "" : "--data '" + requestBody + "' ";
    String headers = "";
    if (requestBody != null)
        for (org.apache.commons.httpclient.Header header : post.getRequestHeaders()) headers += "--header '" + header.toString().trim() + "' ";
    log.info("SSH alternative to HTTP request: curl --stderr /dev/null --insecure " + user + request + data + headers + post.getURI());
    String response = getHTTPResponseAsString(client, post, authenticator, password);
    if (response != null) {
        JSONObject responseAsJSONObect = new JSONObject(response);
        if (responseAsJSONObect.has("displayMessage")) {
            log.warning("Attempt to POST resource '" + path + "' failed: " + responseAsJSONObect.getString("displayMessage"));
        }
    }
    return response;
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) JSONObject(org.json.JSONObject) PostMethod(org.apache.commons.httpclient.methods.PostMethod)

Example 37 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project phabricator-jenkins-plugin by uber.

the class UberallsClient method recordCoverage.

public boolean recordCoverage(String sha, CodeCoverageMetrics codeCoverageMetrics) {
    if (codeCoverageMetrics != null && codeCoverageMetrics.isValid()) {
        JSONObject params = new JSONObject();
        params.put("sha", sha);
        params.put("branch", branch);
        params.put("repository", repository);
        params.put(PACKAGE_COVERAGE_KEY, codeCoverageMetrics.getPackageCoveragePercent());
        params.put(FILES_COVERAGE_KEY, codeCoverageMetrics.getFilesCoveragePercent());
        params.put(CLASSES_COVERAGE_KEY, codeCoverageMetrics.getClassesCoveragePercent());
        params.put(METHOD_COVERAGE_KEY, codeCoverageMetrics.getMethodCoveragePercent());
        params.put(LINE_COVERAGE_KEY, codeCoverageMetrics.getLineCoveragePercent());
        params.put(CONDITIONAL_COVERAGE_KEY, codeCoverageMetrics.getConditionalCoveragePercent());
        try {
            HttpClient client = getClient();
            PostMethod request = new PostMethod(getBuilder().build().toString());
            request.addRequestHeader("Content-Type", "application/json");
            StringRequestEntity requestEntity = new StringRequestEntity(params.toString(), ContentType.APPLICATION_JSON.toString(), "UTF-8");
            request.setRequestEntity(requestEntity);
            int statusCode = client.executeMethod(request);
            if (statusCode != HttpStatus.SC_OK) {
                logger.info(TAG, "Call failed: " + request.getStatusLine());
                return false;
            }
            return true;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (HttpResponseException e) {
            // e.g. 404, pass
            logger.info(TAG, "HTTP Response error recording metrics: " + e);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) JSONObject(net.sf.json.JSONObject) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) HttpResponseException(org.apache.http.client.HttpResponseException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 38 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project cloudstack by apache.

the class BigSwitchBcfApi method executeUpdateObject.

protected <T> String executeUpdateObject(final T newObject, final String uri, final Map<String, String> parameters) throws BigSwitchBcfApiException, IllegalArgumentException {
    checkInvariants();
    PutMethod pm = (PutMethod) createMethod("put", uri, _port);
    setHttpHeader(pm);
    try {
        pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), CONTENT_JSON, null));
    } catch (UnsupportedEncodingException e) {
        throw new BigSwitchBcfApiException("Failed to encode json request body", e);
    }
    executeMethod(pm);
    String hash = checkResponse(pm, "BigSwitch HTTP update failed: ");
    pm.releaseConnection();
    return hash;
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) PutMethod(org.apache.commons.httpclient.methods.PutMethod) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 39 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project cloudstack by apache.

the class SecurityGroupHttpClient method call.

public SecurityGroupRuleAnswer call(String agentIp, SecurityGroupRulesCmd cmd) {
    PostMethod post = new PostMethod(String.format("http://%s:%s", agentIp, getPort()));
    try {
        SecurityGroupVmRuleSet rset = new SecurityGroupVmRuleSet();
        rset.getEgressRules().addAll(generateRules(cmd.getEgressRuleSet()));
        rset.getIngressRules().addAll(generateRules(cmd.getIngressRuleSet()));
        rset.setVmName(cmd.getVmName());
        rset.setVmIp(cmd.getGuestIp());
        rset.setVmMac(cmd.getGuestMac());
        rset.setVmId(cmd.getVmId());
        rset.setSignature(cmd.getSignature());
        rset.setSequenceNumber(cmd.getSeqNum());
        Marshaller marshaller = context.createMarshaller();
        StringWriter writer = new StringWriter();
        marshaller.marshal(rset, writer);
        String xmlContents = writer.toString();
        logger.debug(xmlContents);
        post.addRequestHeader("command", "set_rules");
        StringRequestEntity entity = new StringRequestEntity(xmlContents);
        post.setRequestEntity(entity);
        if (httpClient.executeMethod(post) != 200) {
            return new SecurityGroupRuleAnswer(cmd, false, post.getResponseBodyAsString());
        } else {
            return new SecurityGroupRuleAnswer(cmd);
        }
    } catch (Exception e) {
        return new SecurityGroupRuleAnswer(cmd, false, e.getMessage());
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}
Also used : Marshaller(javax.xml.bind.Marshaller) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) StringWriter(java.io.StringWriter) PostMethod(org.apache.commons.httpclient.methods.PostMethod) SecurityGroupVmRuleSet(com.cloud.baremetal.networkservice.schema.SecurityGroupVmRuleSet) SecurityGroupRuleAnswer(com.cloud.agent.api.SecurityGroupRuleAnswer) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SocketTimeoutException(java.net.SocketTimeoutException)

Example 40 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project cloudstack by apache.

the class UcsHttpClient method call.

public String call(String xml) {
    PostMethod post = new PostMethod(url);
    post.setRequestEntity(new StringRequestEntity(xml));
    post.setRequestHeader("Content-type", "text/xml");
    // post.setFollowRedirects(true);
    try {
        int result = client.executeMethod(post);
        if (result == 302) {
            // Handle HTTPS redirect
            // Ideal way might be to configure from add manager API
            // for using either HTTP / HTTPS
            // Allow only one level of redirect
            String redirectLocation;
            Header locationHeader = post.getResponseHeader("location");
            if (locationHeader != null) {
                redirectLocation = locationHeader.getValue();
            } else {
                throw new CloudRuntimeException("Call failed: Bad redirect from UCS Manager");
            }
            post.setURI(new URI(redirectLocation));
            result = client.executeMethod(post);
        }
        // Check for errors
        if (result != 200) {
            throw new CloudRuntimeException("Call failed: " + post.getResponseBodyAsString());
        }
        String res = post.getResponseBodyAsString();
        if (res.contains("errorCode")) {
            String err = String.format("ucs call failed:\nsubmitted doc:%s\nresponse:%s\n", xml, res);
            throw new CloudRuntimeException(err);
        }
        return res;
    } catch (Exception e) {
        throw new CloudRuntimeException(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) Header(org.apache.commons.httpclient.Header) PostMethod(org.apache.commons.httpclient.methods.PostMethod) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) URI(org.apache.commons.httpclient.URI) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Aggregations

StringRequestEntity (org.apache.commons.httpclient.methods.StringRequestEntity)102 PostMethod (org.apache.commons.httpclient.methods.PostMethod)63 HttpClient (org.apache.commons.httpclient.HttpClient)33 Test (org.junit.Test)23 PutMethod (org.apache.commons.httpclient.methods.PutMethod)19 RequestEntity (org.apache.commons.httpclient.methods.RequestEntity)18 IOException (java.io.IOException)15 UnsupportedEncodingException (java.io.UnsupportedEncodingException)13 AuthRequestHandler (org.apache.commons.httpclient.server.AuthRequestHandler)12 HttpRequestHandlerChain (org.apache.commons.httpclient.server.HttpRequestHandlerChain)12 HttpServiceHandler (org.apache.commons.httpclient.server.HttpServiceHandler)12 Header (org.apache.commons.httpclient.Header)9 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)9 GetMethod (org.apache.commons.httpclient.methods.GetMethod)9 InputStream (java.io.InputStream)8 InputStreamRequestEntity (org.apache.commons.httpclient.methods.InputStreamRequestEntity)7 StringWriter (java.io.StringWriter)6 Map (java.util.Map)6 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)6 PutMethod (org.apache.jackrabbit.webdav.client.methods.PutMethod)6