Example usage for org.apache.http.client.fluent Executor newInstance

List of usage examples for org.apache.http.client.fluent Executor newInstance

Introduction

In this page you can find the example usage for org.apache.http.client.fluent Executor newInstance.

Prototype

public static Executor newInstance() 

Source Link

Usage

From source file:org.apache.infra.reviewboard.ReviewBoard.java

public static void main(String... args) throws IOException {

    URL url = new URL(REVIEW_BOARD_URL);
    HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    Executor executor = Executor.newInstance().auth(host, REVIEW_BOARD_USERNAME, REVIEW_BOARD_PASSWORD)
            .authPreemptive(host);/*  w w  w . ja  v a  2s  .  com*/

    Request request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/");
    Response response = executor.execute(request);

    request = Request.Get(REVIEW_BOARD_URL + "/api/review-requests/");
    response = executor.execute(request);

    ObjectMapper mapper = new ObjectMapper();
    JsonNode json = mapper.readTree(response.returnResponse().getEntity().getContent());

    JsonFactory factory = new JsonFactory();
    JsonGenerator generator = factory.createGenerator(new PrintWriter(System.out));
    generator.setPrettyPrinter(new DefaultPrettyPrinter());
    mapper.writeTree(generator, json);
}

From source file:interoperabilite.webservice.fluent.FluentExecutor.java

public static void main(String[] args) throws Exception {
    Executor executor = Executor.newInstance().auth(new HttpHost("somehost"), "username", "password")
            .auth(new HttpHost("myproxy", 8080), "username", "password")
            .authPreemptive(new HttpHost("myproxy", 8080));

    // Execute a GET with timeout settings and return response content as String.
    executor.execute(Request.Get("http://somehost/").connectTimeout(1000).socketTimeout(1000)).returnContent()
            .asString();//from   w  w w  .  ja  v  a2s . c o  m

    // Execute a POST with the 'expect-continue' handshake, using HTTP/1.1,
    // containing a request body as String and return response content as byte array.
    executor.execute(Request.Post("http://somehost/do-stuff").useExpectContinue().version(HttpVersion.HTTP_1_1)
            .bodyString("Important stuff", ContentType.DEFAULT_TEXT)).returnContent().asBytes();

    // Execute a POST with a custom header through the proxy containing a request body
    // as an HTML form and save the result to the file
    executor.execute(Request.Post("http://somehost/some-form").addHeader("X-Custom-header", "stuff")
            .viaProxy(new HttpHost("myproxy", 8080))
            .bodyForm(Form.form().add("username", "vip").add("password", "secret").build()))
            .saveContent(new File("result.dump"));
}

From source file:io.aos.protocol.http.httpcommon.FluentExecutor.java

public static void main(String... args) throws Exception {
    Executor executor = Executor.newInstance().auth(new HttpHost("somehost"), "username", "password")
            .auth(new HttpHost("myproxy", 8080), "username", "password")
            .authPreemptive(new HttpHost("myproxy", 8080));

    // Execute a GET with timeout settings and return response content as String.
    executor.execute(Request.Get("http://somehost/").connectTimeout(1000).socketTimeout(1000)).returnContent()
            .asString();//from ww w .ja  v  a 2 s .  co m

    // Execute a POST with the 'expect-continue' handshake, using HTTP/1.1,
    // containing a request body as String and return response content as byte array.
    executor.execute(Request.Post("http://somehost/do-stuff").useExpectContinue().version(HttpVersion.HTTP_1_1)
            .bodyString("Important stuff", ContentType.DEFAULT_TEXT)).returnContent().asBytes();

    // Execute a POST with a custom header through the proxy containing a request body
    // as an HTML form and save the result to the file
    executor.execute(Request.Post("http://somehost/some-form").addHeader("X-Custom-header", "stuff")
            .viaProxy(new HttpHost("myproxy", 8080))
            .bodyForm(Form.form().add("username", "vip").add("password", "secret").build()))
            .saveContent(new File("result.dump"));
}

From source file:eu.esdihumboldt.util.http.client.fluent.FluentProxyUtil.java

/**
 * setup the given request object to go via proxy
 * //ww  w .  j  a v  a 2  s  .co  m
 * @param request A fluent request
 * @param proxy applying proxy to the fluent request
 * @return Executor, for a fluent request
 */
public static Executor setProxy(Request request, Proxy proxy) {
    ProxyUtil.init();
    Executor executor = Executor.newInstance();

    if (proxy != null && proxy.type() == Type.HTTP) {
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();

        // set the proxy
        HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort());
        request.viaProxy(proxyHost);

        String userName = System.getProperty("http.proxyUser");
        String password = System.getProperty("http.proxyPassword");

        boolean useProxyAuth = userName != null && !userName.isEmpty();

        if (useProxyAuth) {
            Credentials cred = ClientProxyUtil.createCredentials(userName, password);

            executor.auth(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), cred);
        }
    }
    return executor;
}

From source file:com.github.sebhoss.camel.slack.webhook.SlackWebhookProcessor.java

@Override
public void process(final Exchange exchange) throws Exception {
    final String message = exchange.getIn().getBody(String.class);
    final String payload = payload(defaultName(exchange), message);
    final Executor executor = Executor.newInstance();

    executor.execute(Post(hook).bodyString(payload, APPLICATION_JSON));
}

From source file:org.exist.xquery.RestBinariesTest.java

@BeforeClass
public static void setupExecutor() {
    executor = Executor.newInstance()
            .auth(new HttpHost("localhost", existWebServer.getPort()), ADMIN_DB_USER, ADMIN_DB_PWD)
            .authPreemptive(new HttpHost("localhost", existWebServer.getPort()));
}

From source file:org.apache.sling.replication.transport.authentication.impl.NopTransportAuthenticationProviderTest.java

@Test
public void testAuthenticationWithAuthenticableAndNullContext() throws Exception {
    NopTransportAuthenticationProvider authenticationHandler = new NopTransportAuthenticationProvider();
    Executor authenticable = Executor.newInstance();
    TransportAuthenticationContext context = null;
    assertEquals(authenticable, authenticationHandler.authenticate(authenticable, context));
}

From source file:es.upm.oeg.examples.watson.service.PersonalityInsightsService.java

public String analyse(String text) throws IOException, URISyntaxException {

    logger.info("Analyzing the text: \n" + text);

    URI profileURI = new URI(baseURL + "/v2/profile").normalize();
    logger.info("Profile URI: " + profileURI.toString());

    Request profileRequest = Request.Post(profileURI).addHeader("Accept", "application/json").bodyString(text,
            ContentType.TEXT_PLAIN);// w w  w .j a v  a  2 s.  c o  m

    Executor executor = Executor.newInstance().auth(username, password);
    Response response = executor.execute(profileRequest);
    HttpResponse httpResponse = response.returnResponse();
    StatusLine statusLine = httpResponse.getStatusLine();

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    httpResponse.getEntity().writeTo(os);
    String responseBody = new String(os.toByteArray());

    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {

        return responseBody;

    } else {

        String msg = String.format("Personality Insights Service failed - %d %s \n %s",
                statusLine.getStatusCode(), statusLine.getReasonPhrase(), response);
        logger.severe(msg);
        throw new RuntimeException(msg);
    }
}

From source file:es.upm.oeg.examples.watson.service.LanguageIdentificationService.java

public String getLang(String text) throws IOException, URISyntaxException {

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("txt", text));
    qparams.add(new BasicNameValuePair("sid", "lid-generic"));
    qparams.add(new BasicNameValuePair("rt", "json"));

    Executor executor = Executor.newInstance().auth(username, password);

    URI serviceURI = new URI(baseURL).normalize();
    String auth = username + ":" + password;
    String resp = executor.execute(Request.Post(serviceURI)
            .addHeader("Authorization", "Basic " + Base64.encodeBase64String(auth.getBytes()))
            .bodyString(URLEncodedUtils.format(qparams, "utf-8"), ContentType.APPLICATION_FORM_URLENCODED))
            .returnContent().asString();

    JSONObject lang = JSONObject.parse(resp);

    return lang.get("lang").toString();

}

From source file:org.apache.sling.replication.transport.authentication.impl.UserCredentialsTransportAuthenticationProviderTest.java

@Test
public void testAuthenticationWithAuthenticableAndNullContext() throws Exception {
    UserCredentialsTransportAuthenticationProvider authenticationHandler = new UserCredentialsTransportAuthenticationProvider(
            "foo", "bar");
    Executor authenticable = Executor.newInstance();
    TransportAuthenticationContext context = null;
    try {/*from   w w  w. j  av  a  2 s .  c  om*/
        authenticationHandler.authenticate(authenticable, context);
        fail("could not authenticate with a null context");
    } catch (Exception e) {
        // expected to fail
    }
}