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.apache.wookie.tests.functional.WidgetAccessRequestPolicyControllerTest.java

@Test
public void deletePolicy() {
    try {/*from w  ww .  java2 s . co  m*/
        HttpClient client = new HttpClient();
        setAuthenticationCredentials(client);
        DeleteMethod del = new DeleteMethod(TEST_WARP_SERVICE_URL_VALID + "/" + id);
        del.setDoAuthentication(true);
        client.executeMethod(del);
        int code = del.getStatusCode();
        assertEquals(200, code);
        del.releaseConnection();
    } catch (Exception e) {
        e.printStackTrace();
        fail("put failed");
    }
    // Now lets make sure it was deleted OK
    Element[] policies = getPolicies();
    for (Element policy : policies) {
        if (policy.getAttribute("id").getValue().equals(id)) {
            fail("Policy was not deleted");
        }
    }
}

From source file:org.apache.wookie.tests.functional.WidgetServicesControllerTest.java

@Test
public void deleteService() {
    try {//from w  w  w . ja va 2  s.c o  m
        HttpClient client = new HttpClient();
        setAuthenticationCredentials(client);
        DeleteMethod del = new DeleteMethod(TEST_SERVICES_SERVICE_URL_VALID + "/test2");
        del.setDoAuthentication(true);
        client.executeMethod(del);
        int code = del.getStatusCode();
        assertEquals(200, code);
        del.releaseConnection();
    } catch (Exception e) {
        e.printStackTrace();
        fail("put failed");
    }
    // Now lets GET it to make sure it was deleted OK
    try {
        HttpClient client = new HttpClient();
        GetMethod get = new GetMethod(TEST_SERVICES_SERVICE_URL_VALID + "/test2");
        client.executeMethod(get);
        int code = get.getStatusCode();
        assertEquals(404, code);
        get.releaseConnection();
    } catch (Exception e) {
        e.printStackTrace();
        fail("get failed");
    }
}

From source file:org.apache.wookie.tests.functional.WidgetServicesControllerTest.java

@Test
public void deleteServiceNoAuth() {
    try {/*  w ww .j av a 2s  .c om*/
        HttpClient client = new HttpClient();
        DeleteMethod del = new DeleteMethod(TEST_SERVICES_SERVICE_URL_VALID + "/test2");
        del.setQueryString("name=test2");
        client.executeMethod(del);
        int code = del.getStatusCode();
        assertEquals(401, code);
        del.releaseConnection();
    } catch (Exception e) {
        e.printStackTrace();
        fail("put failed");
    }
}

From source file:org.apache.wookie.tests.functional.WidgetServicesControllerTest.java

@Test
public void addServiceAlreadyExists() {
    try {//from  w w w .  j  a  v  a  2 s .c  om
        HttpClient client = new HttpClient();
        setAuthenticationCredentials(client);
        PostMethod post = new PostMethod(TEST_SERVICES_SERVICE_URL_VALID + "/test_add2");
        post.setDoAuthentication(true);
        client.executeMethod(post);
        int code = post.getStatusCode();
        assertEquals(201, code);
        post.releaseConnection();
    } catch (Exception e) {
        e.printStackTrace();
        fail("post failed");
    }
    try {
        HttpClient client = new HttpClient();
        setAuthenticationCredentials(client);
        PostMethod post = new PostMethod(TEST_SERVICES_SERVICE_URL_VALID + "/test_add2");
        post.setDoAuthentication(true);
        client.executeMethod(post);
        int code = post.getStatusCode();
        assertEquals(409, code);
        post.releaseConnection();
    } catch (Exception e) {
        e.printStackTrace();
        fail("post failed");
    }
    // clean up
    try {
        HttpClient client = new HttpClient();
        setAuthenticationCredentials(client);
        DeleteMethod del = new DeleteMethod(TEST_SERVICES_SERVICE_URL_VALID + "/test_add2");
        del.setDoAuthentication(true);
        client.executeMethod(del);
        int code = del.getStatusCode();
        assertEquals(200, code);
        del.releaseConnection();
    } catch (Exception e) {
        e.printStackTrace();
        fail("put failed");
    }
}

From source file:org.apache.wookie.tests.functional.WidgetServicesControllerTest.java

@Test
public void deleteServiceNonExists() {
    try {//from  w  w w  .jav  a  2s. c  om
        HttpClient client = new HttpClient();
        setAuthenticationCredentials(client);
        DeleteMethod del = new DeleteMethod(TEST_SERVICES_SERVICE_URL_VALID + "/test999");
        del.setDoAuthentication(true);
        client.executeMethod(del);
        int code = del.getStatusCode();
        assertEquals(404, code);
        del.releaseConnection();
    } catch (Exception e) {
        e.printStackTrace();
        fail("put failed");
    }
}

From source file:org.apache.zeppelin.rest.AbstractTestRestApi.java

protected static DeleteMethod httpDelete(String path) throws IOException {
    LOG.info("Connecting to {}", url + path);
    HttpClient httpClient = new HttpClient();
    DeleteMethod deleteMethod = new DeleteMethod(url + path);
    deleteMethod.addRequestHeader("Origin", url);
    httpClient.executeMethod(deleteMethod);
    LOG.info("{} - {}", deleteMethod.getStatusCode(), deleteMethod.getStatusText());
    return deleteMethod;
}

From source file:org.appcelerator.transport.ProxyTransportServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String method = request.getMethod();
    String url = request.getParameter("url");
    if (url == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;//ww w. ja  v a 2 s  .co  m
    }

    url = URLDecoder.decode(url, "UTF-8");

    if (url.indexOf("://") == -1) {
        url = new String(Base64.decode(url));
    }

    HttpClient client = new HttpClient();
    HttpMethodBase methodBase = null;

    if (method.equalsIgnoreCase("POST")) {
        methodBase = new PostMethod(url);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Util.copy(request.getInputStream(), out);
        ByteArrayRequestEntity req = new ByteArrayRequestEntity(out.toByteArray());
        ((PostMethod) methodBase).setRequestEntity(req);
    } else if (method.equalsIgnoreCase("GET")) {
        methodBase = new GetMethod(url);
        methodBase.setFollowRedirects(true);
    } else if (method.equalsIgnoreCase("PUT")) {
        methodBase = new PutMethod(url);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Util.copy(request.getInputStream(), out);
        ByteArrayRequestEntity req = new ByteArrayRequestEntity(out.toByteArray());
        ((PutMethod) methodBase).setRequestEntity(req);
    } else if (method.equalsIgnoreCase("DELETE")) {
        methodBase = new DeleteMethod(url);
    } else if (method.equalsIgnoreCase("OPTIONS")) {
        methodBase = new OptionsMethod(url);
    }

    methodBase.setRequestHeader("User-Agent", request.getHeader("user-agent") + " (Appcelerator Proxy)");

    if (LOG.isDebugEnabled()) {
        LOG.debug("Proxying url: " + url + ", method: " + method);
    }

    int status = client.executeMethod(methodBase);

    response.setStatus(status);
    response.setContentLength((int) methodBase.getResponseContentLength());

    for (Header header : methodBase.getResponseHeaders()) {
        String name = header.getName();
        if (name.equalsIgnoreCase("Set-Cookie") == false && name.equals("Transfer-Encoding") == false) {
            response.setHeader(name, header.getValue());
        }
    }
    InputStream in = methodBase.getResponseBodyAsStream();
    Util.copy(in, response.getOutputStream());
}

From source file:org.artifactory.cli.rest.RestClient.java

public static byte[] delete(String uri, int expectedStatus, String expectedResultType, boolean printStream,
        int timeout, Credentials credentials) throws IOException {
    DeleteMethod method;//w w  w  .ja v a 2s  .  com
    try {
        method = new DeleteMethod(uri);
    } catch (IllegalStateException ise) {
        throw new RemoteCommandException("\nAn error has occurred while trying to resolve the given url: " + uri
                + "\n" + ise.getMessage());
    }
    return executeMethod(uri, method, expectedStatus, expectedResultType, timeout, credentials, printStream);
}

From source file:org.asynchttpclient.providers.apache.ApacheAsyncHttpProvider.java

private HttpMethodBase createMethod(HttpClient client, Request request)
        throws IOException, FileNotFoundException {
    String methodName = request.getMethod();
    HttpMethodBase method = null;/*from w w  w . ja va  2  s.c o m*/
    if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
        EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl())
                : new PutMethod(request.getUrl());

        String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

        post.getParams().setContentCharset("ISO-8859-1");
        if (request.getByteData() != null) {
            post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData()));
            post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length));
        } else if (request.getStringData() != null) {
            post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset));
            post.setRequestHeader("Content-Length",
                    String.valueOf(request.getStringData().getBytes(bodyCharset).length));
        } else if (request.getStreamData() != null) {
            InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData());
            post.setRequestEntity(r);
            post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));

        } else if (request.getParams() != null) {
            StringBuilder sb = new StringBuilder();
            for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
                final String key = paramEntry.getKey();
                for (final String value : paramEntry.getValue()) {
                    if (sb.length() > 0) {
                        sb.append("&");
                    }
                    UTF8UrlEncoder.appendEncoded(sb, key);
                    sb.append("=");
                    UTF8UrlEncoder.appendEncoded(sb, value);
                }
            }

            post.setRequestHeader("Content-Length", String.valueOf(sb.length()));
            post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1"));

            if (!request.getHeaders().containsKey("Content-Type")) {
                post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
        } else if (request.getParts() != null) {
            MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(),
                    post.getParams());
            post.setRequestEntity(mre);
            post.setRequestHeader("Content-Type", mre.getContentType());
            post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength()));
        } else if (request.getEntityWriter() != null) {
            post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(),
                    computeAndSetContentLength(request, post)));
        } else if (request.getFile() != null) {
            File file = request.getFile();
            if (!file.isFile()) {
                throw new IOException(
                        String.format(Thread.currentThread() + "File %s is not a file or doesn't exist",
                                file.getAbsolutePath()));
            }
            post.setRequestHeader("Content-Length", String.valueOf(file.length()));

            FileInputStream fis = new FileInputStream(file);
            try {
                InputStreamRequestEntity r = new InputStreamRequestEntity(fis);
                post.setRequestEntity(r);
                post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));
            } finally {
                fis.close();
            }
        } else if (request.getBodyGenerator() != null) {
            Body body = request.getBodyGenerator().createBody();
            try {
                int length = (int) body.getContentLength();
                if (length < 0) {
                    length = (int) request.getContentLength();
                }

                // TODO: This is suboptimal
                if (length >= 0) {
                    post.setRequestHeader("Content-Length", String.valueOf(length));

                    // This is totally sub optimal
                    byte[] bytes = new byte[length];
                    ByteBuffer buffer = ByteBuffer.wrap(bytes);
                    for (;;) {
                        buffer.clear();
                        if (body.read(buffer) < 0) {
                            break;
                        }
                    }
                    post.setRequestEntity(new ByteArrayRequestEntity(bytes));
                }
            } finally {
                try {
                    body.close();
                } catch (IOException e) {
                    logger.warn("Failed to close request body: {}", e.getMessage(), e);
                }
            }
        }

        String expect = request.getHeaders().getFirstValue("Expect");
        if (expect != null && expect.equalsIgnoreCase("100-Continue")) {
            post.setUseExpectHeader(true);
        }
        method = post;
    } else if (methodName.equalsIgnoreCase("DELETE")) {
        method = new DeleteMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("HEAD")) {
        method = new HeadMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("GET")) {
        method = new GetMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("OPTIONS")) {
        method = new OptionsMethod(request.getUrl());
    } else {
        throw new IllegalStateException(String.format("Invalid Method", methodName));
    }

    ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request);
    if (proxyServer != null) {

        if (proxyServer.getPrincipal() != null) {
            Credentials defaultcreds = new UsernamePasswordCredentials(proxyServer.getPrincipal(),
                    proxyServer.getPassword());
            client.getState().setProxyCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);
        }

        ProxyHost proxyHost = proxyServer == null ? null
                : new ProxyHost(proxyServer.getHost(), proxyServer.getPort());
        client.getHostConfiguration().setProxyHost(proxyHost);
    }
    if (request.getLocalAddress() != null) {
        client.getHostConfiguration().setLocalAddress(request.getLocalAddress());
    }

    method.setFollowRedirects(false);
    Collection<Cookie> cookies = request.getCookies();
    if (isNonEmpty(cookies)) {
        method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
    }

    if (request.getHeaders() != null) {
        for (String name : request.getHeaders().keySet()) {
            if (!"host".equalsIgnoreCase(name)) {
                for (String value : request.getHeaders().get(name)) {
                    method.setRequestHeader(name, value);
                }
            }
        }
    }

    String ua = request.getHeaders().getFirstValue("User-Agent");
    if (ua != null) {
        method.setRequestHeader("User-Agent", ua);
    } else if (config.getUserAgent() != null) {
        method.setRequestHeader("User-Agent", config.getUserAgent());
    } else {
        method.setRequestHeader("User-Agent",
                AsyncHttpProviderUtils.constructUserAgent(ApacheAsyncHttpProvider.class, config));
    }

    if (config.isCompressionEnabled()) {
        Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding");
        if (acceptableEncodingHeader != null) {
            String acceptableEncodings = acceptableEncodingHeader.getValue();
            if (acceptableEncodings.indexOf("gzip") == -1) {
                StringBuilder buf = new StringBuilder(acceptableEncodings);
                if (buf.length() > 1) {
                    buf.append(",");
                }
                buf.append("gzip");
                method.setRequestHeader("Accept-Encoding", buf.toString());
            }
        } else {
            method.setRequestHeader("Accept-Encoding", "gzip");
        }
    }

    if (request.getVirtualHost() != null) {

        String vs = request.getVirtualHost();
        int index = vs.indexOf(":");
        if (index > 0) {
            vs = vs.substring(0, index);
        }
        method.getParams().setVirtualHost(vs);
    }

    return method;
}

From source file:org.attribyte.api.http.impl.commons.Commons3Client.java

@Override
public Response send(Request request, RequestOptions options) throws IOException {

    HttpMethod method = null;//  w  ww  .  j a  va  2  s.  c  o  m

    switch (request.getMethod()) {
    case GET:
        method = new GetMethod(request.getURI().toString());
        method.setFollowRedirects(options.followRedirects);
        break;
    case DELETE:
        method = new DeleteMethod(request.getURI().toString());
        break;
    case HEAD:
        method = new HeadMethod(request.getURI().toString());
        method.setFollowRedirects(options.followRedirects);
        break;
    case POST:
        method = new PostMethod(request.getURI().toString());
        if (request.getBody() != null) {
            ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(request.getBody().toByteArray());
            ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
        } else {
            PostMethod postMethod = (PostMethod) method;
            Collection<Parameter> parameters = request.getParameters();
            for (Parameter parameter : parameters) {
                String[] values = parameter.getValues();
                for (String value : values) {
                    postMethod.addParameter(parameter.getName(), value);
                }
            }
        }
        break;
    case PUT:
        method = new PutMethod(request.getURI().toString());
        if (request.getBody() != null) {
            ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(request.getBody().toByteArray());
            ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
        }
        break;
    }

    if (userAgent != null && Strings.isNullOrEmpty(request.getHeaderValue("User-Agent"))) {
        method.setRequestHeader("User-Agent", userAgent);
    }

    Collection<Header> headers = request.getHeaders();
    for (Header header : headers) {
        String[] values = header.getValues();
        for (String value : values) {
            method.setRequestHeader(header.getName(), value);
        }
    }

    int responseCode;
    InputStream is = null;

    try {
        responseCode = httpClient.executeMethod(method);
        is = method.getResponseBodyAsStream();
        if (is != null) {
            byte[] body = Request.bodyFromInputStream(is, options.maxResponseBytes);
            ResponseBuilder builder = new ResponseBuilder();
            builder.setStatusCode(responseCode);
            builder.addHeaders(getMap(method.getResponseHeaders()));
            return builder.setBody(body.length != 0 ? body : null).create();
        } else {
            ResponseBuilder builder = new ResponseBuilder();
            builder.setStatusCode(responseCode);
            builder.addHeaders(getMap(method.getResponseHeaders()));
            return builder.create();
        }

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioe) {
                //Ignore
            }
        }
        method.releaseConnection();
    }
}