List of usage examples for org.apache.commons.httpclient.methods DeleteMethod DeleteMethod
public DeleteMethod(String paramString)
From source file:ar.com.zauber.commons.web.proxy.HttpClientRequestProxy.java
/** * @param request/* ww w .j av a 2 s . co m*/ * @return */ private HttpMethod buildRequest(final HttpServletRequest request, final URLResult urlResult) { final String method = request.getMethod().toUpperCase(); final HttpMethod ret; final String uri = urlResult.getURL().toExternalForm(); if ("GET".equals(method)) { ret = new GetMethod(uri); proxyHeaders(request, ret); } else if ("POST".equals(method) || "PUT".equals(method)) { final EntityEnclosingMethod pm = "POST".equals(method) ? new PostMethod(uri) : new PutMethod(uri); proxyHeaders(request, pm); try { pm.setRequestEntity(new InputStreamRequestEntity(request.getInputStream())); } catch (IOException e) { throw new UnhandledException("No pudo abrirse el InputStream" + "del request.", e); } ret = pm; } else if ("DELETE".equals(method)) { /* rfc2616 The Content-Length field of a request or response is added or deleted according to the rules in section 4.4. A transparent proxy MUST preserve the entity-length (section 7.2.2) of the entity-body, although it MAY change the transfer-length (section 4.4). */ final DeleteMethod dm = new DeleteMethod(uri); proxyHeaders(request, dm); //No body => No Header dm.removeRequestHeader("Content-Length"); ret = dm; } else { throw new NotImplementedException("i accept patches :)"); } if (request.getQueryString() != null) { ret.setQueryString(request.getQueryString()); } return ret; }
From source file:com.zimbra.cs.zimlet.ProxyServlet.java
private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException { ZimbraLog.clearContext();//from ww w. jav a 2s . c o m 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(); } }
From source file:io.fabric8.gateway.servlet.ProxyServlet.java
/** * Performs an HTTP DELETE request//from ww w. j a v a2 s. c o m * * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} object passed * in by the servlet engine representing the * client request to be proxied * @param httpServletResponse The {@link javax.servlet.http.HttpServletResponse} object by which * we can send a proxied response to the client */ @Override public void doDelete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { ProxyDetails proxyDetails = createProxyDetails(httpServletRequest, httpServletResponse); if (!proxyDetails.isValid()) { noMappingFound(httpServletRequest, httpServletResponse); } else { DeleteMethod deleteMethodProxyRequest = new DeleteMethod(proxyDetails.getStringProxyURL()); // Forward the request headers setProxyRequestHeaders(proxyDetails, httpServletRequest, deleteMethodProxyRequest); // Execute the proxy request executeProxyRequest(proxyDetails, deleteMethodProxyRequest, httpServletRequest, httpServletResponse); } }
From source file:edu.indiana.d2i.htrc.portal.HTRCAgentClient.java
public boolean deleteJobs(List<String> jobIds) { boolean res = true; for (String id : jobIds) { DeleteMethod deleteJobId = null; try {/* w w w .ja v a 2 s . co m*/ String jobdeleteURL = String .format(PlayConfWrapper.agentEndpoint() + PlayConfWrapper.jobDeleteURLTemplate(), id); deleteJobId = new DeleteMethod(jobdeleteURL); deleteJobId.setRequestHeader("Authorization", "Bearer " + accessToken); // client.getHttpConnectionManager().getParams().setConnectionTimeout(PlayConfWrapper.agentConnectTimeout()); // client.getHttpConnectionManager().getParams().setSoTimeout(PlayConfWrapper.agentWaitTimeout()); int response = client.executeMethod(deleteJobId); this.responseCode = response; if (response == 200) { boolean success = parseJobDeleteResponse(deleteJobId.getResponseBodyAsStream()); if (!success) { log.error("Error occurs while deleting job " + id); } } else if (response == 401 && (renew < MAX_RENEW)) { try { accessToken = HTRCPersistenceAPIClient.renewToken(refreshToken); renew++; return deleteJobs(jobIds); // bugs here! } catch (Exception e) { throw new IOException(e); } } else { renew = 0; log.error(String.format("Unable to delete job %s from agent. Response code %d", id, response)); res = false; } } catch (Exception e) { log.error(String.valueOf(e)); } finally { if (deleteJobId != null) { deleteJobId.releaseConnection(); deleteJobId = null; } } } return res; }
From source file:edu.stanford.epad.epadws.xnat.XNATDeletionOperations.java
public static int deleteXNATSubject(String xnatProjectLabelOrID, String xnatSubjectLabelOrID, String jsessionID) {/*ww w. ja v a 2 s .com*/ String xnatSubjectDeleteURL = XNATUtil.buildXNATSubjectDeletionURL(xnatProjectLabelOrID, xnatSubjectLabelOrID); HttpClient client = new HttpClient(); DeleteMethod method = new DeleteMethod(xnatSubjectDeleteURL); int xnatStatusCode; method.setRequestHeader("Cookie", "JSESSIONID=" + jsessionID); try { log.info("Invoking XNAT with URL " + xnatSubjectDeleteURL); xnatStatusCode = client.executeMethod(method); if (unexpectedDeletionStatusCode(xnatStatusCode)) log.warning("Failure calling XNAT to delete subject; status code = " + xnatStatusCode); else { eventTracker.recordPatientEvent(jsessionID, xnatProjectLabelOrID, xnatSubjectLabelOrID); } } catch (IOException e) { log.warning("Error calling XNAT to delete patient " + xnatSubjectLabelOrID + " from project " + xnatProjectLabelOrID, e); xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } finally { method.releaseConnection(); } return xnatStatusCode; }
From source file:com.groupon.odo.Proxy.java
/** * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse * response)//from www. j a v a 2 s . c o m */ protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // create thread specific session data requestInformation.set(new RequestInformation()); History history = new History(); logOriginalRequestHistory("DELETE", request, history); try { DeleteMethod getMethodProxyRequest = new DeleteMethod( getProxyURL(request, history, Constants.REQUEST_TYPE_DELETE)); // set headers setProxyRequestHeaders(request, getMethodProxyRequest); // execute request executeProxyRequest(getMethodProxyRequest, request, response, history); } catch (Exception e) { // TODO log to history logger.info("ERROR: cannot execute request: {}", e.getMessage()); } }
From source file:com.cloudbees.api.BeesClient.java
/** * Sends a request in JSON and expects a JSON response back. * * @param urlTail The end point to hit. Appended to {@link #base}. Shouldn't start with '/' * @param method HTTP method name like GET or POST. * @param headers/*from w w w.j a v a2 s .c o m*/ *@param jsonContent The json request payload, or null if none. @throws IOException If the communication fails. */ public HttpReply jsonRequest(String urlTail, String method, Map<String, String> headers, String jsonContent) throws IOException { HttpMethodBase httpMethod; String urlString = absolutize(urlTail); trace("API call: " + urlString); if (method.equalsIgnoreCase("GET")) { httpMethod = new GetMethod(urlString); } else if ((method.equalsIgnoreCase("POST"))) { httpMethod = new PostMethod(urlString); } else if ((method.equalsIgnoreCase("PUT"))) { httpMethod = new PutMethod(urlString); } else if ((method.equalsIgnoreCase("DELETE"))) { httpMethod = new DeleteMethod(urlString); } else if ((method.equalsIgnoreCase("PATCH"))) { httpMethod = new PatchMethod(urlString); } else if ((method.equalsIgnoreCase("HEAD"))) { httpMethod = new HeadMethod(urlString); } else if ((method.equalsIgnoreCase("TRACE"))) { httpMethod = new TraceMethod(urlString); } else if ((method.equalsIgnoreCase("OPTIONS"))) { httpMethod = new OptionsMethod(urlString); } else throw new IOException("Method not supported: " + method); httpMethod.setRequestHeader("Accept", "application/json"); if (jsonContent != null && httpMethod instanceof EntityEnclosingMethod) { StringRequestEntity requestEntity = new StringRequestEntity(jsonContent, "application/json", "UTF-8"); ((EntityEnclosingMethod) httpMethod).setRequestEntity(requestEntity); trace("Payload: " + jsonContent); } return executeRequest(httpMethod, headers); }
From source file:com.clarkparsia.sbol.editor.sparql.StardogEndpoint.java
@Override public void clear(String namedGraph) throws HttpException, IOException, QueryEvaluationException { DeleteMethod delete = new DeleteMethod(url); delete.setQueryString(new NameValuePair[] { graphParam(namedGraph) }); execute(delete);/*from ww w. j av a2s . c o m*/ }
From source file:it.geosolutions.figis.requester.HTTPUtils.java
public static boolean delete(String url, final String user, final String pw) { DeleteMethod httpMethod = null;// www . j a v a 2 s.c o m try { HttpClient client = new HttpClient(); setAuth(client, url, user, pw); httpMethod = new DeleteMethod(url); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(httpMethod); String response = ""; if (status == HttpStatus.SC_OK) { InputStream is = httpMethod.getResponseBodyAsStream(); response = IOUtils.toString(is); if (response.trim().equals("")) // sometimes gs rest fails { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "ResponseBody is empty (this may be not an error since we just performed a DELETE call)"); } return true; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("(" + status + ") " + httpMethod.getStatusText() + " -- " + url); } return true; } else { if (LOGGER.isInfoEnabled()) { LOGGER.info("(" + status + ") " + httpMethod.getStatusText() + " -- " + url); LOGGER.info("Response: '" + response + "'"); } } } catch (ConnectException e) { LOGGER.info("Couldn't connect to [" + url + "]", e); } catch (IOException e) { LOGGER.info("Error talking to [" + url + "]", e); } finally { if (httpMethod != null) { httpMethod.releaseConnection(); } } return false; }
From source file:edu.stanford.epad.epadws.xnat.XNATSessionOperations.java
public static int invalidateXNATSessionID(HttpServletRequest httpRequest) { String xnatSessionURL = buildXNATSessionURL(); HttpClient client = new HttpClient(); DeleteMethod method = new DeleteMethod(xnatSessionURL); String jsessionID = getJSessionIDFromRequest(httpRequest); int xnatStatusCode; method.setRequestHeader("Cookie", "JSESSIONID=" + jsessionID); try {//from w w w. ja va2 s . c om xnatStatusCode = client.executeMethod(method); } catch (IOException e) { log.warning("Error calling XNAT session service to invalidate session ID", e); xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } finally { method.releaseConnection(); } if (xnatStatusCode != HttpServletResponse.SC_OK) log.warning("XNAT delete session call returned status code " + xnatStatusCode); return xnatStatusCode; }