use of org.apache.http.impl.cookie.BasicClientCookie in project zm-mailbox by Zimbra.
the class SoapHttpTransport method invoke.
public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId, String changeToken, String tokenType, NotificationFormat nFormat, String curWaitSetID, ResponseHandler respHandler) throws IOException, ServiceException {
HttpPost method = null;
HttpClient client = null;
try {
// Assemble post method. Append document name, so that the request
// type is written to the access log.
String uri = getUriWithPath(document);
method = new HttpPost(uri);
// Set user agent if it's specified.
String agentName = getUserAgentName();
if (agentName != null) {
String agentVersion = getUserAgentVersion();
if (agentVersion != null)
agentName += " " + agentVersion;
method.addHeader(new BasicHeader("User-Agent", agentName));
}
// Set the original user agent if it's specified.
String originalUserAgent = getOriginalUserAgent();
if (originalUserAgent != null) {
method.addHeader(new BasicHeader(HeaderConstants.HTTP_HEADER_ORIG_USER_AGENT, originalUserAgent));
}
// the content-type charset will determine encoding used
// when we set the request body
method.addHeader("Content-Type", getRequestProtocol().getContentType());
if (getClientIp() != null) {
method.addHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
if (ZimbraLog.misc.isDebugEnabled()) {
ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
}
}
Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken, tokenType, nFormat, curWaitSetID);
String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
method.setEntity(new StringEntity(soapMessage, ContentType.create(ContentType.APPLICATION_XML.getMimeType(), "UTF-8")));
if (getRequestProtocol().hasSOAPActionHeader())
method.addHeader("SOAPAction", mUri);
if (mCustomHeaders != null) {
for (Map.Entry<String, String> entry : mCustomHeaders.entrySet()) method.addHeader(entry.getKey(), entry.getValue());
}
String host = method.getURI().getHost();
ZAuthToken zToken = getAuthToken();
BasicCookieStore cookieStore = HttpClientUtil.newHttpState(zToken, host, this.isAdmin());
String trustedToken = getTrustedToken();
if (trustedToken != null) {
BasicClientCookie cookie = new BasicClientCookie(ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken);
cookie.setDomain(host);
cookie.setPath("/");
cookie.setSecure(false);
cookieStore.addCookie(cookie);
}
if (zToken instanceof ZJWToken) {
method.addHeader(Constants.AUTH_HEADER, Constants.BEARER + " " + zToken.getValue());
}
ZimbraLog.soap.trace("Httpclient timeout: %s", mTimeout);
RequestConfig reqConfig = RequestConfig.custom().setCookieSpec(cookieStore.getCookies().size() == 0 ? CookieSpecs.IGNORE_COOKIES : CookieSpecs.BROWSER_COMPATIBILITY).setSocketTimeout(mTimeout).build();
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(mTimeout).setTcpNoDelay(LC.httpclient_external_connmgr_tcp_nodelay.booleanValue()).build();
method.setProtocolVersion(HttpVersion.HTTP_1_1);
method.addHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");
client = mClientBuilder.setDefaultRequestConfig(reqConfig).setDefaultSocketConfig(socketConfig).setDefaultCookieStore(cookieStore).build();
ZimbraLog.soap.trace("Httpclient request config timeout: %s", reqConfig.getSocketTimeout());
if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
Credentials credentials = new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword());
AuthScope authScope = new AuthScope(null, -1);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(authScope, credentials);
client = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(reqConfig).setDefaultSocketConfig(socketConfig).setDefaultCookieStore(cookieStore).build();
}
if (mHttpDebugListener != null) {
mHttpDebugListener.sendSoapMessage(method, soapReq, cookieStore);
}
HttpResponse response = client.execute(method);
int responseCode = response.getStatusLine().getStatusCode();
// real server issues will probably be "503" or "404"
if (responseCode != HttpServletResponse.SC_OK && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
throw ServiceException.PROXY_ERROR(response.getStatusLine().getReasonPhrase(), uri);
// Read the response body. Use the stream API instead of the byte[]
// version to avoid HTTPClient whining about a large response.
InputStreamReader reader = new InputStreamReader(response.getEntity().getContent(), SoapProtocol.getCharset());
String responseStr = "";
try {
if (respHandler != null) {
respHandler.process(reader);
return null;
} else {
HttpEntity httpEntity = response.getEntity();
httpEntity.getContentLength();
responseStr = ByteUtil.getContent(reader, (int) httpEntity.getContentLength(), false);
Element soapResp = parseSoapResponse(responseStr, raw);
if (mHttpDebugListener != null) {
mHttpDebugListener.receiveSoapMessage(method, soapResp);
}
return soapResp;
}
} catch (SoapFaultException x) {
// attach request/response to the exception and rethrow
x.setFaultRequest(soapMessage);
x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length())));
throw x;
}
} finally {
// Release the connection to the connection manager
if (method != null)
method.releaseConnection();
// exits. Leave it here anyway.
if (!mKeepAlive)
ZimbraHttpConnectionManager.getInternalHttpConnMgr().closeIdleConnections();
}
}
use of org.apache.http.impl.cookie.BasicClientCookie in project zm-mailbox by Zimbra.
the class SoapHttpTransport method invokeAsync.
@Override
public Future<HttpResponse> invokeAsync(Element document, boolean raw, boolean noSession, String requestedAccountId, String changeToken, String tokenType, NotificationFormat nFormat, String curWaitSetID, FutureCallback<HttpResponse> cb) throws IOException {
HttpPost post = new HttpPost(getUriWithPath(document));
// Set user agent if it's specified.
String agentName = getUserAgentName();
if (agentName != null) {
String agentVersion = getUserAgentVersion();
if (agentVersion != null)
agentName += " " + agentVersion;
post.setHeader("User-Agent", agentName);
}
// request headers
post.setHeader("Content-Type", getRequestProtocol().getContentType());
if (getClientIp() != null) {
post.setHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
if (ZimbraLog.misc.isDebugEnabled()) {
ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
}
}
if (getRequestProtocol().hasSOAPActionHeader())
post.setHeader("SOAPAction", mUri);
if (mCustomHeaders != null) {
for (Map.Entry<String, String> entry : mCustomHeaders.entrySet()) post.setHeader(entry.getKey(), entry.getValue());
}
// SOAP message
Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken, tokenType, nFormat, curWaitSetID);
String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
post.setEntity(new ByteArrayEntity(soapMessage.getBytes("UTF-8")));
HttpClientContext context = HttpClientContext.create();
String host = post.getURI().getHost();
CookieStore cookieStore = HttpClientUtil.newCookieStore(getAuthToken(), host, isAdmin());
String trustedToken = getTrustedToken();
if (trustedToken != null) {
BasicClientCookie cookie = new BasicClientCookie(ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken);
cookie.setDomain(post.getURI().getHost());
cookie.setPath("/");
cookie.setSecure(false);
cookieStore.addCookie(cookie);
}
context.setCookieStore(cookieStore);
CloseableHttpAsyncClient httpClient = ZimbraHttpClientManager.getInstance().getInternalAsyncHttpClient();
return httpClient.execute(post, context, cb);
}
use of org.apache.http.impl.cookie.BasicClientCookie in project zm-mailbox by Zimbra.
the class WebDavClient method setAuthCookie.
public void setAuthCookie(ZAuthToken auth) {
Map<String, String> cookieMap = auth.cookieMap(false);
if (cookieMap != null) {
String host = null;
try {
host = new URL(mBaseUrl).getHost();
} catch (Exception e) {
}
BasicCookieStore cookieStore = new BasicCookieStore();
for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
BasicClientCookie cookie = new BasicClientCookie(ck.getKey(), ck.getValue());
cookie.setDomain(host);
cookie.setPath("/");
cookie.setSecure(false);
cookieStore.addCookie(cookie);
}
mClient.setDefaultCookieStore(cookieStore);
RequestConfig reqConfig = RequestConfig.copy(ZimbraHttpConnectionManager.getInternalHttpConnMgr().getZimbraConnMgrParams().getReqConfig()).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
mClient.setDefaultRequestConfig(reqConfig);
}
}
use of org.apache.http.impl.cookie.BasicClientCookie in project zm-mailbox by Zimbra.
the class LmcMessage method downloadAttachment.
public byte[] downloadAttachment(String partNo, String baseURL, LmcSession session, String cookieDomain, int msTimeout) throws Exception {
// set the cookie.
if (session == null)
System.err.println(System.currentTimeMillis() + " " + Thread.currentThread() + " LmcMessage.downloadAttachment session=null");
HttpClientBuilder clientBuilder = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
String url = baseURL + "?id=" + getID() + "&part=" + partNo;
HttpGet get = new HttpGet(url);
ZAuthToken zat = session.getAuthToken();
Map<String, String> cookieMap = zat.cookieMap(false);
if (cookieMap != null) {
BasicCookieStore initialState = new BasicCookieStore();
for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
BasicClientCookie cookie = new BasicClientCookie(ck.getKey(), ck.getValue());
cookie.setDomain(cookieDomain);
cookie.setPath("/");
cookie.setSecure(false);
cookie.setExpiryDate(null);
initialState.addCookie(cookie);
}
clientBuilder.setDefaultCookieStore(initialState);
RequestConfig reqConfig = RequestConfig.copy(ZimbraHttpConnectionManager.getInternalHttpConnMgr().getZimbraConnMgrParams().getReqConfig()).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
clientBuilder.setDefaultRequestConfig(reqConfig);
}
SocketConfig config = SocketConfig.custom().setSoTimeout(msTimeout).build();
clientBuilder.setDefaultSocketConfig(config);
HttpClient client = clientBuilder.build();
int statusCode = -1;
try {
HttpResponse response = HttpClientUtil.executeMethod(client, get);
// parse the response
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toByteArray(response.getEntity());
} else {
throw new LmcSoapClientException("Attachment download failed, status=" + statusCode);
}
} catch (IOException | HttpException e) {
System.err.println("Attachment download failed");
e.printStackTrace();
throw e;
} finally {
get.releaseConnection();
}
}
use of org.apache.http.impl.cookie.BasicClientCookie in project jmeter by apache.
the class TestHC4CookieManager method testAddCookieFromHeaderWithWildcard2.
@Test
public void testAddCookieFromHeaderWithWildcard2() throws Exception {
URL url = new URL("https://www.bt.com/page");
String headerLine = "SMTRYNO=1; path=/; domain=.bt.com";
man.addCookieFromHeader(headerLine, url);
Assert.assertEquals(1, man.getCookieCount());
HC4CookieHandler cookieHandler = (HC4CookieHandler) man.getCookieHandler();
URL urlSubDomain = new URL("https://subdomain.bt.com/page");
List<org.apache.http.cookie.Cookie> cookies = cookieHandler.getCookiesForUrl(man.getCookies(), urlSubDomain, CookieManager.ALLOW_VARIABLE_COOKIES);
Assert.assertEquals(1, cookies.size());
for (org.apache.http.cookie.Cookie cookie : cookies) {
// See http://tools.ietf.org/html/rfc6265#section-5.2.3
Assert.assertEquals("bt.com", cookie.getDomain());
Assert.assertTrue(((BasicClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR));
}
}
Aggregations