Example usage for org.apache.http.client.methods HttpDelete HttpDelete

List of usage examples for org.apache.http.client.methods HttpDelete HttpDelete

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpDelete HttpDelete.

Prototype

public HttpDelete(final String uri) 

Source Link

Usage

From source file:com.appjma.appdeployer.service.Downloader.java

private void deleteApp(String token, String id, String guid)
        throws ClientProtocolException, IOException, UnauthorizedResponseCode, WrongHttpResponseCode {
    String url = new GetBuilder(BASE_API_URL).appendPathSegment("apps").appendPathSegment(guid).build();
    HttpDelete request = new HttpDelete(url);
    setupDefaultHeaders(request, token);
    HttpResponse response = getHttpClient().execute(request);
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        throw new UnauthorizedResponseCode(response, token);
    }//from   w w w. j  a  v  a 2s.c o m
    if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NOT_FOUND) {
        // if not (deleted or already deleted)
        throw new WrongHttpResponseCode(response);
    }
    try {
        mParserResult.deleteApp(id);
        mParserResult.apply();
    } finally {
        mParserResult.clear();
    }
}

From source file:org.onehippo.forge.camel.demo.rest.services.ElasticSearchRestUpdateResource.java

/**
 * {@inheritDoc}/*from w  ww . jav  a2 s  . c  o  m*/
 */
@Override
protected HttpRequestBase createHttpRequest(final String action, final JSONObject payload) throws IOException {
    HttpRequestBase request = null;
    final String indexTypePath = getIndexTypePath(payload);

    if (INDEX_ACTION.equals(action)) {
        request = new HttpPut(getBaseUrl() + "/" + indexTypePath + "/" + payload.get("id"));
        request.setHeader("Content-Type", "application/json; charset=UTF-8");
        HttpEntity entity = new StringEntity(payload.toString(), "UTF-8");
        ((HttpPut) request).setEntity(entity);
    } else if (DELETE_ACTION.equals(action)) {
        request = new HttpDelete(getBaseUrl() + "/" + indexTypePath + "/" + payload.get("id"));
    }

    return request;
}

From source file:com.ysheng.auth.common.restful.RestClient.java

/**
 * Creates a HTTP request object.// www .j a  va2 s .c o m
 *
 * @param method The HTTP verb.
 * @param path The path that the HTTP request being sent to.
 * @param payload The request payload.
 * @return The HTTP request object.
 * @throws IOException The error that contains the detail information.
 */
private HttpUriRequest createHttpRequest(final Method method, final String path, final HttpEntity payload)
        throws IOException {
    String uri = target + path;
    HttpUriRequest request;

    switch (method) {
    case GET:
        request = new HttpGet(uri);
        break;
    case PUT:
        request = new HttpPut(uri);
        ((HttpPut) request).setEntity(payload);
        break;
    case POST:
        request = new HttpPost(uri);
        ((HttpPost) request).setEntity(payload);
        break;
    case DELETE:
        request = new HttpDelete(uri);
        break;

    default:
        throw new RuntimeException("Unknown method: " + method.name());
    }

    return request;
}

From source file:com.android.volley.toolbox.ExtHttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from  w w w  .j  a va2 s  .  c  om
@SuppressWarnings("deprecation")
/* protected */static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards
        // compatibility.
        // If the request's post body is null, then the assumption is that
        // the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:ca.ualberta.cs.cmput301w15t04team04project.CLmanager.CLmanager.java

/**
 * remover a claim from the server by a given claimName
 * /*from  ww w  .  j av  a  2 s  . co  m*/
 * @author youdong
 * @param claimId
 */
public void deleteClaim(String claimName, Context context, String name) {
    ClaimList claimList = MyLocalClaimListManager.loadClaimList(context, name);
    controller = new MyLocalClaimListController(claimList);
    controller.delete(claimName);
    MyLocalClaimListManager.saveClaimList(context, controller.getClaimList(), name);
    HttpDelete deleteRequest = new HttpDelete(RESOURCE_URL + claimName);
    deleteRequest.setHeader("Accept", "application/json");
    @SuppressWarnings("unused")
    HttpResponse deleteResponse = null;
    try {
        deleteResponse = httpClient.execute(deleteRequest);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:pt.lunacloud.http.HttpRequestFactory.java

/**
 * Creates an HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the original request.
 *
 * @param request/*w w w.  ja  va2 s .  c  o m*/
 *            The request to convert to an HttpClient method object.
 * @param previousEntity
 *            The optional, previous HTTP entity to reuse in the new
 *            request.
 * @param context
 *            The execution context of the HTTP method to be executed
 *
 * @return The converted HttpClient method object with any parameters,
 *         headers, etc. from the original request set.
 */
HttpRequestBase createHttpRequest(Request<?> request, ClientConfiguration clientConfiguration,
        HttpEntity previousEntity, ExecutionContext context) {
    URI endpoint = request.getEndpoint();
    String uri = endpoint.toString();
    if (request.getResourcePath() != null && request.getResourcePath().length() > 0) {
        if (request.getResourcePath().startsWith("/")) {
            if (uri.endsWith("/")) {
                uri = uri.substring(0, uri.length() - 1);
            }
        } else if (!uri.endsWith("/")) {
            uri += "/";
        }
        uri += request.getResourcePath();
    } else if (!uri.endsWith("/")) {
        uri += "/";
    }

    String encodedParams = HttpUtils.encodeParameters(request);

    /*
     * For all non-POST requests, and any POST requests that already have a
     * payload, we put the encoded params directly in the URI, otherwise,
     * we'll put them in the POST request's payload.
     */
    boolean requestHasNoPayload = request.getContent() != null;
    boolean requestIsPost = request.getHttpMethod() == HttpMethodName.POST;
    boolean putParamsInUri = !requestIsPost || requestHasNoPayload;
    if (encodedParams != null && putParamsInUri) {
        uri += "?" + encodedParams;
    }

    HttpRequestBase httpRequest;
    if (request.getHttpMethod() == HttpMethodName.POST) {
        HttpPost postMethod = new HttpPost(uri);

        /*
         * If there isn't any payload content to include in this request,
         * then try to include the POST parameters in the query body,
         * otherwise, just use the query string. For all AWS Query services,
         * the best behavior is putting the params in the request body for
         * POST requests, but we can't do that for S3.
         */
        if (request.getContent() == null && encodedParams != null) {
            postMethod.setEntity(newStringEntity(encodedParams));
        } else {
            postMethod.setEntity(new RepeatableInputStreamRequestEntity(request));
        }
        httpRequest = postMethod;
    } else if (request.getHttpMethod() == HttpMethodName.PUT) {
        HttpPut putMethod = new HttpPut(uri);
        httpRequest = putMethod;

        /*
         * Enable 100-continue support for PUT operations, since this is
         * where we're potentially uploading large amounts of data and want
         * to find out as early as possible if an operation will fail. We
         * don't want to do this for all operations since it will cause
         * extra latency in the network interaction.
         */
        putMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

        if (previousEntity != null) {
            putMethod.setEntity(previousEntity);
        } else if (request.getContent() != null) {
            HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
            if (request.getHeaders().get("Content-Length") == null) {
                entity = newBufferedHttpEntity(entity);
            }
            putMethod.setEntity(entity);
        }
    } else if (request.getHttpMethod() == HttpMethodName.GET) {
        httpRequest = new HttpGet(uri);
    } else if (request.getHttpMethod() == HttpMethodName.DELETE) {
        httpRequest = new HttpDelete(uri);
    } else if (request.getHttpMethod() == HttpMethodName.HEAD) {
        httpRequest = new HttpHead(uri);
    } else {
        throw new LunacloudClientException("Unknown HTTP method name: " + request.getHttpMethod());
    }

    configureHeaders(httpRequest, request, context, clientConfiguration);

    return httpRequest;
}

From source file:org.eclipse.om2m.binding.http.RestHttpClient.java

/**
 * Converts a protocol-independent {@link RequestPrimitive} object into a standard HTTP request and sends a standard HTTP request.
 * Converts the received standard HTTP request into {@link ResponsePrimitive} object and returns it back.
 * @param requestPrimitive - protocol independent request.
 * @return protocol independent response.
 *//*from ww  w.j  a v  a  2 s.c  o m*/
public ResponsePrimitive sendRequest(RequestPrimitive requestPrimitive) {
    LOGGER.info("Sending request: " + requestPrimitive);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    ResponsePrimitive responsePrimitive = new ResponsePrimitive(requestPrimitive);
    HttpUriRequest method = null;

    // Retrieve the url
    String url = requestPrimitive.getTo();
    if (!url.startsWith(protocol + "://")) {
        if (url.startsWith("://")) {
            url = protocol + url;
        } else if (url.startsWith("//")) {
            url = protocol + ":" + url;
        } else {
            url = protocol + "://" + url;
        }
    }

    Map<String, List<String>> parameters = getParameters(requestPrimitive);
    parameters.putAll(requestPrimitive.getQueryStrings());
    if (!parameters.isEmpty()) {
        String queryString = "";
        for (String parameter : parameters.keySet()) {
            for (String value : parameters.get(parameter)) {
                queryString += "&" + parameter + "=" + value;
            }
        }
        queryString = queryString.replaceFirst("&", "?");
        LOGGER.info("Query string generated: " + queryString);
        url += queryString;
    }

    try {
        // Set the operation
        BigInteger operation = requestPrimitive.getOperation();
        if (operation != null) {
            if (operation.equals(Operation.CREATE)) {
                method = new HttpPost(url);
                if (requestPrimitive.getContent() != null) {
                    ((HttpPost) method).setEntity(new StringEntity((String) requestPrimitive.getContent()));
                }
            } else if (operation.equals(Operation.RETRIEVE)) {
                method = new HttpGet(url);
            } else if (operation.equals(Operation.UPDATE)) {
                method = new HttpPut(url);
                if (requestPrimitive.getContent() != null) {
                    ((HttpPut) method).setEntity(new StringEntity((String) requestPrimitive.getContent()));
                }
            } else if (operation.equals(Operation.DELETE)) {
                method = new HttpDelete(url);
            } else if (operation.equals(Operation.NOTIFY)) {
                method = new HttpPost(url);
                if (requestPrimitive.getContent() != null) {
                    ((HttpPost) method).setEntity(new StringEntity((String) requestPrimitive.getContent()));
                }
            }
        } else {
            return null;
        }

        // Set the return content type
        method.addHeader(HttpHeaders.ACCEPT, requestPrimitive.getReturnContentType());

        // Set the request content type
        String contentTypeHeader = requestPrimitive.getRequestContentType();

        // Set the request identifier header
        if (requestPrimitive.getRequestIdentifier() != null) {
            method.addHeader(HttpHeaders.REQUEST_IDENTIFIER, requestPrimitive.getRequestIdentifier());
        }

        // Set the originator header
        if (requestPrimitive.getFrom() != null) {
            method.addHeader(HttpHeaders.ORIGINATOR, requestPrimitive.getFrom());
        }

        // Add the content type header with the resource type for create operation
        if (requestPrimitive.getResourceType() != null) {
            contentTypeHeader += ";ty=" + requestPrimitive.getResourceType().toString();
        }
        method.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeHeader);

        // Add the notification URI in the case of non-blocking request
        if (requestPrimitive.getResponseTypeInfo() != null) {
            String uris = "";
            for (String notifUri : requestPrimitive.getResponseTypeInfo().getNotificationURI()) {
                uris += "&" + notifUri;
            }
            uris = uris.replaceFirst("&", "");
            method.addHeader(HttpHeaders.RESPONSE_TYPE, uris);
        }

        if (requestPrimitive.getName() != null) {
            method.addHeader(HttpHeaders.NAME, requestPrimitive.getName());
        }

        LOGGER.info("Request to be send: " + method.toString());
        String headers = "";
        for (Header h : method.getAllHeaders()) {
            headers += h.toString() + "\n";
        }
        LOGGER.info("Headers:\n" + headers);

        HttpResponse httpResponse = httpClient.execute(method);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (httpResponse.getFirstHeader(HttpHeaders.RESPONSE_STATUS_CODE) != null) {
            responsePrimitive.setResponseStatusCode(
                    new BigInteger(httpResponse.getFirstHeader(HttpHeaders.RESPONSE_STATUS_CODE).getValue()));
        } else {
            responsePrimitive.setResponseStatusCode(getResponseStatusCode(httpResponse, statusCode));
        }
        if (statusCode != 204) {
            if (httpResponse.getEntity() != null) {
                responsePrimitive.setContent(Util.convertStreamToString(httpResponse.getEntity().getContent()));
                if (httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE) != null) {
                    responsePrimitive
                            .setContentType(httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
                }
            }
        }
        if (statusCode == 201) {
            String contentHeader = "";
            for (Header header : httpResponse.getHeaders(HttpHeaders.CONTENT_LOCATION)) {
                contentHeader += header.getValue();
            }
            responsePrimitive.setLocation(contentHeader);
        }
        LOGGER.info("Http Client response: " + responsePrimitive);
        httpClient.close();
    } catch (HttpHostConnectException e) {
        LOGGER.info("Target is not reachable: " + requestPrimitive.getTo());
        responsePrimitive.setResponseStatusCode(ResponseStatusCode.TARGET_NOT_REACHABLE);
        responsePrimitive.setContent("Target is not reachable: " + requestPrimitive.getTo());
        responsePrimitive.setContentType(MimeMediaType.TEXT_PLAIN);
    } catch (IOException e) {
        LOGGER.error(url + " not found", e);
        responsePrimitive.setResponseStatusCode(ResponseStatusCode.TARGET_NOT_REACHABLE);
    }
    return responsePrimitive;
}

From source file:com.android.providers.downloads.ui.network.ExtHttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*w  w w.  j  a va  2  s. c  o m*/
@SuppressWarnings("deprecation")
/* protected */static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for
        // backwards compatibility.
        // If the request's post body is null, then the assumption is
        // that the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:com.amazon.s3.http.HttpRequestFactory.java

/**
 * Creates an HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the original request.
 * //from w  ww  .  j  a v  a  2  s  .  c  om
 * @param request
 *            The request to convert to an HttpClient method object.
 * @param previousEntity
 *            The optional, previous HTTP entity to reuse in the new
 *            request.
 * @param context
 *            The execution context of the HTTP method to be executed
 * 
 * @return The converted HttpClient method object with any parameters,
 *         headers, etc. from the original request set.
 */
HttpRequestBase createHttpRequest(Request<?> request, ClientConfiguration clientConfiguration,
        HttpEntity previousEntity, ExecutionContext context) {
    URI endpoint = request.getEndpoint();
    String uri = endpoint.toString();
    if (request.getResourcePath() != null && request.getResourcePath().length() > 0) {
        if (request.getResourcePath().startsWith("/")) {
            if (uri.endsWith("/")) {
                uri = uri.substring(0, uri.length() - 1);
            }
        } else if (!uri.endsWith("/")) {
            uri += "/";
        }
        uri += request.getResourcePath();
    } else if (!uri.endsWith("/")) {
        uri += "/";
    }

    String encodedParams = HttpUtils.encodeParameters(request);

    /*
     * For all non-POST requests, and any POST requests that already have a
     * payload, we put the encoded params directly in the URI, otherwise,
     * we'll put them in the POST request's payload.
     */
    boolean requestHasNoPayload = request.getContent() != null;
    boolean requestIsPost = request.getHttpMethod() == HttpMethodName.POST;
    boolean putParamsInUri = !requestIsPost || requestHasNoPayload;
    if (encodedParams != null && putParamsInUri) {
        uri += "?" + encodedParams;
    }

    HttpRequestBase httpRequest;
    if (request.getHttpMethod() == HttpMethodName.POST) {
        HttpPost postMethod = new HttpPost(uri);

        /*
         * If there isn't any payload content to include in this request,
         * then try to include the POST parameters in the query body,
         * otherwise, just use the query string. For all AWS Query services,
         * the best behavior is putting the params in the request body for
         * POST requests, but we can't do that for S3.
         */
        if (request.getContent() == null && encodedParams != null) {
            postMethod.setEntity(newStringEntity(encodedParams));
        } else {
            postMethod.setEntity(new RepeatableInputStreamRequestEntity(request));
        }
        httpRequest = postMethod;
    } else if (request.getHttpMethod() == HttpMethodName.PUT) {
        HttpPut putMethod = new HttpPut(uri);
        httpRequest = putMethod;

        /*
         * Enable 100-continue support for PUT operations, since this is
         * where we're potentially uploading large amounts of data and want
         * to find out as early as possible if an operation will fail. We
         * don't want to do this for all operations since it will cause
         * extra latency in the network interaction.
         */
        putMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

        if (previousEntity != null) {
            putMethod.setEntity(previousEntity);
        } else if (request.getContent() != null) {
            HttpEntity entity = new RepeatableInputStreamRequestEntity(request);
            if (request.getHeaders().get("Content-Length") == null) {
                entity = newBufferedHttpEntity(entity);
            }
            putMethod.setEntity(entity);
        }
    } else if (request.getHttpMethod() == HttpMethodName.GET) {
        httpRequest = new HttpGet(uri);
    } else if (request.getHttpMethod() == HttpMethodName.DELETE) {
        httpRequest = new HttpDelete(uri);
    } else if (request.getHttpMethod() == HttpMethodName.HEAD) {
        httpRequest = new HttpHead(uri);
    } else {
        throw new AmazonClientException("Unknown HTTP method name: " + request.getHttpMethod());
    }

    configureHeaders(httpRequest, request, context, clientConfiguration);

    return httpRequest;
}

From source file:org.fcrepo.auth.roles.basic.integration.AbstractBasicRolesIT.java

protected HttpDelete deleteRolesMethod(final String param) {
    final HttpDelete delete = new HttpDelete(serverAddress + param + "/" + SUFFIX);
    logger.debug("DELETE: {}", delete.getURI());
    return delete;
}