use of org.apache.commons.httpclient.Header in project zm-mailbox by Zimbra.
the class UserServlet method getRemoteResource.
public static Pair<Header[], byte[]> getRemoteResource(ZAuthToken authToken, String url) throws ServiceException {
HttpMethod get = null;
try {
Pair<Header[], HttpMethod> pair = doHttpOp(authToken, new GetMethod(url));
get = pair.getSecond();
return new Pair<Header[], byte[]>(pair.getFirst(), get.getResponseBody());
} catch (IOException x) {
throw ServiceException.FAILURE("Can't read response body " + url, x);
} finally {
if (get != null) {
get.releaseConnection();
}
}
}
use of org.apache.commons.httpclient.Header in project zm-mailbox by Zimbra.
the class TestAccessKeyGrant method executeHttpMethod.
private void executeHttpMethod(HttpClient client, HttpMethod method) throws Exception {
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();
}
}
use of org.apache.commons.httpclient.Header in project zm-mailbox by Zimbra.
the class HtmlFormatter method dispatchJspRest.
static void dispatchJspRest(Servlet servlet, UserServletContext context) throws ServiceException, ServletException, IOException {
AuthToken auth = null;
long expiration = System.currentTimeMillis() + AUTH_EXPIRATION;
if (context.basicAuthHappened) {
Account acc = context.getAuthAccount();
if (acc instanceof GuestAccount) {
auth = AuthToken.getAuthToken(acc.getId(), acc.getName(), null, ((GuestAccount) acc).getDigest(), expiration);
} else {
auth = AuthProvider.getAuthToken(context.getAuthAccount(), expiration);
}
} else if (context.cookieAuthHappened) {
auth = UserServlet.getAuthTokenFromCookie(context.req, context.resp, true);
} else {
auth = AuthToken.getAuthToken(GuestAccount.GUID_PUBLIC, null, null, null, expiration);
}
if (auth != null && context.targetAccount != null && context.targetAccount != context.getAuthAccount()) {
auth.setProxyAuthToken(Provisioning.getInstance().getProxyAuthToken(context.targetAccount.getId(), null));
}
String authString = null;
try {
if (auth != null)
authString = auth.getEncoded();
} catch (AuthTokenException e) {
throw new ServletException("error generating the authToken", e);
}
Account targetAccount = context.targetAccount;
MailItem targetItem = context.target;
String uri = (String) context.req.getAttribute("requestedPath");
if (targetItem instanceof Mountpoint && ((Mountpoint) targetItem).getDefaultView() != MailItem.Type.APPOINTMENT) {
Mountpoint mp = (Mountpoint) targetItem;
Provisioning prov = Provisioning.getInstance();
targetAccount = prov.getAccountById(mp.getOwnerId());
Pair<Header[], HttpInputStream> remoteItem = UserServlet.getRemoteResourceAsStream((auth == null) ? null : auth.toZAuthToken(), mp.getTarget(), context.extraPath);
remoteItem.getSecond().close();
String remoteItemId = null;
String remoteItemType = null;
String remoteItemName = null;
String remoteItemPath = null;
for (Header h : remoteItem.getFirst()) if (h.getName().compareToIgnoreCase("X-Zimbra-ItemId") == 0)
remoteItemId = h.getValue();
else if (h.getName().compareToIgnoreCase("X-Zimbra-ItemType") == 0)
remoteItemType = h.getValue();
else if (h.getName().compareToIgnoreCase("X-Zimbra-ItemName") == 0)
remoteItemName = h.getValue();
else if (h.getName().compareToIgnoreCase("X-Zimbra-ItemPath") == 0)
remoteItemPath = h.getValue();
context.req.setAttribute(ATTR_TARGET_ITEM_ID, remoteItemId);
context.req.setAttribute(ATTR_TARGET_ITEM_TYPE, remoteItemType);
context.req.setAttribute(ATTR_TARGET_ITEM_NAME, remoteItemName);
context.req.setAttribute(ATTR_TARGET_ITEM_PATH, remoteItemPath);
context.req.setAttribute(ATTR_TARGET_ITEM_COLOR, mp.getColor());
context.req.setAttribute(ATTR_TARGET_ITEM_VIEW, mp.getDefaultView().toByte());
targetItem = null;
}
context.req.setAttribute(ATTR_INTERNAL_DISPATCH, "yes");
context.req.setAttribute(ATTR_REQUEST_URI, uri != null ? uri : context.req.getRequestURI());
context.req.setAttribute(ATTR_AUTH_TOKEN, authString);
context.req.setAttribute(ATTR_CSRF_ENABLED, auth.isCsrfTokenEnabled());
if (targetAccount != null) {
context.req.setAttribute(ATTR_TARGET_ACCOUNT_NAME, targetAccount.getName());
context.req.setAttribute(ATTR_TARGET_ACCOUNT_ID, targetAccount.getId());
context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_TIME_ZONE, targetAccount.getAttr(Provisioning.A_zimbraPrefTimeZoneId));
context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_SKIN, targetAccount.getAttr(Provisioning.A_zimbraPrefSkin));
context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_LOCALE, targetAccount.getAttr(Provisioning.A_zimbraPrefLocale));
context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_FIRST_DAY_OF_WEEK, targetAccount.getAttr(Provisioning.A_zimbraPrefCalendarFirstDayOfWeek));
context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_START, targetAccount.getAttr(Provisioning.A_zimbraPrefCalendarDayHourStart));
context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_END, targetAccount.getAttr(Provisioning.A_zimbraPrefCalendarDayHourEnd));
} else {
// Useful when faking results - e.g. FREEBUSY html view for non-existent account
if (context.fakeTarget != null) {
context.req.setAttribute(ATTR_TARGET_ACCOUNT_NAME, context.fakeTarget.getAccount());
}
com.zimbra.cs.account.Cos defaultCos = Provisioning.getInstance().get(com.zimbra.common.account.Key.CosBy.name, Provisioning.DEFAULT_COS_NAME);
context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_TIME_ZONE, defaultCos.getAttr(Provisioning.A_zimbraPrefTimeZoneId));
context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_SKIN, defaultCos.getAttr(Provisioning.A_zimbraPrefSkin));
context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_LOCALE, defaultCos.getAttr(Provisioning.A_zimbraPrefLocale));
context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_FIRST_DAY_OF_WEEK, defaultCos.getAttr(Provisioning.A_zimbraPrefCalendarFirstDayOfWeek));
context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_START, defaultCos.getAttr(Provisioning.A_zimbraPrefCalendarDayHourStart));
context.req.setAttribute(ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_END, defaultCos.getAttr(Provisioning.A_zimbraPrefCalendarDayHourEnd));
}
if (targetItem != null) {
context.req.setAttribute(ATTR_TARGET_ITEM_ID, targetItem.getId());
context.req.setAttribute(ATTR_TARGET_ITEM_PATH, targetItem.getPath());
context.req.setAttribute(ATTR_TARGET_ITEM_NAME, targetItem.getName());
context.req.setAttribute(ATTR_TARGET_ITEM_TYPE, targetItem.getType().toString());
context.req.setAttribute(ATTR_TARGET_ITEM_COLOR, targetItem.getColor());
if (targetItem instanceof Folder) {
context.req.setAttribute(ATTR_TARGET_ITEM_VIEW, ((Folder) targetItem).getDefaultView().toString());
}
} else {
context.req.setAttribute(ATTR_TARGET_ITEM_COLOR, Color.getMappedColor(null));
}
if (context.fakeTarget != null) {
// Override to avoid address harvesting
context.req.setAttribute(ATTR_TARGET_ITEM_PATH, context.fakeTarget.getPath());
context.req.setAttribute(ATTR_TARGET_ITEM_NAME, context.fakeTarget.getName());
}
String mailUrl = PATH_MAIN_CONTEXT;
if (WebSplitUtil.isZimbraServiceSplitEnabled()) {
mailUrl = Provisioning.getInstance().getLocalServer().getWebClientURL() + PATH_JSP_REST_PAGE;
HttpClient httpclient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().getDefaultHttpClient();
/*
* Retest the code with POST to check whether it works
PostMethod postMethod = new PostMethod(mailUrl);
Enumeration<String> attributeNames = context.req.getAttributeNames();
List<Part> parts = new ArrayList<Part>();
while(attributeNames.hasMoreElements())
{
String attrName = (String) attributeNames.nextElement();
String attrValue = context.req.getAttribute(attrName).toString();
Part part = new StringPart(attrName, attrValue);
parts.add(part);
}
postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams()));
HttpClientUtil.executeMethod(httpclient, postMethod);
ByteUtil.copy(postMethod.getResponseBodyAsStream(), true, context.resp.getOutputStream(), true);
*/
Enumeration<String> attributeNames = context.req.getAttributeNames();
StringBuilder sb = new StringBuilder(mailUrl);
sb.append("?");
while (attributeNames.hasMoreElements()) {
String attrName = attributeNames.nextElement();
String attrValue = context.req.getAttribute(attrName).toString();
sb.append(attrName).append("=").append(HttpUtil.urlEscape(attrValue)).append("&");
}
GetMethod postMethod = new GetMethod(sb.toString());
HttpClientUtil.executeMethod(httpclient, postMethod);
ByteUtil.copy(postMethod.getResponseBodyAsStream(), true, context.resp.getOutputStream(), false);
} else {
try {
mailUrl = Provisioning.getInstance().getLocalServer().getMailURL();
} catch (Exception e) {
}
ServletContext targetContext = servlet.getServletConfig().getServletContext().getContext(mailUrl);
RequestDispatcher dispatcher = targetContext.getRequestDispatcher(PATH_JSP_REST_PAGE);
dispatcher.forward(context.req, context.resp);
}
}
use of org.apache.commons.httpclient.Header in project zm-mailbox by Zimbra.
the class TestAuth method clearCookie.
@Test
public void clearCookie() throws Exception {
// 2 seconds
int authTokenLifetimeMSecs = 2000;
int waitMSecs = authTokenLifetimeMSecs + 1000;
Account acct = provUtil.createGlobalAdmin(genAcctNameLocalPart(), domain);
// set the account's auth token lifetime to a short period
acct.setAdminAuthTokenLifetime(String.valueOf(authTokenLifetimeMSecs) + "ms");
// String authToken = getAuthToken(acct.getName(), true);
SoapTransport transport = authAdmin(acct.getName());
// wait till the auto token expire
Thread.sleep(waitMSecs);
// make sure the auth token is indeed expired
boolean caughtAuthExpired = false;
try {
NoOpRequest noOpReq = new NoOpRequest();
NoOpResponse noOpResp = invokeJaxb(transport, noOpReq);
} catch (ServiceException e) {
if (AccountServiceException.AUTH_EXPIRED.equals(e.getCode())) {
caughtAuthExpired = true;
}
}
assertTrue(caughtAuthExpired);
List<CookieSpec> cookiesToClear = Lists.newArrayList(new CookieSpec(ZimbraCookie.COOKIE_ZM_ADMIN_AUTH_TOKEN));
ClearCookieRequest req = new ClearCookieRequest(cookiesToClear);
/*
* test the regular path when auto token control is not set
* (auth token in soap header)
*/
caughtAuthExpired = false;
try {
invokeJaxb(transport, req);
} catch (ServiceException e) {
if (AccountServiceException.AUTH_EXPIRED.equals(e.getCode())) {
caughtAuthExpired = true;
}
}
assertTrue(caughtAuthExpired);
/*
* test the regular path when auto token control is not set
* (auth token in cookie)
*/
String authToken = transport.getAuthToken().getValue();
SoapTransport authTokenInCookieTransport = new AuthTokenInCookieTransport(authToken, true);
caughtAuthExpired = false;
try {
invokeJaxb(authTokenInCookieTransport, req);
} catch (ServiceException e) {
if (AccountServiceException.AUTH_EXPIRED.equals(e.getCode())) {
caughtAuthExpired = true;
}
}
assertTrue(caughtAuthExpired);
/*
* test the path when auth token control voidOnExpired is true
*/
// debug listener to verify the cookie is cleared
SoapDebugListener verifyCookieClearedListener = new SoapDebugListener(Level.ALL) {
@Override
public void receiveSoapMessage(PostMethod postMethod, Element envelope) {
super.receiveSoapMessage(postMethod, envelope);
// verify cookies are cleared
Header[] headers = postMethod.getResponseHeaders();
boolean cookieCleared = false;
for (Header header : headers) {
if (header.toString().trim().equals("Set-Cookie: ZM_ADMIN_AUTH_TOKEN=;Path=/;Expires=Thu, 01-Jan-1970 00:00:00 GMT")) {
cookieCleared = true;
}
// System.out.println(header.toString().trim()); // trim the ending crlf
}
assertTrue(cookieCleared);
}
};
authTokenInCookieTransport = new AuthTokenInCookieTransport(authToken, true, true, verifyCookieClearedListener);
// should NOT get AUTH_EXPIRED
ClearCookieResponse resp = invokeJaxb(authTokenInCookieTransport, req);
provUtil.deleteAccount(acct);
}
use of org.apache.commons.httpclient.Header in project cloudstack by apache.
the class UcsHttpClient method call.
public String call(String xml) {
PostMethod post = new PostMethod(url);
post.setRequestEntity(new StringRequestEntity(xml));
post.setRequestHeader("Content-type", "text/xml");
//post.setFollowRedirects(true);
try {
int result = client.executeMethod(post);
if (result == 302) {
// Handle HTTPS redirect
// Ideal way might be to configure from add manager API
// for using either HTTP / HTTPS
// Allow only one level of redirect
String redirectLocation;
Header locationHeader = post.getResponseHeader("location");
if (locationHeader != null) {
redirectLocation = locationHeader.getValue();
} else {
throw new CloudRuntimeException("Call failed: Bad redirect from UCS Manager");
}
post.setURI(new URI(redirectLocation));
result = client.executeMethod(post);
}
// Check for errors
if (result != 200) {
throw new CloudRuntimeException("Call failed: " + post.getResponseBodyAsString());
}
String res = post.getResponseBodyAsString();
if (res.contains("errorCode")) {
String err = String.format("ucs call failed:\nsubmitted doc:%s\nresponse:%s\n", xml, res);
throw new CloudRuntimeException(err);
}
return res;
} catch (Exception e) {
throw new CloudRuntimeException(e.getMessage(), e);
} finally {
post.releaseConnection();
}
}
Aggregations