List of usage examples for org.apache.commons.httpclient.methods DeleteMethod DeleteMethod
public DeleteMethod(String paramString)
From source file:org.apache.excalibur.source.factories.HTTPClientSource.java
/** * Factory method to create a {@link DeleteMethod} object. * * @param uri URI to delete//from w w w . j av a2s. c om * @return {@link DeleteMethod} instance. */ private DeleteMethod createDeleteMethod(final String uri) { return new DeleteMethod(uri); }
From source file:org.apache.hcatalog.templeton.TestWebHCatE2e.java
/** * Does a basic HTTP GET and returns Http Status code + response body * Will add the dummy user query string/* www. j a v a 2 s .co m*/ */ private static MethodCallRetVal doHttpCall(String uri, HTTP_METHOD_TYPE type, Map<String, Object> data, NameValuePair[] params) throws IOException { HttpClient client = new HttpClient(); HttpMethod method; switch (type) { case GET: method = new GetMethod(uri); break; case DELETE: method = new DeleteMethod(uri); break; case PUT: method = new PutMethod(uri); if (data == null) { break; } String msgBody = JsonBuilder.mapToJson(data); LOG.info("Msg Body: " + msgBody); StringRequestEntity sre = new StringRequestEntity(msgBody, "application/json", charSet); ((PutMethod) method).setRequestEntity(sre); break; default: throw new IllegalArgumentException("Unsupported method type: " + type); } if (params == null) { method.setQueryString(new NameValuePair[] { new NameValuePair("user.name", username) }); } else { NameValuePair[] newParams = new NameValuePair[params.length + 1]; System.arraycopy(params, 0, newParams, 1, params.length); newParams[0] = new NameValuePair("user.name", username); method.setQueryString(newParams); } String actualUri = "no URI"; try { actualUri = method.getURI().toString();//should this be escaped string? LOG.debug(type + ": " + method.getURI().getEscapedURI()); int httpStatus = client.executeMethod(method); LOG.debug("Http Status Code=" + httpStatus); String resp = method.getResponseBodyAsString(); LOG.debug("response: " + resp); return new MethodCallRetVal(httpStatus, resp, actualUri, method.getName()); } catch (IOException ex) { LOG.error("doHttpCall() failed", ex); } finally { method.releaseConnection(); } return new MethodCallRetVal(-1, "Http " + type + " failed; see log file for details", actualUri, method.getName()); }
From source file:org.apache.jmeter.protocol.oauth.sampler.OAuthSampler.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading * page resources as appropriate./* ww w.j a v a 2 s .co m*/ * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { String urlStr = url.toExternalForm(); // Check if this is an entity-enclosing method boolean isPost = method.equals(POST) || method.equals(PUT); HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); // Handles OAuth signing try { message = getOAuthMessage(url, method); urlStr = message.URL; if (isPost) { urlStr = message.URL; } else { if (useAuthHeader) urlStr = OAuth.addParameters(message.URL, nonOAuthParams); else urlStr = OAuth.addParameters(message.URL, message.getParameters()); } } catch (IOException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } catch (OAuthException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } catch (URISyntaxException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } log.debug("Start : sample " + urlStr); //$NON-NLS-1$ log.debug("method " + method); //$NON-NLS-1$ HttpMethodBase httpMethod = null; res.setSampleLabel(urlStr); // May be replaced later res.setHTTPMethod(method); res.sampleStart(); // Count the retries as well in the time HttpClient client = null; InputStream instream = null; try { // May generate IllegalArgumentException if (method.equals(POST)) { httpMethod = new PostMethod(urlStr); } else if (method.equals(PUT)) { httpMethod = new PutMethod(urlStr); } else if (method.equals(HEAD)) { httpMethod = new HeadMethod(urlStr); } else if (method.equals(TRACE)) { httpMethod = new TraceMethod(urlStr); } else if (method.equals(OPTIONS)) { httpMethod = new OptionsMethod(urlStr); } else if (method.equals(DELETE)) { httpMethod = new DeleteMethod(urlStr); } else if (method.equals(GET)) { httpMethod = new GetMethod(urlStr); } else { log.error("Unexpected method (converted to GET): " + method); //$NON-NLS-1$ httpMethod = new GetMethod(urlStr); } // Set any default request headers setDefaultRequestHeaders(httpMethod); // Setup connection client = setupConnection(new URL(urlStr), httpMethod, res); // Handle POST and PUT if (isPost) { String postBody = sendPostData(httpMethod); res.setQueryString(postBody); } res.setRequestHeaders(getConnectionHeaders(httpMethod)); int statusCode = client.executeMethod(httpMethod); // Request sent. Now get the response: instream = httpMethod.getResponseBodyAsStream(); if (instream != null) {// will be null for HEAD Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING); if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) { instream = new GZIPInputStream(instream); } res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setSampleLabel(httpMethod.getURI().toString()); // Pick up Actual path (after redirects) res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE); if (h != null)// Can be missing, e.g. on redirect { ct = h.getValue(); res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } res.setResponseHeaders(getResponseHeaders(httpMethod)); if (res.isRedirect()) { final Header headerLocation = httpMethod.getResponseHeader(HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but avoids NPE throw new IllegalArgumentException("Missing location header"); //$NON-NLS-1$ } res.setRedirectLocation(headerLocation.getValue()); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(new URL(httpMethod.getURI().toString())); } // Store any cookies received in the cookie manager: saveConnectionCookies(httpMethod, res.getURL(), getCookieManager()); // Save cache information final CacheManager cacheManager = getCacheManager(); if (cacheManager != null) { cacheManager.saveDetails(httpMethod, res); } // Follow redirects and download page resources if appropriate: res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); //$NON-NLS-1$ httpMethod.releaseConnection(); return res; } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } catch (IOException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$ return err; } finally { JOrphanUtils.closeQuietly(instream); if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:org.apache.manifoldcf.examples.ManifoldCFAPIConnect.java
/** Perform an API DELETE operation. *@param restPath is the URL path of the REST object, starting with "/". *@return the json response./*ww w . ja v a 2 s. c o m*/ */ public String performAPIRawDeleteOperation(String restPath) throws IOException { HttpClient client = new HttpClient(); DeleteMethod method = new DeleteMethod(formURL(restPath)); int response = client.executeMethod(method); byte[] responseData = method.getResponseBody(); // We presume that the data is utf-8, since that's what the API // uses throughout. String responseString = new String(responseData, "utf-8"); if (response != HttpStatus.SC_OK) throw new IOException("API http error; expected " + HttpStatus.SC_OK + ", saw " + Integer.toString(response) + ": " + responseString); return responseString; }
From source file:org.apache.sling.commons.testing.integration.SlingIntegrationTestClient.java
/** Delete a file from the Sling repository * @return the HTTP status code//w w w .j a va2s. c om */ public int delete(String url) throws IOException { final DeleteMethod delete = new DeleteMethod(url); return httpClient.executeMethod(delete); }
From source file:org.apache.sling.discovery.impl.topology.connector.TopologyConnectorClient.java
/** Disconnect this connector **/ public void disconnect() { final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json"; if (logger.isDebugEnabled()) { logger.debug("disconnect: connectorUrl=" + connectorUrl + ", complete uri=" + uri); }/*from w ww .j a v a 2s . c o m*/ if (lastInheritedAnnouncement != null) { announcementRegistry.unregisterAnnouncement(lastInheritedAnnouncement.getOwnerId()); } HttpClient httpClient = new HttpClient(); final DeleteMethod method = new DeleteMethod(uri); try { String userInfo = connectorUrl.getUserInfo(); if (userInfo != null) { Credentials c = new UsernamePasswordCredentials(userInfo); httpClient.getState() .setCredentials(new AuthScope(method.getURI().getHost(), method.getURI().getPort()), c); } requestValidator.trustMessage(method, null); httpClient.executeMethod(method); if (logger.isDebugEnabled()) { logger.debug("disconnect: done. code=" + method.getStatusCode() + " - " + method.getStatusText()); } // ignoring the actual statuscode though as there's little we can // do about it after this point } catch (URIException e) { logger.warn("disconnect: Got URIException: " + e); } catch (IOException e) { logger.warn("disconnect: got IOException: " + e); } catch (RuntimeException re) { logger.error("disconnect: got RuntimeException: " + re, re); } finally { method.releaseConnection(); } }
From source file:org.apache.sling.maven.bundlesupport.BundleUninstallMojo.java
protected void deleteViaWebDav(String targetURL, File file) throws MojoExecutionException { final DeleteMethod delete = new DeleteMethod(getURLWithFilename(targetURL, file.getName())); try {/*from ww w.j a v a 2s .c om*/ int status = getHttpClient().executeMethod(delete); if (status >= 200 && status < 300) { getLog().info("Bundle uninstalled"); } else { getLog().error("Uninstall failed, cause: " + HttpStatus.getStatusText(status)); } } catch (Exception ex) { throw new MojoExecutionException("Uninstall from " + targetURL + " failed, cause: " + ex.getMessage(), ex); } finally { delete.releaseConnection(); } }
From source file:org.apache.wink.itest.addressbook.StringTest.java
/** * This will drive a POST, GET, UPDATE, and DELETE on the * AddressBookResource/*from w w w . ja v a 2 s . com*/ */ public void testAddressBookResource() { PostMethod method = null; GetMethod getMethod = null; PutMethod put = null; DeleteMethod deleteMethod = null; try { // make sure everything is clear before testing HttpClient client = new HttpClient(); method = new PostMethod(getBaseURI() + "/fromBody"); String input = "tempAddress&1234 Any Street&AnyTown&90210&TX&US"; RequestEntity entity = new ByteArrayRequestEntity(input.getBytes(), "text/xml"); method.setRequestEntity(entity); client.executeMethod(method); // now let's see if the address we just created is available getMethod = new GetMethod(getBaseURI() + "/tempAddress"); client.executeMethod(getMethod); String responseBody = getMethod.getResponseBodyAsString(); getMethod.releaseConnection(); assertNotNull(responseBody); assertTrue(responseBody, responseBody.contains("tempAddress")); assertTrue(responseBody, responseBody.contains("1234 Any Street")); assertTrue(responseBody, responseBody.contains("AnyTown")); assertTrue(responseBody, responseBody.contains("90210")); assertTrue(responseBody, responseBody.contains("TX")); assertTrue(responseBody, responseBody.contains("US")); // let's update the state String query = "entryName=tempAddress&streetAddress=1234+Any+Street&city=" + "AnyTown&zipCode=90210&state=AL&country=US"; client = new HttpClient(); put = new PutMethod(getBaseURI()); put.setQueryString(query); client.executeMethod(put); // make sure the state has been updated client = new HttpClient(); client.executeMethod(getMethod); responseBody = getMethod.getResponseBodyAsString(); assertNotNull(responseBody); assertTrue(responseBody.contains("tempAddress")); assertFalse(responseBody.contains("TX")); assertTrue(responseBody.contains("AL")); // now let's delete the address client = new HttpClient(); deleteMethod = new DeleteMethod(getBaseURI() + "/tempAddress"); client.executeMethod(deleteMethod); assertEquals(204, deleteMethod.getStatusCode()); // now try to get the address client = new HttpClient(); client.executeMethod(getMethod); assertEquals(404, getMethod.getStatusCode()); responseBody = getMethod.getResponseBodyAsString(); ServerContainerAssertions.assertExceptionBodyFromServer(404, getMethod.getResponseBodyAsString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { if (method != null) { method.releaseConnection(); } if (getMethod != null) { getMethod.releaseConnection(); } if (put != null) { put.releaseConnection(); } if (deleteMethod != null) { deleteMethod.releaseConnection(); } } }
From source file:org.apache.wink.itest.contextresolver.DepartmentTest.java
/** * This will drive several different requests that interact with the * Departments resource class.// w w w . j ava 2 s.co m */ public void testDepartmentsResourceJAXB() throws Exception { PostMethod postMethod = null; GetMethod getAllMethod = null; GetMethod getOneMethod = null; HeadMethod headMethod = null; DeleteMethod deleteMethod = null; try { // make sure everything is clear before testing DepartmentDatabase.clearEntries(); // create a new Department Department newDepartment = new Department(); newDepartment.setDepartmentId("1"); newDepartment.setDepartmentName("Marketing"); JAXBContext context = JAXBContext .newInstance(new Class<?>[] { Department.class, DepartmentListWrapper.class }); Marshaller marshaller = context.createMarshaller(); StringWriter sw = new StringWriter(); marshaller.marshal(newDepartment, sw); HttpClient client = new HttpClient(); postMethod = new PostMethod(getBaseURI()); RequestEntity reqEntity = new ByteArrayRequestEntity(sw.toString().getBytes(), "text/xml"); postMethod.setRequestEntity(reqEntity); client.executeMethod(postMethod); newDepartment = new Department(); newDepartment.setDepartmentId("2"); newDepartment.setDepartmentName("Sales"); sw = new StringWriter(); marshaller.marshal(newDepartment, sw); client = new HttpClient(); postMethod = new PostMethod(getBaseURI()); reqEntity = new ByteArrayRequestEntity(sw.toString().getBytes(), "text/xml"); postMethod.setRequestEntity(reqEntity); client.executeMethod(postMethod); // now let's get the list of Departments that we just created // (should be 2) client = new HttpClient(); getAllMethod = new GetMethod(getBaseURI()); client.executeMethod(getAllMethod); byte[] bytes = getAllMethod.getResponseBody(); assertNotNull(bytes); InputStream bais = new ByteArrayInputStream(bytes); Unmarshaller unmarshaller = context.createUnmarshaller(); Object obj = unmarshaller.unmarshal(bais); assertTrue(obj instanceof DepartmentListWrapper); DepartmentListWrapper wrapper = (DepartmentListWrapper) obj; List<Department> dptList = wrapper.getDepartmentList(); assertNotNull(dptList); assertEquals(2, dptList.size()); // now get a specific Department that was created client = new HttpClient(); getOneMethod = new GetMethod(getBaseURI() + "/1"); client.executeMethod(getOneMethod); bytes = getOneMethod.getResponseBody(); assertNotNull(bytes); bais = new ByteArrayInputStream(bytes); obj = unmarshaller.unmarshal(bais); assertTrue(obj instanceof Department); Department dept = (Department) obj; assertEquals("1", dept.getDepartmentId()); assertEquals("Marketing", dept.getDepartmentName()); // let's send a Head request for both an existent and non-existent // resource // we are testing to see if header values being set in the resource // implementation // are sent back appropriately client = new HttpClient(); headMethod = new HeadMethod(getBaseURI() + "/3"); client.executeMethod(headMethod); assertNotNull(headMethod.getResponseHeaders()); Header header = headMethod.getResponseHeader("unresolved-id"); assertNotNull(header); assertEquals("3", header.getValue()); headMethod.releaseConnection(); // now the resource that should exist headMethod = new HeadMethod(getBaseURI() + "/1"); client.executeMethod(headMethod); assertNotNull(headMethod.getResponseHeaders()); header = headMethod.getResponseHeader("resolved-id"); assertNotNull(header); assertEquals("1", header.getValue()); deleteMethod = new DeleteMethod(getBaseURI() + "/1"); client.executeMethod(deleteMethod); assertEquals(204, deleteMethod.getStatusCode()); deleteMethod = new DeleteMethod(getBaseURI() + "/2"); client.executeMethod(deleteMethod); assertEquals(204, deleteMethod.getStatusCode()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { if (postMethod != null) { postMethod.releaseConnection(); } if (getAllMethod != null) { getAllMethod.releaseConnection(); } if (getOneMethod != null) { getOneMethod.releaseConnection(); } if (headMethod != null) { headMethod.releaseConnection(); } if (deleteMethod != null) { deleteMethod.releaseConnection(); } } }
From source file:org.apache.wink.itest.exceptionmappers.JAXRSExceptionsMappedProvidersTest.java
/** * Tests a method that throws a runtime exception. * /* www.ja v a2 s . c om*/ * @throws Exception */ public void testRuntimeExceptionMappedProvider() throws Exception { HttpClient client = new HttpClient(); /* * abcd is an invalid ID so a NumberFormatException will be thrown in * the resource */ DeleteMethod postMethod = new DeleteMethod(getBaseURI() + "/abcd"); client.executeMethod(postMethod); assertEquals(450, postMethod.getStatusCode()); CommentError c = (CommentError) JAXBContext.newInstance(CommentError.class.getPackage().getName()) .createUnmarshaller().unmarshal(postMethod.getResponseBodyAsStream()); assertEquals("For input string: \"abcd\"", c.getErrorMessage()); }