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() 

Source Link

Usage

From source file:com.basho.riak.client.response.TestDefaultHttpResponse.java

@Test
public void status_2xx_and_404_success_for_delete() {
    DeleteMethod delete = new DeleteMethod();

    for (int i = 200; i < 300; i++) {
        impl = new DefaultHttpResponse(null, null, i, null, null, null, delete);
        assertTrue(impl.isSuccess());//ww w .jav  a  2 s. c o  m
    }

    impl = new DefaultHttpResponse(null, null, 404, null, null, null, delete);
    assertTrue(impl.isSuccess());
}

From source file:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java

/**
 * @see it.greenvulcano.gvesb.virtual.CallOperation#perform(it.greenvulcano.gvesb.buffer.GVBuffer)
 *//*from   w w  w.  ja v a 2s.  co  m*/
@Override
public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException {
    logger.debug("BEGIN perform(GVBuffer gvBuffer)");
    HttpMethod method = null;
    try {
        String currMethodURI = null;
        Map<String, Object> params = GVBufferPropertiesHelper.getPropertiesMapSO(gvBuffer, true);

        String currHost = PropertiesHandler.expand(host, params, gvBuffer);
        String currPort = PropertiesHandler.expand(port, params, gvBuffer);
        logger.debug("Server Host: " + currHost + " - Port: " + currPort);
        httpClient.getHostConfiguration().setHost(currHost, Integer.parseInt(currPort), protocol);

        auth.setAuthentication(httpClient, host, Integer.parseInt(currPort), gvBuffer, params);
        proxy.setProxy(httpClient, gvBuffer, params);

        currMethodURI = PropertiesHandler.expand(contextPath + methodURI, params, gvBuffer);
        logger.debug("MethodURI[escaped:" + uriEscaped + "]=[" + currMethodURI + "]");
        switch (methodName) {
        case OPTIONS:
            method = new OptionsMethod();
            break;
        case GET:
            method = new GetMethod();
            break;
        case HEAD:
            method = new HeadMethod();
            break;
        case POST:
            method = new PostMethod();
            break;
        case PUT:
            method = new PutMethod();
            break;
        case DELETE:
            method = new DeleteMethod();
            break;
        default:
            throw new CallException("GV_CALL_SERVICE_ERROR",
                    new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                            { "id", gvBuffer.getId().toString() },
                            { "message", "Unknown method = " + methodName } });
        }
        method.setURI(new URI(currMethodURI, uriEscaped));

        if ((refDP != null) && (refDP.length() > 0)) {
            logger.debug("Calling configured Data Provider: " + refDP);
            DataProviderManager dataProviderManager = DataProviderManager.instance();
            IDataProvider dataProvider = dataProviderManager.getDataProvider(refDP);
            try {
                dataProvider.setContext(method);
                dataProvider.setObject(gvBuffer);
                method = (HttpMethod) dataProvider.getResult();
            } finally {
                dataProviderManager.releaseDataProvider(refDP, dataProvider);
            }
        }

        int status = httpClient.executeMethod(method);
        gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(status));
        String statusTxt = method.getStatusText();
        gvBuffer.setProperty(RESPONSE_MESSAGE, (statusTxt != null ? statusTxt : "NULL"));
        Header[] responseHeaders = method.getResponseHeaders();
        for (Header header : responseHeaders) {
            String headerName = RESPONSE_HEADER_PREFIX + header.getName();
            String value = header.getValue();
            if (value == null) {
                value = "";
            }
            gvBuffer.setProperty(headerName, value);
        }
        String cType = "text/html";
        Header cTypeHeader = method.getResponseHeader("Content-Type");
        if (cTypeHeader != null) {
            String cTypeValue = cTypeHeader.getValue();
            if (cTypeValue != null) {
                cType = cTypeValue;
            }
        }
        logger.debug("Response content-type: " + cType);
        ContentType contentType = new ContentType(cType);
        byte[] responseBody = method.getResponseBody();
        Object object = responseBody;
        if (contentType.getPrimaryType().equals("multipart")) {
            object = handleMultipart(responseBody, cType);
        }
        gvBuffer.setObject(object);
    } catch (CallException exc) {
        throw exc;
    } catch (Exception exc) {
        logger.error("ERROR perform(GVBuffer gvBuffer)", exc);
        throw new CallException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                        { "id", gvBuffer.getId().toString() }, { "message", exc.getMessage() } },
                exc);
    } finally {
        try {
            if (method != null) {
                method.releaseConnection();
            }
        } catch (Exception exc) {
            logger.warn("Error while releasing connection", exc);
        }
        logger.debug("END perform(GVBuffer gvBuffer)");
    }
    return gvBuffer;
}

From source file:com.sa.npopa.samples.hbase.rest.client.Client.java

/**
 * Send a DELETE request// ww  w.ja v a2  s.co m
 * @param cluster the cluster definition
 * @param path the path or URI
 * @return a Response object with response detail
 * @throws IOException
 */
public Response delete(Cluster cluster, String path) throws IOException {
    DeleteMethod method = new DeleteMethod();
    try {
        int code = execute(cluster, method, null, path);
        Header[] headers = method.getResponseHeaders();
        byte[] content = method.getResponseBody();
        return new Response(code, headers, content);
    } finally {
        method.releaseConnection();
    }
}

From source file:net.xmind.signin.internal.XMindNetRequest.java

public XMindNetRequest delete() {
    this.method = new DeleteMethod();
    return execute();
}

From source file:org.apache.axis2.transport.http.HTTPSender.java

/**
 * Used to send a request via HTTP Delete Method
 *
 * @param msgContext        - The MessageContext of the message
 * @param url               - The target URL
 * @param soapActiionString - The soapAction string of the request
 * @throws AxisFault - Thrown in case an exception occurs
 *//*from w  w w  .  ja va2  s. c o m*/
private void sendViaDelete(MessageContext msgContext, URL url, String soapActiionString) throws AxisFault {

    DeleteMethod deleteMethod = new DeleteMethod();
    HttpClient httpClient = getHttpClient(msgContext);
    populateCommonProperties(msgContext, url, deleteMethod, httpClient, soapActiionString);

    try {
        executeMethod(httpClient, msgContext, url, deleteMethod);
        handleResponse(msgContext, deleteMethod);
    } catch (IOException e) {
        log.info("Unable to sendViaDelete to url[" + url + "]", e);
        throw AxisFault.makeFault(e);
    } finally {
        cleanup(msgContext, deleteMethod);
    }
}

From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java

/**
 * Used to send a request via HTTP Delete Method
 * // w  w  w  .j a  va 2s  .  c o  m
 * @param msgContext
 *            - The MessageContext of the message
 * @param url
 *            - The target URL
 * @param soapActiionString
 *            - The soapAction string of the request
 * @throws AxisFault
 *             - Thrown in case an exception occurs
 */
protected void sendViaDelete(MessageContext msgContext, URL url, String soapActiionString) throws AxisFault {

    DeleteMethod deleteMethod = new DeleteMethod();
    HttpClient httpClient = getHttpClient(msgContext);
    populateCommonProperties(msgContext, url, deleteMethod, httpClient, soapActiionString);

    try {
        executeMethod(httpClient, msgContext, url, deleteMethod);
        handleResponse(msgContext, deleteMethod);
    } catch (IOException e) {
        log.info("Unable to sendViaDelete to url[" + url + "]", e);
        throw AxisFault.makeFault(e);
    } finally {
        cleanup(msgContext, deleteMethod);
    }
}

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java

/**
 * create and initialize the http method.
 * Http Headers that may been passed in the params are not set in this method.
 * Headers will be automatically set by HttpClient.
 * See usages of HostParams.DEFAULT_HEADERS
 * See org.apache.commons.httpclient.HttpMethodDirector#executeMethod(org.apache.commons.httpclient.HttpMethod)
 */// w  ww.  j  av a2s.co m
protected HttpMethod prepareHttpMethod(BindingOperation opBinding, String verb, Map<String, Element> partValues,
        Map<String, Node> headers, final String rootUri, HttpParams params)
        throws UnsupportedEncodingException {
    if (log.isDebugEnabled())
        log.debug("Preparing http request...");
    // convenience variables...
    BindingInput bindingInput = opBinding.getBindingInput();
    HTTPOperation httpOperation = (HTTPOperation) WsdlUtils.getOperationExtension(opBinding);
    MIMEContent content = WsdlUtils.getMimeContent(bindingInput.getExtensibilityElements());
    String contentType = content == null ? null : content.getType();
    boolean useUrlEncoded = WsdlUtils.useUrlEncoded(bindingInput)
            || PostMethod.FORM_URL_ENCODED_CONTENT_TYPE.equalsIgnoreCase(contentType);
    boolean useUrlReplacement = WsdlUtils.useUrlReplacement(bindingInput);

    // the http method to be built and returned
    HttpMethod method = null;

    // the 4 elements the http method may be made of
    String relativeUri = httpOperation.getLocationURI();
    String queryPath = null;
    RequestEntity requestEntity;
    String encodedParams = null;

    // ODE supports uri template in both port and operation location.
    // so assemble the final url *before* replacement
    String completeUri = rootUri;
    if (StringUtils.isNotEmpty(relativeUri)) {
        completeUri = completeUri + (completeUri.endsWith("/") || relativeUri.startsWith("/") ? "" : "/")
                + relativeUri;
    }

    if (useUrlReplacement) {
        // insert part values in the url
        completeUri = new UrlReplacementTransformer().transform(completeUri, partValues);
    } else if (useUrlEncoded) {
        // encode part values
        encodedParams = new URLEncodedTransformer().transform(partValues);
    }

    // http-client api is not really neat
    // something similar to the following would save some if/else manipulations.
    // But we have to deal with it as-is.
    //
    //  method = new Method(verb);
    //  method.setRequestEnity(..)
    //  etc...
    if ("GET".equalsIgnoreCase(verb) || "DELETE".equalsIgnoreCase(verb)) {
        if ("GET".equalsIgnoreCase(verb)) {
            method = new GetMethod();
        } else if ("DELETE".equalsIgnoreCase(verb)) {
            method = new DeleteMethod();
        }
        method.getParams().setDefaults(params);
        if (useUrlEncoded) {
            queryPath = encodedParams;
        }

        // Let http-client manage the redirection
        // see org.apache.commons.httpclient.params.HttpClientParams.MAX_REDIRECTS
        // default is 100
        method.setFollowRedirects(true);
    } else if ("POST".equalsIgnoreCase(verb) || "PUT".equalsIgnoreCase(verb)) {

        if ("POST".equalsIgnoreCase(verb)) {
            method = new PostMethod();
        } else if ("PUT".equalsIgnoreCase(verb)) {
            method = new PutMethod();
        }
        method.getParams().setDefaults(params);
        // some body-building...
        final String contentCharset = method.getParams().getContentCharset();
        if (log.isDebugEnabled())
            log.debug("Content-Type [" + contentType + "] Charset [" + contentCharset + "]");
        if (useUrlEncoded) {
            requestEntity = new StringRequestEntity(encodedParams, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE,
                    contentCharset);
        } else {
            // get the part to be put in the body
            Part part = opBinding.getOperation().getInput().getMessage().getPart(content.getPart());
            Element partValue = partValues.get(part.getName());

            if (part.getElementName() == null) {
                String errMsg = "XML Types are not supported. Parts must use elements.";
                if (log.isErrorEnabled())
                    log.error(errMsg);
                throw new RuntimeException(errMsg);
            } else if (HttpUtils.isXml(contentType)) {
                if (log.isDebugEnabled())
                    log.debug("Content-Type [" + contentType + "] equivalent to 'text/xml'");
                // stringify the first element
                String xmlString = DOMUtils.domToString(DOMUtils.getFirstChildElement(partValue));
                requestEntity = new StringRequestEntity(xmlString, contentType, contentCharset);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Content-Type [" + contentType
                            + "] NOT equivalent to 'text/xml'. The text content of part value will be sent as text");
                // encoding conversion is managed by StringRequestEntity if necessary
                requestEntity = new StringRequestEntity(DOMUtils.getTextContent(partValue), contentType,
                        contentCharset);
            }
        }

        // cast safely, PUT and POST are subclasses of EntityEnclosingMethod
        final EntityEnclosingMethod enclosingMethod = (EntityEnclosingMethod) method;
        enclosingMethod.setRequestEntity(requestEntity);
        enclosingMethod
                .setContentChunked(params.getBooleanParameter(Properties.PROP_HTTP_REQUEST_CHUNK, false));

    } else {
        // should not happen because of HttpBindingValidator, but never say never
        throw new IllegalArgumentException("Unsupported HTTP method: " + verb);
    }

    method.setPath(completeUri); // assumes that the path is properly encoded (URL safe).
    method.setQueryString(queryPath);

    // set headers
    setHttpRequestHeaders(method, opBinding, partValues, headers, params);
    return method;
}

From source file:org.apache.wink.itest.methodannotations.HttpMethodWarningsTest.java

/**
 * Tests that non-public HttpMethod annotations generate a warning.
 *///from  w ww. ja  v a2  s .  co  m
public void testNonPublicMethodsWarning() {
    try {
        GetMethod httpMethod = new GetMethod();
        httpMethod.setURI(new URI(BASE_URI + "/abcd", false));
        httpclient = new HttpClient();

        try {
            int result = httpclient.executeMethod(httpMethod);
            System.out.println("Response status code: " + result);
            System.out.println("Response body: ");
            String responseBody = httpMethod.getResponseBodyAsString();
            System.out.println(responseBody);
            assertEquals(404, result);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail(ioe.getMessage());
        } finally {
            httpMethod.releaseConnection();
        }
    } catch (URIException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    try {
        DeleteMethod httpMethod = new DeleteMethod();
        httpMethod.setURI(new URI(BASE_URI, false));
        httpclient = new HttpClient();

        try {
            int result = httpclient.executeMethod(httpMethod);
            System.out.println("Response status code: " + result);
            System.out.println("Response body: ");
            String responseBody = httpMethod.getResponseBodyAsString();
            System.out.println(responseBody);
            /*
             * if a filter is used, then the 404 will fall through to the
             * container
             */
            assertTrue("The result is " + result,
                    (result == 403 && "tomcat".equals(ServerEnvironmentInfo.getContainerName()))
                            || result == 405 || result == 404);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail(ioe.getMessage());
        } finally {
            httpMethod.releaseConnection();
        }
    } catch (URIException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:org.easyj.http.RESTHttpClient.java

/**
 * Executes a DELETE HTTP request and returns the body response as {@code String}
 *
 * @param uri URI of the resource to be requested
 * @return The body response of the request as {@code String}
 *//* ww  w.  ja va 2s .  com*/
public RESTHttpClient delete(String uri) {
    method = new DeleteMethod();
    return execute(uri);
}

From source file:org.eclipse.swordfish.internal.resolver.backend.base.impl.HttpClientProxy.java

protected HttpMethod getMethod(Method method) {
    HttpMethod result = null;//w w  w  .j  ava  2 s  .co  m

    if (method.equals(Method.GET)) {
        result = new GetMethod();
    } else if (method.equals(Method.POST)) {
        result = new PostMethod();
    } else if (method.equals(Method.DELETE)) {
        result = new DeleteMethod();
    } else if (method.equals(Method.PUT)) {
        result = new PutMethod();
    }
    return result;
}