use of org.apache.http.impl.cookie.BasicClientCookie in project nanohttpd by NanoHttpd.
the class CookieIntegrationTest method testServerReceivesMultipleCookiesSentFromClient.
@Test
public void testServerReceivesMultipleCookiesSentFromClient() throws Exception {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 100);
Date date = calendar.getTime();
BasicClientCookie clientCookie0 = new BasicClientCookie("name0", "value0");
BasicClientCookie clientCookie1 = new BasicClientCookie("name1", "value1");
BasicClientCookie clientCookie2 = new BasicClientCookie("name2", "value2");
BasicClientCookie clientCookie3 = new BasicClientCookie("name3", "value3");
clientCookie0.setExpiryDate(date);
clientCookie0.setDomain("localhost");
clientCookie1.setExpiryDate(date);
clientCookie1.setDomain("localhost");
clientCookie2.setExpiryDate(date);
clientCookie2.setDomain("localhost");
clientCookie3.setExpiryDate(date);
clientCookie3.setDomain("localhost");
this.httpclient.getCookieStore().addCookie(clientCookie0);
this.httpclient.getCookieStore().addCookie(clientCookie1);
this.httpclient.getCookieStore().addCookie(clientCookie2);
this.httpclient.getCookieStore().addCookie(clientCookie3);
HttpGet httpget = new HttpGet("http://localhost:8192/");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
this.httpclient.execute(httpget, responseHandler);
assertEquals(4, this.testServer.cookiesReceived.size());
}
use of org.apache.http.impl.cookie.BasicClientCookie in project new-cloud by xie-summer.
the class HttpUtils method executeHttpRequestWithCookie.
private static HttpResult executeHttpRequestWithCookie(HttpUriRequest request, Map<String, String> reqHeader, int timeoutMills, String charset, List<BasicClientCookie> cookies) {
hostCount(request);
CookieStore cookieStore = getCookieStore(cookies);
CloseableHttpClient client = getHttpClient(CONNECTION_TIMEOUT, timeoutMills, cookieStore);
if (reqHeader != null) {
for (String name : reqHeader.keySet()) {
request.addHeader(name, reqHeader.get(name));
}
}
try {
List<Cookie> reqcookie = cookieStore.getCookies();
CloseableHttpResponse response = client.execute(request);
try {
HttpEntity entiry = getEntity(response);
String result = "";
if (entiry != null) {
result = EntityUtils.toString(getEntity(response), charset);
}
if (isSuccess(response)) {
HttpResult ret = HttpResult.getSuccessReturn(result);
addHeader(ret, response);
List<Cookie> cookieList = cookieStore.getCookies();
addCookie(ret, cookieList, reqcookie);
return ret;
} else {
int statusCode = response.getStatusLine().getStatusCode();
HttpResult ret = HttpResult.getFailure("httpStatus:" + response.getStatusLine().getStatusCode(), statusCode, result);
addHeader(ret, response);
String msg = "httpStatus:" + statusCode + response.getStatusLine().getReasonPhrase() + ", Header: " + ret.getAllHeaders();
DB_LOGGER.error("ERROR HttpUtils:" + msg + request.getURI());
request.abort();
return ret;
}
} finally {
response.close();
}
} catch (HttpHostConnectException e) {
request.abort();
DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_HTTP_HOST_CONNECT_EXCEPTION);
} catch (ConnectTimeoutException e) {
request.abort();
DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_CONNECT_TIMEOUT_EXCEPTION);
} catch (SocketTimeoutException e) {
request.abort();
DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), HTTP_STATUSCODE_SOCKET_TIMEOUT_EXCEPTION);
} catch (Exception e) {
request.abort();
DB_LOGGER.error(request.getURI() + ":" + LoggerUtils.getExceptionTrace(e, 30));
return HttpResult.getFailure(request.getURI() + " exception:" + e.getClass().getCanonicalName(), EXCEPTION_HTTP_STATUSCODE);
}
}
use of org.apache.http.impl.cookie.BasicClientCookie 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.cookie.BasicClientCookie 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);
}
}
use of org.apache.http.impl.cookie.BasicClientCookie in project zm-mailbox by Zimbra.
the class StatsImageServlet method doGet.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
AuthToken authToken = getAdminAuthTokenFromCookie(req, resp);
if (authToken == null)
return;
String imgName = null;
InputStream is = null;
boolean imgAvailable = true;
boolean localServer = false;
boolean systemWide = false;
String serverAddr = "";
String noDefaultImg = req.getParameter("nodef");
boolean noDefault = false;
if (noDefaultImg != null && !noDefaultImg.equals("") && noDefaultImg.equals("1")) {
noDefault = true;
}
String reqPath = req.getRequestURI();
try {
// check if this is the logger host, otherwise proxy the request to the logger host
String serviceHostname = Provisioning.getInstance().getLocalServer().getAttr(Provisioning.A_zimbraServiceHostname);
String logHost = Provisioning.getInstance().getConfig().getAttr(Provisioning.A_zimbraLogHostname);
if (!serviceHostname.equalsIgnoreCase(logHost)) {
StringBuffer url = new StringBuffer("https");
url.append("://").append(logHost).append(':').append(LC.zimbra_admin_service_port.value());
url.append(reqPath);
String queryStr = req.getQueryString();
if (queryStr != null)
url.append('?').append(queryStr);
// create an HTTP client with the same cookies
BasicCookieStore cookieStore = new BasicCookieStore();
try {
BasicClientCookie cookie = new BasicClientCookie(ZimbraCookie.COOKIE_ZM_ADMIN_AUTH_TOKEN, authToken.getEncoded());
cookie.setDomain(logHost);
cookie.setPath("/");
cookie.setSecure(false);
cookieStore.addCookie(cookie);
} catch (AuthTokenException ate) {
throw ServiceException.PROXY_ERROR(ate, url.toString());
}
HttpClientBuilder clientBuilder = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
clientBuilder.setDefaultCookieStore(cookieStore);
HttpGet get = new HttpGet(url.toString());
HttpClient client = clientBuilder.build();
HttpResponse httpResp = null;
try {
httpResp = HttpClientUtil.executeMethod(client, get);
int statusCode = httpResp.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
throw ServiceException.RESOURCE_UNREACHABLE(httpResp.getStatusLine().getReasonPhrase(), null);
resp.setContentType("image/gif");
ByteUtil.copy(httpResp.getEntity().getContent(), true, resp.getOutputStream(), false);
return;
} catch (HttpException | IOException e) {
throw ServiceException.RESOURCE_UNREACHABLE(httpResp.getStatusLine().getReasonPhrase(), e);
} finally {
EntityUtils.consumeQuietly(httpResp.getEntity());
}
}
} catch (Exception ex) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
return;
}
try {
if (reqPath == null || reqPath.length() == 0) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
if (mLog.isDebugEnabled())
mLog.debug("received request to:(" + reqPath + ")");
String[] reqParts = reqPath.split("/");
String reqFilename = reqParts[3];
imgName = LC.stats_img_folder.value() + File.separator + reqFilename;
try {
is = new FileInputStream(imgName);
} catch (FileNotFoundException ex) {
// unlikely case - only if the server's files are broken
if (is != null)
is.close();
if (!noDefault) {
imgName = LC.stats_img_folder.value() + File.separator + IMG_NOT_AVAIL;
is = new FileInputStream(imgName);
} else {
resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
return;
}
}
} catch (Exception ex) {
if (is != null)
is.close();
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "FNF image File not found");
return;
}
resp.setContentType("image/gif");
ByteUtil.copy(is, true, resp.getOutputStream(), false);
}
Aggregations