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:com.twinsoft.convertigo.beans.connectors.HttpConnector.java

public byte[] getData(Context context) throws IOException, EngineException {
    HttpMethod method = null;/*www  .  jav  a 2  s. com*/

    try {
        // Fire event for plugins
        long t0 = System.currentTimeMillis();
        Engine.theApp.pluginsManager.fireHttpConnectorGetDataStart(context);

        // Retrieving httpState
        getHttpState(context);

        Engine.logBeans.trace("(HttpConnector) Retrieving data as a bytes array...");
        Engine.logBeans.debug("(HttpConnector) Connecting to: " + sUrl);

        // Setting the referer
        referer = sUrl;

        URL url = null;
        url = new URL(sUrl);

        // Proxy configuration
        Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);

        Engine.logBeans.debug("(HttpConnector) Https: " + https);

        String host = "";
        int port = -1;
        if (sUrl.toLowerCase().startsWith("https:")) {
            if (!https) {
                Engine.logBeans.debug("(HttpConnector) Setting up SSL properties");
                certificateManager.collectStoreInformation(context);
            }

            url = new URL(sUrl);
            host = url.getHost();
            port = url.getPort();
            if (port == -1)
                port = 443;

            Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port);

            Engine.logBeans
                    .debug("(HttpConnector) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost()))
                    || (hostConfiguration.getPort() != port)) {
                Engine.logBeans.debug("(HttpConnector) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https",
                        MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                                certificateManager.keyStorePassword, certificateManager.trustStore,
                                certificateManager.trustStorePassword, this.trustAllServerCertificates),
                        port);

                hostConfiguration.setHost(host, port, myhttps);
            }

            sUrl = url.getFile();
            Engine.logBeans.debug("(HttpConnector) Updated URL for SSL purposes: " + sUrl);
        } else {
            url = new URL(sUrl);
            host = url.getHost();
            port = url.getPort();

            Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port);
            hostConfiguration.setHost(host, port);
        }
        AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) context.transaction;

        // Retrieve HTTP method
        HttpMethodType httpVerb = httpTransaction.getHttpVerb();
        String sHttpVerb = httpVerb.name();
        final String sCustomHttpVerb = httpTransaction.getCustomHttpVerb();

        if (sCustomHttpVerb.length() > 0) {
            Engine.logBeans.debug(
                    "(HttpConnector) HTTP verb: " + sHttpVerb + " overridden to '" + sCustomHttpVerb + "'");

            switch (httpVerb) {
            case GET:
                method = new GetMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case POST:
                method = new PostMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case PUT:
                method = new PutMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case DELETE:
                method = new DeleteMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case HEAD:
                method = new HeadMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case OPTIONS:
                method = new OptionsMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case TRACE:
                method = new TraceMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            }
        } else {
            Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb);

            switch (httpVerb) {
            case GET:
                method = new GetMethod(sUrl);
                break;
            case POST:
                method = new PostMethod(sUrl);
                break;
            case PUT:
                method = new PutMethod(sUrl);
                break;
            case DELETE:
                method = new DeleteMethod(sUrl);
                break;
            case HEAD:
                method = new HeadMethod(sUrl);
                break;
            case OPTIONS:
                method = new OptionsMethod(sUrl);
                break;
            case TRACE:
                method = new TraceMethod(sUrl);
                break;
            }
        }

        // Setting HTTP parameters
        boolean hasUserAgent = false;

        for (List<String> httpParameter : httpParameters) {
            String key = httpParameter.get(0);
            String value = httpParameter.get(1);
            if (key.equalsIgnoreCase("host") && !value.equals(host)) {
                value = host;
            }

            if (!key.startsWith(DYNAMIC_HEADER_PREFIX)) {
                method.setRequestHeader(key, value);
            }
            if (HeaderName.UserAgent.is(key)) {
                hasUserAgent = true;
            }
        }

        // set user-agent header if not found
        if (!hasUserAgent) {
            HeaderName.UserAgent.setRequestHeader(method, getUserAgent(context));
        }

        // Setting POST or PUT parameters if any
        Engine.logBeans.debug("(HttpConnector) Setting " + httpVerb + " data");
        if (method instanceof EntityEnclosingMethod) {
            EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) method;
            AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject;

            if (doMultipartFormData) {
                RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction
                        .getVariable(Parameter.HttpBody.getName());
                if (body != null && body.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) {
                    String stringValue = httpTransaction.getParameterStringValue(Parameter.HttpBody.getName());
                    String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue,
                            getProject().getName());
                    File file = new File(filepath);
                    if (file.exists()) {
                        HeaderName.ContentType.setRequestHeader(method, contentType);
                        entityEnclosingMethod.setRequestEntity(new FileRequestEntity(file, contentType));
                    } else {
                        throw new FileNotFoundException(file.getAbsolutePath());
                    }
                } else {
                    List<Part> parts = new LinkedList<Part>();

                    for (RequestableVariable variable : transaction.getVariablesList()) {
                        if (variable instanceof RequestableHttpVariable) {
                            RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable;

                            if ("POST".equals(httpVariable.getHttpMethod())) {
                                Object httpObjectVariableValue = transaction
                                        .getVariableValue(httpVariable.getName());

                                if (httpVariable.isMultiValued()) {
                                    if (httpObjectVariableValue instanceof Collection<?>) {
                                        for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                                            addFormDataPart(parts, httpVariable, httpVariableValue);
                                        }
                                    }
                                } else {
                                    addFormDataPart(parts, httpVariable, httpObjectVariableValue);
                                }
                            }
                        }
                    }
                    MultipartRequestEntity mre = new MultipartRequestEntity(
                            parts.toArray(new Part[parts.size()]), entityEnclosingMethod.getParams());
                    HeaderName.ContentType.setRequestHeader(method, mre.getContentType());
                    entityEnclosingMethod.setRequestEntity(mre);
                }
            } else if (MimeType.TextXml.is(contentType)) {
                final MimeMultipart[] mp = { null };

                for (RequestableVariable variable : transaction.getVariablesList()) {
                    if (variable instanceof RequestableHttpVariable) {
                        RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable;

                        if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.MTOM) {
                            Engine.logBeans.trace(
                                    "(HttpConnector) Variable " + httpVariable.getName() + " detected as MTOM");

                            MimeMultipart mimeMultipart = mp[0];
                            try {
                                if (mimeMultipart == null) {
                                    Engine.logBeans.debug("(HttpConnector) Preparing the MTOM request");

                                    mimeMultipart = new MimeMultipart("related; type=\"application/xop+xml\"");
                                    MimeBodyPart bp = new MimeBodyPart();
                                    bp.setText(postQuery, "UTF-8");
                                    bp.setHeader(HeaderName.ContentType.value(), contentType);
                                    mimeMultipart.addBodyPart(bp);
                                }

                                Object httpObjectVariableValue = transaction
                                        .getVariableValue(httpVariable.getName());

                                if (httpVariable.isMultiValued()) {
                                    if (httpObjectVariableValue instanceof Collection<?>) {
                                        for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                                            addMtomPart(mimeMultipart, httpVariable, httpVariableValue);
                                        }
                                    }
                                } else {
                                    addMtomPart(mimeMultipart, httpVariable, httpObjectVariableValue);
                                }
                                mp[0] = mimeMultipart;
                            } catch (Exception e) {
                                Engine.logBeans.warn(
                                        "(HttpConnector) Failed to add MTOM part for " + httpVariable.getName(),
                                        e);
                            }
                        }
                    }
                }

                if (mp[0] == null) {
                    entityEnclosingMethod.setRequestEntity(
                            new StringRequestEntity(postQuery, MimeType.TextXml.value(), "UTF-8"));
                } else {
                    Engine.logBeans.debug("(HttpConnector) Commit the MTOM request with the ContentType: "
                            + mp[0].getContentType());

                    HeaderName.ContentType.setRequestHeader(method, mp[0].getContentType());
                    entityEnclosingMethod.setRequestEntity(new RequestEntity() {

                        @Override
                        public void writeRequest(OutputStream outputStream) throws IOException {
                            try {
                                mp[0].writeTo(outputStream);
                            } catch (MessagingException e) {
                                new IOException(e);
                            }
                        }

                        @Override
                        public boolean isRepeatable() {
                            return true;
                        }

                        @Override
                        public String getContentType() {
                            return mp[0].getContentType();
                        }

                        @Override
                        public long getContentLength() {
                            return -1;
                        }
                    });
                }
            } else {
                String charset = httpTransaction.getComputedUrlEncodingCharset();
                HeaderName.ContentType.setRequestHeader(method, contentType);
                entityEnclosingMethod
                        .setRequestEntity(new StringRequestEntity(postQuery, contentType, charset));
            }
        }

        // Getting the result
        Engine.logBeans.debug("(HttpConnector) HttpClient: getting response body");
        byte[] result = executeMethod(method, context);
        Engine.logBeans.debug("(HttpConnector) Total read bytes: " + ((result != null) ? result.length : 0));

        // Fire event for plugins
        long t1 = System.currentTimeMillis();
        Engine.theApp.pluginsManager.fireHttpConnectorGetDataEnd(context, t0, t1);

        fireDataChanged(new ConnectorEvent(this, result));

        return result;
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:fedora.test.api.TestRESTAPI.java

private HttpResponse getOrDelete(String method, boolean authenticate) throws Exception {
    if (url == null || url.length() == 0) {
        throw new IllegalArgumentException("url must be a non-empty value");
    } else if (!(url.startsWith("http://") || url.startsWith("https://"))) {
        url = getBaseURL() + url;//from   w  w  w  .  j a va 2 s  .c om
    }
    HttpMethod httpMethod = null;
    try {
        if (method.equals("GET")) {
            httpMethod = new GetMethod(url);
        } else if (method.equals("DELETE")) {
            httpMethod = new DeleteMethod(url);
        } else {
            throw new IllegalArgumentException("method must be one of GET or DELETE.");
        }

        httpMethod.setDoAuthentication(authenticate);
        httpMethod.getParams().setParameter("Connection", "Keep-Alive");
        getClient(authenticate).executeMethod(httpMethod);
        return new HttpResponse(httpMethod);
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

@Test
public void testAndroidMeetingSeries() throws Exception {
    Account dav1 = users[1].create();//from  w  w w  . jav a  2  s .  c o  m
    Account dav2 = users[2].create();
    users[2].getZMailbox(); // Force creation of mailbox - shouldn't be needed
    String calFolderUrl = getFolderUrl(dav1, "Calendar").replaceAll("@", "%40");
    String url = String.format("%s%s.ics", calFolderUrl, androidSeriesMeetingUid);
    HttpClient client = new HttpClient();
    PutMethod putMethod = new PutMethod(url);
    addBasicAuthHeaderForUser(putMethod, dav1);
    putMethod.addRequestHeader("Content-Type", "text/calendar");

    String body = androidSeriesMeetingTemplate.replace("%%ORG%%", dav1.getName())
            .replace("%%ATT%%", dav2.getName()).replace("%%UID%%", androidSeriesMeetingUid);
    putMethod.setRequestEntity(new ByteArrayRequestEntity(body.getBytes(), MimeConstants.CT_TEXT_CALENDAR));
    HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_CREATED);

    String inboxhref = TestCalDav.waitForNewSchedulingRequestByUID(dav2, androidSeriesMeetingUid);
    assertTrue("Found meeting request for newly created item", inboxhref.contains(androidSeriesMeetingUid));

    GetMethod getMethod = new GetMethod(url);
    addBasicAuthHeaderForUser(getMethod, dav1);
    HttpMethodExecutor exe = HttpMethodExecutor.execute(client, getMethod, HttpStatus.SC_OK);
    String etag = null;
    for (Header hdr : exe.respHeaders) {
        if (DavProtocol.HEADER_ETAG.equals(hdr.getName())) {
            etag = hdr.getValue();
        }
    }
    assertNotNull("ETag from get", etag);

    // Check that we fail if the etag is wrong
    putMethod = new PutMethod(url);
    addBasicAuthHeaderForUser(putMethod, dav1);
    putMethod.addRequestHeader("Content-Type", "text/calendar");
    putMethod.addRequestHeader(DavProtocol.HEADER_IF_MATCH, "willNotMatch");
    putMethod.setRequestEntity(new ByteArrayRequestEntity(body.getBytes(), MimeConstants.CT_TEXT_CALENDAR));
    HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_PRECONDITION_FAILED);

    PropFindMethod propFindMethod = new PropFindMethod(getFolderUrl(dav1, "Calendar"));
    addBasicAuthHeaderForUser(propFindMethod, dav1);
    TestCalDav.HttpMethodExecutor executor;
    String respBody;
    Element respElem;
    propFindMethod.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    propFindMethod.addRequestHeader("Depth", "1");
    propFindMethod.setRequestEntity(
            new ByteArrayRequestEntity(propFindEtagResType.getBytes(), MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, propFindMethod, HttpStatus.SC_MULTI_STATUS);
    respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    respElem = Element.XMLElement.parseXML(respBody);
    assertEquals("name of top element in propfind response", DavElements.P_MULTISTATUS, respElem.getName());
    assertTrue("propfind response should have child elements", respElem.hasChildren());
    Iterator<Element> iter = respElem.elementIterator();
    boolean hasCalendarHref = false;
    boolean hasCalItemHref = false;
    while (iter.hasNext()) {
        Element child = iter.next();
        if (DavElements.P_RESPONSE.equals(child.getName())) {
            Iterator<Element> hrefIter = child.elementIterator(DavElements.P_HREF);
            while (hrefIter.hasNext()) {
                Element href = hrefIter.next();
                calFolderUrl.endsWith(href.getText());
                hasCalendarHref = hasCalendarHref || calFolderUrl.endsWith(href.getText());
                hasCalItemHref = hasCalItemHref || url.endsWith(href.getText());
            }
        }
    }
    assertTrue("propfind response contained entry for calendar", hasCalendarHref);
    assertTrue("propfind response contained entry for calendar entry ", hasCalItemHref);

    DeleteMethod deleteMethod = new DeleteMethod(url);
    addBasicAuthHeaderForUser(deleteMethod, dav1);
    HttpMethodExecutor.execute(client, deleteMethod, HttpStatus.SC_NO_CONTENT);
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testDeleteOperation1() throws Exception {
    String url = URL_RESOURCE1 + "/pathDeleteOperation1";
    DeleteMethod method = new DeleteMethod(url);

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);//from  ww  w .ja va 2 s .  c  o m
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testDeleteOperation2() throws Exception {
    String url = URL_RESOURCE1 + "/pathDeleteOperation2";
    DeleteMethod method = new DeleteMethod(url);

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);//ww w. j av  a  2 s .  c o  m
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testDeleteOperation3() throws Exception {
    String url = URL_RESOURCE1 + "/pathDeleteOperation3";
    DeleteMethod method = new DeleteMethod(url);

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);/*from w  w w  .  j  ava  2 s .c om*/
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testDeleteOperation4() throws Exception {
    String url = URL_RESOURCE1 + "/pathDeleteOperation4/4/5";
    DeleteMethod method = new DeleteMethod(url);

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);//from w w  w.  j  a  v  a 2 s  .  c om
}

From source file:com.sun.faban.driver.transport.hc3.ApacheHC3Transport.java

/**
 * Makes a DELETE request to the URL. Reads data back and returns the data
 * read. Note that this method only works with text data as it does the
 * byte-to-char conversion. This method will return null for responses
 * with binary MIME types. The addTextType(String) method is used to
 * register additional MIME types as text types. Use getContentSize() to
 *  obtain the bytes of binary data read.
 *
 * @param url The URL to read from//www.  j  a  v a  2  s  .c o m
 * @param headers The request headers, or null
 * @return The StringBuilder buffer containing the resulting document
 * @throws java.io.IOException
 */
public StringBuilder deleteURL(String url, Map<String, String> headers) throws IOException {
    DeleteMethod method = new DeleteMethod(url);
    method.setFollowRedirects(followRedirects);
    setHeaders(method, headers);
    try {
        responseCode = hc.executeMethod(method);
        buildResponseHeaders(method);
        return fetchResponse(method);
    } finally {
        method.releaseConnection();
    }
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testDeleteOperation5() throws Exception {
    String url = URL_RESOURCE1 + "/pathDeleteOperation5/55?date=2010-07-08";
    DeleteMethod method = new DeleteMethod(url);

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);/*from   w ww .  j ava 2s  .co  m*/
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

private void attendeeDeleteFromCalendar(boolean suppressReply) throws Exception {
    Account dav1 = users[1].create();//from   www  . ja va  2s  . com
    users[2].create();
    String url = getSchedulingInboxUrl(dav1, dav1);
    ReportMethod method = new ReportMethod(url);
    addBasicAuthHeaderForUser(method, dav1);

    ZMailbox organizer = users[2].getZMailbox();
    users[1].getZMailbox(); // Force creation of mailbox - shouldn't be needed
    String subject = String.format("%s %s", NAME_PREFIX,
            suppressReply ? "testInvite which shouldNOT be replied to" : "testInvite to be auto-declined");
    Date startDate = new Date(System.currentTimeMillis() + Constants.MILLIS_PER_DAY);
    Date endDate = new Date(startDate.getTime() + Constants.MILLIS_PER_HOUR);
    TestUtil.createAppointment(organizer, subject, dav1.getName(), startDate, endDate);

    // Wait for appointment to arrive
    String href = waitForNewSchedulingRequestByUID(dav1, "");
    assertNotNull("href for inbox invitation", href);
    String uid = href.substring(href.lastIndexOf('/') + 1);
    uid = uid.substring(0, uid.indexOf(',') - 1);
    String calFolderUrl = getFolderUrl(dav1, "Calendar");
    String delurl = waitForItemInCalendarCollectionByUID(calFolderUrl, dav1, uid, true, 5000);
    StringBuilder sb = getLocalServerRoot().append(delurl);
    DeleteMethod delMethod = new DeleteMethod(sb.toString());
    addBasicAuthHeaderForUser(delMethod, dav1);
    if (suppressReply) {
        delMethod.addRequestHeader(DavProtocol.HEADER_SCHEDULE_REPLY, "F");
    }

    HttpClient client = new HttpClient();
    HttpMethodExecutor.execute(client, delMethod, HttpStatus.SC_NO_CONTENT);
    List<ZMessage> msgs;
    if (suppressReply) {
        // timeout may be a bit short but don't want long time wastes in test suite.
        msgs = TestUtil.waitForMessages(organizer, "is:invite is:unread inid:2 after:\"-1month\"", 0, 2000);
        if (msgs != null) {
            assertEquals("Should be no DECLINE reply msg", 0, msgs.size());
        }
    } else {
        msgs = TestUtil.waitForMessages(organizer, "is:invite is:unread inid:2 after:\"-1month\"", 1, 10000);
        assertNotNull("inbox DECLINE reply msgs", msgs);
        assertEquals("Should be 1 DECLINE reply msg", 1, msgs.size());
        assertNotNull("inbox DECLINE reply msg invite", msgs.get(0).getInvite());
    }
}