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

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

Introduction

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

Prototype

@Override
public InputStream getResponseBodyAsStream() throws IOException 

Source Link

Document

Returns the response body of the HTTP method, if any, as an InputStream .

Usage

From source file:it.geosolutions.figis.requester.HTTPUtils.java

public static boolean delete(String url, final String user, final String pw) {

    DeleteMethod httpMethod = null;

    try {/*from  w ww.j  a va2 s  .c  om*/
        HttpClient client = new HttpClient();
        setAuth(client, url, user, pw);
        httpMethod = new DeleteMethod(url);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        int status = client.executeMethod(httpMethod);
        String response = "";
        if (status == HttpStatus.SC_OK) {
            InputStream is = httpMethod.getResponseBodyAsStream();
            response = IOUtils.toString(is);
            if (response.trim().equals("")) // sometimes gs rest fails
            {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                            "ResponseBody is empty (this may be not an error since we just performed a DELETE call)");
                }

                return true;
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("(" + status + ") " + httpMethod.getStatusText() + " -- " + url);
            }

            return true;
        } else {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("(" + status + ") " + httpMethod.getStatusText() + " -- " + url);
                LOGGER.info("Response: '" + response + "'");
            }
        }
    } catch (ConnectException e) {
        LOGGER.info("Couldn't connect to [" + url + "]", e);
    } catch (IOException e) {
        LOGGER.info("Error talking to [" + url + "]", e);
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }

    return false;
}

From source file:it.geosolutions.geoserver.rest.HTTPUtils.java

public static boolean delete(String url, final String user, final String pw) {

    DeleteMethod httpMethod = null;
    HttpClient client = new HttpClient();
    HttpConnectionManager connectionManager = client.getHttpConnectionManager();
    try {/*from w w w .j ava2 s.  c  om*/
        setAuth(client, url, user, pw);
        httpMethod = new DeleteMethod(url);
        connectionManager.getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(httpMethod);
        String response = "";
        if (status == HttpStatus.SC_OK) {
            InputStream is = httpMethod.getResponseBodyAsStream();
            response = IOUtils.toString(is);
            IOUtils.closeQuietly(is);
            if (response.trim().equals("")) {
                if (LOGGER.isTraceEnabled())
                    LOGGER.trace(
                            "ResponseBody is empty (this may be not an error since we just performed a DELETE call)");
                return true;
            }
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("(" + status + ") " + httpMethod.getStatusText() + " -- " + url);
            return true;
        } else {
            LOGGER.info("(" + status + ") " + httpMethod.getStatusText() + " -- " + url);
            LOGGER.info("Response: '" + response + "'");
        }
    } catch (ConnectException e) {
        LOGGER.info("Couldn't connect to [" + url + "]");
    } catch (IOException e) {
        LOGGER.info("Error talking to [" + url + "]", e);
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
        connectionManager.closeIdleConnections(0);
    }

    return false;
}

From source file:com.owncloud.android.lib.resources.users.DeletePublicKeyOperation.java

/**
 * @param client Client object//from  w w w .  jav  a 2s  .c o m
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    DeleteMethod postMethod = null;
    RemoteOperationResult result;

    try {
        // remote request
        postMethod = new DeleteMethod(client.getBaseUri() + PUBLIC_KEY_URL);
        postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);

        int status = client.executeMethod(postMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);

        result = new RemoteOperationResult(status == HttpStatus.SC_OK, postMethod);

        client.exhaustResponse(postMethod.getResponseBodyAsStream());
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Deletion of public key failed: " + result.getLogMessage(), result.getException());
    } finally {
        if (postMethod != null)
            postMethod.releaseConnection();
    }
    return result;
}

From source file:com.owncloud.android.lib.resources.files.UnlockFileOperation.java

/**
 * @param client Client object/*  w  w  w . ja  va2s .c om*/
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result;
    DeleteMethod deleteMethod = null;

    try {
        // remote request
        deleteMethod = new DeleteMethod(client.getBaseUri() + LOCK_FILE_URL + localId);
        deleteMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        deleteMethod.addRequestHeader(CONTENT_TYPE, FORM_URLENCODED);
        deleteMethod.addRequestHeader(TOKEN, token);

        int status = client.executeMethod(deleteMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);

        result = new RemoteOperationResult(status == HttpStatus.SC_OK, deleteMethod);

        client.exhaustResponse(deleteMethod.getResponseBodyAsStream());
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Unlock file with id " + localId + " failed: " + result.getLogMessage(),
                result.getException());
    } finally {
        if (deleteMethod != null)
            deleteMethod.releaseConnection();
    }
    return result;
}

From source file:it.geosolutions.geonetwork.util.HTTPUtils.java

public boolean delete(String url) {

    DeleteMethod httpMethod = null;

    try {//  ww  w .  j a v  a  2  s.  c o m
        //            HttpClient client = new HttpClient();
        setAuth(client, url, username, pw);
        httpMethod = new DeleteMethod(url);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        lastHttpStatus = client.executeMethod(httpMethod);
        String response = "";
        if (lastHttpStatus == HttpStatus.SC_OK) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("(" + lastHttpStatus + ") " + httpMethod.getStatusText() + " -- " + url);

            if (!ignoreResponseContentOnSuccess) {
                InputStream is = httpMethod.getResponseBodyAsStream();
                response = IOUtils.toString(is);
                if (response.trim().equals("")) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug(
                                "ResponseBody is empty (this may be not an error since we just performed a DELETE call)");
                }
            }
            return true;
        } else {
            LOGGER.info("(" + lastHttpStatus + ") " + httpMethod.getStatusText() + " -- " + url);
            LOGGER.info("Response: '" + response + "'");
        }
    } catch (ConnectException e) {
        LOGGER.info("Couldn't connect to [" + url + "]");
    } catch (IOException e) {
        LOGGER.info("Error talking to [" + url + "]", e);
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
    }

    return false;
}

From source file:edu.indiana.d2i.htrc.portal.HTRCAgentClient.java

public boolean deleteJobs(List<String> jobIds) {
    boolean res = true;
    for (String id : jobIds) {
        DeleteMethod deleteJobId = null;
        try {//from   ww  w  .j  av a 2  s.c  o  m
            String jobdeleteURL = String
                    .format(PlayConfWrapper.agentEndpoint() + PlayConfWrapper.jobDeleteURLTemplate(), id);
            deleteJobId = new DeleteMethod(jobdeleteURL);
            deleteJobId.setRequestHeader("Authorization", "Bearer " + accessToken);

            //                client.getHttpConnectionManager().getParams().setConnectionTimeout(PlayConfWrapper.agentConnectTimeout());
            //                client.getHttpConnectionManager().getParams().setSoTimeout(PlayConfWrapper.agentWaitTimeout());

            int response = client.executeMethod(deleteJobId);
            this.responseCode = response;
            if (response == 200) {
                boolean success = parseJobDeleteResponse(deleteJobId.getResponseBodyAsStream());
                if (!success) {
                    log.error("Error occurs while deleting job " + id);

                }
            } else if (response == 401 && (renew < MAX_RENEW)) {
                try {
                    accessToken = HTRCPersistenceAPIClient.renewToken(refreshToken);
                    renew++;
                    return deleteJobs(jobIds); // bugs here!
                } catch (Exception e) {
                    throw new IOException(e);
                }
            } else {
                renew = 0;
                log.error(String.format("Unable to delete job %s from agent. Response code %d", id, response));
                res = false;
            }
        } catch (Exception e) {
            log.error(String.valueOf(e));
        } finally {
            if (deleteJobId != null) {
                deleteJobId.releaseConnection();
                deleteJobId = null;
            }
        }
    }
    return res;
}

From source file:gr.upatras.ece.nam.fci.panlab.PanlabGWClient.java

/**
 * It makes a DELETE towards the gateway
 * @author ctranoris//  ww  w  .  j  a va2  s .  c o  m
 * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27
 * @param ptmAlias sets the name of the provider URI, e.g.: uop
 * @param content sets the name of the content; send in utf8
 */
public void DELETEexecute(String resourceInstance, String ptmAlias, String content) {
    System.out.println("content body=" + "\n" + content);
    HttpClient client = new HttpClient();
    String tgwcontent = content;

    // resource instance is like uop.rubis_db-6 so we need to make it like
    // this /uop/uop.rubis_db-6
    String ptm = ptmAlias;
    String url = panlabGWAddress + "/" + ptm + "/" + resourceInstance;
    System.out.println("Request: " + url);

    // Create a method instance.

    DeleteMethod delMethod = new DeleteMethod(url);
    delMethod.setRequestHeader("User-Agent", userAgent);
    delMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    // Provide custom retry handler is necessary
    //      delMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
    //            new DefaultHttpMethodRetryHandler(3, false));

    //      RequestEntity requestEntity = null;
    //      try {
    //         requestEntity = new StringRequestEntity(tgwcontent,
    //               "application/x-www-form-urlencoded", "utf-8");
    //      } catch (UnsupportedEncodingException e1) {
    //         e1.printStackTrace();
    //      }

    //delMethod.setRequestEntity(requestEntity);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(delMethod);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + delMethod.getStatusLine());
        }

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary
        // data
        // print the status and response
        InputStream responseBody = delMethod.getResponseBodyAsStream();

        CopyInputStream cis = new CopyInputStream(responseBody);
        response_stream = cis.getCopy();
        System.out.println("Response body=" + "\n" + convertStreamToString(response_stream));
        response_stream.reset();

        //         System.out.println("for address: " + url + " the response is:\n "
        //               + post.getResponseBodyAsString());

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        delMethod.releaseConnection();
    }

}

From source file:gr.upatras.ece.nam.fci.uop.UoPGWClient.java

/**
 * It makes a DELETE towards the gateway
 * @author ctranoris/*from w  w w . j av a2 s. c om*/
 * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27
 * @param ptmAlias sets the name of the provider URI, e.g.: uop
 * @param content sets the name of the content; send in utf8
 */
public void DELETEexecute(String resourceInstance, String ptmAlias, String content) {
    log.info("content body=" + "\n" + content);
    HttpClient client = new HttpClient();
    String tgwcontent = content;

    // resource instance is like uop.rubis_db-6 so we need to make it like
    // this /uop/uop.rubis_db-6
    String ptm = ptmAlias;
    String url = uopGWAddress + "/" + ptm + "/" + resourceInstance;
    log.info("Request: " + url);

    // Create a method instance.

    DeleteMethod delMethod = new DeleteMethod(url);
    delMethod.setRequestHeader("User-Agent", userAgent);
    delMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    // Provide custom retry handler is necessary
    //      delMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
    //            new DefaultHttpMethodRetryHandler(3, false));

    //      RequestEntity requestEntity = null;
    //      try {
    //         requestEntity = new StringRequestEntity(tgwcontent,
    //               "application/x-www-form-urlencoded", "utf-8");
    //      } catch (UnsupportedEncodingException e1) {
    //         e1.printStackTrace();
    //      }

    //delMethod.setRequestEntity(requestEntity);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(delMethod);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + delMethod.getStatusLine());
        }

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary
        // data
        // print the status and response
        InputStream responseBody = delMethod.getResponseBodyAsStream();

        CopyInputStream cis = new CopyInputStream(responseBody);
        response_stream = cis.getCopy();
        log.info("Response body=" + "\n" + convertStreamToString(response_stream));
        response_stream.reset();

        //         log.info("for address: " + url + " the response is:\n "
        //               + post.getResponseBodyAsString());

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        delMethod.releaseConnection();
    }

}

From source file:com.inbravo.scribe.rest.service.crm.ZDRESTCRMService.java

@Override
public final boolean deleteObject(final ScribeCommandObject cADCommandObject, final String idToBeDeleted)
        throws Exception {

    logger.debug("----Inside deleteObject");
    DeleteMethod deleteMethod = null;
    try {/*from w w w  .  j  av  a  2  s.  c  o  m*/
        String serviceURL = null;
        String serviceProtocol = null;
        String userId = null;
        String password = null;
        String sessionId = null;
        String crmPort = "80";

        /* Check if CrmUserId is present in request */
        if (cADCommandObject.getCrmUserId() != null) {

            /* Get agent from session manager */
            final ScribeCacheObject agent = zDCRMSessionManager
                    .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId());

            /* Get CRM information from agent */
            serviceURL = agent.getScribeMetaObject().getCrmServiceURL();
            serviceProtocol = agent.getScribeMetaObject().getCrmServiceProtocol();
            userId = agent.getScribeMetaObject().getCrmUserId();
            password = agent.getScribeMetaObject().getCrmPassword();
            sessionId = agent.getScribeMetaObject().getCrmSessionId();
            crmPort = agent.getScribeMetaObject().getCrmPort();
        }

        /* Check if id is available in request */
        if (idToBeDeleted == null) {
            /* Inform user about invalid request */
            throw new ScribeException(
                    ScribeResponseCodes._1008 + "CRM object id for deletion purpose is not present in request");
        }

        /* Create Zen desk URL */
        final String zenDeskURL = serviceProtocol + "://" + serviceURL + "/" + cADCommandObject.getObjectType()
                + "s/" + idToBeDeleted.trim() + ".xml";

        logger.debug("----Inside deleteObject zenDeskURL: " + zenDeskURL);

        /* Instantiate delete method */
        deleteMethod = new DeleteMethod(zenDeskURL);

        /* Set request content type */
        deleteMethod.addRequestHeader("Content-Type", "application/xml");
        deleteMethod.addRequestHeader("accept", "application/xml");

        /* Cookie is required to be set for session management */
        deleteMethod.addRequestHeader("Cookie", sessionId);

        final HttpClient httpclient = new HttpClient();

        /* Set credentials */
        httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)),
                new UsernamePasswordCredentials(userId, password));

        /* Execute method */
        int result = httpclient.executeMethod(deleteMethod);
        logger.debug("----Inside deleteObject response code: " + result + " & body: "
                + deleteMethod.getResponseBodyAsString());

        /* Check if object is updated */
        if (result == HttpStatus.SC_OK || result == HttpStatus.SC_CREATED) {

            /* Return the original object */
            return true;
        } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED
                || result == HttpStatus.SC_NOT_ACCEPTABLE) {
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : "
                    + ZDCRMMessageFormatUtils.getErrorFromResponse(deleteMethod.getResponseBodyAsStream()));
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM");
        } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {
            throw new ScribeException(ScribeResponseCodes._1004
                    + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct");
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final ParserConfigurationException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final SAXException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final IOException exception) {
        throw new ScribeException(
                ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                exception);
    } finally {
        /* Release connection socket */
        if (deleteMethod != null) {
            deleteMethod.releaseConnection();
        }
    }
    return false;
}

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

/**
 * Tests a method that throws a runtime exception.
 * //from   w  w  w  . ja v  a 2  s.co  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());
}