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

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

Introduction

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

Prototype

public HttpPut(final String uri) 

Source Link

Usage

From source file:eu.trentorise.smartcampus.storage.ResourceRetriever.java

private byte[] getFileContent(Token token) throws ClientProtocolException, IOException {
    HttpUriRequest request = null;/* w  w w  . ja va  2  s.  co  m*/
    if (token.getUrl() != null && token.getMethodREST() != null) {
        if (token.getMethodREST().equals("GET")) {
            request = new HttpGet(token.getUrl());
        } else if (token.getMethodREST().equals("POST")) {
            request = new HttpPost(token.getUrl());
        } else if (token.getMethodREST().equals("PUT")) {
            request = new HttpPut(token.getUrl());
        } else if (token.getMethodREST().equals("DELETE")) {
            request = new HttpDelete(token.getUrl());
        }

        if (token.getHttpHeaders() != null) {
            for (Entry<String, String> entry : token.getHttpHeaders().entrySet()) {
                request.setHeader(entry.getKey(), entry.getValue());
            }
        }
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            InputStream is = response.getEntity().getContent();
            return eu.trentorise.smartcampus.storage.Utils.read(is);
        }
    } else if (token.getMetadata() != null) {
        return retrieveContent(token.getMetadata());
    }
    return null;
}

From source file:com.foundationdb.http.CsrfProtectionITBase.java

@Test
public void requestBlockedWithEmptyReferer() throws Exception {
    HttpUriRequest request = new HttpPut(defaultURI());
    request.setHeader("Referer", "");

    response = client.execute(request);/*from w  w w. ja  va  2s.  com*/
    assertEquals("status", HttpStatus.SC_FORBIDDEN, response.getStatusLine().getStatusCode());
    assertThat("reason", response.getStatusLine().getReasonPhrase(), containsString("Referer"));
}

From source file:org.elasticsearch.wildfly.WildflyIT.java

public void testTransportClient() throws URISyntaxException, IOException {
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        final String str = String.format(Locale.ROOT,
                "http://localhost:38080/wildfly-%s%s/transport/employees/1", Version.CURRENT,
                Build.CURRENT.isSnapshot() ? "-SNAPSHOT" : "");
        final HttpPut put = new HttpPut(new URI(str));
        final String body;
        try (XContentBuilder builder = jsonBuilder()) {
            builder.startObject();/*from   w w w  .ja  v a 2s.c  o m*/
            {
                builder.field("first_name", "John");
                builder.field("last_name", "Smith");
                builder.field("age", 25);
                builder.field("about", "I love to go rock climbing");
                builder.startArray("interests");
                {
                    builder.value("sports");
                    builder.value("music");
                }
                builder.endArray();
            }
            builder.endObject();
            body = builder.string();
        }
        put.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
        try (CloseableHttpResponse response = client.execute(put)) {
            assertThat(response.getStatusLine().getStatusCode(), equalTo(201));
        }

        final HttpGet get = new HttpGet(new URI(str));
        try (CloseableHttpResponse response = client.execute(get);
                XContentParser parser = JsonXContent.jsonXContent.createParser(
                        new NamedXContentRegistry(ClusterModule.getNamedXWriteables()),
                        response.getEntity().getContent())) {
            final Map<String, Object> map = parser.map();
            assertThat(map.get("first_name"), equalTo("John"));
            assertThat(map.get("last_name"), equalTo("Smith"));
            assertThat(map.get("age"), equalTo(25));
            assertThat(map.get("about"), equalTo("I love to go rock climbing"));
            final Object interests = map.get("interests");
            assertThat(interests, instanceOf(List.class));
            @SuppressWarnings("unchecked")
            final List<String> interestsAsList = (List<String>) interests;
            assertThat(interestsAsList, containsInAnyOrder("sports", "music"));
        }
    }
}

From source file:org.deviceconnect.android.profile.restful.test.FailNetworkServiceDiscoveryProfileTestCase.java

/**
 * PUT?getnetworkservices????./*from  w  w w  .  j a  va2s. c  o m*/
 * 
 * <pre>
 * ?HTTP
 * Method: PUT
 * Path: /network_service_discovery/getnetworkservices
 * </pre>
 * 
 * <pre>
 * ??
 * result?1???????
 * </pre>
 */
public void testGetNetworkServices002() {
    URIBuilder builder = TestURIBuilder.createURIBuilder();
    builder.setProfile(NetworkServiceDiscoveryProfileConstants.PROFILE_NAME);
    builder.setAttribute(NetworkServiceDiscoveryProfileConstants.ATTRIBUTE_GET_NETWORK_SERVICES);
    try {
        HttpUriRequest request = new HttpPut(builder.toString());
        JSONObject root = sendRequest(request);
        assertResultError(ErrorCode.NOT_SUPPORT_ATTRIBUTE.getCode(), root);
    } catch (JSONException e) {
        fail("Exception in JSONObject." + e.getMessage());
    }
}

From source file:com.aliyun.android.oss.task.PutObjectTask.java

/**
 * HttpPut/*  www .  ja v  a  2  s.  c o  m*/
 */
protected HttpUriRequest generateHttpRequest() {
    // ?Http
    String requestUri = this.getOSSEndPoint()
            + httpTool.generateCanonicalizedResource("/" + OSSHttpTool.encodeUri(objectKey));
    HttpPut httpPut = new HttpPut(requestUri);

    // HttpPut
    String resource = httpTool.generateCanonicalizedResource("/" + bucketName + "/" + objectKey);
    String dateStr = Helper.getGMTDate();
    String xossHeader = OSSHttpTool.generateCanonicalizedHeader(objectMetaData.getAttrs());
    String authorization = OSSHttpTool.generateAuthorization(accessId, accessKey, httpMethod.toString(), "",
            objectMetaData.getContentType(), dateStr, xossHeader, resource);

    httpPut.setHeader(AUTHORIZATION, authorization);
    httpPut.setHeader(DATE, dateStr);

    OSSHttpTool.addHttpRequestHeader(httpPut, CACHE_CONTROL, objectMetaData.getCacheControl());
    OSSHttpTool.addHttpRequestHeader(httpPut, CONTENT_DISPOSITION, objectMetaData.getContentDisposition());
    OSSHttpTool.addHttpRequestHeader(httpPut, CONTENT_ENCODING, objectMetaData.getContentEncoding());
    OSSHttpTool.addHttpRequestHeader(httpPut, CONTENT_TYPE, objectMetaData.getContentType());
    OSSHttpTool.addHttpRequestHeader(httpPut, EXPIRES, Helper.getGMTDate(objectMetaData.getExpirationTime()));

    // header
    for (Entry<String, String> entry : objectMetaData.getAttrs().entrySet()) {
        OSSHttpTool.addHttpRequestHeader(httpPut, entry.getKey(), entry.getValue());
    }

    if (objectMetaData.getContentType().equals(HttpContentType.DIR.toString())) {
        data = new byte[0];
        httpPut.setEntity(new ByteArrayEntity(this.data));
    } else {
        httpPut.setEntity(entity);
    }

    return httpPut;
}

From source file:com.cubeia.backoffice.wallet.service.IndexingPlugin.java

private void addTask(final Account tx) {
    exec.submit(new Runnable() {

        @Override//from w w  w  . j a v a2s  . com
        public void run() {
            log.debug("Indexing account " + tx.getId());
            DefaultHttpClient dhc = new DefaultHttpClient();
            HttpPut method = new HttpPut(baseUrl + tx.getId());
            method.addHeader(CONTENT_TYPE, APPLICATION_JSON);
            try {
                String json = mapper.writeValueAsString(tx);
                if (log.isTraceEnabled()) {
                    log.trace("Account " + tx.getId() + " JSON: " + json);
                }
                StringEntity ent = new StringEntity(json, "UTF-8");
                ent.setContentType(APPLICATION_JSON);
                method.setEntity(ent);
                HttpResponse resp = dhc.execute(method);
                if (!String.valueOf(resp.getStatusLine().getStatusCode()).startsWith("2")) {
                    log.warn("Failed to index account " + tx.getId() + "; Server responded with status: "
                            + resp.getStatusLine());
                } else {
                    HttpEntity entity = resp.getEntity();
                    String string = EntityUtils.toString(entity, "UTF-8");
                    if (log.isTraceEnabled()) {
                        log.trace("Account " + tx.getId() + " return JSON: " + string);
                    }
                    JsonNode node = mapper.readTree(string);
                    if (!node.get("ok").asBoolean()) {
                        log.warn("Failed to index account " + tx.getId() + "; Response JSON: " + string);
                    }
                }
            } catch (Exception e) {
                log.error("Failed to account transaction " + tx.getId(), e);
            }
        }
    });
}

From source file:org.hawkular.apm.tests.agent.opentracing.client.http.ApacheHttpClientITest.java

@Test
public void testHttpClientWithoutResponseHandlerPUT() throws IOException {
    testHttpClientWithoutResponseHandler(new HttpPut(SAY_HELLO_URL), false, true);
}

From source file:org.apache.hadoop.hbase.client.example.TestHttpProxyExample.java

@Test
public void test() throws Exception {
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpPut put = new HttpPut(
                String.format(URL_TEMPLCATE, PORT, TABLE_NAME.getNameAsString(), ROW, FAMILY, QUALIFIER));
        put.setEntity(EntityBuilder.create().setText(VALUE)
                .setContentType(ContentType.create("text-plain", StandardCharsets.UTF_8)).build());
        try (CloseableHttpResponse resp = client.execute(put)) {
            assertEquals(HttpStatus.SC_OK, resp.getStatusLine().getStatusCode());
        }/*from ww  w .ja v  a  2s.  c om*/
        HttpGet get = new HttpGet(
                String.format(URL_TEMPLCATE, PORT, TABLE_NAME.getNameAsString(), ROW, FAMILY, QUALIFIER));
        try (CloseableHttpResponse resp = client.execute(get)) {
            assertEquals(HttpStatus.SC_OK, resp.getStatusLine().getStatusCode());
            assertEquals("value", Bytes.toString(ByteStreams.toByteArray(resp.getEntity().getContent())));
        }
        get = new HttpGet(String.format(URL_TEMPLCATE, PORT, TABLE_NAME.getNameAsString(), "whatever", FAMILY,
                QUALIFIER));
        try (CloseableHttpResponse resp = client.execute(get)) {
            assertEquals(HttpStatus.SC_NOT_FOUND, resp.getStatusLine().getStatusCode());
        }
    }
}

From source file:com.urbancode.ud.client.PropertyClient.java

public UUID createPropDef(UUID propSheetDefId, String propSheetDefPath, String name, String description,
        String label, Boolean required, String type, String value) throws IOException, JSONException {
    UUID result;/*from ww w  . j a  v a2 s  .co  m*/

    String uri = url + "/property/propSheetDef/" + encodePath(propSheetDefPath) + ".-1/propDefs";
    JSONObject propDefObject = new JSONObject();

    propDefObject.put("name", name);
    propDefObject.put("description", description);
    propDefObject.put("label", label);
    propDefObject.put("required", required.toString());
    propDefObject.put("type", type);
    propDefObject.put("value", value);
    propDefObject.put("definitionGroupId", propSheetDefId);

    HttpPut method = new HttpPut(uri);
    method.setEntity(getStringEntity(propDefObject));

    HttpResponse response = invokeMethod(method);
    String body = getBody(response);
    result = UUID.fromString(new JSONObject(body).getString("id"));
    return result;
}

From source file:com.googlesource.gerrit.plugins.its.rtc.network.Transport.java

public <T> T put(final String path, final Type typeOrClass, JsonObject data, String etag) throws IOException {
    HttpPut request = new HttpPut(toUri(path));
    if (log.isDebugEnabled())
        log.debug("Preparing PUT against " + request.getURI() + " using etag " + etag + " and data " + data);
    request.setEntity(new StringEntity(data.toString(), StandardCharsets.UTF_8));
    if (etag != null)
        request.addHeader("If-Match", etag);
    return invoke(request, typeOrClass, APP_OSLC, APP_OSLC);
}