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.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java

/** {@inheritDoc} */
public HttpResponse fetch(HttpRequest request) {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod;/*w  w w  . j a  v a 2 s  .co  m*/
    String methodType = request.getMethod();
    String requestUri = request.getUri().toString();

    ProxyHelper.fillProxy(httpClient, requestUri);

    // true for non-HEAD requests
    boolean requestCompressedContent = true;

    if ("POST".equals(methodType) || "PUT".equals(methodType)) {
        EntityEnclosingMethod enclosingMethod = ("POST".equals(methodType)) ? new PostMethod(requestUri)
                : new PutMethod(requestUri);

        if (request.getPostBodyLength() > 0) {
            enclosingMethod.setRequestEntity(new InputStreamRequestEntity(request.getPostBody()));
            enclosingMethod.setRequestHeader("Content-Length", String.valueOf(request.getPostBodyLength()));
        }
        httpMethod = enclosingMethod;
    } else if ("DELETE".equals(methodType)) {
        httpMethod = new DeleteMethod(requestUri);
    } else if ("HEAD".equals(methodType)) {
        httpMethod = new HeadMethod(requestUri);
    } else {
        httpMethod = new GetMethod(requestUri);
    }

    httpMethod.setFollowRedirects(false);
    httpMethod.getParams().setSoTimeout(connectionTimeoutMs);

    if (requestCompressedContent)
        httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate");

    for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
        httpMethod.setRequestHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
    }

    try {

        int statusCode = httpClient.executeMethod(httpMethod);

        // Handle redirects manually
        if (request.getFollowRedirects() && ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER)
                || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT))) {

            Header header = httpMethod.getResponseHeader("location");
            if (header != null) {
                String redirectUri = header.getValue();

                if ((redirectUri == null) || (redirectUri.equals(""))) {
                    redirectUri = "/";
                }
                httpMethod.releaseConnection();
                httpMethod = new GetMethod(redirectUri);

                statusCode = httpClient.executeMethod(httpMethod);
            }
        }

        return makeResponse(httpMethod, statusCode);

    } catch (IOException e) {
        if (e instanceof java.net.SocketTimeoutException || e instanceof java.net.SocketException) {
            return HttpResponse.timeout();
        }

        return HttpResponse.error();

    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:org.obm.caldav.client.AbstractPushTest.java

protected Document deleteQuery(Document doc) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DOMUtils.serialise(doc, out);/*from  www.j  a va  2 s .  c o  m*/
    DeleteMethod pfq = new DeleteMethod(url);
    appendHeader(pfq, out);
    return doRequest(pfq);
}

From source file:org.olat.test.OlatJerseyTestCase.java

public DeleteMethod createDelete(final URI requestURI, final String accept, final boolean cookie) {
    final DeleteMethod method = new DeleteMethod(requestURI.toString());
    if (cookie) {
        method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    }/*from  w w w  .j av  a  2  s .c  o  m*/
    if (StringHelper.containsNonWhitespace(accept)) {
        method.addRequestHeader("Accept", accept);
    }
    return method;
}

From source file:org.openhab.binding.garadget.internal.Connection.java

/**
 * Factory method to create a {@link HttpMethod}-object according to the
 * given String <code>httpMethod</code>
 *
 * @param httpMethodString/*from   w  ww  .  j  a  va2s.co  m*/
 *            the name of the {@link HttpMethod} to create
 * @param url
 *            the URL to include in the returned Method
 * @return
 *         an object of type {@link GetMethod}, {@link PutMethod},
 *         {@link PostMethod} or {@link DeleteMethod}
 * @throws
 *             IllegalArgumentException if <code>httpMethod</code> is none of
 *             <code>GET</code>, <code>PUT</code>, <code>POST</POST> or <code>DELETE</code>
 */
private static HttpMethod createHttpMethod(String httpMethodString, String url) {

    if (HTTP_GET.equals(httpMethodString)) {
        return new GetMethod(url);
    } else if (HTTP_PUT.equals(httpMethodString)) {
        return new PutMethod(url);
    } else if (HTTP_POST.equals(httpMethodString)) {
        return new PostMethod(url);
    } else if (HTTP_DELETE.equals(httpMethodString)) {
        return new DeleteMethod(url);
    } else {
        throw new IllegalArgumentException("given httpMethod '" + httpMethodString + "' is unknown");
    }
}

From source file:org.openrdf.http.client.HTTPClient.java

public void removeNamespacePrefix(String prefix)
        throws IOException, RepositoryException, UnauthorizedException {
    checkRepositoryURL();//from w w  w  .  j a v a 2 s.c  om

    HttpMethod method = new DeleteMethod(Protocol.getNamespacePrefixLocation(repositoryURL, prefix));
    setDoAuthentication(method);

    try {
        int httpCode = httpClient.executeMethod(method);

        if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new UnauthorizedException();
        } else if (!is2xx(httpCode)) {
            ErrorInfo errInfo = getErrorInfo(method);
            throw new RepositoryException("Failed to remove namespace: " + errInfo + " (" + httpCode + ")");
        }
    } finally {
        releaseConnection(method);
    }
}

From source file:org.openrdf.http.client.HTTPClient.java

public void clearNamespaces() throws IOException, RepositoryException, UnauthorizedException {
    checkRepositoryURL();/*from   w  w  w.  j av a 2 s .c o m*/

    HttpMethod method = new DeleteMethod(Protocol.getNamespacesLocation(repositoryURL));
    setDoAuthentication(method);

    try {
        int httpCode = httpClient.executeMethod(method);

        if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new UnauthorizedException();
        } else if (!is2xx(httpCode)) {
            ErrorInfo errInfo = getErrorInfo(method);
            throw new RepositoryException("Failed to clear namespaces: " + errInfo + " (" + httpCode + ")");
        }
    } finally {
        releaseConnection(method);
    }
}

From source file:org.openrdf.http.client.HTTPClient.java

public void deleteRepository(String repositoryID) throws HttpException, IOException, RepositoryException {

    HttpMethod method = new DeleteMethod(Protocol.getRepositoryLocation(serverURL, repositoryID));
    setDoAuthentication(method);//from w ww. j  av a2  s .  c o  m

    try {
        int httpCode = httpClient.executeMethod(method);

        if (httpCode == HttpURLConnection.HTTP_NO_CONTENT) {
            return;
        } else if (httpCode == HttpURLConnection.HTTP_FORBIDDEN) {
            ErrorInfo errInfo = getErrorInfo(method);
            throw new UnauthorizedException(errInfo.getErrorMessage());
        } else {
            ErrorInfo errInfo = getErrorInfo(method);
            throw new RepositoryException("Failed to delete repository: " + errInfo + " (" + httpCode + ")");
        }
    } finally {
        releaseConnection(method);
    }
}

From source file:org.owtf.runtime.core.ZestBasicRunner.java

private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException {
    HttpMethod method;/*  ww  w .j av a2s  .  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")) {
        // Do this after setting the headers so the length is corrected
        RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null);
        ((PostMethod) method).setRequestEntity(requestEntity);
    }

    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() + "\n" + arrayToStr(method.getResponseHeaders());
        //   httpclient.getParams().setParameter("http.method.response.buffer.warnlimit",new Integer(1000000000));
        responseBody = method.getResponseBodyAsString();

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

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

From source file:org.ozsoft.xmldb.exist.ExistConnector.java

@Override
public void deleteResource(String uri) throws XmldbException {
    // Use the REST interface for deleting resources.
    String actualUri = String.format("%s/rest%s", existUri, uri);
    DeleteMethod deleteMethod = new DeleteMethod(actualUri);
    try {/* w  w w .j a  v a2  s . co  m*/
        int statusCode = httpClient.executeMethod(deleteMethod);
        if (statusCode >= STATUS_ERROR) {
            if (statusCode == NOT_FOUND) {
                // Resource does not exist (no problem).
            } else if (statusCode == AUTHORIZATION_REQUIRED || statusCode == NOT_AUTHORIZED) {
                throw new NotAuthorizedException(String.format("Not authorized to delete resource '%s'", uri));
            } else {
                throw new XmldbException(String.format("Could not delete resource '%s' (HTTP status code: %d)",
                        uri, statusCode));
            }
        }
    } catch (IOException e) {
        String msg = String.format("Could not delete resource '%s': %s", uri, e.getMessage());
        LOG.error(msg, e);
        throw new XmldbException(msg, e);
    }
}

From source file:org.panlab.software.fci.uop.UoPGWClient.java

/**
 * It makes a DELETE towards the gateway
 * @author ctranoris/* w w w  .ja v  a2  s . co m*/
 * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27
 * @param ptmAlias sets the name of the provider URI, e.g.: uop
 * @param content sets the name of the content; send in utf8
 */
public void DELETEexecute(String resourceInstance, String ptmAlias, String content) {
    System.out.println("content body=" + "\n" + content);
    HttpClient client = new HttpClient();
    String tgwcontent = content;

    // resource instance is like uop.rubis_db-6 so we need to make it like
    // this /uop/uop.rubis_db-6
    String ptm = ptmAlias;
    String url = uopGWAddress + "/" + ptm + "/" + resourceInstance;
    System.out.println("Request: " + url);

    // Create a method instance.

    DeleteMethod delMethod = new DeleteMethod(url);
    delMethod.setRequestHeader("User-Agent", userAgent);
    delMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    // Provide custom retry handler is necessary
    //      delMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
    //            new DefaultHttpMethodRetryHandler(3, false));

    //      RequestEntity requestEntity = null;
    //      try {
    //         requestEntity = new StringRequestEntity(tgwcontent,
    //               "application/x-www-form-urlencoded", "utf-8");
    //      } catch (UnsupportedEncodingException e1) {
    //         e1.printStackTrace();
    //      }

    //delMethod.setRequestEntity(requestEntity);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(delMethod);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + delMethod.getStatusLine());
        }

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary
        // data
        // print the status and response
        InputStream responseBody = delMethod.getResponseBodyAsStream();

        CopyInputStream cis = new CopyInputStream(responseBody);
        response_stream = cis.getCopy();
        System.out.println("Response body=" + "\n" + convertStreamToString(response_stream));
        response_stream.reset();

        //         System.out.println("for address: " + url + " the response is:\n "
        //               + post.getResponseBodyAsString());

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        delMethod.releaseConnection();
    }

}