Search in sources :

Example 51 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project knox by apache.

the class GatewayMultiFuncTest method testPostWithContentTypeKnox681.

@Test(timeout = TestUtils.MEDIUM_TIMEOUT)
public void testPostWithContentTypeKnox681() throws Exception {
    LOG_ENTER();
    MockServer mock = new MockServer("REPEAT", true);
    params = new Properties();
    params.put("MOCK_SERVER_PORT", mock.getPort());
    params.put("LDAP_URL", driver.getLdapUrl());
    String topoStr = TestUtils.merge(DAT, "topologies/test-knox678-utf8-chars-topology.xml", params);
    File topoFile = new File(config.getGatewayTopologyDir(), "knox681.xml");
    FileUtils.writeStringToFile(topoFile, topoStr, StandardCharsets.UTF_8);
    topos.reloadTopologies();
    mock.expect().method("PUT").pathInfo("/repeat-context/").respond().status(HttpStatus.SC_CREATED).content("{\"name\":\"value\"}".getBytes(StandardCharsets.UTF_8)).contentLength(-1).contentType("application/json;charset=UTF-8").header("Location", gatewayUrl + "/knox681/repeat");
    String uname = "guest";
    String pword = uname + "-password";
    HttpHost targetHost = new HttpHost("localhost", gatewayPort, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(uname, pword));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPut request = new HttpPut(gatewayUrl + "/knox681/repeat");
    request.addHeader("X-XSRF-Header", "jksdhfkhdsf");
    request.addHeader("Content-Type", "application/json");
    CloseableHttpResponse response = client.execute(request, context);
    assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_CREATED));
    assertThat(response.getFirstHeader("Location").getValue(), endsWith("/gateway/knox681/repeat"));
    assertThat(response.getFirstHeader("Content-Type").getValue(), is("application/json;charset=utf-8"));
    String body = new String(IOUtils.toByteArray(response.getEntity().getContent()), StandardCharsets.UTF_8);
    assertThat(body, is("{\"name\":\"value\"}"));
    response.close();
    client.close();
    mock.expect().method("PUT").pathInfo("/repeat-context/").respond().status(HttpStatus.SC_CREATED).content("<test-xml/>".getBytes(StandardCharsets.UTF_8)).contentType("application/xml; charset=UTF-8").header("Location", gatewayUrl + "/knox681/repeat");
    client = HttpClients.createDefault();
    request = new HttpPut(gatewayUrl + "/knox681/repeat");
    request.addHeader("X-XSRF-Header", "jksdhfkhdsf");
    request.addHeader("Content-Type", "application/xml");
    response = client.execute(request, context);
    assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_CREATED));
    assertThat(response.getFirstHeader("Location").getValue(), endsWith("/gateway/knox681/repeat"));
    assertThat(response.getFirstHeader("Content-Type").getValue(), is("application/xml; charset=UTF-8"));
    body = new String(IOUtils.toByteArray(response.getEntity().getContent()), StandardCharsets.UTF_8);
    assertThat(the(body), hasXPath("/test-xml"));
    response.close();
    client.close();
    mock.stop();
    LOG_EXIT();
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) Properties(java.util.Properties) HttpPut(org.apache.http.client.methods.HttpPut) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) MockServer(org.apache.knox.test.mock.MockServer) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) File(java.io.File) ReleaseTest(org.apache.knox.test.category.ReleaseTest) Test(org.junit.Test)

Example 52 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project knox by apache.

the class GatewaySslFuncTest method testKnox674SslCipherSuiteConfig.

@Test(timeout = TestUtils.MEDIUM_TIMEOUT)
public void testKnox674SslCipherSuiteConfig() throws Exception {
    LOG_ENTER();
    String topoStr = TestUtils.merge(DAT, "test-admin-topology.xml", params);
    File topoFile = new File(config.getGatewayTopologyDir(), "test-topology.xml");
    FileUtils.writeStringToFile(topoFile, topoStr, StandardCharsets.UTF_8);
    topos.reloadTopologies();
    String username = "guest";
    String password = "guest-password";
    String serviceUrl = gatewayUrl + "/test-topology/api/v1/version";
    HttpHost targetHost = new HttpHost("localhost", gatewayPort, gatewayScheme);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" }, new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts())).build();
    HttpGet request = new HttpGet(serviceUrl);
    CloseableHttpResponse response = client.execute(request, context);
    assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version"));
    response.close();
    client.close();
    gateway.stop();
    config.setExcludedSSLCiphers(Arrays.asList(new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }));
    config.setIncludedSSLCiphers(Arrays.asList(new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" }));
    startGatewayServer();
    serviceUrl = gatewayUrl + "/test-topology/api/v1/version";
    try {
        client = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" }, new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts())).build();
        request = new HttpGet(serviceUrl);
        client.execute(request, context);
        fail("Expected SSLHandshakeException");
    } catch (SSLHandshakeException e) {
        // Expected.
        client.close();
    }
    client = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" }, new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" }, new TrustAllHosts())).build();
    request = new HttpGet(serviceUrl);
    response = client.execute(request, context);
    assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version"));
    response.close();
    client.close();
    LOG_EXIT();
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpGet(org.apache.http.client.methods.HttpGet) StreamSource(javax.xml.transform.stream.StreamSource) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) File(java.io.File) ReleaseTest(org.apache.knox.test.category.ReleaseTest) Test(org.junit.Test)

Example 53 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project knox by apache.

the class GatewayBasicFuncTest method oozieQueryJobStatus.

/* GET /oozie/v1/jobs?filter=user%3Dbansalm&offset=1&len=50 (body JSON; contains URL)
    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8
    Content-Length: 46
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 16:10:25 GMT
  */
/* GET /oozie/v1/job/0000000-130214094519989-oozie-oozi-W
    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8
    Content-Length: 2611
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 17:39:36 GMT
  */
/* http://192.168.56.101:11000/oozie/v1/job/0000000-130214094519989-oozie-oozi-W?action=start&user.name=sandbox
    HTTP/1.1 200 OK
    Date: Thu, 14 Feb 2013 17:52:13 GMT
    Content-Length: 0
    Server: Apache-Coyote/1.1
    Set-Cookie: hadoop.auth="u=sandbox&p=sandbox&t=simple&e=1360900333149&s=AU/GeHDNBuK9RBRaBJfrqatjfz8="; Version=1; Path=/
  */
/* PUT /oozie/v1/job/job-3?action=rerun (request body XML, contains URL)
    HTTP/1.1 200 OK
    Date: Thu, 14 Feb 2013 18:07:45 GMT
    Content-Length: 0
    Server: Apache-Coyote/1.1
    Set-Cookie: hadoop.auth="u=sandbox&p=sandbox&t=simple&e=1360901264892&s=DCOczPqn9mcisCeOb5x2C7LIRc8="; Version=1; Path=/
  */
/* GET /oozie/v1/job/0000000-130214094519989-oozie-oozi-W?show=info (body JSON, contains URL)
    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8
    Content-Length: 2611
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 17:45:23 GMT
  */
private String oozieQueryJobStatus(String user, String password, String id, int status) throws Exception {
    driver.getMock("OOZIE").expect().method("GET").pathInfo("/v1/job/" + id).respond().status(HttpStatus.SC_OK).content(driver.getResourceBytes("oozie-job-show-info.json")).contentType("application/json");
    // NOTE:  For some reason REST-assured doesn't like this and ends up failing with Content-Length issues.
    URL url = new URL(driver.getUrl("OOZIE") + "/v1/job/" + id + (driver.isUseGateway() ? "" : "?user.name=" + user));
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();
    HttpClientContext context = HttpClientContext.create();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(user, password));
    context.setCredentialsProvider(credsProvider);
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    context.setAuthCache(authCache);
    HttpGet request = new HttpGet(url.toURI());
    request.setHeader("X-XSRF-Header", "ksdhfjkhdsjkf");
    HttpResponse response = client.execute(targetHost, request, context);
    assertThat(response.getStatusLine().getStatusCode(), Matchers.is(status));
    String json = EntityUtils.toString(response.getEntity());
    return JsonPath.from(json).getString("status");
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpGet(org.apache.http.client.methods.HttpGet) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) Matchers.emptyString(org.hamcrest.Matchers.emptyString) Matchers.containsString(org.hamcrest.Matchers.containsString) URL(java.net.URL) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope)

Example 54 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project knox by apache.

the class GatewayBasicFuncTest method oozieSubmitJob.

/* GET /oozie/v1/admin/status
    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8
    Content-Length: 23
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 15:49:16 GMT
    See: oozie-admin-status.json
   */
/* PUT /oozie/v1/admin/status?safemode=true
  TODO
  */
/* GET /oozie/v1/admin/os-env
    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8
    Content-Length: 2039
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 15:51:56 GMT
    See: oozie-admin-os-env.json
   */
/* GET /oozie/v1/admin/java-sys-properties
    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8
    Content-Length: 3673
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 15:53:00 GMT
    See: oozie-admin-java-sys-properties.json
  */
/* GET /oozie/v1/admin/configuration
    HTTP/1.1 200 OK
    Transfer-Encoding: Identity
    Content-Type: application/json;charset=UTF-8
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 15:53:31 GMT
    See: oozie-admin-configuration.json
  */
/* GET /oozie/v1/admin/instrumentation
    HTTP/1.1 200 OK
    Transfer-Encoding: Identity
    Content-Type: application/json;charset=UTF-8
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 15:55:43 GMT
    See: oozie-admin-instrumentation.json
  */
/* GET /oozie/v1/admin/build-version
    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8
    Content-Length: 27
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 16:08:31 GMT
    See: oozie-admin-build-version.json
  */
/* POST /oozie/v1/jobs (request XML; contains URL, response JSON)
    Content-Type: application/json;charset=UTF-8
    Content-Length: 45
    Server: Apache-Coyote/1.1
    Date: Thu, 14 Feb 2013 18:10:52 GMT
  */
private String oozieSubmitJob(String user, String password, String request, int status) throws IOException, URISyntaxException {
    driver.getMock("OOZIE").expect().method("POST").pathInfo("/v1/jobs").respond().status(HttpStatus.SC_CREATED).content(driver.getResourceBytes("oozie-jobs-submit-response.json")).contentType("application/json");
    URL url = new URL(driver.getUrl("OOZIE") + "/v1/jobs?action=start" + (driver.isUseGateway() ? "" : "&user.name=" + user));
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();
    HttpClientContext context = HttpClientContext.create();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(user, password));
    context.setCredentialsProvider(credsProvider);
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    context.setAuthCache(authCache);
    HttpPost post = new HttpPost(url.toURI());
    // post.getParams().setParameter( "action", "start" );
    StringEntity entity = new StringEntity(request, org.apache.http.entity.ContentType.create("application/xml", StandardCharsets.UTF_8.name()));
    post.setEntity(entity);
    post.setHeader("X-XSRF-Header", "ksdjfhdsjkfhds");
    HttpResponse response = client.execute(targetHost, post, context);
    assertThat(response.getStatusLine().getStatusCode(), Matchers.is(status));
    String json = EntityUtils.toString(response.getEntity());
    // .when().post( getUrl( "OOZIE" ) + "/v1/jobs" + ( isUseGateway() ? "" : "?user.name=" + user ) ).asString();
    return JsonPath.from(json).getString("id");
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicScheme(org.apache.http.impl.auth.BasicScheme) HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) Matchers.emptyString(org.hamcrest.Matchers.emptyString) Matchers.containsString(org.hamcrest.Matchers.containsString) URL(java.net.URL) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) StringEntity(org.apache.http.entity.StringEntity) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope)

Example 55 with BasicAuthCache

use of org.apache.http.impl.client.BasicAuthCache in project groovity by disney.

the class Http method tag.

@SuppressWarnings({ "rawtypes", "unchecked" })
public Object tag(Map attributes, Closure body) throws Exception {
    Object url = resolve(attributes, "url");
    if (url == null) {
        throw new RuntimeException("<g:http> requires 'url' attribute");
    }
    Object var = resolve(attributes, VAR);
    String method = "GET";
    Object methodAtt = resolve(attributes, "method");
    if (methodAtt != null) {
        method = methodAtt.toString();
    }
    boolean followRedirects = true;
    Object redirectsAtt = resolve(attributes, "redirects");
    if (redirectsAtt != null) {
        followRedirects = Boolean.parseBoolean(redirectsAtt.toString());
    }
    CookieOption cookieOption = CookieOption.DEFAULT;
    Object cookiesAtt = resolve(attributes, "cookies");
    if (cookiesAtt != null) {
        cookieOption = CookieOption.valueOf(cookiesAtt.toString().toUpperCase());
    }
    Object timeout = resolve(attributes, TIMEOUT);
    final int timeoutSeconds = timeout == null ? -1 : timeout instanceof Number ? ((Number) timeout).intValue() : Integer.parseInt(timeout.toString());
    Object target = resolve(attributes, "to");
    if (target instanceof Class) {
        if (!Object.class.equals(target)) {
            target = ((Class) target).newInstance();
        }
    }
    if (target == null) {
        target = Object.class;
    }
    Object async = resolve(attributes, "async");
    if (async != null && !(async instanceof Boolean)) {
        async = Boolean.valueOf(async.toString());
    }
    HttpEntity dataEntity = null;
    Object data = resolve(attributes, "data");
    HttpClientContext clientContext = resolve(attributes, "context", HttpClientContext.class);
    if (clientContext == null) {
        clientContext = HttpClientContext.create();
    }
    if (clientContext.getCookieStore() == null) {
        // we don't want to let cookies be shared across contexts
        clientContext.setCookieStore(new BasicCookieStore());
    }
    if (clientContext.getAuthCache() == null) {
        // we also don't want to share credentials across contexts
        clientContext.setAuthCache(new BasicAuthCache());
    }
    final HttpClientContext fContext = clientContext;
    ScriptHelper context = getScriptHelper(body);
    Object oldOut = get(context, OUT);
    // execute body to assemble URL params, headers, post body
    Map variables = context.getBinding().getVariables();
    URI uri;
    URIBuilder builder;
    ArrayList<Header> headers;
    Optional<UserPass> userPass;
    Optional<HttpSignatureSigner> signer;
    Optional<HttpRequestInterceptor> interceptor;
    ContentType targetType = null;
    try {
        builder = new URIBuilder(url.toString());
        bind(context, Uri.CURRENT_URI_BUILDER, builder);
        headers = new ArrayList<Header>();
        bind(context, com.disney.groovity.tags.Header.CURRENT_LIST_FOR_HEADERS, headers);
        Credentials.acceptCredentials(variables);
        Signature.acceptSigner(variables);
        acceptInterceptor(variables);
        StringWriter sw = new StringWriter();
        bind(context, OUT, sw);
        try {
            Object rval = body.call();
            if (rval instanceof Writable) {
                ((Writable) rval).writeTo(sw);
            }
        } finally {
            bind(context, OUT, oldOut);
            userPass = Credentials.resolveCredentials(variables);
            signer = Signature.resolveSigner(variables);
            interceptor = resolveInterceptor(variables);
        }
        for (Header header : headers) {
            if (header.getName().equalsIgnoreCase("Content-Type")) {
                targetType = ContentType.parse(header.getValue());
                String m = targetType.getMimeType();
                if (targetType.getCharset() == null && (m.startsWith("text") || m.contains("xml") || m.contains("json"))) {
                    targetType = targetType.withCharset("UTF-8");
                }
                break;
            }
        }
        String val = sw.toString();
        if (val.trim().length() > 0) {
            dataEntity = new StringEntity(val, targetType);
        }
        if (builder.getScheme().equals("http") && builder.getPort() == 80) {
            builder.setPort(-1);
        } else if (builder.getScheme().equals("https") && builder.getPort() == 443) {
            builder.setPort(-1);
        }
        uri = builder.build();
        if (userPass.isPresent()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(userPass.get().getUser(), new String(userPass.get().getPass())));
            clientContext.setCredentialsProvider(credsProvider);
        }
    } catch (URISyntaxException e1) {
        throw new RuntimeException("Invalid URI " + url, e1);
    } finally {
        unbind(context, Uri.CURRENT_URI_BUILDER);
        unbind(context, com.disney.groovity.tags.Header.CURRENT_LIST_FOR_HEADERS);
    }
    final HttpRequestBase request = "POST".equalsIgnoreCase(method) ? new HttpPost(uri) : "PUT".equalsIgnoreCase(method) ? new HttpPut(uri) : "HEAD".equalsIgnoreCase(method) ? new HttpHead(uri) : "DELETE".equalsIgnoreCase(method) ? (data != null ? new HttpBodyDelete(uri) : new HttpDelete(uri)) : "OPTIONS".equalsIgnoreCase(method) ? new HttpOptions(uri) : new HttpGet(uri);
    if (headers.size() > 0) {
        request.setHeaders(headers.toArray(new Header[0]));
    }
    if (request instanceof HttpEntityEnclosingRequest) {
        if (data != null) {
            // decide on strategy to convert data to entity
            if (data instanceof HttpEntity) {
                dataEntity = (HttpEntity) data;
            } else if (data instanceof CharSequence) {
                if (targetType != null) {
                    dataEntity = new StringEntity(data.toString(), targetType);
                } else {
                    dataEntity = new StringEntity(data.toString(), "UTF-8");
                }
            } else if (data instanceof byte[]) {
                dataEntity = new ByteArrayEntity((byte[]) data, targetType);
            } else if (data instanceof File) {
                dataEntity = new FileEntity((File) data, targetType);
            } else if (data instanceof InputStream) {
                dataEntity = new InputStreamEntity((InputStream) data, targetType);
            } else {
                // look at content type for a hint
                if (targetType != null && targetType.getMimeType().contains("json")) {
                    CharArrayWriter caw = new CharArrayWriter();
                    new ModelJsonWriter(caw).visit(data);
                    dataEntity = new StringEntity(caw.toString(), targetType);
                } else if (targetType != null && targetType.getMimeType().contains("xml")) {
                    if (data instanceof groovy.util.Node) {
                        dataEntity = new StringEntity(XmlUtil.serialize((groovy.util.Node) data), targetType);
                    } else if (data instanceof GPathResult) {
                        dataEntity = new StringEntity(XmlUtil.serialize((GPathResult) data), targetType);
                    } else if (data instanceof Element) {
                        dataEntity = new StringEntity(XmlUtil.serialize((Element) data), targetType);
                    } else if (data instanceof Document) {
                        dataEntity = new StringEntity(XmlUtil.serialize(((Document) data).getDocumentElement()), targetType);
                    } else {
                        CharArrayWriter caw = new CharArrayWriter();
                        new ModelXmlWriter(caw).visit(data);
                        dataEntity = new StringEntity(caw.toString(), targetType);
                    }
                } else if ((targetType != null && targetType.getMimeType().contains("x-www-form-urlencoded")) || (targetType == null && (data instanceof Map || data instanceof List))) {
                    // key/value pairs, accept a map, a list of maps, or a list of NameValuePairs
                    Iterator source = data instanceof Map ? ((Map) data).entrySet().iterator() : ((List) data).iterator();
                    ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
                    while (source.hasNext()) {
                        Object next = source.next();
                        if (next instanceof Map.Entry) {
                            Map.Entry entry = (Entry) next;
                            pairs.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue() != null ? entry.getValue().toString() : ""));
                        } else if (next instanceof NameValuePair) {
                            pairs.add((NameValuePair) next);
                        } else if (next instanceof Map) {
                            Iterator<Map.Entry> sub = ((Map) next).entrySet().iterator();
                            while (sub.hasNext()) {
                                Map.Entry se = sub.next();
                                pairs.add(new BasicNameValuePair(se.getKey().toString(), se.getValue() != null ? se.getValue().toString() : ""));
                            }
                        }
                    }
                    dataEntity = new UrlEncodedFormEntity(pairs, "UTF-8");
                } else if (targetType != null && targetType.getMimeType().contains("multipart/form-data")) {
                    // list of maps, each map must contain "name" and "body", plus optional "type" and "filename"
                    Iterator<Map> parts = ((List<Map>) data).iterator();
                    MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
                    while (parts.hasNext()) {
                        Map part = parts.next();
                        Object pbody = part.get("body");
                        String name = (String) part.get("name");
                        String type = (String) part.get("type");
                        String filename = (String) part.get("filename");
                        ContentType ct = type != null ? ContentType.parse(type) : null;
                        if (pbody instanceof File) {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_BINARY;
                            }
                            meBuilder.addBinaryBody(name, (File) pbody, ct, filename);
                        } else if (pbody instanceof byte[]) {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_BINARY;
                            }
                            meBuilder.addBinaryBody(name, (byte[]) pbody, ct, filename);
                        } else if (pbody instanceof ContentBody) {
                            meBuilder.addPart(name, (ContentBody) pbody);
                        } else if (pbody instanceof InputStream) {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_BINARY;
                            }
                            meBuilder.addBinaryBody(name, (InputStream) pbody, ct, filename);
                        } else {
                            if (ct == null) {
                                ct = ContentType.DEFAULT_TEXT;
                            }
                            meBuilder.addTextBody(name, pbody.toString(), ct);
                        }
                    }
                    dataEntity = meBuilder.build();
                } else {
                    // no help from content type header, check for modeled XML
                    if (data instanceof groovy.util.Node) {
                        dataEntity = new StringEntity(XmlUtil.serialize((groovy.util.Node) data), ContentType.APPLICATION_XML.withCharset("UTF-8"));
                    } else if (data instanceof GPathResult) {
                        dataEntity = new StringEntity(XmlUtil.serialize((GPathResult) data), ContentType.APPLICATION_XML.withCharset("UTF-8"));
                    } else if (data instanceof Element) {
                        dataEntity = new StringEntity(XmlUtil.serialize((Element) data), ContentType.APPLICATION_XML.withCharset("UTF-8"));
                    } else if (data instanceof Document) {
                        dataEntity = new StringEntity(XmlUtil.serialize(((Document) data).getDocumentElement()), ContentType.APPLICATION_XML.withCharset("UTF-8"));
                    } else if (data instanceof byte[]) {
                        dataEntity = new ByteArrayEntity((byte[]) data);
                    } else if (data instanceof InputStream) {
                        dataEntity = new InputStreamEntity((InputStream) data);
                    } else if (data instanceof File) {
                        dataEntity = new FileEntity((File) data);
                    } else {
                        // best option left is to post the toString value of the data
                        dataEntity = new StringEntity(data.toString(), "UTF-8");
                    }
                }
            }
        }
        if (dataEntity != null) {
            ((HttpEntityEnclosingRequest) request).setEntity(dataEntity);
            if (dataEntity.getContentType() != null) {
                request.setHeader("Content-Type", dataEntity.getContentType().getValue());
            }
        }
    }
    RequestConfig.Builder configBuilder = request.getConfig() == null ? RequestConfig.custom() : RequestConfig.copy(request.getConfig());
    if (!followRedirects) {
        configBuilder.setRedirectsEnabled(followRedirects);
    }
    configBuilder.setCookieSpec(cookieOption.getCookieSpec());
    request.setConfig(configBuilder.build());
    final String varName = var != null ? var.toString() : null;
    ResponseHandler handler = null;
    try {
        Function handlerFunction = (Function) get(body, Handler.HANDLER_BINDING);
        if (handlerFunction != null) {
            handler = new ResponseHandler<Object>() {

                @Override
                public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                    return handlerFunction.apply(response);
                }
            };
        }
        unbind(body, Handler.HANDLER_BINDING);
    } catch (Exception e) {
    }
    if (handler == null) {
        handler = new AutoParsingResponseHandler(target);
    }
    final List<HttpRequestInterceptor> interceptors = new ArrayList<>();
    if (signer.isPresent()) {
        interceptors.add(signer.get());
    }
    if (interceptor.isPresent()) {
        interceptors.add(interceptor.get());
    }
    final ResponseHandler rHandler = handler;
    final boolean isAsync = (async != null && Boolean.TRUE.equals(async));
    Callable<Object> requester = new Callable() {

        public Object call() throws Exception {
            TimeoutTask timeoutTask = null;
            if (timeoutSeconds > 0) {
                timeoutTask = new TimeoutTask(request);
                timeoutTimer.schedule(timeoutTask, timeoutSeconds * 1000);
            }
            try {
                Binding oldThreadBinding = null;
                if (isAsync) {
                    oldThreadBinding = ScriptHelper.THREAD_BINDING.get();
                    Binding asyncBinding = new Binding();
                    asyncBinding.setVariable("request", request);
                    ScriptHelper.THREAD_BINDING.set(asyncBinding);
                }
                try {
                    for (HttpRequestInterceptor interceptor : interceptors) {
                        interceptor.process(request, null);
                    }
                    return httpClient.execute(request, rHandler, fContext);
                } finally {
                    if (isAsync) {
                        if (oldThreadBinding == null) {
                            ScriptHelper.THREAD_BINDING.remove();
                        } else {
                            ScriptHelper.THREAD_BINDING.set(oldThreadBinding);
                        }
                    }
                }
            } catch (HttpResponseException e) {
                if (isAsync) {
                    log.error("Async HTTP response error for " + request.getURI() + ": " + e.getMessage());
                }
                throw e;
            } catch (Exception e) {
                if (request.isAborted()) {
                    if (isAsync) {
                        log.error("Async <g:http> request timed out for " + request.getURI());
                    }
                    throw new TimeoutException("Timed out executing <g:http> for " + request.getURI());
                } else {
                    if (isAsync) {
                        log.error("Async <g:http> request error for " + request.getURI(), e);
                    }
                    throw new RuntimeException("Error executing <g:http> for " + request.getURI(), e);
                }
            } finally {
                if (timeoutTask != null) {
                    timeoutTask.cancel();
                }
            }
        }
    };
    Object responseVar = null;
    if (isAsync) {
        // return the Future to the calling code
        Future<Object> f = asyncExecutor.submit(requester);
        responseVar = new Future<Object>() {

            @Override
            public boolean cancel(boolean mayInterruptIfRunning) {
                return f.cancel(mayInterruptIfRunning);
            }

            @Override
            public boolean isCancelled() {
                return f.isCancelled();
            }

            @Override
            public boolean isDone() {
                return f.isDone();
            }

            @Override
            public Object get() throws InterruptedException, ExecutionException {
                GroovityStatistics.startExecution("http(async)");
                try {
                    return f.get();
                } finally {
                    GroovityStatistics.endExecution();
                }
            }

            @Override
            public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
                GroovityStatistics.startExecution("http(async)");
                try {
                    return f.get(timeout, unit);
                } finally {
                    GroovityStatistics.endExecution();
                }
            }
        };
    } else {
        // return the parsed/handled response object
        GroovityStatistics.startExecution("http(sync)");
        try {
            responseVar = requester.call();
        } finally {
            GroovityStatistics.endExecution();
        }
    }
    if (varName != null) {
        bind(context, varName, responseVar);
    }
    return responseVar;
}
Also used : Entry(java.util.Map.Entry) HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) ContentType(org.apache.http.entity.ContentType) ResponseHandler(org.apache.http.client.ResponseHandler) HttpOptions(org.apache.http.client.methods.HttpOptions) ArrayList(java.util.ArrayList) Writable(groovy.lang.Writable) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) Document(org.w3c.dom.Document) HttpPut(org.apache.http.client.methods.HttpPut) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ArrayList(java.util.ArrayList) TimeoutException(java.util.concurrent.TimeoutException) Binding(groovy.lang.Binding) RequestConfig(org.apache.http.client.config.RequestConfig) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) ContentBody(org.apache.http.entity.mime.content.ContentBody) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) AuthScope(org.apache.http.auth.AuthScope) ModelJsonWriter(com.disney.groovity.model.ModelJsonWriter) ScriptHelper(com.disney.groovity.util.ScriptHelper) Map(java.util.Map) File(java.io.File) HttpEntity(org.apache.http.HttpEntity) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpGet(org.apache.http.client.methods.HttpGet) Element(org.w3c.dom.Element) HttpResponseException(org.apache.http.client.HttpResponseException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) HttpHead(org.apache.http.client.methods.HttpHead) CharArrayWriter(java.io.CharArrayWriter) Callable(java.util.concurrent.Callable) Function(java.util.function.Function) Entry(java.util.Map.Entry) StringWriter(java.io.StringWriter) HttpSignatureSigner(com.disney.http.auth.client.signer.HttpSignatureSigner) Iterator(java.util.Iterator) GPathResult(groovy.util.slurpersupport.GPathResult) ExecutionException(java.util.concurrent.ExecutionException) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) FileEntity(org.apache.http.entity.FileEntity) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) UserPass(com.disney.groovity.tags.Credentials.UserPass) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) InputStreamEntity(org.apache.http.entity.InputStreamEntity) ModelXmlWriter(com.disney.groovity.model.ModelXmlWriter)

Aggregations

BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)55 AuthCache (org.apache.http.client.AuthCache)49 BasicScheme (org.apache.http.impl.auth.BasicScheme)48 HttpHost (org.apache.http.HttpHost)39 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)36 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)33 CredentialsProvider (org.apache.http.client.CredentialsProvider)33 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)32 AuthScope (org.apache.http.auth.AuthScope)27 IOException (java.io.IOException)14 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)14 URI (java.net.URI)10 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)10 HttpGet (org.apache.http.client.methods.HttpGet)10 HttpResponse (org.apache.http.HttpResponse)9 HttpPost (org.apache.http.client.methods.HttpPost)7 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)7 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)7 File (java.io.File)6 URISyntaxException (java.net.URISyntaxException)6