Search in sources :

Example 31 with HttpContext

use of org.apache.http.protocol.HttpContext in project LogHub by fbacchella.

the class AbstractHttpSender method configure.

@Override
public boolean configure(Properties properties) {
    endPoints = Helpers.stringsToUrl(destinations, port, protocol, logger);
    if (endPoints.length == 0) {
        return false;
    }
    // Create the senders threads and the common queue
    batch = new Batch();
    threads = new Thread[publisherThreads];
    for (int i = 1; i <= publisherThreads; i++) {
        String tname = getPublishName() + "Publisher" + i;
        threads[i - 1] = new Thread(publisher) {

            {
                setDaemon(false);
                setName(tname);
                start();
            }
        };
    }
    // The HTTP connection management
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setUserAgent(VersionInfo.getUserAgent("LogHub-HttpClient", "org.apache.http.client", HttpClientBuilder.class));
    // Set the Configuration manager
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", new SSLConnectionSocketFactory(properties.ssl)).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setDefaultMaxPerRoute(2);
    cm.setMaxTotal(2 * publisherThreads);
    cm.setValidateAfterInactivity(timeout * 1000);
    builder.setConnectionManager(cm);
    if (properties.ssl != null) {
        builder.setSSLContext(properties.ssl);
    }
    builder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000).setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build());
    builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).setSoTimeout(timeout * 1000).build());
    builder.setDefaultConnectionConfig(ConnectionConfig.custom().build());
    builder.disableCookieManagement();
    builder.setRetryHandler(new HttpRequestRetryHandler() {

        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }
    });
    client = builder.build();
    if (user != null && password != null) {
        credsProvider = new BasicCredentialsProvider();
        for (URL i : endPoints) {
            credsProvider.setCredentials(new AuthScope(i.getHost(), i.getPort()), new UsernamePasswordCredentials(user, password));
        }
    }
    // Schedule a task to flush every 5 seconds
    Runnable flush = () -> {
        synchronized (publisher) {
            long now = new Date().getTime();
            if ((now - lastFlush) > 5000) {
                batches.add(batch);
                batch = new Batch();
                publisher.notify();
            }
        }
    };
    properties.registerScheduledTask(getPublishName() + "Flusher", flush, 5000);
    return true;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpContext(org.apache.http.protocol.HttpContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) URL(java.net.URL) Date(java.util.Date) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) AuthScope(org.apache.http.auth.AuthScope) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler)

Example 32 with HttpContext

use of org.apache.http.protocol.HttpContext in project iNaturalistAndroid by inaturalist.

the class INaturalistService method request.

private JSONArray request(String url, String method, ArrayList<NameValuePair> params, JSONObject jsonContent, boolean authenticated, boolean useJWTToken, boolean allowAnonymousJWTToken) throws AuthenticationException {
    DefaultHttpClient client = new DefaultHttpClient();
    // Handle redirects (301/302) for all HTTP methods (including POST)
    client.setRedirectHandler(new DefaultRedirectHandler() {

        @Override
        public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
            boolean isRedirect = super.isRedirectRequested(response, context);
            if (!isRedirect) {
                int responseCode = response.getStatusLine().getStatusCode();
                if (responseCode == 301 || responseCode == 302) {
                    return true;
                }
            }
            return isRedirect;
        }
    });
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, getUserAgent(mApp));
    // Log.d(TAG, String.format("%s (%b - %s): %s", method, authenticated,
    // authenticated ? mCredentials : "<null>",
    // url));
    HttpRequestBase request;
    Log.d(TAG, String.format("URL: %s - %s (%s)", method, url, (params != null ? params.toString() : "null")));
    if (method.equalsIgnoreCase("post")) {
        request = new HttpPost(url);
    } else if (method.equalsIgnoreCase("delete")) {
        request = new HttpDelete(url);
    } else if (method.equalsIgnoreCase("put")) {
        request = new HttpPut(url);
    } else {
        request = new HttpGet(url);
    }
    // POST params
    if (jsonContent != null) {
        // JSON body content
        request.setHeader("Content-type", "application/json");
        StringEntity entity = null;
        try {
            entity = new StringEntity(jsonContent.toString(), HTTP.UTF_8);
        } catch (UnsupportedEncodingException exc) {
            exc.printStackTrace();
        }
        if (method.equalsIgnoreCase("put")) {
            ((HttpPut) request).setEntity(entity);
        } else {
            ((HttpPost) request).setEntity(entity);
        }
    } else if (params != null) {
        // "Standard" multipart encoding
        Charset utf8Charset = Charset.forName("UTF-8");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        for (int i = 0; i < params.size(); i++) {
            if (params.get(i).getName().equalsIgnoreCase("image") || params.get(i).getName().equalsIgnoreCase("file") || params.get(i).getName().equalsIgnoreCase("user[icon]")) {
                // If the key equals to "image", we use FileBody to transfer the data
                String value = params.get(i).getValue();
                if (value != null)
                    entity.addPart(params.get(i).getName(), new FileBody(new File(value)));
            } else {
                // Normal string data
                try {
                    entity.addPart(params.get(i).getName(), new StringBody(params.get(i).getValue(), utf8Charset));
                } catch (UnsupportedEncodingException e) {
                    Log.e(TAG, "failed to add " + params.get(i).getName() + " to entity for a " + method + " request: " + e);
                }
            }
        }
        if (method.equalsIgnoreCase("put")) {
            ((HttpPut) request).setEntity(entity);
        } else {
            ((HttpPost) request).setEntity(entity);
        }
    }
    if (url.startsWith(API_HOST) && (mCredentials != null)) {
        // For the node API, if we're logged in, *always* use JWT authentication
        authenticated = true;
        useJWTToken = true;
    }
    if (authenticated) {
        if (useJWTToken && allowAnonymousJWTToken && (mCredentials == null)) {
            // User not logged in, but allow using anonymous JWT
            request.setHeader("Authorization", getAnonymousJWTToken());
        } else {
            ensureCredentials();
            if (useJWTToken) {
                // Use JSON Web Token for this request
                request.setHeader("Authorization", getJWTToken());
            } else if (mLoginType == LoginType.PASSWORD) {
                // Old-style password authentication
                request.setHeader("Authorization", "Basic " + mCredentials);
            } else {
                // OAuth2 token (Facebook/G+/etc)
                request.setHeader("Authorization", "Bearer " + mCredentials);
            }
        }
    }
    try {
        mResponseErrors = null;
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        String content = entity != null ? EntityUtils.toString(entity) : null;
        Log.d(TAG, String.format("RESP: %s", content));
        JSONArray json = null;
        mLastStatusCode = response.getStatusLine().getStatusCode();
        switch(response.getStatusLine().getStatusCode()) {
            // switch (response.getStatusCode()) {
            case HttpStatus.SC_UNPROCESSABLE_ENTITY:
                // Validation error - still need to return response
                Log.e(TAG, response.getStatusLine().toString());
            case HttpStatus.SC_OK:
                try {
                    json = new JSONArray(content);
                } catch (JSONException e) {
                    Log.d(TAG, "Failed to create JSONArray, JSONException: " + e.toString());
                    try {
                        JSONObject jo = new JSONObject(content);
                        json = new JSONArray();
                        json.put(jo);
                    } catch (JSONException e2) {
                        Log.d(TAG, "Failed to create JSONObject, JSONException: " + e2.toString());
                    }
                }
                mResponseHeaders = response.getAllHeaders();
                try {
                    if ((json != null) && (json.length() > 0)) {
                        JSONObject result = json.getJSONObject(0);
                        if (result.has("errors")) {
                            // Error response
                            Log.e(TAG, "Got an error response: " + result.get("errors").toString());
                            mResponseErrors = result.getJSONArray("errors");
                            return null;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if ((content != null) && (content.length() == 0)) {
                    // In case it's just non content (but OK HTTP status code) - so there's no error
                    json = new JSONArray();
                }
                return json;
            case HttpStatus.SC_UNAUTHORIZED:
                throw new AuthenticationException();
            case HttpStatus.SC_GONE:
                Log.e(TAG, "GONE: " + response.getStatusLine().toString());
            // or post them as new observations
            default:
                Log.e(TAG, response.getStatusLine().toString());
        }
    } catch (IOException e) {
        // request.abort();
        Log.w(TAG, "Error for URL " + url, e);
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpDelete(org.apache.http.client.methods.HttpDelete) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpContext(org.apache.http.protocol.HttpContext) JSONArray(org.json.JSONArray) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Charset(java.nio.charset.Charset) JSONException(org.json.JSONException) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpPut(org.apache.http.client.methods.HttpPut) StringEntity(org.apache.http.entity.StringEntity) DefaultRedirectHandler(org.apache.http.impl.client.DefaultRedirectHandler) JSONObject(org.json.JSONObject) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) File(java.io.File)

Example 33 with HttpContext

use of org.apache.http.protocol.HttpContext in project epp.mpc by eclipse.

the class TransportFactoryTest method interceptRequest.

private static AbortRequestCustomizer interceptRequest(HttpClientCustomizer... customizers) throws Exception {
    AbortRequestCustomizer abortRequestCustomizer = new AbortRequestCustomizer();
    HttpClientCustomizer[] mergedCustomizers;
    if (customizers == null || customizers.length == 0) {
        mergedCustomizers = new HttpClientCustomizer[] { abortRequestCustomizer };
    } else {
        mergedCustomizers = new HttpClientCustomizer[customizers.length + 1];
        System.arraycopy(customizers, 0, mergedCustomizers, 0, customizers.length);
        mergedCustomizers[customizers.length] = abortRequestCustomizer;
    }
    HttpClientTransport httpClientTransport = createClient(mergedCustomizers);
    HttpClient client = httpClientTransport.getClient();
    HttpContext context = new BasicHttpContext();
    try {
        client.execute(new HttpGet("http://localhost/test"), context);
        fail("Expected request execution to fail");
    } catch (ConnectionClosedException ex) {
    // ignore expected exception
    }
    return abortRequestCustomizer;
}
Also used : HttpClientCustomizer(org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientCustomizer) HttpClientTransport(org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) ConnectionClosedException(org.apache.http.ConnectionClosedException)

Example 34 with HttpContext

use of org.apache.http.protocol.HttpContext in project epp.mpc by eclipse.

the class TransportFactoryTest method testHttpClientCustomizer.

@Test
public void testHttpClientCustomizer() throws Exception {
    final HttpClientCustomizer customizer = Mockito.mock(HttpClientCustomizer.class);
    Mockito.when(customizer.customizeBuilder(Matchers.any())).thenAnswer(new Answer<HttpClientBuilder>() {

        public HttpClientBuilder answer(InvocationOnMock invocation) {
            HttpClientBuilder builder = (HttpClientBuilder) invocation.getArguments()[0];
            return builder == null ? null : builder.addInterceptorFirst(new HttpRequestInterceptor() {

                @Override
                public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                    request.addHeader("X-Customizer-Test", "true");
                }
            });
        }
    });
    Mockito.when(customizer.customizeCredentialsProvider(Matchers.any())).thenReturn(null);
    HttpRequest request = interceptRequest(customizer).getInterceptedRequest();
    Mockito.verify(customizer).customizeBuilder(Matchers.any());
    Mockito.verify(customizer).customizeCredentialsProvider(Matchers.any());
    assertThat(request.getFirstHeader("X-Customizer-Test"), LambdaMatchers.<Header, String>map(x -> x == null ? null : x.getValue()).matches("true"));
}
Also used : HttpRequest(org.apache.http.HttpRequest) HttpClientCustomizer(org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientCustomizer) Header(org.apache.http.Header) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpException(org.apache.http.HttpException) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) IOException(java.io.IOException) Test(org.junit.Test)

Example 35 with HttpContext

use of org.apache.http.protocol.HttpContext in project epp.mpc by eclipse.

the class HttpClientFactory method createCredentialsProvider.

private static CredentialsProvider createCredentialsProvider(HttpClientBuilder clientBuilder) {
    // TODO we should handle configured proxy passwords and dialogs to prompt for unknown credentials on our own...
    CredentialsProvider credentialsProvider = new SystemCredentialsProvider();
    credentialsProvider = customizeCredentialsProvider(credentialsProvider);
    final CacheCredentialsProvider cacheProvider = new CacheCredentialsProvider();
    credentialsProvider = new ChainedCredentialsProvider(cacheProvider, credentialsProvider);
    credentialsProvider = new SynchronizedCredentialsProvider(credentialsProvider);
    clientBuilder.addInterceptorFirst(new HttpRequestInterceptor() {

        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            context.setAttribute(CacheCredentialsAuthenticationStrategy.CREDENTIALS_CACHE_ATTRIBUTE, cacheProvider);
        }
    });
    return credentialsProvider;
}
Also used : HttpRequest(org.apache.http.HttpRequest) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) HttpContext(org.apache.http.protocol.HttpContext) HttpException(org.apache.http.HttpException) CredentialsProvider(org.apache.http.client.CredentialsProvider) IOException(java.io.IOException)

Aggregations

HttpContext (org.apache.http.protocol.HttpContext)187 HttpResponse (org.apache.http.HttpResponse)81 IOException (java.io.IOException)74 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)59 HttpRequest (org.apache.http.HttpRequest)57 HttpException (org.apache.http.HttpException)34 HttpGet (org.apache.http.client.methods.HttpGet)31 Test (org.junit.Test)30 HttpHost (org.apache.http.HttpHost)28 HttpPost (org.apache.http.client.methods.HttpPost)28 StringEntity (org.apache.http.entity.StringEntity)23 ArrayList (java.util.ArrayList)22 Header (org.apache.http.Header)22 MessageContext (org.apache.axis2.context.MessageContext)19 NameValuePair (org.apache.http.NameValuePair)18 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)18 ProtocolException (org.apache.http.ProtocolException)17 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)17 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)17 URI (java.net.URI)16