use of org.apache.commons.httpclient.auth.AuthScope 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.auth.AuthScope in project sling by apache.
the class AuthenticatedTestUtil method assertAuthenticatedPostStatus.
/** Execute a POST request and check status */
public void assertAuthenticatedPostStatus(Credentials creds, String url, int expectedStatusCode, List<NameValuePair> postParams, String assertMessage) throws IOException {
final PostMethod post = new PostMethod(url);
post.setFollowRedirects(false);
URL baseUrl = new URL(HTTP_BASE_URL);
AuthScope authScope = new AuthScope(baseUrl.getHost(), baseUrl.getPort(), AuthScope.ANY_REALM);
post.setDoAuthentication(true);
Credentials oldCredentials = httpClient.getState().getCredentials(authScope);
try {
httpClient.getState().setCredentials(authScope, creds);
if (postParams != null) {
final NameValuePair[] nvp = {};
post.setRequestBody(postParams.toArray(nvp));
}
final int status = httpClient.executeMethod(post);
if (assertMessage == null) {
assertEquals(expectedStatusCode, status);
} else {
assertEquals(assertMessage, expectedStatusCode, status);
}
} finally {
httpClient.getState().setCredentials(authScope, oldCredentials);
}
}
use of org.apache.commons.httpclient.auth.AuthScope in project sling by apache.
the class AnonymousAccessTest method testAnonymousContent.
public void testAnonymousContent() throws Exception {
// disable credentials -> anonymous session
final URL url = new URL(HTTP_BASE_URL);
final AuthScope scope = new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM);
httpClient.getParams().setAuthenticationPreemptive(false);
httpClient.getState().setCredentials(scope, null);
try {
assertContent();
} finally {
// re-enable credentials -> admin session
httpClient.getParams().setAuthenticationPreemptive(true);
Credentials defaultcreds = new UsernamePasswordCredentials("admin", "admin");
httpClient.getState().setCredentials(scope, defaultcreds);
}
}
use of org.apache.commons.httpclient.auth.AuthScope in project sling by apache.
the class AuthenticationResponseCodeTest method testPreventLoopIncorrectHttpBasicCredentials.
@Test
public void testPreventLoopIncorrectHttpBasicCredentials() throws Exception {
// assume http and webdav are on the same host + port
URL url = new URL(HttpTest.HTTP_BASE_URL);
Credentials defaultcreds = new UsernamePasswordCredentials("garbage", "garbage");
H.getHttpClient().getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds);
final String requestUrl = HttpTest.HTTP_BASE_URL + "/junk?param1=1";
HttpMethod get = new GetMethod(requestUrl);
get.setRequestHeader("Referer", requestUrl);
get.setRequestHeader("User-Agent", "Mozilla/5.0 Sling Integration Test");
int status = H.getHttpClient().executeMethod(get);
assertEquals(HttpServletResponse.SC_UNAUTHORIZED, status);
}
use of org.apache.commons.httpclient.auth.AuthScope in project sling by apache.
the class ExternalSlingLaunchpad method before.
@Override
protected void before() throws Throwable {
Credentials creds = new UsernamePasswordCredentials(config.getUsername(), config.getPassword());
HttpClient client = new HttpClient();
client.getState().setCredentials(new AuthScope(config.getHostname(), config.getPort()), creds);
long cutoff = System.currentTimeMillis() + MAX_WAIT_TIME_MS;
List<SlingReadyRule> rules = new ArrayList<>();
rules.add(new StartLevelSlingReadyRule(client));
rules.add(new ActiveBundlesSlingReadyRule(client));
for (SlingReadyRule rule : rules) {
while (true) {
if (rule.evaluate()) {
break;
}
assertTimeout(cutoff);
Thread.sleep(100);
}
}
}
Aggregations