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:com.worldline.easycukes.rest.client.RestService.java

/**
 * Allows to send a DELETE request, with parameters using JSON format
 *
 * @param path path to be used for the DELETE request
 * @param data paremeters to be used (JSON format) as a string
 *//* ww  w.j  a va  2s.  c o m*/
@SuppressWarnings("unchecked")
public void sendDelete(final String path, final String data) {
    String fullpath = path;

    if (path.startsWith("/"))
        fullpath = baseUrl + path;

    log.info("Sending DELETE request to " + fullpath);

    final DeleteMethod method = new DeleteMethod(fullpath);

    for (final Map.Entry<String, String> header : requestHeaders.entrySet())
        method.setRequestHeader(header.getKey(), header.getValue());

    if (data != null) {
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONHelper.toJSONObject(data);

            for (final Iterator<String> iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
                final String param = iterator.next();
                HttpMethodParams methodParams = new HttpMethodParams();
                methodParams.setParameter(param,
                        (jsonObject.get(param) != null) ? jsonObject.get(param).toString() : null);
                method.setParams(methodParams);

            }
        } catch (final ParseException e) {
            log.error("Sorry, parameters are not proper JSON...", e);
        }

    }
    try {
        if (nonProxyHost != null && fullpath.contains(nonProxyHost)) {
            httpClient.getHostConfiguration().setProxyHost(null);
        }
        final int statusCode = httpClient.executeMethod(method);
        response = new ResponseWrapper(method.getResponseBodyAsString(), method.getResponseHeaders(),
                statusCode);
    } catch (final IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.funambol.json.api.dao.FunambolJSONApiDAO.java

protected String sendDeleteRequest(String REQUEST, long since, long until) throws IOOperationException {

    String response = null;//  w ww .ja  v a 2  s.  co  m
    DeleteMethod method = null;
    try {

        HttpClient httpClient = new HttpClient();

        method = new DeleteMethod(REQUEST);

        addSinceUntil(method, since, until);

        if (log.isTraceEnabled()) {
            log.trace("\nREQUEST: " + REQUEST + "");
        }
        if (this.sessionid != null) {
            method.setRequestHeader("Authorization", this.sessionid);
        }

        printHeaderFields(method.getRequestHeaders(), "REQUEST");

        int code = httpClient.executeMethod(method);

        response = method.getResponseBodyAsString();

        if (log.isTraceEnabled()) {
            log.trace("RESPONSE code: " + code);
        }
        printHeaderFields(method.getResponseHeaders(), "RESPONSE");

    } catch (Exception e) {
        throw new IOOperationException("Error GET Request ", e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }

    return response;
}

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  w w  w .  j  ava  2 s .  c om*/
            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//from   w w  w.ja  v  a2s  .  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  a 2s  .  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) {
    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 {/*w  w  w. j  a v a  2s . 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.activiti.kickstart.service.alfresco.AlfrescoKickstartServiceImpl.java

protected void deleteWorkflowInstance(String workflowInstanceId) {
    HttpState state = new HttpState();
    state.setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(cmisUser, cmisPassword));

    // Only fetching one, we're only interested in the paging information, after all
    String url = ALFRESCO_BASE_URL + "api/workflow-instances/" + workflowInstanceId + "?forced=true";
    DeleteMethod deleteMethod = new DeleteMethod(url);
    LOGGER.info("Executing DELETE '" + url + "'");

    try {/*from   w  ww .j a v  a 2 s  . c  o m*/
        HttpClient httpClient = new HttpClient();
        int result = httpClient.executeMethod(null, deleteMethod, state);

        // Display Response
        String responseJson = deleteMethod.getResponseBodyAsString();
        LOGGER.info("Response status code: " + result);
        LOGGER.info("Response body: " + responseJson);

    } catch (Throwable t) {
        System.err.println("Error: " + t.getMessage());
        t.printStackTrace();
    } finally {
        deleteMethod.releaseConnection();
    }
}

From source file:org.alfresco.module.vti.handler.alfresco.ShareUtils.java

/**
 * Deletes site using REST API, http method is sent to appropriate web script
 * /*from   w  w w.j a  v  a  2  s .  co  m*/
 * @param user current user
 * @param shortName shortName of site we are going to delete
 * @throws HttpException
 * @throws IOException
 */
public void deleteSite(SessionUser user, String shortName) throws HttpException, IOException {
    HttpClient httpClient = new HttpClient();
    DeleteMethod deleteSiteMethod = new DeleteMethod(getAlfrescoHostWithPort() + getAlfrescoContext()
            + "/s/api/sites/" + shortName + "?alf_ticket=" + user.getTicket());
    try {
        if (logger.isDebugEnabled())
            logger.debug("Trying to delete site with name: " + shortName);

        int status = httpClient.executeMethod(deleteSiteMethod);
        if (logger.isDebugEnabled())
            logger.debug("Delete site method returned status: " + status);
        if (status != HttpStatus.SC_OK) {
            throw new RuntimeException(
                    "Failed to delete site with name: " + shortName + ". Returned status is: " + status
                            + ". \n Response from server :\n" + deleteSiteMethod.getResponseBodyAsString());
        }
        deleteSiteMethod.getResponseBody();
    } catch (Exception e) {
        if (logger.isDebugEnabled())
            logger.debug("Fail to delete site with name: " + shortName);
        throw new RuntimeException(e);
    } finally {
        deleteSiteMethod.releaseConnection();
    }

    // deletes site dashboard
    deleteSiteDashboard(httpClient, shortName, user);

    // deletes title component
    deleteSiteComponent(httpClient, shortName, user, "title");

    // deletes navigation component
    deleteSiteComponent(httpClient, shortName, user, "navigation");

    // deletes component-2-2 component
    deleteSiteComponent(httpClient, shortName, user, "component-2-2");

    // deletes component-1-1 component
    deleteSiteComponent(httpClient, shortName, user, "component-1-1");

    // deletes component-2-1 component
    deleteSiteComponent(httpClient, shortName, user, "component-2-1");

    // deletes component-1-2 component
    deleteSiteComponent(httpClient, shortName, user, "component-1-2");
}

From source file:org.alfresco.module.vti.handler.alfresco.ShareUtils.java

/**
 * Deletes component from site//from  w w  w .j ava 2s  .c  o m
 * 
 * @param httpClient HTTP client
 * @param siteName name of the site
 * @param user current user
 * @param componentName name of the component
 */
private void deleteSiteComponent(HttpClient httpClient, String siteName, SessionUser user,
        String componentName) {
    DeleteMethod deleteTitleMethod = new DeleteMethod(getAlfrescoHostWithPort() + getAlfrescoContext()
            + "/s/remoteadm/delete/alfresco/site-data/components/page." + componentName + ".site~" + siteName
            + "~dashboard.xml?s=sitestore&alf_ticket=" + user.getTicket());
    try {
        if (logger.isDebugEnabled())
            logger.debug("Trying to delete site component with name: " + siteName);

        int status = httpClient.executeMethod(deleteTitleMethod);
        deleteTitleMethod.getResponseBody();

        if (logger.isDebugEnabled())
            logger.debug("Delete site component method returned status: " + status);
    } catch (Exception e) {
        if (logger.isDebugEnabled())
            logger.debug("Fail to delete component from site with name: " + siteName);
        throw new RuntimeException(e);
    } finally {
        deleteTitleMethod.releaseConnection();
    }
}

From source file:org.alfresco.module.vti.handler.alfresco.ShareUtils.java

/**
 * Deletes site dashboard//www .j  a v  a 2s.c  o m
 * 
 * @param httpClient HTTP client
 * @param siteName name of the site
 * @param user current user
 */
private void deleteSiteDashboard(HttpClient httpClient, String siteName, SessionUser user) {
    DeleteMethod deleteDashboardMethod = new DeleteMethod(getAlfrescoHostWithPort() + getAlfrescoContext()
            + "/s/remoteadm/delete/alfresco/site-data/pages/site/" + siteName
            + "/dashboard.xml?s=sitestore&alf_ticket=" + user.getTicket());
    try {
        if (logger.isDebugEnabled())
            logger.debug("Trying to delete dashboard from site with name: " + siteName);

        int status = httpClient.executeMethod(deleteDashboardMethod);
        deleteDashboardMethod.getResponseBody();

        if (logger.isDebugEnabled())
            logger.debug("Delete dashboard from site method returned status: " + status);
    } catch (Exception e) {
        if (logger.isDebugEnabled())
            logger.debug("Fail to delete dashboard from site with name: " + siteName);
        throw new RuntimeException(e);
    } finally {
        deleteDashboardMethod.releaseConnection();
    }
}