use of org.apache.commons.httpclient.UsernamePasswordCredentials in project tdi-studio-se by Talend.
the class MDMTransaction method commit.
public void commit() throws IOException {
HttpClient client = new HttpClient();
client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
HttpMethod method = new PostMethod(url + "/" + id);
method.setDoAuthentication(true);
try {
//$NON-NLS-1$ //$NON-NLS-2$
method.setRequestHeader("Cookie", getStickySession() + "=" + sessionId);
client.executeMethod(method);
} catch (HttpException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
method.releaseConnection();
}
int statuscode = method.getStatusCode();
if (statuscode >= 400) {
throw new MDMTransactionException("Commit failed. The commit operation has returned the code " + statuscode + ".");
}
}
use of org.apache.commons.httpclient.UsernamePasswordCredentials in project tdi-studio-se by Talend.
the class WSDLLocatorImpl method createHttpClient.
private HttpClient createHttpClient() {
HttpClient httpClient = new HttpClient();
if (configuration.getProxyServer() != null) {
HostConfiguration hostConfiguration = new HostConfiguration();
hostConfiguration.setProxy(configuration.getProxyServer(), configuration.getProxyPort());
httpClient.setHostConfiguration(hostConfiguration);
}
if (configuration.getUsername() != null) {
Credentials credentials = new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword());
httpClient.getState().setCredentials(AuthScope.ANY, credentials);
}
if (configuration.getProxyUsername() != null) {
Credentials credentials = new UsernamePasswordCredentials(configuration.getProxyUsername(), configuration.getProxyPassword());
httpClient.getState().setProxyCredentials(AuthScope.ANY, credentials);
httpClient.getHostConfiguration().setProxy(configuration.getProxyServer(), configuration.getProxyPort());
}
return httpClient;
}
use of org.apache.commons.httpclient.UsernamePasswordCredentials 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.UsernamePasswordCredentials in project zm-mailbox by Zimbra.
the class ProxyServlet method doProxy.
private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ZimbraLog.clearContext();
boolean isAdmin = isAdminRequest(req);
AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true) : getAuthTokenFromCookie(req, resp, true);
if (authToken == null) {
String zAuthToken = req.getParameter(QP_ZAUTHTOKEN);
if (zAuthToken != null) {
try {
authToken = AuthProvider.getAuthToken(zAuthToken);
if (authToken.isExpired()) {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired");
return;
}
if (!authToken.isRegistered()) {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid");
return;
}
if (isAdmin && !authToken.isAdmin()) {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied");
return;
}
} catch (AuthTokenException e) {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken");
return;
}
}
}
if (authToken == null) {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie");
return;
}
// get the posted body before the server read and parse them.
byte[] body = copyPostedData(req);
// sanity check
String target = req.getParameter(TARGET_PARAM);
if (target == null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
// check for permission
URL url = new URL(target);
if (!isAdmin && !checkPermissionOnTarget(url, authToken)) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
// determine whether to return the target inline or store it as an upload
String uploadParam = req.getParameter(UPLOAD_PARAM);
boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true"));
HttpMethod method = null;
try {
HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
HttpProxyUtil.configureProxy(client);
String reqMethod = req.getMethod();
if (reqMethod.equalsIgnoreCase("GET")) {
method = new GetMethod(target);
} else if (reqMethod.equalsIgnoreCase("POST")) {
PostMethod post = new PostMethod(target);
if (body != null)
post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
method = post;
} else if (reqMethod.equalsIgnoreCase("PUT")) {
PutMethod put = new PutMethod(target);
if (body != null)
put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
method = put;
} else if (reqMethod.equalsIgnoreCase("DELETE")) {
method = new DeleteMethod(target);
} else {
ZimbraLog.zimlet.info("unsupported request method: " + reqMethod);
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
return;
}
// handle basic auth
String auth, user, pass;
auth = req.getParameter(AUTH_PARAM);
user = req.getParameter(USER_PARAM);
pass = req.getParameter(PASS_PARAM);
if (auth != null && user != null && pass != null) {
if (!auth.equals(AUTH_BASIC)) {
ZimbraLog.zimlet.info("unsupported auth type: " + auth);
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
HttpState state = new HttpState();
state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
client.setState(state);
method.setDoAuthentication(true);
}
Enumeration headers = req.getHeaderNames();
while (headers.hasMoreElements()) {
String hdr = (String) headers.nextElement();
ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr));
if (canProxyHeader(hdr)) {
ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr));
if (hdr.equalsIgnoreCase("x-host"))
method.getParams().setVirtualHost(req.getHeader(hdr));
else
method.addRequestHeader(hdr, req.getHeader(hdr));
}
}
try {
if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) {
method.setFollowRedirects(true);
}
HttpClientUtil.executeMethod(client, method);
} catch (HttpException ex) {
ZimbraLog.zimlet.info("exception while proxying " + target, ex);
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : method.getStatusCode();
// workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line
Header ctHeader = method.getResponseHeader("Content-Type");
String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE : ctHeader.getValue();
InputStream targetResponseBody = method.getResponseBodyAsStream();
if (asUpload) {
String filename = req.getParameter(FILENAME_PARAM);
if (filename == null || filename.equals(""))
filename = new ContentType(contentType).getParameter("name");
if ((filename == null || filename.equals("")) && method.getResponseHeader("Content-Disposition") != null)
filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue()).getParameter("filename");
if (filename == null || filename.equals(""))
filename = "unknown";
List<Upload> uploads = null;
if (targetResponseBody != null) {
try {
Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType, authToken.getAccountId());
uploads = Arrays.asList(up);
} catch (ServiceException e) {
if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED))
status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE;
else
status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
}
resp.setStatus(status);
FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null);
} else {
resp.setStatus(status);
resp.setContentType(contentType);
for (Header h : method.getResponseHeaders()) if (canProxyHeader(h.getName()))
resp.addHeader(h.getName(), h.getValue());
if (targetResponseBody != null)
ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true);
}
} finally {
if (method != null)
method.releaseConnection();
}
}
use of org.apache.commons.httpclient.UsernamePasswordCredentials in project zm-mailbox by Zimbra.
the class TestProvIDN method testBasicAuth.
@Test
public void testBasicAuth() throws Exception {
Names.IDNName domainName = new Names.IDNName(makeTestDomainName("basicAuthTest."));
Domain domain = createDomain(domainName.uName(), domainName.uName());
Names.IDNName acctName = new Names.IDNName("acct", domainName.uName());
Account acct = (Account) createTest(EntryType.ACCOUNT, NameType.UNAME, acctName);
HttpState initialState = new HttpState();
/*
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 = acct.getUnicodeName();
String guestPassword = "test123";
Credentials loginCredentials = new UsernamePasswordCredentials(guestName, guestPassword);
initialState.setCredentials(AuthScope.ANY, loginCredentials);
HttpClient client = new HttpClient();
client.setState(initialState);
String url = UserServlet.getRestUrl(acct) + "/Calendar";
System.out.println("REST URL: " + url);
HttpMethod method = new GetMethod(url);
HttpMethodParams methodParams = method.getParams();
methodParams.setCredentialCharset("UTF-8");
try {
int respCode = HttpClientUtil.executeMethod(client, method);
if (respCode != HttpStatus.SC_OK) {
System.out.println("failed, respCode=" + respCode);
} else {
boolean chunked = false;
boolean textContent = false;
/*
System.out.println("Headers:");
System.out.println("--------");
for (Header header : method.getRequestHeaders()) {
System.out.print(" " + header.toString());
}
System.out.println();
System.out.println("Body:");
System.out.println("-----");
String respBody = method.getResponseBodyAsString();
System.out.println(respBody);
*/
}
} finally {
// Release the connection.
method.releaseConnection();
}
}
Aggregations