Example usage for org.apache.commons.httpclient.methods DeleteMethod DeleteMethod

List of usage examples for org.apache.commons.httpclient.methods DeleteMethod DeleteMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods DeleteMethod DeleteMethod.

Prototype

public DeleteMethod(String paramString) 

Source Link

Usage

From source file:org.sonar.wsclient.connectors.HttpClient3Connector.java

private HttpMethodBase newDeleteRequest(DeleteQuery query) {
    HttpMethodBase method = new DeleteMethod(server.getHost() + query.getUrl());
    initRequest(method, query);//from  w  ww  . ja v  a  2s .c  o  m
    return method;
}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

@Override
public void deleteItem(ProxyRepository repository, ResourceStoreRequest request)
        throws ItemNotFoundException, UnsupportedStorageOperationException, RemoteStorageException {
    URL remoteURL = getAbsoluteUrlFromBase(repository, request);

    DeleteMethod method = new DeleteMethod(remoteURL.toString());

    try {/*from ww w.  ja  v  a  2  s .c  o  m*/
        int response = executeMethod(repository, request, method, remoteURL);

        if (response != HttpStatus.SC_OK && response != HttpStatus.SC_NO_CONTENT
                && response != HttpStatus.SC_ACCEPTED) {
            throw new RemoteStorageException("The response to HTTP " + method.getName()
                    + " was unexpected HTTP Code " + response + " : " + HttpStatus.getStatusText(response)
                    + " [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath()
                    + "\", remoteUrl=\"" + remoteURL.toString() + "\"]");
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:org.sonatype.nexus.restlight.common.AbstractRESTLightClient.java

/**
 * <p>// w w w . j  a  v  a2s .c  o m
 * Low-level DELETE implementation.
 * </p>
 * <p>
 * Submit a DELETE request to the URL given (absolute or relative-to-base-URL depends on urlIsAbsolute flag), and
 * parse the response as an XML {@link Document} (JDOM) instance <b>if</b> expectResponseBody == true. Use the given
 * requestParams map to inject into the HTTP DELETE method.
 * </p>
 */
protected Document doDelete(final String url, final Map<String, ? extends Object> requestParams,
        final boolean urlIsAbsolute, final boolean expectResponseBody) throws RESTLightClientException {
    DeleteMethod method = urlIsAbsolute ? new DeleteMethod(url) : new DeleteMethod(baseUrl + url);

    addRequestParams(method, requestParams);

    try {
        client.executeMethod(method);
    } catch (HttpException e) {
        throw new RESTLightClientException("DELETE request execution failed. Reason: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new RESTLightClientException("DELETE request execution failed. Reason: " + e.getMessage(), e);
    }

    int status = method.getStatusCode();

    String statusText = method.getStatusText();

    if (status != 200) {
        throw new RESTLightClientException("DELETE request failed; HTTP status: " + status + ": " + statusText);
    }

    if (expectResponseBody) {
        try {
            return new SAXBuilder().build(method.getResponseBodyAsStream());
        } catch (JDOMException e) {
            throw new RESTLightClientException("Failed to parse response body as XML for DELETE request.", e);
        } catch (IOException e) {
            throw new RESTLightClientException("Could not retrieve body as a String from DELETE request.", e);
        } finally {
            method.releaseConnection();
        }
    } else {
        method.releaseConnection();

        return null;
    }
}

From source file:org.sonatype.nexus.restlight.testharness.DELETEFixtureTest.java

@Test
public void testDelete() throws HttpException, IOException, JDOMException {
    Document doc = new Document().setRootElement(new Element("root"));

    fixture.setResponseDocument(doc);//from  w ww. ja v  a 2 s  .c o m

    String url = "http://localhost:" + fixture.getPort();
    HttpClient client = new HttpClient();
    setupAuthentication(client);

    DeleteMethod get = new DeleteMethod(url);

    client.executeMethod(get);

    SAXBuilder builder = new SAXBuilder();
    Document resp = builder.build(get.getResponseBodyAsStream());

    get.releaseConnection();

    XMLOutputter outputter = new XMLOutputter(Format.getCompactFormat());
    assertEquals(outputter.outputString(doc), outputter.outputString(resp));
}

From source file:org.springfield.mojo.http.HttpHelper.java

/**
 * Sends a standard HTTP request to the specified URI using the determined method.
 * Attaches the content, uses the specified content type, sets cookies, timeout and
 * request headers/*from   w  w  w .j  a v  a 2  s.  co m*/
 *  
 * @param method - the request method
 * @param uri - the uri to request
 * @param body - the content  
 * @param contentType - the content type
 * @param cookies - cookies
 * @param timeout - timeout in milliseconds
 * @param charSet - the character set
 * @param requestHeaders - extra user defined headers
 * @return response
 */
public static Response sendRequest(String method, String uri, String body, String contentType, String cookies,
        int timeout, String charSet, Map<String, String> requestHeaders) {
    // http client
    HttpClient client = new HttpClient();

    // method
    HttpMethodBase reqMethod = null;
    if (method.equals(HttpMethods.PUT)) {
        reqMethod = new PutMethod(uri);
    } else if (method.equals(HttpMethods.POST)) {
        reqMethod = new PostMethod(uri);
    } else if (method.equals(HttpMethods.GET)) {
        if (body != null) {
            // hack to be able to send a request body with a get (only if required)
            reqMethod = new PostMethod(uri) {
                public String getName() {
                    return "GET";
                }
            };
        } else {
            reqMethod = new GetMethod(uri);
        }
    } else if (method.equals(HttpMethods.DELETE)) {
        if (body != null) {
            // hack to be able to send a request body with a delete (only if required)
            reqMethod = new PostMethod(uri) {
                public String getName() {
                    return "DELETE";
                }
            };
        } else {
            reqMethod = new DeleteMethod(uri);
        }
    } else if (method.equals(HttpMethods.HEAD)) {
        reqMethod = new HeadMethod(uri);
    } else if (method.equals(HttpMethods.TRACE)) {
        reqMethod = new TraceMethod(uri);
    } else if (method.equals(HttpMethods.OPTIONS)) {
        reqMethod = new OptionsMethod(uri);
    }

    // add request body
    if (body != null) {
        try {
            RequestEntity entity = new StringRequestEntity(body, contentType, charSet);
            ((EntityEnclosingMethod) reqMethod).setRequestEntity(entity);
            reqMethod.setRequestHeader("Content-type", contentType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // add cookies
    if (cookies != null) {
        reqMethod.addRequestHeader("Cookie", cookies);
    }

    // add custom headers
    if (requestHeaders != null) {
        for (Map.Entry<String, String> header : requestHeaders.entrySet()) {
            String name = header.getKey();
            String value = header.getValue();

            reqMethod.addRequestHeader(name, value);
        }
    }

    Response response = new Response();

    // do request
    try {
        if (timeout != -1) {
            client.getParams().setSoTimeout(timeout);
        }
        int statusCode = client.executeMethod(reqMethod);
        response.setStatusCode(statusCode);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // read response
    try {
        InputStream instream = reqMethod.getResponseBodyAsStream();
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int len;
        while ((len = instream.read(buffer)) > 0) {
            outstream.write(buffer, 0, len);
        }
        String resp = new String(outstream.toByteArray(), reqMethod.getResponseCharSet());
        response.setResponse(resp);

        //set content length
        long contentLength = reqMethod.getResponseContentLength();
        response.setContentLength(contentLength);
        //set character set
        String respCharSet = reqMethod.getResponseCharSet();
        response.setCharSet(respCharSet);
        //set all headers
        Header[] headers = reqMethod.getResponseHeaders();
        response.setHeaders(headers);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // release connection
    reqMethod.releaseConnection();

    // return
    return response;
}

From source file:org.springframework.http.client.CommonsClientHttpRequestFactory.java

/**
 * Create a Commons HttpMethodBase object for the given HTTP method
 * and URI specification./*  ww  w  .  j a  v  a 2  s .  com*/
 * @param httpMethod the HTTP method
 * @param uri the URI
 * @return the Commons HttpMethodBase object
 */
protected HttpMethodBase createCommonsHttpMethod(HttpMethod httpMethod, String uri) {
    switch (httpMethod) {
    case GET:
        return new GetMethod(uri);
    case DELETE:
        return new DeleteMethod(uri);
    case HEAD:
        return new HeadMethod(uri);
    case OPTIONS:
        return new OptionsMethod(uri);
    case POST:
        return new PostMethod(uri);
    case PUT:
        return new PutMethod(uri);
    case TRACE:
        return new TraceMethod(uri);
    case PATCH:
        throw new IllegalArgumentException(
                "HTTP method PATCH not available before Apache HttpComponents HttpClient 4.2");
    default:
        throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
    }
}

From source file:org.switchyard.component.test.mixins.http.HTTPMixIn.java

/**
 * Send the specified request payload to the specified HTTP endpoint using the method specified.
 * @param endpointURL The HTTP endpoint URL.
 * @param request The request payload./*from w  w w .j  a v  a  2s. co m*/
 * @param method The request method.
 * @return The HttpMethod object.
 */
public HttpMethod sendStringAndGetMethod(String endpointURL, String request, String method) {
    if (_dumpMessages) {
        _logger.info("Sending a " + method + " request to [" + endpointURL + "]");
        _logger.info("Request body:[" + request + "]");
    }
    HttpMethod httpMethod = null;
    try {
        if (method.equals(HTTP_PUT)) {
            httpMethod = new PutMethod(endpointURL);
            ((PutMethod) httpMethod).setRequestEntity(new StringRequestEntity(request, _contentType, "UTF-8"));
        } else if (method.equals(HTTP_POST)) {
            httpMethod = new PostMethod(endpointURL);
            ((PostMethod) httpMethod).setRequestEntity(new StringRequestEntity(request, _contentType, "UTF-8"));
        } else if (method.equals(HTTP_DELETE)) {
            httpMethod = new DeleteMethod(endpointURL);
        } else if (method.equals(HTTP_OPTIONS)) {
            httpMethod = new OptionsMethod(endpointURL);
        } else if (method.equals(HTTP_HEAD)) {
            httpMethod = new HeadMethod(endpointURL);
        } else {
            httpMethod = new GetMethod(endpointURL);
        }
        execute(httpMethod);
    } catch (UnsupportedEncodingException e) {
        _logger.error("Unable to set request entity", e);
    }
    return httpMethod;
}

From source file:org.ws4d.pipes.modules.http.Delete.java

public void doWork() {

    // execute base module doWork()
    super.doWork();

    // check if we can terminate
    if (canClose()) {
        closeAllPorts();//  www .j  a  v a 2 s. c o m
        return;
    }

    if (getUrl() != null) {
        final DeleteMethod method = new DeleteMethod(getUrl());

        try {
            getClient().executeMethod(method);

            setOutData(PORT_STATUSCODE, method.getStatusCode());
            setOutData(PORT_STATUSLINE, method.getStatusLine());

        } catch (Exception e) {
            getLogger().log(Level.SEVERE, "Can't execute http get request: ", e);
        } finally {
            method.releaseConnection();
        }
    }
}

From source file:org.wso2.carbon.appfactory.common.util.MutualAuthHttpClient.java

/**
 * Send REST DELETE request to stratos SM.
 *
 * @param endPointUrl end point to send the message
 * @throws org.wso2.carbon.appfactory.common.AppFactoryException
 *///from w  ww.  j  a v a2 s.co  m
public static ServerResponse sendDeleteRequest(String endPointUrl, String username) throws AppFactoryException {
    HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    DeleteMethod deleteMethod = new DeleteMethod(endPointUrl);
    deleteMethod.setRequestHeader(AUTHORIZATION_HEADER, getAuthHeaderValue(username));
    return send(httpClient, deleteMethod);
}

From source file:org.wso2.carbon.appfactory.issuetracking.IssueTrackerConnector.java

public boolean deleteProject(Application application, String userName, String tenantDomain)
        throws AppFactoryException {

    String url = issueTrackerUrl + "services/tenant/" + tenantDomain + "/project/" + application.getId();
    DeleteMethod deleteProject = new DeleteMethod(url);
    int result = -1;
    try {//from   ww w. ja v a2s.c om
        HttpClient httpclient = new HttpClient();
        result = httpclient.executeMethod(deleteProject);
    } catch (Exception e) {
        String msg = "Error while  creating project in issue repository for " + application.getName();
        log.error(msg);
        if (log.isDebugEnabled()) {
            log.debug(msg, e);
        }
        throw new AppFactoryException(msg, e);
    } finally {
        // Release current connection to the connection pool once you are done
        deleteProject.releaseConnection();
    }
    return result == HttpStatus.SC_OK;
}