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.pentaho.di.baserver.utils.web.HttpConnectionHelper.java

protected HttpMethod getHttpMethod(String url, Map<String, String> queryParameters, String httpMethod) {
    org.pentaho.di.baserver.utils.inspector.HttpMethod method;
    if (httpMethod == null) {
        httpMethod = "";
    }//from   w w w .jav  a 2  s .  c  o  m
    try {
        method = org.pentaho.di.baserver.utils.inspector.HttpMethod.valueOf(httpMethod);
    } catch (IllegalArgumentException e) {
        logger.warn("Method '" + httpMethod + "' is not supported - using 'GET'");
        method = org.pentaho.di.baserver.utils.inspector.HttpMethod.GET;
    }

    switch (method) {
    case GET:
        return new GetMethod(url + constructQueryString(queryParameters));
    case POST:
        PostMethod postMethod = new PostMethod(url);
        setRequestEntity(postMethod, queryParameters);
        return postMethod;
    case PUT:
        PutMethod putMethod = new PutMethod(url);
        setRequestEntity(putMethod, queryParameters);
        return putMethod;
    case DELETE:
        return new DeleteMethod(url + constructQueryString(queryParameters));
    case HEAD:
        return new HeadMethod(url + constructQueryString(queryParameters));
    case OPTIONS:
        return new OptionsMethod(url + constructQueryString(queryParameters));
    default:
        return new GetMethod(url + constructQueryString(queryParameters));
    }
}

From source file:org.review_board.ereviewboard.core.client.ReviewboardHttpClient.java

public void executeDelete(String url, IProgressMonitor monitor) throws ReviewboardException {

    executeMethod(new DeleteMethod(stripSlash(location.getUrl()) + url), monitor);
}

From source file:org.roda.wui.filter.CasClient.java

/**
 * Logout from the CAS server./*  w  w  w .  j  a  va 2  s  .co m*/
 * 
 * @param ticketGrantingTicket
 *          the <strong>Ticket Granting Ticket</strong>.
 * @throws GenericException
 *           if some error occurred.
 */
public void logout(final String ticketGrantingTicket) throws GenericException {
    final HttpClient client = new HttpClient();
    final DeleteMethod method = new DeleteMethod(
            String.format("%s/v1/tickets/%s", casServerUrlPrefix, ticketGrantingTicket));
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            LOGGER.info("Logged out");
        } else {
            LOGGER.warn(invalidResponseMessage(method));
            throw new GenericException(invalidResponseMessage(method));
        }
    } catch (final IOException e) {
        throw new GenericException(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.roosster.api.TestApi.java

/**
 * /*from  w  w  w.jav  a 2  s  . c  o  m*/
 */
public void testApi() throws Exception {
    // FIRST ADD URL
    System.out.println("Trying to POST '" + TEST_URL + "' as a new entry to " + API_ENDPOINT);

    PostMethod post = new PostMethod(API_ENDPOINT + "?force=true");
    post.setRequestEntity(postRequestBody);

    int statusCode = client.executeMethod(post);

    assertEquals("POST to " + TEST_URL + " failed", 200, statusCode);

    logMethodResponse(post);

    // ... THEN GET IT
    System.out.println("Trying to GET '" + TEST_URL + "' as a new entry to " + API_ENDPOINT);

    GetMethod get = new GetMethod(API_ENDPOINT + "/entry?url=" + TEST_URL);
    statusCode = client.executeMethod(get);

    assertEquals("GET from " + TEST_URL + " failed", 200, statusCode);

    logMethodResponse(get);

    // ... THEN UPDATE IT
    System.out.println("Trying to PUT '" + TEST_URL + "' as a new entry to " + API_ENDPOINT);

    PutMethod put = new PutMethod(API_ENDPOINT);
    put.setRequestEntity(putRequestBody);

    statusCode = client.executeMethod(put);

    assertEquals("PUT to " + TEST_URL + " failed", 200, statusCode);

    logMethodResponse(put);

    // ... THEN GET IT AGAIN
    System.out.println("Trying to GET '" + TEST_URL + "' as a new entry to " + API_ENDPOINT);

    get = new GetMethod(API_ENDPOINT + "/entry?url=" + TEST_URL);

    statusCode = client.executeMethod(get);

    assertEquals("GET from " + TEST_URL + " failed", 200, statusCode);

    logMethodResponse(get);

    // ... AND DELETE IT AGAIN
    System.out.println("Trying to DELETE '" + TEST_URL + "' as a new entry to " + API_ENDPOINT);

    DeleteMethod del = new DeleteMethod(API_ENDPOINT + "?url=" + TEST_URL);

    statusCode = client.executeMethod(del);

    assertEquals("GET from " + TEST_URL + " failed", 200, statusCode);

    logMethodResponse(get);

    // ... THEN GET IT AGAIN
    System.out.println("Trying to GET '" + TEST_URL + "' as a new entry to " + API_ENDPOINT);

    get = new GetMethod(API_ENDPOINT + "/entry?url=" + TEST_URL);

    statusCode = client.executeMethod(get);

    assertEquals("GET from " + TEST_URL + " failed", 200, statusCode);

    logMethodResponse(get);

}

From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java

/**
 * Fire off a request to a URL using the specified method but reuse the client for efficiency,
 * include optional params and data in the request,
 * the response data will be returned in the object if the request can be carried out
 * //  w ww.  j  a  v  a2  s  .  co m
 * @param httpClientWrapper (optional) allows the http client to be reused for efficiency,
 * if null a new one will be created each time, use {@link #makeReusableHttpClient(boolean, int)} to
 * create a reusable instance
 * @param URL the url to send the request to (absolute or relative, can include query params)
 * @param method the method to use (e.g. GET, POST, etc.)
 * @param params (optional) params to send along with the request, will be encoded in the query string or in the body depending on the method
 * @param params (optional) headers to send along with the request, will be encoded in the headers
 * @param data (optional) data to send along in the body of the request, this only works for POST and PUT requests, ignored for the other types
 * @param guaranteeSSL if this is true then the request is sent in a mode which will allow self signed certs to work,
 * otherwise https requests will fail if the certs cannot be centrally verified
 * @return an object representing the response, includes data about the response
 * @throws HttpRequestException if the request cannot be processed for some reason (this is unrecoverable)
 */
@SuppressWarnings("deprecation")
public static HttpResponse fireRequest(HttpClientWrapper httpClientWrapper, String URL, Method method,
        Map<String, String> params, Map<String, String> headers, Object data, boolean guaranteeSSL) {
    if (guaranteeSSL) {
        // added this to attempt to force the SSL self signed certs to work
        Protocol myhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttps);
    }

    if (httpClientWrapper == null || httpClientWrapper.getHttpClient() == null) {
        httpClientWrapper = makeReusableHttpClient(false, 0, null);
    }

    HttpMethod httpMethod = null;
    if (method.equals(Method.GET)) {
        GetMethod gm = new GetMethod(URL);
        // put params into query string
        gm.setQueryString(mergeQueryStringWithParams(gm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in GET requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        gm.setFollowRedirects(true);
        httpMethod = gm;
    } else if (method.equals(Method.POST)) {
        PostMethod pm = new PostMethod(URL);
        // special handling for post params
        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                if (entry.getKey() == null || entry.getValue() == null) {
                    System.out.println("WARN: null value supplied for param name (" + entry.getKey()
                            + ") or value (" + entry.getValue()
                            + ") (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
                }
                pm.addParameter(entry.getKey(), entry.getValue());
            }
        }
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.PUT)) {
        PutMethod pm = new PutMethod(URL);
        // put params into query string
        pm.setQueryString(mergeQueryStringWithParams(pm.getQueryString(), params));
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.DELETE)) {
        DeleteMethod dm = new DeleteMethod(URL);
        // put params into query string
        dm.setQueryString(mergeQueryStringWithParams(dm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in DELETE requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        httpMethod = dm;
    } else {
        throw new IllegalArgumentException("Cannot handle method: " + method);
    }
    // set the headers for the request
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            httpMethod.addRequestHeader(entry.getKey(), entry.getValue());
        }
    }

    HttpResponse response = null;
    try {
        int responseCode = httpClientWrapper.getHttpClient().executeMethod(httpMethod);
        response = new HttpResponse(responseCode);

        // Avoid DOS because of large responses using up all memory in the system - https://jira.sakaiproject.org/browse/SAK-20405
        InputStream is = httpMethod.getResponseBodyAsStream();
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = is.read(b)) != -1;) {
            out.append(new String(b, 0, n));
            if (out.length() > MAX_RESPONSE_SIZE_CHARS) {
                // die if the response exceeds the maximum chars allowed
                throw new HttpRequestException("Response size (" + out.length() + " chars) from url (" + URL
                        + ") exceeded the maximum allowed batch response size (" + MAX_RESPONSE_SIZE_CHARS
                        + " chars) while processing the response");
            }
        }
        String body = out.toString();

        //String body = httpMethod.getResponseBodyAsString();
        //         byte[] responseBody = httpMethod.getResponseBody();
        //         if (responseBody != null) {
        //            body = new String(responseBody, "UTF-8");
        //         }
        response.setResponseBody(body);
        response.setResponseMessage(httpMethod.getStatusText());
        // now get the headers
        HashMap<String, String[]> responseHeaders = new HashMap<String, String[]>();
        Header[] respHeaders = httpMethod.getResponseHeaders();
        for (int i = 0; i < respHeaders.length; i++) {
            Header header = respHeaders[i];
            // now we convert the headers from these odd pairs into something more like servlets expect
            HeaderElement[] elements = header.getElements();
            if (elements == null || elements.length == 0) {
                continue;
            } else if (elements.length >= 1) {
                String[] values = new String[elements.length];
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < elements.length; j++) {
                    sb.setLength(0); // clear the StringBuilder
                    sb.append(elements[j].getName());
                    if (elements[j].getValue() != null) {
                        sb.append("=");
                        sb.append(elements[j].getValue());
                    }
                    values[j] = sb.toString();
                }
                responseHeaders.put(header.getName(), values);
            }
        }
        response.setResponseHeaders(responseHeaders);
    } catch (HttpException he) {
        // error contained in he.getMessage()
        throw new HttpRequestException(
                "Fatal HTTP Request Error: " + "Could not sucessfully fire request to url (" + URL
                        + ") using method (" + method + ")  :: " + he.getMessage(),
                he);
    } catch (IOException ioe) {
        // other exception
        throw new HttpIOException(
                "IOException (transport/connection) Error: " + "Could not sucessfully fire request to url ("
                        + URL + ") using method (" + method + ")  :: " + ioe.getMessage(),
                ioe);
    } finally {
        httpMethod.releaseConnection();
    }
    return response;
}

From source file:org.sakaiproject.nakamura.docproxy.url.UrlRepositoryProcessor.java

public void removeDocument(Node node, String path) throws DocProxyException {
    DeleteMethod method = new DeleteMethod(removeUrl + path);
    executeMethod(method, node);/*from  w ww.  ja  v a  2s  .c  o m*/
}

From source file:org.sharegov.cirm.utils.GenUtils.java

public static String httpDelete(String url, String... headers) {
    HttpClient client = new HttpClient();
    DeleteMethod method = new DeleteMethod(url);
    if (headers != null) {
        if (headers.length % 2 != 0)
            throw new IllegalArgumentException(
                    "Odd number of headers argument, specify HTTP headers in pairs: name then value, etc.");
        for (int i = 0; i < headers.length; i++)
            method.addRequestHeader(headers[i], headers[++i]);
    }//  www.j  a v  a 2 s. c  o m
    try {
        // disable retries from within the HTTP client          
        client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(0, false));
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK)
            throw new RuntimeException("HTTP Error " + statusCode + " while deleting " + url.toString());
        return method.getResponseBodyAsString();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.sipfoundry.sipxconfig.admin.CertificateManagerImpl.java

public void deleteCA(CertificateDecorator cert) {
    if (isSystemGenerated(cert.getFileName())) {
        throw new UserException("&error.delete.default.ca", cert.getFileName());
    }//w  w w. j ava  2 s  .c  o  m

    Collection<File> files = FileUtils.listFiles(new File(m_sslAuthDirectory), SSL_CA_EXTENSIONS, false);
    Collection<File> filesToDelete = new ArrayList<File>();
    try {
        for (File file : files) {
            if (StringUtils.equals(file.getCanonicalFile().getName(), cert.getFileName())) {
                filesToDelete.add(getCAFile(file.getName()));
            }
        }
        HttpClient httpClient = getNewHttpClient();
        Location[] locations = m_locationsManager.getLocations();
        for (Location curLocation : locations) {
            for (File file : filesToDelete) {
                String remoteFileName = join(
                        new Object[] { curLocation.getHttpsServerUrl(), file.getAbsolutePath() });
                DeleteMethod httpDelete = new DeleteMethod(remoteFileName);
                try {
                    int statusCode = httpClient.executeMethod(httpDelete);
                    if (statusCode != 200) {
                        throw new UserException("&error.https.server.status.code", curLocation.getFqdn(),
                                String.valueOf(statusCode));
                    }
                } catch (HttpException ex) {
                    throw new UserException("&error.https.server", curLocation.getFqdn(), ex.getMessage());
                } finally {
                    httpDelete.releaseConnection();
                }
            }
        }
    } catch (IOException ex) {
        throw new UserException("&error.delete.cert");
    }
}

From source file:org.soa4all.dashboard.gwt.module.wsmolite.server.WsmoLiteDataServiceImpl.java

@Override
public String proxifyRequest(String method, String url, Map<String, String> headers) throws Exception {

    HttpMethod httpMtd;/*from w  ww  .  j  a v  a  2s .c om*/
    if (method.equalsIgnoreCase("post")) {
        httpMtd = new PostMethod(url);
    }
    if (method.equalsIgnoreCase("put")) {
        httpMtd = new PutMethod(url);
    }
    if (method.equalsIgnoreCase("delete")) {
        httpMtd = new DeleteMethod(url);
    } else {
        httpMtd = new GetMethod(url);
    }

    if (headers != null) {
        for (String key : headers.keySet()) {
            httpMtd.addRequestHeader(key, headers.get(key));
        }
    }

    HttpClient httpclient = new HttpClient();
    try {
        int result = httpclient.executeMethod(httpMtd);
        if (result != 200) {
            if (httpMtd.getResponseHeader("Error") != null) {
                throw new Exception(httpMtd.getResponseHeader("Error").getValue());
            }
            throw new Exception("Service error code - " + result);
        }
        BufferedInputStream response = new BufferedInputStream(httpMtd.getResponseBodyAsStream());
        ByteArrayOutputStream resultBuffer = new ByteArrayOutputStream();

        byte[] buffer = new byte[1000];
        int i;
        do {
            i = response.read(buffer);
            if (i > 0) {
                resultBuffer.write(buffer, 0, i);
            }
        } while (i > 0);
        httpMtd.releaseConnection();

        return resultBuffer.toString("UTF-8");
    } catch (Exception exc) {
        httpMtd.releaseConnection();
        throw new Exception(exc.getClass().getSimpleName() + " : " + exc.getMessage());
    }
}

From source file:org.soa4all.dashboard.gwt.module.wsmolite.server.WsmoLiteDataServiceImpl.java

@Override
public boolean deleteRepositoryFile(String fullRequestUrl) throws Exception {

    DeleteMethod deleteMtd = new DeleteMethod(fullRequestUrl);
    HttpClient httpclient = new HttpClient();

    try {/*from w w w.  j a  v  a2 s  . c  o m*/
        int result = httpclient.executeMethod(deleteMtd);
        if (result != 200) {
            deleteMtd.releaseConnection();
            throw new Exception("Error " + result + ": " + deleteMtd.getResponseHeader("Error"));
        }
    } finally {
        deleteMtd.releaseConnection();
    }
    return true;
}