Example usage for org.apache.commons.httpclient.methods PostMethod setRequestEntity

List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity

Introduction

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

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

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

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

    // 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_ADD_ROLE_TO_USER;

    sendingXml = sendingXml.replace("<oid></oid>", "<oid>" + userOid + "</oid>");
    sendingXml = sendingXml.replace("oid=\"\"", "oid=\"" + roleOid + "\"");

    RequestEntity userSearchEntity = new StringRequestEntity(sendingXml, "application/xml", "UTF-8");
    post.setRequestEntity(userSearchEntity);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {/*from   www  . j  ava2s .  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:com.apifest.oauth20.tests.OAuth20BasicTest.java

public String registerNewClientWithPredefinedClientId(String clientName, String scope, String redirectUri,
        String clientId, String clientSecret) {
    PostMethod post = new PostMethod(baseOAuth20Uri + APPLICATION_ENDPOINT);
    String response = null;/*from  w w w.j av  a 2s  . 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);
        json.put("client_id", clientId);
        json.put("client_secret", clientSecret);

        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);
    }
    post.releaseConnection();
    return response;
}

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.j  av a  2 s  . 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:eu.learnpad.core.impl.or.XwikiBridgeInterfaceRestResource.java

@Override
public void updateSimulationScore(String modelSetId, String simulationSessionId, String processArtifactId,
        Long timestamp, String userId, SimulationScoresMap scoreMap) throws LpRestException {
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/or/bridge/%s/simulationscore", DefaultRestResource.REST_URI,
            modelSetId);/*from  w  w  w.java  2 s  .  c o m*/
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML);
    String contentType = "application/xml";

    NameValuePair[] queryString = new NameValuePair[4];
    queryString[0] = new NameValuePair("simulationsessionid", simulationSessionId);
    queryString[1] = new NameValuePair("processartifactid", processArtifactId);
    queryString[2] = new NameValuePair("timestamp", timestamp.toString());
    queryString[3] = new NameValuePair("userid", userId);
    postMethod.setQueryString(queryString);

    try {
        Writer scoreMapWriter = new StringWriter();
        JAXBContext jc = JAXBContext.newInstance(SimulationScoresMap.class);
        jc.createMarshaller().marshal(scoreMap, scoreMapWriter);

        RequestEntity requestEntity = new StringRequestEntity(scoreMapWriter.toString(), contentType, "UTF-8");
        postMethod.setRequestEntity(requestEntity);

        httpClient.executeMethod(postMethod);
    } catch (IOException | JAXBException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java

private PostMethod postInternal(String formUrl, Map<String, String> changed, final ITaskAttachment attach)
        throws FogBugzClientException, HttpException, IOException, MarshalException, ValidationException {

    WebClientUtil.setupHttpClient(httpClient, proxy, formUrl, null, null);
    if (!authenticated && hasAuthenticationCredentials()) {
        authenticate();/*from   w ww  .java  2 s  .c o  m*/
    }

    String requestUrl = WebClientUtil.getRequestPath(formUrl + "&token=" + token);

    ArrayList<Part> parts = new ArrayList<Part>();
    if (attach != null) {
        requestUrl += "&nFileCount=1";
        FilePart part = new FilePart("File1", new PartSource() {

            public InputStream createInputStream() throws IOException {
                return attach.createInputStream();
            }

            public String getFileName() {
                return attach.getFilename();
            }

            public long getLength() {
                return attach.getLength();
            }

        });
        part.setTransferEncoding(null);
        parts.add(part);
        parts.add(new StringPart("Content-Type", attach.getContentType()));
    }
    PostMethod postMethod = new PostMethod(requestUrl);
    // postMethod.setRequestHeader("Content-Type",
    // "application/x-www-form-urlencoded; charset="
    // + characterEncoding);

    // postMethod.setRequestBody(formData);
    postMethod.setDoAuthentication(true);

    for (String key : changed.keySet()) {
        StringPart p = new StringPart(key, changed.get(key));
        p.setTransferEncoding(null);
        p.setContentType(null);
        parts.add(p);
    }
    postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), postMethod.getParams()));

    int status = httpClient.executeMethod(postMethod);
    if (status == HttpStatus.SC_OK) {
        return postMethod;
    } else {
        postMethod.getResponseBody();
        postMethod.releaseConnection();
        throw new IOException(
                "Communication error occurred during upload. \n\n" + HttpStatus.getStatusText(status));
    }
}

From source file:com.googlecode.fascinator.redbox.plugins.curation.external.ExternalCurationTransactionManager.java

private JsonSimple createJobInExternalCurationManager(JsonSimple requestJson) throws IOException {

    PostMethod post;
    try {/*from  ww  w .  j av  a2s.  co m*/
        String url = systemConfig.getString(null, "curation", "curation-manager-url");
        url = url + "/job";
        BasicHttpClient client = new BasicHttpClient(url);
        post = new PostMethod(url);
        StringRequestEntity requestEntity = new StringRequestEntity(requestJson.toString(), "application/json",
                "UTF-8");
        post.setRequestEntity(requestEntity);
        client.executeMethod(post);
        int status = post.getStatusCode();
        if (status != 200) {
            String text = post.getStatusText();
            log.error(String.format(
                    "Error accessing Curation Manager, status code '%d' returned with message: %s", status,
                    text));
            log.error(String.format("Request message was: %s", requestJson.toString()));
            return null;
        }

    } catch (IOException ex) {
        log.error("Error during search: ", ex);
        return null;
    }

    // Return our results body
    String response = null;
    try {
        response = post.getResponseBodyAsString();
    } catch (IOException ex) {
        log.error("Error accessing response body: ", ex);
        return null;
    }

    JsonSimple curationManagerResponseJson = new JsonSimple(response);

    return curationManagerResponseJson;
}

From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java

private PostMethod postInternal(String formUrl, Map<String, String> changed, final ITaskAttachment attach,
        IProgressMonitor monitor)//from w  w w  .j a  va  2  s .c om
        throws FogBugzClientException, HttpException, IOException, MarshalException, ValidationException {

    WebClientUtil.setupHttpClient(httpClient, proxy, formUrl, null, null);
    if (!authenticated && hasAuthenticationCredentials()) {
        monitor.subTask("Authenticating request");
        authenticate();
        if (checkMonitor(monitor))
            return null;
    }

    String requestUrl = WebClientUtil.getRequestPath(formUrl + "&token=" + token);

    ArrayList<Part> parts = new ArrayList<Part>();
    if (attach != null) {
        requestUrl += "&nFileCount=1";
        FilePart part = new FilePart("File1", new PartSource() {

            public InputStream createInputStream() throws IOException {
                return attach.createInputStream();
            }

            public String getFileName() {
                return attach.getFilename();
            }

            public long getLength() {
                return attach.getLength();
            }

        });
        part.setTransferEncoding(null);
        parts.add(part);
        parts.add(new StringPart("Content-Type", attach.getContentType()));
    }
    PostMethod postMethod = new PostMethod(requestUrl);
    // postMethod.setRequestHeader("Content-Type",
    // "application/x-www-form-urlencoded; charset="
    // + characterEncoding);

    // postMethod.setRequestBody(formData);
    postMethod.setDoAuthentication(true);

    for (String key : changed.keySet()) {
        StringPart p = new StringPart(key, changed.get(key));
        p.setTransferEncoding(null);
        p.setContentType(null);
        parts.add(p);
    }
    postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), postMethod.getParams()));

    monitor.subTask("Sending request");
    int status = httpClient.executeMethod(postMethod);
    if (status == HttpStatus.SC_OK) {
        return postMethod;
    } else {
        postMethod.getResponseBody();
        postMethod.releaseConnection();
        throw new IOException(
                "Communication error occurred during upload. \n\n" + HttpStatus.getStatusText(status));
    }
}

From source file:com.zimbra.qa.unittest.TestZimbraHttpConnectionManager.java

public void testSoTimeoutViaHttpPostMethod() throws Exception {

    int serverPort = 7778;
    String resourceToPost = "/opt/zimbra/unittest/rights-unittest.xml";
    long delayInServer = 100000; // delay 10 seconds in server
    int soTimeout = 60000; // 3000;  // 3 seconds, 0 for infinite wait

    String qp = "?" + SimpleHttpServer.DelayWhen.BEFORE_WRITING_RESPONSE_HEADERS.name() + "=" + delayInServer;
    String uri = "http://localhost:" + serverPort + resourceToPost + qp;

    // start a http server for testing
    SimpleHttpServer.start(serverPort);//from w  w  w.j  av a2s .c  o m

    // post the exported content to the target server
    HttpClient httpClient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    PostMethod method = new PostMethod(uri);
    method.getParams().setSoTimeout(soTimeout); // infinite wait because it can take a long time to import a large mailbox

    File file = new File(resourceToPost);
    FileInputStream fis = null;

    long startTime = System.currentTimeMillis();
    long endTime;
    try {
        fis = new FileInputStream(file);
        InputStreamRequestEntity isre = new InputStreamRequestEntity(fis, file.length(),
                MimeConstants.CT_APPLICATION_OCTET_STREAM);
        method.setRequestEntity(isre);
        int respCode = httpClient.executeMethod(method);

        dumpResponse(respCode, method, "");
        Assert.fail(); // nope, it should have timed out
    } catch (java.net.SocketTimeoutException e) {
        e.printStackTrace();
        // good, just what we want
        endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;
        System.out.println("Client timed out after " + elapsedTime + " msecs");
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    } finally {
        method.releaseConnection();
    }

    // shutdown the server
    SimpleHttpServer.shutdown();
}

From source file:com.benfante.jslideshare.SlideShareConnectorImpl.java

public InputStream sendMultiPartMessage(String url, Map<String, String> parameters, Map<String, File> files)
        throws IOException, SlideShareErrorException {
    HttpClient client = createHttpClient();
    PostMethod method = new PostMethod(url);
    List<Part> partList = new ArrayList();
    partList.add(createStringPart("api_key", this.apiKey));
    Date now = new Date();
    String ts = Long.toString(now.getTime() / 1000);
    String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase();
    partList.add(createStringPart("ts", ts));
    partList.add(createStringPart("hash", hash));
    Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator();
    while (entryIt.hasNext()) {
        Map.Entry<String, String> entry = entryIt.next();
        partList.add(createStringPart(entry.getKey(), entry.getValue()));
    }/*  w  w w .  j a  v  a 2s .c  om*/
    Iterator<Map.Entry<String, File>> entryFileIt = files.entrySet().iterator();
    while (entryFileIt.hasNext()) {
        Map.Entry<String, File> entry = entryFileIt.next();
        partList.add(createFilePart(entry.getKey(), entry.getValue()));
    }
    MultipartRequestEntity requestEntity = new MultipartRequestEntity(
            partList.toArray(new Part[partList.size()]), method.getParams());
    method.setRequestEntity(requestEntity);
    logger.debug("Sending multipart POST message to " + method.getURI().getURI() + " with parts " + partList);
    int statusCode = client.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        logger.debug("Server replied with a " + statusCode + " HTTP status code ("
                + HttpStatus.getStatusText(statusCode) + ")");
        throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode));
    }
    if (logger.isDebugEnabled()) {
        logger.debug(method.getResponseBodyAsString());
    }
    InputStream result = new ByteArrayInputStream(method.getResponseBody());
    method.releaseConnection();
    return result;
}

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 ww  w .ja va 2 s.  c o 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;
}