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.jboss.wise.core.client.jaxrs.impl.RSDynamicClientImpl.java

public InvocationResult invoke(RequestEntity requestEntity, WiseMapper mapper) {
    InvocationResult result = null;/* w  w w.  ja va2  s .  c  o m*/
    Map<String, Object> responseHolder = new HashMap<String, Object>();

    if (HttpMethod.GET == httpMethod) {
        GetMethod get = new GetMethod(resourceURI);
        setRequestHeaders(get);

        try {
            int statusCode = httpClient.executeMethod(get);
            // TODO: Use InputStream
            String response = get.getResponseBodyAsString();
            responseHolder.put(InvocationResult.STATUS, Integer.valueOf(statusCode));

            result = new InvocationResultImpl(InvocationResult.RESPONSE, null, response, responseHolder);

            // System.out.print(response);
        } catch (IOException e) {
            // TODO:
        } finally {
            get.releaseConnection();
        }
    } else if (HttpMethod.POST == httpMethod) {
        PostMethod post = new PostMethod(resourceURI);
        setRequestHeaders(post);

        post.setRequestEntity(requestEntity);

        try {
            int statusCode = httpClient.executeMethod(post);
            String response = post.getResponseBodyAsString();
            responseHolder.put(InvocationResult.STATUS, Integer.valueOf(statusCode));

            result = new InvocationResultImpl(InvocationResult.RESPONSE, null, response, responseHolder);

            // System.out.print(response);
        } catch (IOException e) {
            // TODO:
        } finally {
            post.releaseConnection();
        }
    } else if (HttpMethod.PUT == httpMethod) {
        PutMethod put = new PutMethod(resourceURI);
        setRequestHeaders(put);

        put.setRequestEntity(requestEntity);

        try {
            int statusCode = httpClient.executeMethod(put);
            String response = put.getResponseBodyAsString();
            responseHolder.put(InvocationResult.STATUS, Integer.valueOf(statusCode));

            result = new InvocationResultImpl(InvocationResult.RESPONSE, null, response, responseHolder);

            // System.out.print(response);
        } catch (IOException e) {
            // TODO:
        } finally {
            put.releaseConnection();
        }
    } else if (HttpMethod.DELETE == httpMethod) {
        DeleteMethod delete = new DeleteMethod(resourceURI);
        setRequestHeaders(delete);

        try {
            int statusCode = httpClient.executeMethod(delete);
            String response = delete.getResponseBodyAsString();
            responseHolder.put(InvocationResult.STATUS, Integer.valueOf(statusCode));

            result = new InvocationResultImpl(InvocationResult.RESPONSE, null, response, responseHolder);

            // System.out.print(response);
        } catch (IOException e) {
            // TODO:
        } finally {
            delete.releaseConnection();
        }
    }

    return result;
}

From source file:org.jbpm.formbuilder.server.GuvnorHelper.java

public DeleteMethod createDeleteMethod(String url) {
    return new DeleteMethod(url);
}

From source file:org.jbpm.process.workitem.rest.RESTWorkItemHandler.java

public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
    // extract required parameters
    String urlStr = (String) workItem.getParameter("Url");
    String method = (String) workItem.getParameter("Method");
    if (urlStr == null) {
        throw new IllegalArgumentException("Url is a required parameter");
    }/*from   ww  w .j  av  a2s.  c  o m*/
    if (method == null || method.trim().length() == 0) {
        method = "GET";
    }
    Map<String, Object> params = workItem.getParameters();

    // optional timeout config parameters, defaulted to 60 seconds
    Integer connectTimeout = (Integer) params.get("ConnectTimeout");
    if (connectTimeout == null)
        connectTimeout = 60000;
    Integer readTimeout = (Integer) params.get("ReadTimeout");
    if (readTimeout == null)
        readTimeout = 60000;

    HttpClient httpclient = new HttpClient();
    httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectTimeout);
    httpclient.getHttpConnectionManager().getParams().setSoTimeout(readTimeout);

    HttpMethod theMethod = null;
    if ("GET".equals(method)) {
        theMethod = new GetMethod(urlStr);
    } else if ("POST".equals(method)) {
        theMethod = new PostMethod(urlStr);
        setBody(theMethod, params);
    } else if ("PUT".equals(method)) {
        theMethod = new PutMethod(urlStr);
        setBody(theMethod, params);
    } else if ("DELETE".equals(method)) {
        theMethod = new DeleteMethod(urlStr);
    } else {
        throw new IllegalArgumentException("Method " + method + " is not supported");
    }
    doAuthorization(httpclient, theMethod, params);
    try {
        int responseCode = httpclient.executeMethod(theMethod);
        Map<String, Object> results = new HashMap<String, Object>();
        if (responseCode >= 200 && responseCode < 300) {
            theMethod.getResponseBody();
            postProcessResult(theMethod.getResponseBodyAsString(), results);
            results.put("StatusMsg",
                    "request to endpoint " + urlStr + " successfully completed " + theMethod.getStatusText());
        } else {
            logger.warn("Unsuccessful response from REST server (status {}, endpoint {}, response {}",
                    responseCode, urlStr, theMethod.getResponseBodyAsString());
            results.put("StatusMsg",
                    "endpoint " + urlStr + " could not be reached: " + theMethod.getResponseBodyAsString());
        }
        results.put("Status", responseCode);

        // notify manager that work item has been completed
        manager.completeWorkItem(workItem.getId(), results);
    } catch (Exception e) {
        handleException(e);
    } finally {
        theMethod.releaseConnection();
    }
}

From source file:org.jivesoftware.openfire.clearspace.ClearspaceManager.java

/**
 * Makes a rest request of any type at the specified urlSuffix. The urlSuffix should be of the
 * form /userService/users./*w  w w .ja v  a 2  s .c  om*/
 * If CS throws an exception it handled and transalated to a Openfire exception if possible.
 * This is done using the check fault method that tries to throw the best maching exception.
 *
 * @param type      Must be GET or DELETE
 * @param urlSuffix The url suffix of the rest request
 * @param xmlParams The xml with the request params, must be null if type is GET or DELETE only
 * @return The response as a xml doc.
 * @throws ConnectionException Thrown if there are issues perfoming the request.
 * @throws Exception Thrown if the response from Clearspace contains an exception.
 */
public Element executeRequest(HttpType type, String urlSuffix, String xmlParams)
        throws ConnectionException, Exception {
    if (Log.isDebugEnabled()) {
        Log.debug("Outgoing REST call [" + type + "] to " + urlSuffix + ": " + xmlParams);
    }

    String wsUrl = getConnectionURI() + WEBSERVICES_PATH + urlSuffix;

    String secret = getSharedSecret();

    HttpClient client = new HttpClient();
    HttpMethod method;

    // Configures the authentication
    client.getParams().setAuthenticationPreemptive(true);
    Credentials credentials = new UsernamePasswordCredentials(OPENFIRE_USERNAME, secret);
    AuthScope scope = new AuthScope(host, port, AuthScope.ANY_REALM);
    client.getState().setCredentials(scope, credentials);

    // Creates the method
    switch (type) {
    case GET:
        method = new GetMethod(wsUrl);
        break;
    case POST:
        PostMethod pm = new PostMethod(wsUrl);
        StringRequestEntity requestEntity = new StringRequestEntity(xmlParams);
        pm.setRequestEntity(requestEntity);
        method = pm;
        break;
    case PUT:
        PutMethod pm1 = new PutMethod(wsUrl);
        StringRequestEntity requestEntity1 = new StringRequestEntity(xmlParams);
        pm1.setRequestEntity(requestEntity1);
        method = pm1;
        break;
    case DELETE:
        method = new DeleteMethod(wsUrl);
        break;
    default:
        throw new IllegalArgumentException();
    }

    method.setRequestHeader("Accept", "text/xml");
    method.setDoAuthentication(true);

    try {
        // Executes the request
        client.executeMethod(method);

        // Parses the result
        String body = method.getResponseBodyAsString();
        if (Log.isDebugEnabled()) {
            Log.debug("Outgoing REST call results: " + body);
        }

        // Checks the http status
        if (method.getStatusCode() != 200) {
            if (method.getStatusCode() == 401) {
                throw new ConnectionException("Invalid password to connect to Clearspace.",
                        ConnectionException.ErrorType.AUTHENTICATION);
            } else if (method.getStatusCode() == 404) {
                throw new ConnectionException("Web service not found in Clearspace.",
                        ConnectionException.ErrorType.PAGE_NOT_FOUND);
            } else if (method.getStatusCode() == 503) {
                throw new ConnectionException("Web service not avaible in Clearspace.",
                        ConnectionException.ErrorType.SERVICE_NOT_AVAIBLE);
            } else {
                throw new ConnectionException(
                        "Error connecting to Clearspace, http status code: " + method.getStatusCode(),
                        new HTTPConnectionException(method.getStatusCode()),
                        ConnectionException.ErrorType.OTHER);
            }
        } else if (body.contains("Clearspace Upgrade Console")) {
            //TODO Change CS to send a more standard error message
            throw new ConnectionException("Clearspace is in an update state.",
                    ConnectionException.ErrorType.UPDATE_STATE);
        }

        Element response = localParser.get().parseDocument(body).getRootElement();

        // Check for exceptions
        checkFault(response);

        // Since there is no exception, returns the response
        return response;
    } catch (DocumentException e) {
        throw new ConnectionException("Error parsing the response of Clearspace.", e,
                ConnectionException.ErrorType.OTHER);
    } catch (HttpException e) {
        throw new ConnectionException("Error performing http request to Clearspace", e,
                ConnectionException.ErrorType.OTHER);
    } catch (UnknownHostException e) {
        throw new ConnectionException("Unknown Host " + getConnectionURI() + " trying to connect to Clearspace",
                e, ConnectionException.ErrorType.UNKNOWN_HOST);
    } catch (IOException e) {
        throw new ConnectionException("Error peforming http request to Clearspace.", e,
                ConnectionException.ErrorType.OTHER);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.mozilla.zest.impl.ZestBasicRunner.java

private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException {
    HttpMethod method;/*from   w  w w  .j ava2s. c  o  m*/
    URI uri = new URI(req.getUrl().toString(), false);

    switch (req.getMethod()) {
    case "GET":
        method = new GetMethod(uri.toString());
        // Can only redirect on GETs
        method.setFollowRedirects(req.isFollowRedirects());
        break;
    case "POST":
        method = new PostMethod(uri.toString());
        break;
    case "OPTIONS":
        method = new OptionsMethod(uri.toString());
        break;
    case "HEAD":
        method = new HeadMethod(uri.toString());
        break;
    case "PUT":
        method = new PutMethod(uri.toString());
        break;
    case "DELETE":
        method = new DeleteMethod(uri.toString());
        break;
    case "TRACE":
        method = new TraceMethod(uri.toString());
        break;
    default:
        throw new IllegalArgumentException("Method not supported: " + req.getMethod());
    }

    setHeaders(method, req.getHeaders());

    for (Cookie cookie : req.getCookies()) {
        // Replace any Zest variables in the value
        cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false));
        httpclient.getState().addCookie(cookie);
    }

    if (req.getMethod().equals("POST")) {
        // The setRequestEntity call trashes any Content-Type specified, so record it and reapply it after
        Header contentType = method.getRequestHeader("Content-Type");
        RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null);

        ((PostMethod) method).setRequestEntity(requestEntity);

        if (contentType != null) {
            method.setRequestHeader(contentType);
        }
    }

    int code = 0;
    String responseHeader = null;
    String responseBody = null;
    Date start = new Date();
    try {
        this.debug(req.getMethod() + " : " + req.getUrl());
        code = httpclient.executeMethod(method);

        responseHeader = method.getStatusLine().toString() + "\r\n" + arrayToStr(method.getResponseHeaders());
        responseBody = method.getResponseBodyAsString();

    } finally {
        method.releaseConnection();
    }
    // Update the headers with the ones actually sent
    req.setHeaders(arrayToStr(method.getRequestHeaders()));

    if (method.getStatusCode() == 302 && req.isFollowRedirects() && !req.getMethod().equals("GET")) {
        // Follow the redirect 'manually' as the httpclient lib only supports them for GET requests
        method = new GetMethod(method.getResponseHeader("Location").getValue());
        // Just in case there are multiple redirects
        method.setFollowRedirects(req.isFollowRedirects());

        try {
            this.debug(req.getMethod() + " : " + req.getUrl());
            code = httpclient.executeMethod(method);

            responseHeader = method.getStatusLine().toString() + "\r\n"
                    + arrayToStr(method.getResponseHeaders());
            responseBody = method.getResponseBodyAsString();

        } finally {
            method.releaseConnection();
        }
    }

    return new ZestResponse(req.getUrl(), responseHeader, responseBody, code,
            new Date().getTime() - start.getTime());
}

From source file:org.mule.transport.http.functional.HttpMethodTestCase.java

@Test
public void testDelete() throws Exception {
    DeleteMethod method = new DeleteMethod(getHttpEndpointAddress());
    int statusCode = client.executeMethod(method);
    assertEquals(HttpStatus.SC_OK, statusCode);
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java

protected HttpMethod createDeleteMethod(MuleMessage message) throws Exception {
    URI uri = getURI(message);/*from   w  w  w. ja  v a2s. c  o m*/
    return new DeleteMethod(uri.toString());
}

From source file:org.nuxeo.ecm.core.storage.sql.ScalityBinaryManager.java

/**
 * Deletes an object using its digest string.
 *
 * @param objectID//www. j  ava2 s  . co  m
 */
protected void removeBinary(String objectID) {
    String url = PROTOCOL_PREFIX + this.bucketName + "." + this.hostBase;
    log.debug(url);
    DeleteMethod deleteMethod = new DeleteMethod(url);
    String contentMD5 = "";

    // date to be provided to the cloud server
    Date currentDate = new Date();

    String cloudDateString = StringGenerator.getCloudFormattedDateString(currentDate);

    String stringToSign = StringGenerator.getStringToSign(HTTPMethod.DELETE, contentMD5, DEFAULT_CONTENT_TYPE,
            this.bucketName, objectID, currentDate);
    try {
        deleteMethod.addRequestHeader("Authorization",
                StringGenerator.getAuthorizationString(stringToSign, awsID, awsSecret));
        deleteMethod.addRequestHeader("x-amz-date", cloudDateString);
        deleteMethod.setPath("/" + objectID);

        HttpClient client = new HttpClient();
        int returnCode = client.executeMethod(deleteMethod);
        log.debug(deleteMethod.getResponseBodyAsString());
        // only for logging
        if (returnCode == HttpStatus.SC_NO_CONTENT) {
            log.info("Object " + objectID + " deleted");
        } else if (returnCode == HttpStatus.SC_NOT_FOUND) {
            log.debug("Object " + objectID + " does not exist");
        } else {
            String connectionMsg = "Scality connection problem. Object could not be verified";
            log.debug(connectionMsg);
            throw new RuntimeException(connectionMsg);
        }
        deleteMethod.releaseConnection();
    } catch (SignatureException e) {
        throw new RuntimeException(e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.nuxeo.ecm.webdav.WebDavClientTest.java

@Test
public void testDeleteFile() throws Exception {
    String name = "test.txt";

    HttpMethod method = new DeleteMethod(ROOT_URI + name);
    int status = client.executeMethod(method);
    assertEquals(HttpStatus.SC_NO_CONTENT, status);

    // check using Nuxeo Core APIs
    session.save(); // process invalidations
    PathRef pathRef = new PathRef("/workspaces/workspace/" + name);
    assertFalse(session.exists(pathRef)); // in trash with different name

    // recreate it, for other tests using the same repo
    byte[] bytes = "Hello, world!".getBytes("UTF-8");
    doTestPutFile(name, bytes, "text/plain", "Note");
}

From source file:org.nuxeo.ecm.webdav.WebDavClientTest.java

@Test
public void testDeleteMissingFile() throws Exception {
    String name = "nosuchfile.txt";

    HttpMethod method = new DeleteMethod(ROOT_URI + name);
    int status = client.executeMethod(method);
    assertEquals(HttpStatus.SC_NOT_FOUND, status);
}