Example usage for org.apache.http.message BasicHeader BasicHeader

List of usage examples for org.apache.http.message BasicHeader BasicHeader

Introduction

In this page you can find the example usage for org.apache.http.message BasicHeader BasicHeader.

Prototype

public BasicHeader(String str, String str2) 

Source Link

Usage

From source file:org.elasticsearch.integration.BulkUpdateTests.java

public void testThatBulkUpdateDoesNotLoseFieldsHttp() throws IOException {
    final String path = "/index1/type/1";
    final Header basicAuthHeader = new BasicHeader("Authorization",
            UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
                    new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray())));

    StringEntity body = new StringEntity("{\"test\":\"test\"}", ContentType.APPLICATION_JSON);
    Response response = getRestClient().performRequest("PUT", path, Collections.emptyMap(), body,
            basicAuthHeader);//from   w  ww. j a  v a  2 s . c o  m
    assertThat(response.getStatusLine().getStatusCode(), equalTo(201));

    response = getRestClient().performRequest("GET", path, basicAuthHeader);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    assertThat(EntityUtils.toString(response.getEntity()), containsString("\"test\":\"test\""));

    if (randomBoolean()) {
        flushAndRefresh();
    }

    //update with new field
    body = new StringEntity("{\"doc\": {\"not test\": \"not test\"}}", ContentType.APPLICATION_JSON);
    response = getRestClient().performRequest("POST", path + "/_update", Collections.emptyMap(), body,
            basicAuthHeader);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

    response = getRestClient().performRequest("GET", path, basicAuthHeader);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    String responseBody = EntityUtils.toString(response.getEntity());
    assertThat(responseBody, containsString("\"test\":\"test\""));
    assertThat(responseBody, containsString("\"not test\":\"not test\""));

    // this part is important. Without this, the document may be read from the translog which would bypass the bug where
    // FLS kicks in because the request can't be found and only returns meta fields
    flushAndRefresh();

    body = new StringEntity("{\"update\": {\"_index\": \"index1\", \"_type\": \"type\", \"_id\": \"1\"}}\n"
            + "{\"doc\": {\"bulk updated\":\"bulk updated\"}}\n", ContentType.APPLICATION_JSON);
    response = getRestClient().performRequest("POST", "/_bulk", Collections.emptyMap(), body, basicAuthHeader);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

    response = getRestClient().performRequest("GET", path, basicAuthHeader);
    responseBody = EntityUtils.toString(response.getEntity());
    assertThat(responseBody, containsString("\"test\":\"test\""));
    assertThat(responseBody, containsString("\"not test\":\"not test\""));
    assertThat(responseBody, containsString("\"bulk updated\":\"bulk updated\""));
}

From source file:cf.client.Token.java

public Header toAuthorizationHeader() {
    return new BasicHeader("Authorization", toAuthorizationString());
}

From source file:org.elasticsearch.client.documentation.RestClientDocumentation.java

@SuppressWarnings("unused")
public void testUsage() throws IOException, InterruptedException {

    //tag::rest-client-init
    RestClient restClient = RestClient// w  w w  .j a  v a  2 s  .  c  o m
            .builder(new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http")).build();
    //end::rest-client-init

    //tag::rest-client-close
    restClient.close();
    //end::rest-client-close

    {
        //tag::rest-client-init-default-headers
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        Header[] defaultHeaders = new Header[] { new BasicHeader("header", "value") };
        builder.setDefaultHeaders(defaultHeaders); // <1>
        //end::rest-client-init-default-headers
    }
    {
        //tag::rest-client-init-max-retry-timeout
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setMaxRetryTimeoutMillis(10000); // <1>
        //end::rest-client-init-max-retry-timeout
    }
    {
        //tag::rest-client-init-failure-listener
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setFailureListener(new RestClient.FailureListener() {
            @Override
            public void onFailure(HttpHost host) {
                // <1>
            }
        });
        //end::rest-client-init-failure-listener
    }
    {
        //tag::rest-client-init-request-config-callback
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                return requestConfigBuilder.setSocketTimeout(10000); // <1>
            }
        });
        //end::rest-client-init-request-config-callback
    }
    {
        //tag::rest-client-init-client-config-callback
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder.setProxy(new HttpHost("proxy", 9000, "http")); // <1>
            }
        });
        //end::rest-client-init-client-config-callback
    }

    {
        //tag::rest-client-sync
        Request request = new Request("GET", // <1>
                "/"); // <2>
        Response response = restClient.performRequest(request);
        //end::rest-client-sync
    }
    {
        //tag::rest-client-async
        Request request = new Request("GET", // <1>
                "/"); // <2>
        restClient.performRequestAsync(request, new ResponseListener() {
            @Override
            public void onSuccess(Response response) {
                // <3>
            }

            @Override
            public void onFailure(Exception exception) {
                // <4>
            }
        });
        //end::rest-client-async
    }
    {
        Request request = new Request("GET", "/");
        //tag::rest-client-parameters
        request.addParameter("pretty", "true");
        //end::rest-client-parameters
        //tag::rest-client-body
        request.setEntity(new NStringEntity("{\"json\":\"text\"}", ContentType.APPLICATION_JSON));
        //end::rest-client-body
        //tag::rest-client-body-shorter
        request.setJsonEntity("{\"json\":\"text\"}");
        //end::rest-client-body-shorter
        {
            //tag::rest-client-headers
            RequestOptions.Builder options = request.getOptions().toBuilder();
            options.addHeader("Accept", "text/plain");
            options.addHeader("Cache-Control", "no-cache");
            request.setOptions(options);
            //end::rest-client-headers
        }
        {
            //tag::rest-client-response-consumer
            RequestOptions.Builder options = request.getOptions().toBuilder();
            options.setHttpAsyncResponseConsumerFactory(
                    new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024));
            request.setOptions(options);
            //end::rest-client-response-consumer
        }
    }
    {
        HttpEntity[] documents = new HttpEntity[10];
        //tag::rest-client-async-example
        final CountDownLatch latch = new CountDownLatch(documents.length);
        for (int i = 0; i < documents.length; i++) {
            Request request = new Request("PUT", "/posts/doc/" + i);
            //let's assume that the documents are stored in an HttpEntity array
            request.setEntity(documents[i]);
            restClient.performRequestAsync(request, new ResponseListener() {
                @Override
                public void onSuccess(Response response) {
                    // <1>
                    latch.countDown();
                }

                @Override
                public void onFailure(Exception exception) {
                    // <2>
                    latch.countDown();
                }
            });
        }
        latch.await();
        //end::rest-client-async-example
    }
    {
        //tag::rest-client-response2
        Response response = restClient.performRequest("GET", "/");
        RequestLine requestLine = response.getRequestLine(); // <1>
        HttpHost host = response.getHost(); // <2>
        int statusCode = response.getStatusLine().getStatusCode(); // <3>
        Header[] headers = response.getHeaders(); // <4>
        String responseBody = EntityUtils.toString(response.getEntity()); // <5>
        //end::rest-client-response2
    }
}

From source file:com.zekke.services.http.RequestBuilder.java

public RequestBuilder setDefaultHeaders() {
    String clientAcceptLanguage = Locale.getDefault().toString().replace('_', '-');
    headers.add(new BasicHeader(HeaderField.ACCEPT_LANGUAGE.getValue(), clientAcceptLanguage));
    return this;
}

From source file:com.spectralogic.ds3client.metadata.PosixMetadataRestore_Test.java

@Test
public void restoreUserAndOwner() throws IOException {
    final int uid = (int) Files.getAttribute(file.toPath(), "unix:uid", NOFOLLOW_LINKS);
    final int gid = (int) Files.getAttribute(file.toPath(), "unix:gid", NOFOLLOW_LINKS);
    final BasicHeader basicHeader[] = new BasicHeader[2];
    basicHeader[0] = new BasicHeader(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_UID,
            String.valueOf(uid));
    basicHeader[1] = new BasicHeader(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_GID,
            String.valueOf(gid));
    final Metadata metadata = genMetadata(basicHeader);
    final PosixMetadataRestore posixMetadataRestore = new PosixMetadataRestore(metadata, file.getPath(),
            MetaDataUtil.getOS());//from  w w  w .j  a  v a  2s  .  c  om
    posixMetadataRestore.restoreUserAndOwner();
    Assert.assertEquals(String.valueOf((int) Files.getAttribute(file.toPath(), "unix:uid", NOFOLLOW_LINKS)),
            basicHeader[0].getValue());
    Assert.assertEquals(String.valueOf((int) Files.getAttribute(file.toPath(), "unix:gid", NOFOLLOW_LINKS)),
            basicHeader[1].getValue());
}

From source file:com.anrisoftware.simplerest.core.AbstractSimpleWorker.java

public void addHeader(String name, String value) {
    headers.add(new BasicHeader(name, value));
}

From source file:org.sharetask.controller.WorkspaceControllerIT.java

@Test
public void testChangeOwnerWorkspace() throws IOException {
    //given/*w  w w. j a v  a2 s  .com*/
    final HttpPut httpPut = new HttpPut(URL_WORKSPACE);
    httpPut.addHeader(new BasicHeader("Content-Type", "application/json"));
    final StringEntity httpEntity = new StringEntity(
            "{\"id\":3," + "\"title\":\"Test Title\"," + "\"owner\":{\"username\":\"dev2@shareta.sk\"}" + "}");
    httpPut.setEntity(httpEntity);

    //when
    final HttpResponse response = getClient().execute(httpPut);

    //then
    Assert.assertEquals(HttpStatus.OK.value(), response.getStatusLine().getStatusCode());
    final String responseData = EntityUtils.toString(response.getEntity());
    Assert.assertTrue(responseData.contains("\"username\":\"dev2@shareta.sk\""));
}

From source file:csic.ceab.movelab.beepath.Fix.java

public boolean uploadJSON(Context context) {

    String response = "";

    String uploadurl = Util.URL_FIXES_JSON;

    try {//from  w  w w.ja  v a  2  s . c  om

        // Create a new HttpClient and Post Header
        HttpPost httppost = new HttpPost(uploadurl);

        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 60000);
        HttpConnectionParams.setTcpNoDelay(myParams, true);

        httppost.setHeader("Content-type", "application/json");
        HttpClient httpclient = new DefaultHttpClient();

        StringEntity se = new StringEntity(exportJSON(context).toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se);

        // Execute HTTP Post Request

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        response = httpclient.execute(httppost, responseHandler);

    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    }

    if (response.contains("SUCCESS")) {

        return true;
    } else {
        return false;
    }

}