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

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

Introduction

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

Prototype

@Override
public void setRequestHeader(String headerName, String headerValue) 

Source Link

Document

Set the specified request header, overwriting any previous value.

Usage

From source file:de.mpg.escidoc.http.UserGroup.java

public Boolean deleteUserGroup() {
    String userGroupID = Util.input("ID of the UserGroup to be deleted: ");
    // String userGroupID = "escidoc:27001";
    if (this.USER_HANDLE != null) {
        DeleteMethod delete = new DeleteMethod(FRAMEWORK_URL + "/aa/user-group/" + userGroupID);
        delete.setRequestHeader("Cookie", "escidocCookie=" + this.USER_HANDLE);
        try {/*from  w  w w  .j  a va 2s  .  com*/
            this.client.executeMethod(delete);
            if (delete.getStatusCode() != 200) {
                System.out.println("Server StatusCode: " + delete.getStatusCode());
                return false;
            }
            System.out.println("Usergroup " + userGroupID + " deleted");
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("Error in deleteUserGroup: No userHandle available");
    }
    return true;
}

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  a2 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:com.cloud.network.nicira.NiciraNvpApi.java

private void executeDeleteObject(String uri) throws NiciraNvpApiException {
    String url;/*from www. jav  a 2s . co  m*/
    try {
        url = new URL(_protocol, _host, uri).toString();
    } catch (MalformedURLException e) {
        s_logger.error("Unable to build Nicira API URL", e);
        throw new NiciraNvpApiException("Unable to build Nicira API URL", e);
    }

    DeleteMethod dm = new DeleteMethod(url);
    dm.setRequestHeader("Content-Type", "application/json");

    executeMethod(dm);

    if (dm.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
        String errorMessage = responseToErrorMessage(dm);
        dm.releaseConnection();
        s_logger.error("Failed to delete object : " + errorMessage);
        throw new NiciraNvpApiException("Failed to delete object : " + errorMessage);
    }
    dm.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 .ja  v  a  2 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: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 ww . j av  a2 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: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
 *///from  w w w  .ja  v  a  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.dao.JsonDAOImpl.java

public JsonResponse removeItem(String token, String id, long since) throws HttpException, IOException {

    String request = Utility.getUrl(jsonServerUrl, resourceType, REMOVE_ITEM_URL) + Utility.URL_SEP + id;

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: start removeItem with id:" + id + "and since=" + since);
    }//from  w  w w.  j  a v a2s.  c o  m

    DeleteMethod remove = new DeleteMethod(request);

    if (since != 0) {
        NameValuePair nvp_since = new NameValuePair();
        nvp_since.setName("since");
        nvp_since.setValue("" + since);
        NameValuePair[] nvp = { nvp_since };
        remove.setQueryString(nvp);
    }

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: removeItem request:" + request);
    }
    remove.setRequestHeader(Utility.TOKEN_HEADER_NAME, token);

    int statusCode = 0;
    String responseBody = null;
    try {
        statusCode = httpClient.executeMethod(remove);
        responseBody = remove.getResponseBodyAsString();
    } finally {
        remove.releaseConnection();
    }

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: deleteItem response " + responseBody);
        log.trace("JsonDAOImpl: item with id:" + id + " removed");
    }

    JsonResponse response = new JsonResponse(statusCode, responseBody);

    return response;
}

From source file:com.funambol.json.dao.JsonDAOImpl.java

public JsonResponse removeAllItems(String token, long since) throws HttpException, IOException {

    String request = Utility.getUrl(jsonServerUrl, resourceType, REMOVE_ITEM_URL);

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: start removeAllItems");
    }//  w w w  .  j a  v a 2s. co m

    DeleteMethod remove = new DeleteMethod(request);

    if (since != 0) {
        NameValuePair nvp_since = new NameValuePair();
        nvp_since.setName("since");
        nvp_since.setValue("" + since);
        NameValuePair[] nvp = { nvp_since };
        remove.setQueryString(nvp);
    }

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: removeAllItem request:" + request);
    }
    remove.setRequestHeader(Utility.TOKEN_HEADER_NAME, token);

    int statusCode = 0;
    String responseBody = null;
    try {
        statusCode = httpClient.executeMethod(remove);
        responseBody = remove.getResponseBodyAsString();
    } finally {
        remove.releaseConnection();
    }

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: deleteAllItem response " + responseBody);
    }

    JsonResponse response = new JsonResponse(statusCode, responseBody);

    return response;
}

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

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

    String response = null;/*from  www  . ja va  2  s  .com*/
    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:nl.nn.adapterframework.http.HttpSender.java

protected HttpMethod getMethod(URI uri, String message, ParameterValueList parameters,
        Map<String, String> headersParamsMap) throws SenderException {
    try {//  w  w  w  . ja  v a 2 s . com
        boolean queryParametersAppended = false;
        if (isEncodeMessages()) {
            message = URLEncoder.encode(message);
        }

        StringBuffer path = new StringBuffer(uri.getPath());
        if (!StringUtils.isEmpty(uri.getQuery())) {
            path.append("?" + uri.getQuery());
            queryParametersAppended = true;
        }

        if (getMethodType().equals("GET")) {
            if (parameters != null) {
                queryParametersAppended = appendParameters(queryParametersAppended, path, parameters,
                        headersParamsMap);
                if (log.isDebugEnabled())
                    log.debug(getLogPrefix() + "path after appending of parameters [" + path.toString() + "]");
            }
            GetMethod result = new GetMethod(path + (parameters == null ? message : ""));
            for (String param : headersParamsMap.keySet()) {
                result.addRequestHeader(param, headersParamsMap.get(param));
            }
            if (log.isDebugEnabled())
                log.debug(
                        getLogPrefix() + "HttpSender constructed GET-method [" + result.getQueryString() + "]");
            return result;
        } else if (getMethodType().equals("POST")) {
            PostMethod postMethod = new PostMethod(path.toString());
            if (StringUtils.isNotEmpty(getContentType())) {
                postMethod.setRequestHeader("Content-Type", getContentType());
            }
            if (parameters != null) {
                StringBuffer msg = new StringBuffer(message);
                appendParameters(true, msg, parameters, headersParamsMap);
                if (StringUtils.isEmpty(message) && msg.length() > 1) {
                    message = msg.substring(1);
                } else {
                    message = msg.toString();
                }
            }
            for (String param : headersParamsMap.keySet()) {
                postMethod.addRequestHeader(param, headersParamsMap.get(param));
            }
            postMethod.setRequestBody(message);

            return postMethod;
        }
        if (getMethodType().equals("PUT")) {
            PutMethod putMethod = new PutMethod(path.toString());
            if (StringUtils.isNotEmpty(getContentType())) {
                putMethod.setRequestHeader("Content-Type", getContentType());
            }
            if (parameters != null) {
                StringBuffer msg = new StringBuffer(message);
                appendParameters(true, msg, parameters, headersParamsMap);
                if (StringUtils.isEmpty(message) && msg.length() > 1) {
                    message = msg.substring(1);
                } else {
                    message = msg.toString();
                }
            }
            putMethod.setRequestBody(message);
            return putMethod;
        }
        if (getMethodType().equals("DELETE")) {
            DeleteMethod deleteMethod = new DeleteMethod(path.toString());
            if (StringUtils.isNotEmpty(getContentType())) {
                deleteMethod.setRequestHeader("Content-Type", getContentType());
            }
            return deleteMethod;
        }
        if (getMethodType().equals("HEAD")) {
            HeadMethod headMethod = new HeadMethod(path.toString());
            if (StringUtils.isNotEmpty(getContentType())) {
                headMethod.setRequestHeader("Content-Type", getContentType());
            }
            return headMethod;
        }
        if (getMethodType().equals("REPORT")) {
            Element element = XmlUtils.buildElement(message, true);
            ReportInfo reportInfo = new ReportInfo(element, 0);
            ReportMethod reportMethod = new ReportMethod(path.toString(), reportInfo);
            if (StringUtils.isNotEmpty(getContentType())) {
                reportMethod.setRequestHeader("Content-Type", getContentType());
            }
            return reportMethod;
        }
        throw new SenderException(
                "unknown methodtype [" + getMethodType() + "], must be either POST, GET, PUT or DELETE");
    } catch (URIException e) {
        throw new SenderException(getLogPrefix() + "cannot find path from url [" + getUrl() + "]", e);
    } catch (DavException e) {
        throw new SenderException(e);
    } catch (DomBuilderException e) {
        throw new SenderException(e);
    } catch (IOException e) {
        throw new SenderException(e);
    }
}