Example usage for org.apache.commons.httpclient.methods DeleteMethod releaseConnection

List of usage examples for org.apache.commons.httpclient.methods DeleteMethod releaseConnection

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods DeleteMethod releaseConnection.

Prototype

@Override
public void releaseConnection() 

Source Link

Document

Releases the connection being used by this HTTP method.

Usage

From source file:org.apache.cloudstack.network.opendaylight.api.resources.Action.java

protected void executeDelete(final String uri) throws NeutronRestApiException {
    try {//  w  ww .  j a v a 2s.  c  om
        validateCredentials();
    } catch (NeutronInvalidCredentialsException e) {
        throw new NeutronRestApiException("Invalid credentials!", e);
    }

    NeutronRestFactory factory = NeutronRestFactory.getInstance();

    NeutronRestApi neutronRestApi = factory.getNeutronApi(DeleteMethod.class);
    DeleteMethod deleteMethod = (DeleteMethod) neutronRestApi.createMethod(url, uri);

    try {
        deleteMethod.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);

        String encodedCredentials = encodeCredentials();
        deleteMethod.setRequestHeader("Authorization", "Basic " + encodedCredentials);

        neutronRestApi.executeMethod(deleteMethod);

        if (deleteMethod.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
            String errorMessage = responseToErrorMessage(deleteMethod);
            deleteMethod.releaseConnection();
            s_logger.error("Failed to update object : " + errorMessage);
            throw new NeutronRestApiException("Failed to create object : " + errorMessage);
        }
    } catch (NeutronRestApiException e) {
        s_logger.error(
                "NeutronRestApiException caught while trying to execute HTTP Method on the Neutron Controller",
                e);
        throw new NeutronRestApiException("API call to Neutron Controller Failed", e);
    } finally {
        deleteMethod.releaseConnection();
    }
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerBookTest.java

@Test
public void testDeleteBook() throws Exception {
    String endpointAddress = "http://localhost:" + PORT + "/bookstore/books/123";

    DeleteMethod post = new DeleteMethod(endpointAddress);
    HttpClient httpclient = new HttpClient();

    try {//from  w  w w . j  av  a  2 s  .c o  m
        int result = httpclient.executeMethod(post);
        assertEquals(200, result);
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerBookTest.java

@Test
public void testDeleteBookByQuery() throws Exception {
    String endpointAddress = "http://localhost:" + PORT + "/bookstore/books/id?value=123";

    DeleteMethod post = new DeleteMethod(endpointAddress);
    HttpClient httpclient = new HttpClient();

    try {/* w  ww. j  a  va 2s . co  m*/
        int result = httpclient.executeMethod(post);
        assertEquals(200, result);
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}

From source file:org.apache.excalibur.source.factories.HTTPClientSource.java

/**
 * Deletes the referenced resource.//w ww  . j  a  v a  2 s .  co m
 *
 * @exception SourceException if an error occurs
 */
public void delete() throws SourceException {
    final DeleteMethod delete = this.createDeleteMethod(this.m_uri);
    try {
        final int response = this.executeMethod(delete);

        if (!this.deleteSuccessful(response)) {
            throw new SourceException("Failed to delete " + this.m_uri + " (" + response + ")");
        }

        if (this.getLogger().isDebugEnabled()) {
            this.getLogger().debug(this.m_uri + " deleted (" + response + ")");
        }
    } catch (final IOException e) {
        throw new SourceException("IOException thrown during delete", e);
    } finally {
        delete.releaseConnection();
    }
}

From source file:org.apache.sling.discovery.impl.topology.connector.TopologyConnectorClient.java

/** Disconnect this connector **/
public void disconnect() {
    final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json";
    if (logger.isDebugEnabled()) {
        logger.debug("disconnect: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
    }/*  w w w . ja va2s.c o  m*/

    if (lastInheritedAnnouncement != null) {
        announcementRegistry.unregisterAnnouncement(lastInheritedAnnouncement.getOwnerId());
    }

    HttpClient httpClient = new HttpClient();
    final DeleteMethod method = new DeleteMethod(uri);

    try {
        String userInfo = connectorUrl.getUserInfo();
        if (userInfo != null) {
            Credentials c = new UsernamePasswordCredentials(userInfo);
            httpClient.getState()
                    .setCredentials(new AuthScope(method.getURI().getHost(), method.getURI().getPort()), c);
        }

        requestValidator.trustMessage(method, null);
        httpClient.executeMethod(method);
        if (logger.isDebugEnabled()) {
            logger.debug("disconnect: done. code=" + method.getStatusCode() + " - " + method.getStatusText());
        }
        // ignoring the actual statuscode though as there's little we can
        // do about it after this point
    } catch (URIException e) {
        logger.warn("disconnect: Got URIException: " + e);
    } catch (IOException e) {
        logger.warn("disconnect: got IOException: " + e);
    } catch (RuntimeException re) {
        logger.error("disconnect: got RuntimeException: " + re, re);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.apache.sling.maven.bundlesupport.BundleUninstallMojo.java

protected void deleteViaWebDav(String targetURL, File file) throws MojoExecutionException {

    final DeleteMethod delete = new DeleteMethod(getURLWithFilename(targetURL, file.getName()));

    try {/*w ww . j  av  a  2s  .  c  om*/

        int status = getHttpClient().executeMethod(delete);
        if (status >= 200 && status < 300) {
            getLog().info("Bundle uninstalled");
        } else {
            getLog().error("Uninstall failed, cause: " + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        throw new MojoExecutionException("Uninstall from " + targetURL + " failed, cause: " + ex.getMessage(),
                ex);
    } finally {
        delete.releaseConnection();
    }
}

From source file:org.apache.wink.itest.addressbook.StringTest.java

/**
 * This will drive a POST, GET, UPDATE, and DELETE on the
 * AddressBookResource/*  w w w. jav  a 2s  .  com*/
 */
public void testAddressBookResource() {
    PostMethod method = null;
    GetMethod getMethod = null;
    PutMethod put = null;
    DeleteMethod deleteMethod = null;
    try {

        // make sure everything is clear before testing
        HttpClient client = new HttpClient();
        method = new PostMethod(getBaseURI() + "/fromBody");
        String input = "tempAddress&1234 Any Street&AnyTown&90210&TX&US";
        RequestEntity entity = new ByteArrayRequestEntity(input.getBytes(), "text/xml");
        method.setRequestEntity(entity);
        client.executeMethod(method);

        // now let's see if the address we just created is available
        getMethod = new GetMethod(getBaseURI() + "/tempAddress");
        client.executeMethod(getMethod);
        String responseBody = getMethod.getResponseBodyAsString();
        getMethod.releaseConnection();
        assertNotNull(responseBody);
        assertTrue(responseBody, responseBody.contains("tempAddress"));
        assertTrue(responseBody, responseBody.contains("1234 Any Street"));
        assertTrue(responseBody, responseBody.contains("AnyTown"));
        assertTrue(responseBody, responseBody.contains("90210"));
        assertTrue(responseBody, responseBody.contains("TX"));
        assertTrue(responseBody, responseBody.contains("US"));

        // let's update the state
        String query = "entryName=tempAddress&streetAddress=1234+Any+Street&city="
                + "AnyTown&zipCode=90210&state=AL&country=US";
        client = new HttpClient();
        put = new PutMethod(getBaseURI());
        put.setQueryString(query);
        client.executeMethod(put);

        // make sure the state has been updated
        client = new HttpClient();
        client.executeMethod(getMethod);
        responseBody = getMethod.getResponseBodyAsString();
        assertNotNull(responseBody);
        assertTrue(responseBody.contains("tempAddress"));
        assertFalse(responseBody.contains("TX"));
        assertTrue(responseBody.contains("AL"));

        // now let's delete the address
        client = new HttpClient();
        deleteMethod = new DeleteMethod(getBaseURI() + "/tempAddress");
        client.executeMethod(deleteMethod);
        assertEquals(204, deleteMethod.getStatusCode());

        // now try to get the address
        client = new HttpClient();
        client.executeMethod(getMethod);
        assertEquals(404, getMethod.getStatusCode());
        responseBody = getMethod.getResponseBodyAsString();
        ServerContainerAssertions.assertExceptionBodyFromServer(404, getMethod.getResponseBodyAsString());

    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
        if (put != null) {
            put.releaseConnection();
        }
        if (deleteMethod != null) {
            deleteMethod.releaseConnection();
        }
    }
}

From source file:org.apache.wink.itest.contextresolver.DepartmentTest.java

/**
 * This will drive several different requests that interact with the
 * Departments resource class.//from   w  ww  .j av a  2 s  .  com
 */
public void testDepartmentsResourceJAXB() throws Exception {
    PostMethod postMethod = null;
    GetMethod getAllMethod = null;
    GetMethod getOneMethod = null;
    HeadMethod headMethod = null;
    DeleteMethod deleteMethod = null;
    try {

        // make sure everything is clear before testing
        DepartmentDatabase.clearEntries();

        // create a new Department
        Department newDepartment = new Department();
        newDepartment.setDepartmentId("1");
        newDepartment.setDepartmentName("Marketing");
        JAXBContext context = JAXBContext
                .newInstance(new Class<?>[] { Department.class, DepartmentListWrapper.class });
        Marshaller marshaller = context.createMarshaller();
        StringWriter sw = new StringWriter();
        marshaller.marshal(newDepartment, sw);
        HttpClient client = new HttpClient();
        postMethod = new PostMethod(getBaseURI());
        RequestEntity reqEntity = new ByteArrayRequestEntity(sw.toString().getBytes(), "text/xml");
        postMethod.setRequestEntity(reqEntity);
        client.executeMethod(postMethod);

        newDepartment = new Department();
        newDepartment.setDepartmentId("2");
        newDepartment.setDepartmentName("Sales");
        sw = new StringWriter();
        marshaller.marshal(newDepartment, sw);
        client = new HttpClient();
        postMethod = new PostMethod(getBaseURI());
        reqEntity = new ByteArrayRequestEntity(sw.toString().getBytes(), "text/xml");
        postMethod.setRequestEntity(reqEntity);
        client.executeMethod(postMethod);

        // now let's get the list of Departments that we just created
        // (should be 2)
        client = new HttpClient();
        getAllMethod = new GetMethod(getBaseURI());
        client.executeMethod(getAllMethod);
        byte[] bytes = getAllMethod.getResponseBody();
        assertNotNull(bytes);
        InputStream bais = new ByteArrayInputStream(bytes);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Object obj = unmarshaller.unmarshal(bais);
        assertTrue(obj instanceof DepartmentListWrapper);
        DepartmentListWrapper wrapper = (DepartmentListWrapper) obj;
        List<Department> dptList = wrapper.getDepartmentList();
        assertNotNull(dptList);
        assertEquals(2, dptList.size());

        // now get a specific Department that was created
        client = new HttpClient();
        getOneMethod = new GetMethod(getBaseURI() + "/1");
        client.executeMethod(getOneMethod);
        bytes = getOneMethod.getResponseBody();
        assertNotNull(bytes);
        bais = new ByteArrayInputStream(bytes);
        obj = unmarshaller.unmarshal(bais);
        assertTrue(obj instanceof Department);
        Department dept = (Department) obj;
        assertEquals("1", dept.getDepartmentId());
        assertEquals("Marketing", dept.getDepartmentName());

        // let's send a Head request for both an existent and non-existent
        // resource
        // we are testing to see if header values being set in the resource
        // implementation
        // are sent back appropriately
        client = new HttpClient();
        headMethod = new HeadMethod(getBaseURI() + "/3");
        client.executeMethod(headMethod);
        assertNotNull(headMethod.getResponseHeaders());
        Header header = headMethod.getResponseHeader("unresolved-id");
        assertNotNull(header);
        assertEquals("3", header.getValue());
        headMethod.releaseConnection();

        // now the resource that should exist
        headMethod = new HeadMethod(getBaseURI() + "/1");
        client.executeMethod(headMethod);
        assertNotNull(headMethod.getResponseHeaders());
        header = headMethod.getResponseHeader("resolved-id");
        assertNotNull(header);
        assertEquals("1", header.getValue());

        deleteMethod = new DeleteMethod(getBaseURI() + "/1");
        client.executeMethod(deleteMethod);
        assertEquals(204, deleteMethod.getStatusCode());

        deleteMethod = new DeleteMethod(getBaseURI() + "/2");
        client.executeMethod(deleteMethod);
        assertEquals(204, deleteMethod.getStatusCode());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
        if (getAllMethod != null) {
            getAllMethod.releaseConnection();
        }
        if (getOneMethod != null) {
            getOneMethod.releaseConnection();
        }
        if (headMethod != null) {
            headMethod.releaseConnection();
        }
        if (deleteMethod != null) {
            deleteMethod.releaseConnection();
        }
    }
}

From source file:org.apache.wink.itest.exceptionmappers.JAXRSExceptionsNullConditionsTest.java

/**
 * Tests that a <code>WebApplicationException</code> constructed with a
 * cause and response status will return the response status and empty
 * response body by default./*from ww w. java  2  s . c  o m*/
 * 
 * @throws Exception
 */
public void testWebExceptionWithCauseAndResponseStatus() throws Exception {
    HttpClient client = new HttpClient();

    DeleteMethod deleteMethod = new DeleteMethod(getBaseURI() + "/webappexceptionwithcauseandresponsestatus");
    try {
        client.executeMethod(deleteMethod);
        assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), deleteMethod.getStatusCode());
        ServerContainerAssertions.assertExceptionBodyFromServer(400, deleteMethod.getResponseBodyAsString());
    } finally {
        deleteMethod.releaseConnection();
    }
}

From source file:org.apache.wink.itest.exceptionmappers.JAXRSExceptionsNullConditionsTest.java

/**
 * Tests that a Throwable can propagate throughout the code.
 * /*from   w  w w  .j av  a 2s .c  o m*/
 * @throws Exception
 */
public void testThrowableCanBeThrown() throws Exception {
    HttpClient client = new HttpClient();

    DeleteMethod deleteMethod = new DeleteMethod(getBaseURI() + "/throwsthrowable");
    try {
        client.executeMethod(deleteMethod);
        assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), deleteMethod.getStatusCode());
        // assertLogContainsException("jaxrs.tests.exceptions.nullconditions.server.GuestbookResource$1: Throwable was thrown");
    } finally {
        deleteMethod.releaseConnection();
    }
}