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

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

Introduction

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

Prototype

@Override
public int getStatusCode() 

Source Link

Document

Returns the response status code.

Usage

From source file:org.apache.cloudstack.network.element.SspClient.java

public boolean deleteTenantPort(String tenantPortUuid) {
    DeleteMethod method = deleteMethod;
    method.setPath("/ssp.v1/tenant-ports/" + tenantPortUuid);

    executeMethod(method);//from www . j a va  2s.  c om
    if (method.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
        return true;
    }
    return false;
}

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

protected void executeDelete(final String uri) throws NeutronRestApiException {
    try {/* w w  w .jav  a 2 s .  c  o  m*/
        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.hadoop.fs.swift.http.SwiftRestClient.java

/**
 * Deletes object from swift./* www  .j  a  v a  2s.  c o  m*/
 * The result is true if this operation did the deletion.
 * @param path           path to file
 * @param requestHeaders http headers
 * @throws IOException on IO Faults
 */
public boolean delete(SwiftObjectPath path, final Header... requestHeaders) throws IOException {
    preRemoteCommand("delete");

    return perform(pathToURI(path), new DeleteMethodProcessor<Boolean>() {
        @Override
        public Boolean extractResult(DeleteMethod method) throws IOException {
            return method.getStatusCode() == SC_NO_CONTENT;
        }

        @Override
        protected void setup(DeleteMethod method) throws SwiftInternalStateException {
            setHeaders(method, requestHeaders);
        }
    });
}

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 . j  a  va2s.  com*/

    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.wink.itest.addressbook.StringTest.java

/**
 * This will drive a POST, GET, UPDATE, and DELETE on the
 * AddressBookResource/*from  w w w  .  j  av a2  s.c o m*/
 */
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   ww w  . ja v a 2s  .c om
 */
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.JAXRSExceptionsMappedProvidersTest.java

/**
 * Tests a method that throws a runtime exception.
 * /* ww  w.  ja  v  a 2  s  .  c o m*/
 * @throws Exception
 */
public void testRuntimeExceptionMappedProvider() throws Exception {
    HttpClient client = new HttpClient();

    /*
     * abcd is an invalid ID so a NumberFormatException will be thrown in
     * the resource
     */
    DeleteMethod postMethod = new DeleteMethod(getBaseURI() + "/abcd");
    client.executeMethod(postMethod);
    assertEquals(450, postMethod.getStatusCode());

    CommentError c = (CommentError) JAXBContext.newInstance(CommentError.class.getPackage().getName())
            .createUnmarshaller().unmarshal(postMethod.getResponseBodyAsStream());
    assertEquals("For input string: \"abcd\"", c.getErrorMessage());
}

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

/**
 * Tests a method that throws a NullPointerException inside a called method.
 * /* w w w  .ja  va  2 s.c  o  m*/
 * @throws Exception
 */
public void testNullPointerExceptionMappedProvider() throws Exception {
    HttpClient client = new HttpClient();

    DeleteMethod postMethod = new DeleteMethod(getBaseURI() + "/10000");
    client.executeMethod(postMethod);
    assertEquals(451, postMethod.getStatusCode());

    CommentError c = (CommentError) JAXBContext.newInstance(CommentError.class.getPackage().getName())
            .createUnmarshaller().unmarshal(postMethod.getResponseBodyAsStream());
    assertEquals("The comment did not previously exist.", c.getErrorMessage());
}

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

/**
 * Tests a method that throws an error.//from  ww w.j  a  v a 2s .c  o  m
 * 
 * @throws Exception
 */
public void testErrorMappedProvider() throws Exception {
    HttpClient client = new HttpClient();

    DeleteMethod postMethod = new DeleteMethod(getBaseURI() + "/-99999");
    client.executeMethod(postMethod);
    assertEquals(453, postMethod.getStatusCode());

    CommentError c = (CommentError) JAXBContext.newInstance(CommentError.class.getPackage().getName())
            .createUnmarshaller().unmarshal(postMethod.getResponseBodyAsStream());
    assertEquals("Simulated error", c.getErrorMessage());
}

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

/**
 * Tests a method that throws a runtime exception.
 * //from   w w w .  j av  a2  s . c om
 * @throws Exception
 */
public void testRuntimeExceptionNoMappingProvider() throws Exception {
    HttpClient client = new HttpClient();

    /*
     * abcd is an invalid ID so a NumberFormatException will be thrown in
     * the resource
     */
    DeleteMethod postMethod = new DeleteMethod(getBaseURI() + "/abcd");
    client.executeMethod(postMethod);
    assertEquals(500, postMethod.getStatusCode());

    // assertLogContainsException("java.lang.NumberFormatException: For input string: \"abcd\"");
}