List of usage examples for org.apache.commons.httpclient.methods DeleteMethod DeleteMethod
public DeleteMethod(String paramString)
From source file:com.eucalyptus.blockstorage.HttpTransfer.java
/** * Constructs the requested method, optionally signing the request via EucaRSA-V2 signing method if signRequest=true * Signing the request can be done later as well by explicitly calling signEucaInternal() and passing it the output of this method. * That case is useful for constructing the request and then adding headers explicitly before signing takes place. * @param verb - The HTTP verb GET|PUT|POST|DELETE|UPDATE * @param addr - THe destination address for the request * @param eucaOperation - The EucaOperation, if any (e.g. StoreSnapshot, GetWalrusSnapshot, or other values from ObjectStorageProperties.StorageOperations) * @param eucaHeader - The Euca Header value, if any. This is not typically used. * @param signRequest - Determines if the request is signed at construction time or must be done explicitly later (boolean) * @return//w ww . j a v a2s .com */ public HttpMethodBase constructHttpMethod(String verb, String addr, String eucaOperation, String eucaHeader, boolean signRequest) { String date = DateUtil.formatDate(new Date(), ISO_8601_FORMAT); //String date = new Date().toString(); String httpVerb = verb; String addrPath = null; java.net.URI addrUri = null; try { addrUri = new URL(addr).toURI(); addrPath = addrUri.getPath().toString(); String query = addrUri.getQuery(); if (query != null) { addrPath += "?" + query; } } catch (Exception ex) { LOG.error(ex, ex); return null; } HttpMethodBase method = null; if (httpVerb.equals("PUT")) { method = new PutMethodWithProgress(addr); } else if (httpVerb.equals("DELETE")) { method = new DeleteMethod(addr); } else { method = new GetMethod(addr); } method.setRequestHeader("Date", date); //method.setRequestHeader("Expect", "100-continue"); method.setRequestHeader(EUCALYPTUS_OPERATION, eucaOperation); if (eucaHeader != null) { method.setRequestHeader(EUCALYPTUS_HEADER, eucaHeader); } if (signRequest) { signEucaInternal(method); } return method; }
From source file:icom.jpa.bdk.BdkAbstractDAO.java
static protected DeleteMethod prepareDeleteMethod(String resource, String collabId, String antiCSRF) { String query = "/comb/v1/d/" + resource + "/" + collabId; if (antiCSRF != null) { query += "?antiCSRF=" + antiCSRF; }/* w w w. j a v a 2 s .com*/ return new DeleteMethod(query); }
From source file:com.zimbra.cs.index.elasticsearch.ElasticSearchIndex.java
@Override public void deleteIndex() { HttpMethod method = new DeleteMethod(ElasticSearchConnector.actualUrl(indexUrl)); try {//from w w w. j a va 2s . c o m ElasticSearchConnector connector = new ElasticSearchConnector(); int statusCode = connector.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { boolean ok = connector.getBooleanAtJsonPath(new String[] { "ok" }, false); boolean acknowledged = connector.getBooleanAtJsonPath(new String[] { "acknowledged" }, false); if (!ok || !acknowledged) { ZimbraLog.index.debug("Delete index status ok=%b acknowledged=%b", ok, acknowledged); } } else { String error = connector.getStringAtJsonPath(new String[] { "error" }); if (error != null && error.startsWith("IndexMissingException")) { ZimbraLog.index.debug("Unable to delete index for key=%s. Index is missing", key); } else { ZimbraLog.index.error("Problem deleting index for key=%s error=%s", key, error); } } } catch (HttpException e) { ZimbraLog.index.error("Problem Deleting index with key=" + key, e); } catch (IOException e) { ZimbraLog.index.error("Problem Deleting index with key=" + key, e); } haveMappingInfo = false; }
From source file:com.ning.http.client.providers.apache.ApacheAsyncHttpProvider.java
private HttpMethodBase createMethod(HttpClient client, Request request) throws IOException, FileNotFoundException { String methodName = request.getMethod(); HttpMethodBase method = null;/*from w ww . ja v a 2 s. c om*/ if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) { EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl()) : new PutMethod(request.getUrl()); String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding(); post.getParams().setContentCharset("ISO-8859-1"); if (request.getByteData() != null) { post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData())); post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length)); } else if (request.getStringData() != null) { post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset)); post.setRequestHeader("Content-Length", String.valueOf(request.getStringData().getBytes(bodyCharset).length)); } else if (request.getStreamData() != null) { InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData()); post.setRequestEntity(r); post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength())); } else if (request.getParams() != null) { StringBuilder sb = new StringBuilder(); for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) { final String key = paramEntry.getKey(); for (final String value : paramEntry.getValue()) { if (sb.length() > 0) { sb.append("&"); } UTF8UrlEncoder.appendEncoded(sb, key); sb.append("="); UTF8UrlEncoder.appendEncoded(sb, value); } } post.setRequestHeader("Content-Length", String.valueOf(sb.length())); post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1")); if (!request.getHeaders().containsKey("Content-Type")) { post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } } else if (request.getParts() != null) { MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(), post.getParams()); post.setRequestEntity(mre); post.setRequestHeader("Content-Type", mre.getContentType()); post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength())); } else if (request.getEntityWriter() != null) { post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(), computeAndSetContentLength(request, post))); } else if (request.getFile() != null) { File file = request.getFile(); if (!file.isFile()) { throw new IOException( String.format(Thread.currentThread() + "File %s is not a file or doesn't exist", file.getAbsolutePath())); } post.setRequestHeader("Content-Length", String.valueOf(file.length())); FileInputStream fis = new FileInputStream(file); try { InputStreamRequestEntity r = new InputStreamRequestEntity(fis); post.setRequestEntity(r); post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength())); } finally { fis.close(); } } else if (request.getBodyGenerator() != null) { Body body = request.getBodyGenerator().createBody(); try { int length = (int) body.getContentLength(); if (length < 0) { length = (int) request.getContentLength(); } // TODO: This is suboptimal if (length >= 0) { post.setRequestHeader("Content-Length", String.valueOf(length)); // This is totally sub optimal byte[] bytes = new byte[length]; ByteBuffer buffer = ByteBuffer.wrap(bytes); for (;;) { buffer.clear(); if (body.read(buffer) < 0) { break; } } post.setRequestEntity(new ByteArrayRequestEntity(bytes)); } } finally { try { body.close(); } catch (IOException e) { logger.warn("Failed to close request body: {}", e.getMessage(), e); } } } if (request.getHeaders().getFirstValue("Expect") != null && request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) { post.setUseExpectHeader(true); } method = post; } else if (methodName.equalsIgnoreCase("DELETE")) { method = new DeleteMethod(request.getUrl()); } else if (methodName.equalsIgnoreCase("HEAD")) { method = new HeadMethod(request.getUrl()); } else if (methodName.equalsIgnoreCase("GET")) { method = new GetMethod(request.getUrl()); } else if (methodName.equalsIgnoreCase("OPTIONS")) { method = new OptionsMethod(request.getUrl()); } else { throw new IllegalStateException(String.format("Invalid Method", methodName)); } ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer(); boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, request); if (!avoidProxy) { if (proxyServer.getPrincipal() != null) { Credentials defaultcreds = new UsernamePasswordCredentials(proxyServer.getPrincipal(), proxyServer.getPassword()); client.getState().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds); } ProxyHost proxyHost = proxyServer == null ? null : new ProxyHost(proxyServer.getHost(), proxyServer.getPort()); client.getHostConfiguration().setProxyHost(proxyHost); } method.setFollowRedirects(false); if ((request.getCookies() != null) && !request.getCookies().isEmpty()) { for (Cookie cookie : request.getCookies()) { method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies())); } } if (request.getHeaders() != null) { for (String name : request.getHeaders().keySet()) { if (!"host".equalsIgnoreCase(name)) { for (String value : request.getHeaders().get(name)) { method.setRequestHeader(name, value); } } } } if (request.getHeaders().getFirstValue("User-Agent") != null) { method.setRequestHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent")); } else if (config.getUserAgent() != null) { method.setRequestHeader("User-Agent", config.getUserAgent()); } else { method.setRequestHeader("User-Agent", AsyncHttpProviderUtils.constructUserAgent(ApacheAsyncHttpProvider.class)); } if (config.isCompressionEnabled()) { Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding"); if (acceptableEncodingHeader != null) { String acceptableEncodings = acceptableEncodingHeader.getValue(); if (acceptableEncodings.indexOf("gzip") == -1) { StringBuilder buf = new StringBuilder(acceptableEncodings); if (buf.length() > 1) { buf.append(","); } buf.append("gzip"); method.setRequestHeader("Accept-Encoding", buf.toString()); } } else { method.setRequestHeader("Accept-Encoding", "gzip"); } } if (request.getVirtualHost() != null) { String vs = request.getVirtualHost(); int index = vs.indexOf(":"); if (index > 0) { vs = vs.substring(0, index); } method.getParams().setVirtualHost(vs); } return method; }
From source file:com.cloud.network.nicira.NiciraNvpApi.java
private void executeDeleteObject(String uri) throws NiciraNvpApiException { String url;/*from w w w . j a va 2s . co m*/ try { url = new URL(_protocol, _host, uri).toString(); } catch (MalformedURLException e) { s_logger.error("Unable to build Nicira API URL", e); throw new NiciraNvpApiException("Unable to build Nicira API URL", e); } DeleteMethod dm = new DeleteMethod(url); dm.setRequestHeader("Content-Type", "application/json"); executeMethod(dm); if (dm.getStatusCode() != HttpStatus.SC_NO_CONTENT) { String errorMessage = responseToErrorMessage(dm); dm.releaseConnection(); s_logger.error("Failed to delete object : " + errorMessage); throw new NiciraNvpApiException("Failed to delete object : " + errorMessage); } dm.releaseConnection(); }
From source file:com.esri.gpt.framework.http.HttpClientRequest.java
/** * Create the HTTP method./* w w w .j a va2 s. co m*/ * <br/>A GetMethod will be created if the RequestEntity associated with * the ContentProvider is null. Otherwise, a PostMethod will be created. * @return the HTTP method */ private HttpMethodBase createMethod() throws IOException { HttpMethodBase method = null; MethodName name = this.getMethodName(); // make the method if (name == null) { if (this.getContentProvider() == null) { this.setMethodName(MethodName.GET); method = new GetMethod(this.getUrl()); } else { this.setMethodName(MethodName.POST); method = new PostMethod(this.getUrl()); } } else if (name.equals(MethodName.DELETE)) { method = new DeleteMethod(this.getUrl()); } else if (name.equals(MethodName.GET)) { method = new GetMethod(this.getUrl()); } else if (name.equals(MethodName.POST)) { method = new PostMethod(this.getUrl()); } else if (name.equals(MethodName.PUT)) { method = new PutMethod(this.getUrl()); } // write the request body if necessary if (this.getContentProvider() != null) { if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod eMethod = (EntityEnclosingMethod) method; RequestEntity eAdapter = getContentProvider() instanceof MultiPartContentProvider ? new MultiPartProviderAdapter(this, eMethod, (MultiPartContentProvider) getContentProvider()) : new ApacheEntityAdapter(this, this.getContentProvider()); eMethod.setRequestEntity(eAdapter); if (eAdapter.getContentType() != null) { eMethod.setRequestHeader("Content-type", eAdapter.getContentType()); } } else { // TODO: possibly will need an exception here in the future } } // set headers, add the retry method for (Map.Entry<String, String> hdr : this.requestHeaders.entrySet()) { method.addRequestHeader(hdr.getKey(), hdr.getValue()); } // declare possible gzip handling method.setRequestHeader("Accept-Encoding", "gzip"); this.addRetryHandler(method); return method; }
From source file:davmail.http.DavGatewayHttpClientFacade.java
/** * Execute a delete method on the given path with httpClient. * * @param httpClient Http client instance * @param path Path to be deleted// w w w . j av a 2 s. co m * @return http status * @throws IOException on error */ public static int executeDeleteMethod(HttpClient httpClient, String path) throws IOException { DeleteMethod deleteMethod = new DeleteMethod(path); deleteMethod.setFollowRedirects(false); int status = executeHttpMethod(httpClient, deleteMethod); // do not throw error if already deleted if (status != HttpStatus.SC_OK && status != HttpStatus.SC_NOT_FOUND) { throw DavGatewayHttpClientFacade.buildHttpException(deleteMethod); } return status; }
From source file:it.geosolutions.httpproxy.HTTPProxy.java
/** * Performs an HTTP DELETE request//from w ww . ja va 2s.c o m * * @param httpServletRequest The {@link HttpServletRequest} object passed in by the servlet engine representing the client request to be proxied * @param httpServletResponse The {@link HttpServletResponse} object by which we can send a proxied response to the client */ public void doDelete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { try { URL url = null; String user = null, password = null; //Parse the queryString to not read the request body calling getParameter from httpServletRequest Map<String, String> pars = splitQuery(httpServletRequest.getQueryString()); for (String key : pars.keySet()) { String value = pars.get(key); if ("user".equals(key)) { user = value; } else if ("password".equals(key)) { password = value; } else if ("url".equals(key)) { url = new URL(value); } } if (url != null) { onInit(httpServletRequest, httpServletResponse, url); // //////////////////////////////// // Create a standard DELETE request // //////////////////////////////// DeleteMethod deleteMethodProxyRequest = new DeleteMethod(url.toExternalForm()); // //////////////////////////////// // Forward the request headers // //////////////////////////////// final ProxyInfo proxyInfo = setProxyRequestHeaders(url, httpServletRequest, deleteMethodProxyRequest); // //////////////////////////////// // Execute the proxy request // //////////////////////////////// this.executeProxyRequest(deleteMethodProxyRequest, httpServletRequest, httpServletResponse, user, password, proxyInfo); } } catch (HttpErrorException ex) { httpServletResponse.sendError(ex.getCode(), ex.getMessage()); } finally { onFinish(); } }
From source file:com.xmlcalabash.library.HttpRequest.java
private DeleteMethod doDelete() { DeleteMethod method = new DeleteMethod(requestURI.toASCIIString()); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); for (Header header : headers) { method.addRequestHeader(header); }/*from w ww .java 2s . c o m*/ return method; }
From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java
public String deleteScope(String scope) { DeleteMethod delete = new DeleteMethod(baseOAuth20Uri + SCOPE_ENDPOINT + "/" + scope); String response = null;/* ww w . ja v a2 s .c o m*/ try { response = readResponse(delete); log.info(response); } catch (IOException e) { log.error("cannot delete scope", e); } return response; }