use of org.apache.commons.httpclient.HttpState in project zm-mailbox by Zimbra.
the class ZimbraAuthToken method encode.
@Override
public void encode(HttpClient client, HttpMethod method, boolean isAdminReq, String cookieDomain) throws ServiceException {
String origAuthData = getOrigAuthData();
HttpState state = new HttpState();
client.setState(state);
state.addCookie(new org.apache.commons.httpclient.Cookie(cookieDomain, ZimbraCookie.authTokenCookieName(isAdminReq), origAuthData, "/", null, false));
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
}
use of org.apache.commons.httpclient.HttpState 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, ResponseHandler respHandler) throws IOException, HttpException, ServiceException {
PostMethod method = null;
try {
// Assemble post method. Append document name, so that the request
// type is written to the access log.
String uri, query;
int i = mUri.indexOf('?');
if (i >= 0) {
uri = mUri.substring(0, i);
query = mUri.substring(i);
} else {
uri = mUri;
query = "";
}
if (!uri.endsWith("/"))
uri += '/';
uri += getDocumentName(document);
method = new PostMethod(uri + query);
// Set user agent if it's specified.
String agentName = getUserAgentName();
if (agentName != null) {
String agentVersion = getUserAgentVersion();
if (agentVersion != null)
agentName += " " + agentVersion;
method.setRequestHeader(new Header("User-Agent", agentName));
}
// the content-type charset will determine encoding used
// when we set the request body
method.setRequestHeader("Content-Type", getRequestProtocol().getContentType());
if (getClientIp() != null) {
method.setRequestHeader(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);
String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
HttpMethodParams params = method.getParams();
method.setRequestEntity(new StringRequestEntity(soapMessage, null, "UTF-8"));
if (getRequestProtocol().hasSOAPActionHeader())
method.setRequestHeader("SOAPAction", mUri);
if (mCustomHeaders != null) {
for (Map.Entry<String, String> entry : mCustomHeaders.entrySet()) method.setRequestHeader(entry.getKey(), entry.getValue());
}
String host = method.getURI().getHost();
HttpState state = HttpClientUtil.newHttpState(getAuthToken(), host, this.isAdmin());
String trustedToken = getTrustedToken();
if (trustedToken != null) {
state.addCookie(new Cookie(host, ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken, "/", null, false));
}
params.setCookiePolicy(state.getCookies().length == 0 ? CookiePolicy.IGNORE_COOKIES : CookiePolicy.BROWSER_COMPATIBILITY);
params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(mRetryCount - 1, true));
params.setSoTimeout(mTimeout);
params.setVersion(HttpVersion.HTTP_1_1);
method.setRequestHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");
if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
state.setProxyCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword()));
}
if (mHttpDebugListener != null) {
mHttpDebugListener.sendSoapMessage(method, soapReq, state);
}
int responseCode = mClient.executeMethod(mHostConfig, method, state);
// real server issues will probably be "503" or "404"
if (responseCode != HttpServletResponse.SC_OK && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
throw ServiceException.PROXY_ERROR(method.getStatusLine().toString(), 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(method.getResponseBodyAsStream(), SoapProtocol.getCharset());
String responseStr = "";
try {
if (respHandler != null) {
respHandler.process(reader);
return null;
} else {
responseStr = ByteUtil.getContent(reader, (int) method.getResponseContentLength(), 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)
mClient.getHttpConnectionManager().closeIdleConnections(0);
}
}
use of org.apache.commons.httpclient.HttpState in project zm-mailbox by Zimbra.
the class TestCookieReuse method testValidSessionCookieReuse.
/**
* Verify that we can RE-use the cookie for REST session if the session is valid
*/
@Test
public void testValidSessionCookieReuse() throws ServiceException, IOException {
//establish legitimate connection
ZMailbox mbox = TestUtil.getZMailbox(USER_NAME);
URI uri = mbox.getRestURI("Inbox?fmt=rss");
HttpClient alice = mbox.getHttpClient(uri);
//create evesdropper's connection
HttpClient eve = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
Cookie[] cookies = alice.getState().getCookies();
HttpState state = new HttpState();
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
state.addCookie(new Cookie(uri.getHost(), cookie.getName(), cookie.getValue(), "/", null, false));
}
eve.setState(state);
GetMethod get = new GetMethod(uri.toString());
int statusCode = HttpClientUtil.executeMethod(eve, get);
Assert.assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode);
}
use of org.apache.commons.httpclient.HttpState in project zm-mailbox by Zimbra.
the class ExchangeFreeBusyProvider method basicAuth.
private boolean basicAuth(HttpClient client, ServerInfo info) {
HttpState state = new HttpState();
Credentials cred = new UsernamePasswordCredentials(info.authUsername, info.authPassword);
state.setCredentials(AuthScope.ANY, cred);
client.setState(state);
ArrayList<String> authPrefs = new ArrayList<String>();
authPrefs.add(AuthPolicy.BASIC);
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
return true;
}
use of org.apache.commons.httpclient.HttpState in project zm-mailbox by Zimbra.
the class ExchangeFreeBusyProvider method formAuth.
private boolean formAuth(HttpClient client, ServerInfo info) throws IOException {
StringBuilder buf = new StringBuilder();
buf.append("destination=");
buf.append(URLEncoder.encode(info.url, "UTF-8"));
buf.append("&username=");
buf.append(info.authUsername);
buf.append("&password=");
buf.append(URLEncoder.encode(info.authPassword, "UTF-8"));
buf.append("&flags=0");
buf.append("&SubmitCreds=Log On");
buf.append("&trusted=0");
String url = info.url + LC.calendar_exchange_form_auth_url.value();
PostMethod method = new PostMethod(url);
ByteArrayRequestEntity re = new ByteArrayRequestEntity(buf.toString().getBytes(), "x-www-form-urlencoded");
method.setRequestEntity(re);
HttpState state = new HttpState();
client.setState(state);
try {
int status = HttpClientUtil.executeMethod(client, method);
if (status >= 400) {
ZimbraLog.fb.error("form auth to Exchange returned an error: " + status);
return false;
}
} finally {
method.releaseConnection();
}
return true;
}
Aggregations