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();
}
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;
}
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");
}
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);
}
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);
}
}
Aggregations