Search in sources :

Example 56 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project openolat by klemens.

the class HttpClientFactory method getHttpClientInstance.

/**
 * @param host For basic authentication
 * @param port For basic authentication
 * @param user For basic authentication
 * @param password For basic authentication
 * @param redirect If redirect is allowed
 * @return CloseableHttpClient
 */
public static CloseableHttpClient getHttpClientInstance(String host, int port, String user, String password, boolean redirect) {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketRegistry);
    SocketConfig.Builder socketConfigBuilder = SocketConfig.copy(SocketConfig.DEFAULT);
    socketConfigBuilder.setSoTimeout(10000);
    cm.setDefaultSocketConfig(socketConfigBuilder.build());
    HttpClientBuilder clientBuilder = HttpClientBuilder.create().setConnectionManager(cm).setMaxConnTotal(10).setDefaultCookieStore(new BasicCookieStore());
    if (redirect) {
        clientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
    } else {
        clientBuilder.setRedirectStrategy(new NoRedirectStrategy());
    }
    if (user != null && user.length() > 0) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, password));
        clientBuilder.setDefaultCredentialsProvider(provider);
    }
    return clientBuilder.build();
}
Also used : BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SocketConfig(org.apache.http.config.SocketConfig) AuthScope(org.apache.http.auth.AuthScope) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) LaxRedirectStrategy(org.apache.http.impl.client.LaxRedirectStrategy) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 57 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project webmagic by code4craft.

the class HttpUriRequestConverter method convertHttpClientContext.

private HttpClientContext convertHttpClientContext(Request request, Site site, Proxy proxy) {
    HttpClientContext httpContext = new HttpClientContext();
    if (proxy != null && proxy.getUsername() != null) {
        AuthState authState = new AuthState();
        authState.update(new BasicScheme(ChallengeState.PROXY), new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()));
        httpContext.setAttribute(HttpClientContext.PROXY_AUTH_STATE, authState);
    }
    if (request.getCookies() != null && !request.getCookies().isEmpty()) {
        CookieStore cookieStore = new BasicCookieStore();
        for (Map.Entry<String, String> cookieEntry : request.getCookies().entrySet()) {
            BasicClientCookie cookie1 = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
            cookie1.setDomain(UrlUtils.removePort(UrlUtils.getDomain(request.getUrl())));
            cookieStore.addCookie(cookie1);
        }
        httpContext.setCookieStore(cookieStore);
    }
    return httpContext;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) AuthState(org.apache.http.auth.AuthState) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) Map(java.util.Map) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 58 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project gerrit by GerritCodeReview.

the class CorsIT method crossDomainPutTopic.

@Test
public void crossDomainPutTopic() throws Exception {
    // Setting cookies with HttpOnly requires Servlet API 3+ which not all deployments might have
    // available.
    assume().that(cookieHasSetHttpOnlyMethod()).isTrue();
    Result change = createChange();
    BasicCookieStore cookies = new BasicCookieStore();
    Executor http = Executor.newInstance().use(cookies);
    Request req = Request.Get(canonicalWebUrl.get() + "/login/?account_id=" + admin.id().get());
    http.execute(req);
    String auth = null;
    for (Cookie c : cookies.getCookies()) {
        if ("GerritAccount".equals(c.getName())) {
            auth = c.getValue();
        }
    }
    assertWithMessage("GerritAccount cookie").that(auth).isNotNull();
    cookies.clear();
    UrlEncoded url = new UrlEncoded(canonicalWebUrl.get() + "/changes/" + change.getChangeId() + "/topic");
    url.put("$m", "PUT");
    url.put("$ct", "application/json; charset=US-ASCII");
    url.put("access_token", auth);
    String origin = "http://example.com";
    req = Request.Post(url.toString());
    req.setHeader(CONTENT_TYPE, "text/plain");
    req.setHeader(ORIGIN, origin);
    req.bodyByteArray("{\"topic\":\"test-xd\"}".getBytes(StandardCharsets.US_ASCII));
    HttpResponse r = http.execute(req).returnResponse();
    assertThat(r.getStatusLine().getStatusCode()).isEqualTo(200);
    Header vary = r.getFirstHeader(VARY);
    assertWithMessage(VARY).that(vary).isNotNull();
    assertWithMessage(VARY).that(Splitter.on(", ").splitToList(vary.getValue())).contains(ORIGIN);
    Header allowOrigin = r.getFirstHeader(ACCESS_CONTROL_ALLOW_ORIGIN);
    assertWithMessage(ACCESS_CONTROL_ALLOW_ORIGIN).that(allowOrigin).isNotNull();
    assertWithMessage(ACCESS_CONTROL_ALLOW_ORIGIN).that(allowOrigin.getValue()).isEqualTo(origin);
    Header allowAuth = r.getFirstHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS);
    assertWithMessage(ACCESS_CONTROL_ALLOW_CREDENTIALS).that(allowAuth).isNotNull();
    assertWithMessage(ACCESS_CONTROL_ALLOW_CREDENTIALS).that(allowAuth.getValue()).isEqualTo("true");
    checkTopic(change, "test-xd");
}
Also used : Cookie(org.apache.http.cookie.Cookie) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Executor(org.apache.http.client.fluent.Executor) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) Request(org.apache.http.client.fluent.Request) HttpResponse(org.apache.http.HttpResponse) UrlEncoded(com.google.gerrit.server.UrlEncoded) Result(com.google.gerrit.acceptance.PushOneCommit.Result) Test(org.junit.Test) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest)

Example 59 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project zm-mailbox by Zimbra.

the class TestAccessKeyGrant method testCalendarGet_guest.

/*
     * use zmmailbox to grant guest access:
     * zmmailbox -z -m user1@phoebe.mac mfg Calendar guest g1@guest.com zzz r
     */
public void testCalendarGet_guest() throws Exception {
    BasicCookieStore initialState = new BasicCookieStore();
    /*
        Cookie authCookie = new Cookie(restURL.getURL().getHost(), "ZM_AUTH_TOKEN", mAuthToken, "/", null, false);
        Cookie sessionCookie = new Cookie(restURL.getURL().getHost(), "JSESSIONID", mSessionId, "/zimbra", null, false);
        initialState.addCookie(authCookie);
        initialState.addCookie(sessionCookie);
        */
    String guestName = "g1@guest.com";
    String guestPassword = "zzz";
    Credentials loginCredentials = new UsernamePasswordCredentials(guestName, guestPassword);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, loginCredentials);
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultCookieStore(initialState);
    clientBuilder.setDefaultCredentialsProvider(credsProvider);
    HttpClient client = clientBuilder.build();
    String url = getRestCalendarUrl(OWNER_NAME);
    System.out.println("REST URL: " + url);
    HttpRequestBase method = new HttpGet(url);
    executeHttpMethod(client, method);
}
Also used : BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 60 with BasicCookieStore

use of org.apache.http.impl.client.BasicCookieStore in project zm-mailbox by Zimbra.

the class UserServlet method doHttpOp.

private static Pair<Header[], HttpResponse> doHttpOp(ZAuthToken authToken, HttpRequestBase method) throws ServiceException {
    // create an HTTP client with the same cookies
    String url = "";
    String hostname = "";
    url = method.getURI().toString();
    hostname = method.getURI().getHost();
    HttpClientBuilder clientBuilder = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    Map<String, String> cookieMap = authToken.cookieMap(false);
    if (cookieMap != null) {
        BasicCookieStore cookieStore = new BasicCookieStore();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            BasicClientCookie cookie = new BasicClientCookie(ck.getKey(), ck.getValue());
            cookie.setDomain(hostname);
            cookie.setPath("/");
            cookie.setSecure(false);
            cookieStore.addCookie(cookie);
        }
        clientBuilder.setDefaultCookieStore(cookieStore);
        RequestConfig reqConfig = RequestConfig.copy(ZimbraHttpConnectionManager.getInternalHttpConnMgr().getZimbraConnMgrParams().getReqConfig()).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
        clientBuilder.setDefaultRequestConfig(reqConfig);
        if (method.getMethod().equalsIgnoreCase("PUT")) {
            clientBuilder.setRetryHandler(new InputStreamRequestHttpRetryHandler());
        }
    }
    if (method instanceof HttpPut) {
        long contentLength = ((HttpPut) method).getEntity().getContentLength();
        if (contentLength > 0) {
            // 100kbps in millis
            int timeEstimate = Math.max(10000, (int) (contentLength / 100));
            // cannot set connection time using our ZimbrahttpConnectionManager,
            // see comments in ZimbrahttpConnectionManager.
            // actually, length of the content to Put should not be a factor for
            // establishing a connection, only read time out matter, which we set
            // client.getHttpConnectionManager().getParams().setConnectionTimeout(timeEstimate);
            SocketConfig config = SocketConfig.custom().setSoTimeout(timeEstimate).build();
            clientBuilder.setDefaultSocketConfig(config);
        }
    }
    HttpClient client = clientBuilder.build();
    try {
        HttpResponse response = HttpClientUtil.executeMethod(client, method);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_NOT_FOUND || statusCode == HttpStatus.SC_FORBIDDEN)
            throw MailServiceException.NO_SUCH_ITEM(-1);
        else if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_NO_CONTENT)
            throw ServiceException.RESOURCE_UNREACHABLE(response.getStatusLine().getReasonPhrase(), null, new ServiceException.InternalArgument(HTTP_URL, url, ServiceException.Argument.Type.STR), new ServiceException.InternalArgument(HTTP_STATUS_CODE, statusCode, ServiceException.Argument.Type.NUM));
        List<Header> headers = new ArrayList<Header>(Arrays.asList(response.getAllHeaders()));
        headers.add(new BasicHeader("X-Zimbra-Http-Status", "" + statusCode));
        return new Pair<Header[], HttpResponse>(headers.toArray(new Header[0]), response);
    } catch (HttpException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("HttpException while fetching " + url, e);
    } catch (IOException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("IOException while fetching " + url, e);
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) SocketConfig(org.apache.http.config.SocketConfig) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) IOException(java.io.IOException) HttpPut(org.apache.http.client.methods.HttpPut) Mountpoint(com.zimbra.cs.mailbox.Mountpoint) InputStreamRequestHttpRetryHandler(com.zimbra.common.httpclient.InputStreamRequestHttpRetryHandler) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) AccountServiceException(com.zimbra.cs.account.AccountServiceException) ServiceException(com.zimbra.common.service.ServiceException) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) HttpClient(org.apache.http.client.HttpClient) HttpException(org.apache.http.HttpException) Map(java.util.Map) HashMap(java.util.HashMap) BasicHeader(org.apache.http.message.BasicHeader) Pair(com.zimbra.common.util.Pair)

Aggregations

BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)138 HttpResponse (org.apache.http.HttpResponse)54 HttpGet (org.apache.http.client.methods.HttpGet)51 Test (org.junit.Test)44 BasicClientCookie (org.apache.http.impl.cookie.BasicClientCookie)40 RequestConfig (org.apache.http.client.config.RequestConfig)36 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)36 CookieStore (org.apache.http.client.CookieStore)26 Header (org.apache.http.Header)25 HttpClient (org.apache.http.client.HttpClient)25 IOException (java.io.IOException)23 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)22 Cookie (org.apache.http.cookie.Cookie)19 HttpPost (org.apache.http.client.methods.HttpPost)15 CredentialsProvider (org.apache.http.client.CredentialsProvider)14 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)14 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)14 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)13 URI (java.net.URI)12 HttpEntity (org.apache.http.HttpEntity)12