Example usage for org.apache.http.client.methods HttpPut setEntity

List of usage examples for org.apache.http.client.methods HttpPut setEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPut setEntity.

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:com.mongolduu.android.ng.misc.HttpConnector.java

public static String httpPUT(String url, String data) throws ClientProtocolException, IOException {
    HttpClient httpClient = createHttpClient();
    HttpPut httpPut = new HttpPut(url);
    httpPut.setEntity(new StringEntity(data));
    HttpResponse response = httpClient.execute(httpPut);
    if (response.getStatusLine().getStatusCode() >= 400) {
        throw new IOException("HTTP client error: " + response.getStatusLine().getStatusCode());
    }/* w w w  .  j a  va2s  . c  o m*/
    return processEntity(response.getEntity());
}

From source file:com.talis.labs.api.sparql11.http.Sparql11HttpRdfUpdateTest.java

private static void put(Model model, String graph, String mediaType, String lang)
        throws URISyntaxException, ClientProtocolException, IOException {
    StringWriter content = new StringWriter();
    model.write(content, lang);/*from  ww w .j  ava2  s  .  c o  m*/

    StringEntity entity = new StringEntity(content.toString(), "UTF-8");

    URI uri = uri(graph);

    HttpPut httpput = new HttpPut(uri);
    httpput.setHeader("Content-Type", mediaType);
    httpput.setHeader("Accept", "text/plain");
    httpput.setEntity(entity);

    HttpResponse response = httpclient.execute(httpput);

    assertEquals(201, response.getStatusLine().getStatusCode());

    assertEquals(0, response.getHeaders("Location").length);

    response.getEntity().consumeContent();
}

From source file:org.opencastproject.remotetest.util.WorkflowUtils.java

/**
 * Registers a new workflow definition// ww w.  j  a v a 2 s  .  c  o m
 * 
 * @param workflowDefinition
 *          the new workflow definition
 * @return the id of the workflow definition
 */
public static String registerWorkflowDefinition(String workflowDefinition) throws Exception {
    HttpPut put = new HttpPut(BASE_URL + "/workflow/definition");
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("workflowDefinition", workflowDefinition));
    put.setEntity(new UrlEncodedFormEntity(params));
    TrustedHttpClient client = Main.getClient();
    HttpResponse response = client.execute(put);
    assertEquals(HttpStatus.SC_CREATED, response.getStatusLine().getStatusCode());
    String id = (String) Utils.xpath(workflowDefinition,
            "/*[local-name() = 'definition']/*[local-name() = 'id']", XPathConstants.STRING);
    assertNotNull(id);
    Main.returnClient(client);
    return id;
}

From source file:tech.beshu.ror.integration.FiltersAndFieldsSecurityTests.java

private static void insertDoc(String docName, RestClient restClient, String idx, String field) {
    if (adminClient == null) {
        adminClient = restClient;/*w  ww  .  ja  v a 2 s  .  c om*/
    }

    String path = "/" + IDX_PREFIX + idx + "/documents/doc-" + docName + String.valueOf(Math.random());
    try {

        HttpPut request = new HttpPut(restClient.from(path));
        request.setHeader("Content-Type", "application/json");
        request.setHeader("refresh", "true");
        request.setHeader("timeout", "50s");
        request.setEntity(new StringEntity("{\"" + field + "\": \"" + docName + "\", \"dummy\": true}"));
        System.out.println(body(restClient.execute(request)));

    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Test problem", e);
    }

    // Polling phase.. #TODO is there a better way?
    try {
        HttpResponse response;
        do {
            HttpHead request = new HttpHead(restClient.from(path));
            request.setHeader("x-api-key", "p");
            response = restClient.execute(request);
            System.out.println(
                    "polling for " + docName + ".. result: " + response.getStatusLine().getReasonPhrase());
            Thread.sleep(200);
        } while (response.getStatusLine().getStatusCode() != 200);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Cannot configure test case", e);
    }
}

From source file:tech.beshu.ror.integration.IndicesReverseWildcardTests.java

private static void insertDoc(String docName, RestClient restClient) {
    if (adminClient == null) {
        adminClient = restClient;// ww  w. j  a v a 2 s . c om
    }

    try {
        HttpPut request = new HttpPut(restClient.from("/logstash-" + docName + "/documents/doc-" + docName));
        request.setHeader("refresh", "true");
        request.setHeader("timeout", "50s");
        request.setHeader("Content-Type", "application/json");
        request.setEntity(new StringEntity("{\"title\": \"" + docName + "\"}"));
        System.out.println(body(restClient.execute(request)));

    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Test problem", e);
    }

    // Polling phase.. #TODO is there a better way?
    try {
        HttpResponse response;
        do {
            Thread.sleep(200);
            HttpHead request = new HttpHead(
                    restClient.from("/logstash-" + docName + "/documents/doc-" + docName));
            response = restClient.execute(request);
            System.out.println(
                    "polling for " + docName + ".. result: " + response.getStatusLine().getReasonPhrase());
        } while (response.getStatusLine().getStatusCode() != 200);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Cannot configure test case", e);
    }
}

From source file:io.github.data4all.util.upload.ChangesetUtil.java

/**
 * Requests a changeset-id from the OSM-API.
 * /*w w  w .ja va 2 s  .c om*/
 * @param user
 *            The {@link User} to request a id for.
 * @param comment
 *            The Comment for the Changeset.
 * @return The Changeset ID.
 * @throws OsmException
 *             If the Changeset ID cannot be grabbed.
 */
public static CloseableRequest requestId(final User user, final String comment) throws OsmException {
    try {
        final HttpPut request = getChangeSetPut(user);
        // Add the xml-request-string
        request.setEntity(new StringEntity(getChangesetRequest(comment)));

        return new CloseableRequest(request);

    } catch (UnsupportedEncodingException e) {
        throw new OsmException(e);
    }
}

From source file:eu.cassandra.training.utils.APIUtilities.java

/**
 * This function is used to send the entity models to the Cassandra Server,
 * specifically on the connected user's Library.
 * /*from  ww w  .j  a  v a 2s .co  m*/
 * @param message
 *          The JSON schema of the entity.
 * @param suffix
 *          The library the model must be sent to.
 * @param id
 *          The id of the entity model in the Cassandra server.
 * @return a simple string of success or failure.
 * @throws IOException
 * @throws AuthenticationException
 * @throws NoSuchAlgorithmException
 */
public static String updateEntity(String message, String suffix, String id)
        throws IOException, AuthenticationException, NoSuchAlgorithmException {

    System.out.println(message);
    HttpPut httpput = new HttpPut(url + suffix + "/" + id);

    StringEntity entity = new StringEntity(message, "UTF-8");
    entity.setContentType("application/json");
    httpput.setEntity(entity);
    System.out.println("executing request: " + httpput.getRequestLine());

    HttpResponse response = httpclient.execute(httpput, localcontext);
    HttpEntity responseEntity = response.getEntity();
    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
    System.out.println(responseString);

    return "Done";

}

From source file:com.portfolio.data.utils.PostForm.java

public static boolean updateResource(String sessionid, String backend, String uuid, String lang, String json)
        throws Exception {
    /// Parse and create xml from JSON
    JSONObject files = (JSONObject) JSONValue.parse(json);
    JSONArray array = (JSONArray) files.get("files");

    if ("".equals(lang) || lang == null)
        lang = "fr";

    JSONObject obj = (JSONObject) array.get(0);
    String ressource = "";
    String attLang = " lang=\"" + lang + "\"";
    ressource += "<asmResource>" + "<filename" + attLang + ">" + obj.get("name") + "</filename>" + // filename
            "<size" + attLang + ">" + obj.get("size") + "</size>" + "<type" + attLang + ">" + obj.get("type")
            + "</type>" +
            //      obj.get("url");   // Backend source, when there is multiple backend
            "<fileid" + attLang + ">" + obj.get("fileid") + "</fileid>" + "</asmResource>";

    /// Send data to resource
    /// Server + "/resources/resource/file/" + uuid +"?lang="+ lang
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from w  ww. j av a  2  s .co  m
        HttpPut put = new HttpPut("http://" + backend + "/rest/api/resources/resource/" + uuid);
        put.setHeader("Cookie", "JSESSIONID=" + sessionid); // So that the receiving servlet allow us

        StringEntity se = new StringEntity(ressource);
        se.setContentEncoding("application/xml");
        put.setEntity(se);

        CloseableHttpResponse response = httpclient.execute(put);

        try {
            HttpEntity resEntity = response.getEntity();
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

    return false;
}

From source file:com.impetus.client.couchdb.CouchDBUtils.java

/**
 * Creates the design document if not exist.
 * /*  w ww . ja  v a 2  s . c  o m*/
 * @param httpClient
 *            the http client
 * @param httpHost
 *            the http host
 * @param gson
 *            the gson
 * @param tableName
 *            the table name
 * @param schemaName
 *            the schema name
 * @param viewName
 *            the view name
 * @param columns
 *            the columns
 * @throws URISyntaxException
 *             the URI syntax exception
 * @throws UnsupportedEncodingException
 *             the unsupported encoding exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ClientProtocolException
 *             the client protocol exception
 */
public static void createDesignDocumentIfNotExist(HttpClient httpClient, HttpHost httpHost, Gson gson,
        String tableName, String schemaName, String viewName, List<String> columns)
        throws URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException {
    URI uri;
    HttpResponse response = null;
    CouchDBDesignDocument designDocument = CouchDBUtils.getDesignDocument(httpClient, httpHost, gson, tableName,
            schemaName);
    Map<String, MapReduce> views = designDocument.getViews();
    if (views == null) {
        views = new HashMap<String, MapReduce>();
    }

    if (views.get(viewName.toString()) == null) {
        CouchDBUtils.createView(views, viewName, columns);
    }
    String id = CouchDBConstants.DESIGN + tableName;
    if (designDocument.get_rev() == null) {
        uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR + id,
                null, null);
    } else {
        StringBuilder builder = new StringBuilder("rev=");
        builder.append(designDocument.get_rev());
        uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR + id,
                builder.toString(), null);
    }
    HttpPut put = new HttpPut(uri);

    designDocument.setViews(views);
    String jsonObject = gson.toJson(designDocument);
    StringEntity entity = new StringEntity(jsonObject);
    put.setEntity(entity);
    try {
        response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));
    } finally {
        CouchDBUtils.closeContent(response);
    }
}

From source file:org.eclipse.lyo.testsuite.server.util.OSLCUtils.java

public static HttpResponse putDataToUrl(String url, Credentials creds, String acceptTypes, String contentType,
        String content, Header[] headers) throws IOException {
    getHttpClient(creds);/*from   w  w  w . ja  va2s  . c om*/

    //Create the post and add headers
    HttpPut httpput = new HttpPut(url);
    StringEntity entity = new StringEntity(content);

    httpput.setEntity(entity);
    if (headers != null) {
        httpput.setHeaders(headers);
    }
    if (contentType != null && !contentType.isEmpty())
        httpput.addHeader("Content-Type", contentType);
    if (acceptTypes != null && !acceptTypes.isEmpty())
        httpput.addHeader("Accept", acceptTypes);

    //Send the request and return the response
    HttpResponse resp = httpclient.execute(httpput, new BasicHttpContext());
    return resp;
}