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:it.larusba.integration.couchbase.document.transformer.RemoteNeo4jTransformer.java

/**
 * It perform the REST call to the URL configured in the
 * transofrmer.properties file/*from   w  w w.j a  v  a2s.  co  m*/
 * 
 * @throws IOException
 */
private void transformJson2Cypher(String documentKey, String documentType, String jsonDocument)
        throws IOException {

    Properties prop = new Properties();
    String propFileName = "transformer.properties";

    inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

    if (inputStream != null) {
        prop.load(inputStream);
    } else {
        throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
    }

    // get the URL property value
    String urlJson2Cypher = prop.getProperty("transformer.url");

    JsonDocument documentToTransform = new JsonDocument(documentKey, jsonDocument, documentType);

    HttpClient httpClient = HttpClientBuilder.create().build();

    HttpPut putRequest = new HttpPut(urlJson2Cypher);
    putRequest.addHeader("content-type", MediaType.APPLICATION_JSON);

    JSONObject json = new JSONObject(documentToTransform);

    StringEntity entity = new StringEntity(json.toString());

    putRequest.setEntity(entity);

    HttpResponse response = httpClient.execute(putRequest);

    if (response.getStatusLine().getStatusCode() != 200) {

        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }
}

From source file:org.fcrepo.integration.api.FedoraDatastreamsIT.java

License:asdf

@Test
public void testMutateDatastream() throws Exception {
    final HttpPost createObjectMethod = postObjMethod("FedoraDatastreamsTest3");
    assertEquals("Couldn't create an object!", 201, getStatus(createObjectMethod));

    final HttpPost createDataStreamMethod = postDSMethod("FedoraDatastreamsTest3", "ds1", "foo");
    assertEquals("Couldn't create a datastream!", 201, getStatus(createDataStreamMethod));

    final HttpPut mutateDataStreamMethod = putDSMethod("FedoraDatastreamsTest3", "ds1");
    mutateDataStreamMethod.setEntity(new StringEntity(faulkner1, "UTF-8"));
    final HttpResponse response = client.execute(mutateDataStreamMethod);
    final String location = response.getFirstHeader("Location").getValue();
    assertEquals("Couldn't mutate a datastream!", 201, response.getStatusLine().getStatusCode());
    assertEquals("Got wrong URI in Location header for datastream creation!",
            serverAddress + OBJECT_PATH.replace("/", "") + "/FedoraDatastreamsTest3/datastreams/ds1", location);

    final HttpGet retrieveMutatedDataStreamMethod = new HttpGet(
            serverAddress + "objects/FedoraDatastreamsTest3/datastreams/ds1/content");
    assertTrue("Datastream didn't accept mutation!", faulkner1
            .equals(EntityUtils.toString(client.execute(retrieveMutatedDataStreamMethod).getEntity())));
}

From source file:uk.ac.horizon.aestheticodes.controllers.ExperienceListUpdater.java

private HttpResponse put(String url, String data) throws Exception {
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut(new URL(url).toURI());
    put.addHeader("content-type", "application/json");
    put.setEntity(new StringEntity(data));

    String token = null;/* www  .  j a v a 2s .  c  o m*/
    try {
        AccountManager accountManager = AccountManager.get(context);
        Account[] accounts = accountManager.getAccountsByType("com.google");
        if (accounts.length >= 1) {
            Log.i("", "Getting token for " + accounts[0].name);
            token = GoogleAuthUtil.getToken(context, accounts[0].name, context.getString(R.string.app_scope));
            put.addHeader("Authorization", "Bearer " + token);
            Log.i("", token);
        }
    } catch (Exception e) {
        Log.e("", e.getMessage(), e);
    }

    Log.i("", "PUT " + url);
    Log.i("", data);
    HttpResponse response = client.execute(put);
    if (response.getStatusLine().getStatusCode() == 401) {
        Log.w("", "Response " + response.getStatusLine().getStatusCode());
        if (token != null) {
            GoogleAuthUtil.invalidateToken(context, token);
        }
    } else if (response.getStatusLine().getStatusCode() != 200) {
        Log.w("", "Response " + response.getStatusLine().getStatusCode() + ": "
                + response.getStatusLine().getReasonPhrase());
    }

    return response;
}

From source file:org.metaeffekt.dcc.agent.UnitBasedEndpointUriBuilder.java

public HttpUriRequest buildHttpUriRequest(Commands command, Id<DeploymentId> deploymentId, Id<UnitId> unitId,
        Id<PackageId> packageId, Map<String, byte[]> executionProperties) {
    Validate.isTrue(executionProperties != null && !executionProperties.isEmpty());

    StringBuilder sb = new StringBuilder("/");
    sb.append(PATH_ROOT).append("/");
    sb.append(deploymentId).append("/");
    sb.append("packages").append("/").append(packageId).append("/");
    sb.append("units").append("/").append(unitId).append("/");
    sb.append(command);/*from  ww  w  .  j  av a2s  . c o  m*/
    String path = sb.toString();

    URIBuilder uriBuilder = createUriBuilder();
    uriBuilder.setPath(path);
    URI uri;
    try {
        uri = uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    HttpPut put = new HttpPut(uri);

    final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
    for (Map.Entry<String, byte[]> entry : executionProperties.entrySet()) {
        multipartBuilder.addBinaryBody(entry.getKey(), entry.getValue());
    }

    put.setEntity(multipartBuilder.build());
    if (requestConfig != null) {
        put.setConfig(requestConfig);
    }
    return put;
}

From source file:com.momock.service.HttpService.java

@Override
public HttpSession put(String url, Header[] headers, IDataMap<String, String> params) {
    HttpPut httpPut = new HttpPut(url);
    HttpEntity entity = getHttpEntity(params);
    if (entity != null)
        httpPut.setEntity(entity);
    if (headers != null)
        httpPut.setHeaders(headers);//from  w  w w. j a v a  2 s.co m
    return new HttpSession(httpClient, httpPut, uiTaskService, asyncTaskService);
}

From source file:com.drillster.api.Api.java

private String sendRequestInternal(String url, String content, HttpMethod method) throws ApiException {
    String target = url + this.contentType.extension;
    this.log.debug("Sending request to " + target + ". Content:\n" + content);

    HttpRequest request;/*from w w  w . jav  a2 s  . co m*/
    if (method == HttpMethod.GET) {
        request = new HttpGet(target);
    } else {
        try {
            if (method == HttpMethod.PUT) {
                HttpPut put = new HttpPut(target);
                put.setEntity(new StringEntity(content, this.contentType.contentTypeString, "UTF-8"));
                request = put;
            } else if (method == HttpMethod.POST) {
                HttpPost post = new HttpPost(target);
                post.setEntity(new StringEntity(content, this.contentType.contentTypeString, "UTF-8"));
                request = post;
            } else {
                throw new IllegalArgumentException();
            }
        } catch (UnsupportedEncodingException e) {
            throw new ApiException(e);
        }
    }
    return sendRequestInternal(request);
}

From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.bibsonomy.BibsonomyUtils.java

/** send a POST request and return the response as string */
String sendPutRequest(String url, String bodytext) throws Exception {
    String sresponse;/*from  w  w w. ja v  a2 s . co m*/

    HttpClient httpclient = new DefaultHttpClient();
    HttpPut httpput = new HttpPut(url);

    // add authorization header
    httpput.addHeader("Authorization", authHeader);

    StringEntity body = new StringEntity(bodytext);
    httpput.setEntity(body);

    HttpResponse response = httpclient.execute(httpput);

    // check statuscode
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK
            || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED) {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        httpclient.getConnectionManager().shutdown();
    } else {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        String httpcode = Integer.toString(response.getStatusLine().getStatusCode());
        httpclient.getConnectionManager().shutdown();
        throw new ReferenceSystemException(httpcode, "Bibsonomy Error", XMLUtils.parseError(sresponse));
    }
    return sresponse;

}

From source file:com.intel.iotkitlib.LibHttp.HttpPutTask.java

private CloudResponse doWork(HttpClient httpClient, String url) {
    try {/* ww  w .  j a v a2  s . co  m*/
        HttpContext localContext = new BasicHttpContext();
        HttpPut httpPut = new HttpPut(url);

        if (httpBody != null) {
            //setting HTTP body in entity
            StringEntity bodyEntity = new StringEntity(httpBody, "UTF-8");
            httpPut.setEntity(bodyEntity);
        }

        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpPut.addHeader(nvp.getName(), nvp.getValue());
        }

        if (debug) {
            Log.e(TAG, "URI is : " + httpPut.getURI());
            Header[] headers = httpPut.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
            if (httpBody != null) {
                BufferedReader reader123 = new BufferedReader(
                        new InputStreamReader(httpPut.getEntity().getContent(), HTTP.UTF_8));
                StringBuilder builder123 = new StringBuilder();
                for (String line = null; (line = reader123.readLine()) != null;) {
                    builder123.append(line).append("\n");
                }
                Log.e(TAG, "Body is :" + builder123.toString());
            }
        }

        HttpResponse response = httpClient.execute(httpPut, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }

        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }

        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return null;
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return null;
    }
}

From source file:org.activiti.rest.service.api.identity.UserResourceTest.java

/**
 * Test updating an unexisting user./*from  w  ww. ja v  a2s.co m*/
 */
public void testUpdateUnexistingUser() throws Exception {
    HttpPut httpPut = new HttpPut(
            SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER, "unexisting"));
    httpPut.setEntity(new StringEntity(objectMapper.createObjectNode().toString()));
    closeResponse(executeRequest(httpPut, HttpStatus.SC_NOT_FOUND));
}

From source file:org.eclipse.packagedrone.testing.server.channel.UploadApiV3Test.java

protected CloseableHttpResponse upload(final URIBuilder uri, final File file)
        throws IOException, URISyntaxException {
    final HttpPut http = new HttpPut(uri.build());

    final String encodedAuth = Base64.getEncoder()
            .encodeToString(uri.getUserInfo().getBytes(StandardCharsets.ISO_8859_1));

    http.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth);

    http.setEntity(new FileEntity(file));
    return httpclient.execute(http);
}