use of org.apache.commons.httpclient.methods.PutMethod 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.methods.PutMethod in project zm-mailbox by Zimbra.
the class TestCalDav method testCreateContactWithIfNoneMatchTesting.
@Test
public void testCreateContactWithIfNoneMatchTesting() throws ServiceException, IOException {
Account dav1 = users[1].create();
// Based on UID
String davBaseName = "SCRUFF1.vcf";
String contactsFolderUrl = getFolderUrl(dav1, "Contacts");
String url = String.format("%s%s", contactsFolderUrl, davBaseName);
HttpClient client = new HttpClient();
PutMethod putMethod = new PutMethod(url);
addBasicAuthHeaderForUser(putMethod, dav1);
putMethod.addRequestHeader("Content-Type", "text/vcard");
putMethod.setRequestEntity(new ByteArrayRequestEntity(simpleVcard.getBytes(), MimeConstants.CT_TEXT_VCARD));
// Bug 84246 this used to fail with 409 Conflict because we used to require an If-None-Match header
HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_CREATED);
// Check that trying to put the same thing again when we don't expect it to exist (i.e. Using If-None-Match
// header) will fail.
putMethod = new PutMethod(url);
addBasicAuthHeaderForUser(putMethod, dav1);
putMethod.addRequestHeader("Content-Type", "text/vcard");
putMethod.addRequestHeader(DavProtocol.HEADER_IF_NONE_MATCH, "*");
putMethod.setRequestEntity(new ByteArrayRequestEntity(simpleVcard.getBytes(), MimeConstants.CT_TEXT_VCARD));
HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_PRECONDITION_FAILED);
}
use of org.apache.commons.httpclient.methods.PutMethod in project zm-mailbox by Zimbra.
the class UserServlet method putRemoteResource.
public static Pair<Header[], HttpInputStream> putRemoteResource(ZAuthToken authToken, String url, InputStream req, Header[] headers) throws ServiceException, IOException {
StringBuilder u = new StringBuilder(url);
u.append("?").append(QP_AUTH).append('=').append(AUTH_COOKIE);
PutMethod method = new PutMethod(u.toString());
String contentType = "application/octet-stream";
if (headers != null) {
for (Header hdr : headers) {
String name = hdr.getName();
method.addRequestHeader(hdr);
if (name.equals("Content-Type"))
contentType = hdr.getValue();
}
}
method.setRequestEntity(new InputStreamRequestEntity(req, contentType));
Pair<Header[], HttpMethod> pair = doHttpOp(authToken, method);
return new Pair<Header[], HttpInputStream>(pair.getFirst(), new HttpInputStream(pair.getSecond()));
}
use of org.apache.commons.httpclient.methods.PutMethod in project zm-mailbox by Zimbra.
the class TestCalDav method testCreateUsingClientChosenName.
/**
* dav - sending http error 302 because: wrong url - redirecting to:
* http://pan.local:7070/dav/dav1@pan.local/Calendar/d123f102-42a7-4283-b025-3376dabe53b3.ics
* com.zimbra.cs.dav.DavException: wrong url - redirecting to:
* http://pan.local:7070/dav/dav1@pan.local/Calendar/d123f102-42a7-4283-b025-3376dabe53b3.ics
* at com.zimbra.cs.dav.resource.CalendarCollection.createItem(CalendarCollection.java:431)
* at com.zimbra.cs.dav.service.method.Put.handle(Put.java:49)
* at com.zimbra.cs.dav.service.DavServlet.service(DavServlet.java:322)
*/
@Test
public void testCreateUsingClientChosenName() throws ServiceException, IOException {
Account dav1 = users[1].create();
String davBaseName = "clientInvented.now";
String calFolderUrl = getFolderUrl(dav1, "Calendar");
String url = String.format("%s%s", calFolderUrl, davBaseName);
HttpClient client = new HttpClient();
PutMethod putMethod = new PutMethod(url);
addBasicAuthHeaderForUser(putMethod, dav1);
putMethod.addRequestHeader("Content-Type", "text/calendar");
putMethod.setRequestEntity(new ByteArrayRequestEntity(simpleEvent(dav1), MimeConstants.CT_TEXT_CALENDAR));
if (DebugConfig.enableDAVclientCanChooseResourceBaseName) {
HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_CREATED);
} else {
HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_MOVED_TEMPORARILY);
// Not testing much in this mode but...
return;
}
doGetMethod(url, dav1, HttpStatus.SC_OK);
PropFindMethod propFindMethod = new PropFindMethod(getFolderUrl(dav1, "Calendar"));
addBasicAuthHeaderForUser(propFindMethod, dav1);
TestCalDav.HttpMethodExecutor executor;
String respBody;
Element respElem;
propFindMethod.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
propFindMethod.addRequestHeader("Depth", "1");
propFindMethod.setRequestEntity(new ByteArrayRequestEntity(propFindEtagResType.getBytes(), MimeConstants.CT_TEXT_XML));
executor = new TestCalDav.HttpMethodExecutor(client, propFindMethod, HttpStatus.SC_MULTI_STATUS);
respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
respElem = Element.XMLElement.parseXML(respBody);
assertEquals("name of top element in propfind response", DavElements.P_MULTISTATUS, respElem.getName());
assertTrue("propfind response should have child elements", respElem.hasChildren());
Iterator<Element> iter = respElem.elementIterator();
boolean hasCalendarHref = false;
boolean hasCalItemHref = false;
while (iter.hasNext()) {
Element child = iter.next();
if (DavElements.P_RESPONSE.equals(child.getName())) {
Iterator<Element> hrefIter = child.elementIterator(DavElements.P_HREF);
while (hrefIter.hasNext()) {
Element href = hrefIter.next();
calFolderUrl.endsWith(href.getText());
hasCalendarHref = hasCalendarHref || calFolderUrl.endsWith(href.getText());
hasCalItemHref = hasCalItemHref || url.endsWith(href.getText());
}
}
}
assertTrue("propfind response contained entry for calendar", hasCalendarHref);
assertTrue("propfind response contained entry for calendar entry ", hasCalItemHref);
doDeleteMethod(url, dav1, HttpStatus.SC_NO_CONTENT);
}
use of org.apache.commons.httpclient.methods.PutMethod in project zm-mailbox by Zimbra.
the class ElasticSearchIndex method initializeIndex.
private void initializeIndex() {
if (haveMappingInfo) {
return;
}
if (!refreshIndexIfNecessary()) {
try {
ElasticSearchConnector connector = new ElasticSearchConnector();
JSONObject mappingInfo = createMappingInfo();
PutMethod putMethod = new PutMethod(ElasticSearchConnector.actualUrl(indexUrl));
putMethod.setRequestEntity(new StringRequestEntity(mappingInfo.toString(), MimeConstants.CT_APPLICATION_JSON, MimeConstants.P_CHARSET_UTF8));
int statusCode = connector.executeMethod(putMethod);
if (statusCode == HttpStatus.SC_OK) {
haveMappingInfo = true;
// Sometimes searches don't seem to honor mapping info. Try to force it
refreshIndexIfNecessary();
} else {
ZimbraLog.index.error("Problem Setting mapping information for index with key=%s httpstatus=%d", key, statusCode);
}
} catch (HttpException e) {
ZimbraLog.index.error("Problem Getting mapping information for index with key=" + key, e);
} catch (IOException e) {
ZimbraLog.index.error("Problem Getting mapping information for index with key=" + key, e);
} catch (JSONException e) {
ZimbraLog.index.error("Problem Setting mapping information for index with key=" + key, e);
}
}
}
Aggregations