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

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

Introduction

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

Prototype

@Override
public void setQueryString(String queryString) 

Source Link

Document

Sets the query string of this HTTP method.

Usage

From source file:org.eclipse.orion.server.cf.commands.DeleteApplicationCommand.java

@Override
protected ServerStatus _doIt() {
    try {//from  w  ww . j  av a2 s .  c  o m

        /* read deploy parameters */
        JSONObject appMetadata = null;
        JSONObject appEntity = null;

        URI targetURI = URIUtil.toURI(target.getUrl());

        /* get application details */
        String appsUrl = target.getSpace().getCFJSON().getJSONObject("entity").getString("apps_url"); //$NON-NLS-1$//$NON-NLS-2$
        URI appsURI = targetURI.resolve(appsUrl);
        GetMethod getAppsMethod = new GetMethod(appsURI.toString());
        HttpUtil.configureHttpMethod(getAppsMethod, target);
        getAppsMethod.setQueryString("q=name:" + appName + "&inline-relations-depth=1"); //$NON-NLS-1$ //$NON-NLS-2$

        ServerStatus appsStatus = HttpUtil.executeMethod(getAppsMethod);
        if (!appsStatus.isOK())
            return appsStatus;

        JSONObject apps = appsStatus.getJsonData();
        if (!apps.has("resources") || apps.getJSONArray("resources").length() == 0) //$NON-NLS-1$//$NON-NLS-2$
            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "Application not found",
                    null);

        appMetadata = apps.getJSONArray("resources").getJSONObject(0).getJSONObject("metadata"); //$NON-NLS-1$ //$NON-NLS-2$
        appEntity = apps.getJSONArray("resources").getJSONObject(0).getJSONObject("entity"); //$NON-NLS-1$ //$NON-NLS-2$

        if (application.getGuid() == null) {

            String summaryAppUrl = appMetadata.getString("url") + "/summary"; //$NON-NLS-1$ //$NON-NLS-2$
            URI summaryAppURI = targetURI.resolve(summaryAppUrl);

            GetMethod getSummaryMethod = new GetMethod(summaryAppURI.toString());
            HttpUtil.configureHttpMethod(getSummaryMethod, target);

            ServerStatus getStatus = HttpUtil.executeMethod(getSummaryMethod);
            if (!getStatus.isOK())
                return getStatus;

            JSONObject summaryJSON = getStatus.getJsonData();

            /* set known application GUID */
            application.setGuid(summaryJSON.getString(CFProtocolConstants.V2_KEY_GUID));
        }

        /* gather application service bindings */
        ArrayList<String> serviceInstances = new ArrayList<String>();
        JSONArray appServiceBindings = appEntity.getJSONArray("service_bindings"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
        for (int i = 0; i < appServiceBindings.length(); ++i) {
            JSONObject binding = appServiceBindings.getJSONObject(i).getJSONObject("entity"); //$NON-NLS-1$
            serviceInstances.add(binding.getString("service_instance_url")); //$NON-NLS-1$
        }

        /* delete the application */
        URI appURI = targetURI.resolve("/v2/apps/" + application.getGuid()); //$NON-NLS-1$

        DeleteMethod deleteAppMethod = new DeleteMethod(appURI.toString());
        HttpUtil.configureHttpMethod(deleteAppMethod, target);
        deleteAppMethod.setQueryString("recursive=true"); //$NON-NLS-1$

        ServerStatus status = HttpUtil.executeMethod(deleteAppMethod);
        return status;

    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName);
        logger.error(msg, e);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
}

From source file:org.eclipse.orion.server.cf.commands.DeleteRouteCommand.java

@Override
protected ServerStatus _doIt() {
    try {//  ww  w  . j av  a 2s . c om
        URI targetURI = URIUtil.toURI(target.getUrl());

        /* delete the route */
        URI routeURI = targetURI.resolve("/v2/routes/" + route.getGuid()); //$NON-NLS-1$

        DeleteMethod deleteRouteMethod = new DeleteMethod(routeURI.toString());
        HttpUtil.configureHttpMethod(deleteRouteMethod, target);
        deleteRouteMethod.setQueryString("recursive=true"); //$NON-NLS-1$

        ServerStatus status = HttpUtil.executeMethod(deleteRouteMethod);
        return status;

    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName);
        logger.error(msg, e);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
}

From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java

/**
 * Fire off a request to a URL using the specified method but reuse the client for efficiency,
 * include optional params and data in the request,
 * the response data will be returned in the object if the request can be carried out
 * //from  ww w.ja v a2 s  .  com
 * @param httpClientWrapper (optional) allows the http client to be reused for efficiency,
 * if null a new one will be created each time, use {@link #makeReusableHttpClient(boolean, int)} to
 * create a reusable instance
 * @param URL the url to send the request to (absolute or relative, can include query params)
 * @param method the method to use (e.g. GET, POST, etc.)
 * @param params (optional) params to send along with the request, will be encoded in the query string or in the body depending on the method
 * @param params (optional) headers to send along with the request, will be encoded in the headers
 * @param data (optional) data to send along in the body of the request, this only works for POST and PUT requests, ignored for the other types
 * @param guaranteeSSL if this is true then the request is sent in a mode which will allow self signed certs to work,
 * otherwise https requests will fail if the certs cannot be centrally verified
 * @return an object representing the response, includes data about the response
 * @throws HttpRequestException if the request cannot be processed for some reason (this is unrecoverable)
 */
@SuppressWarnings("deprecation")
public static HttpResponse fireRequest(HttpClientWrapper httpClientWrapper, String URL, Method method,
        Map<String, String> params, Map<String, String> headers, Object data, boolean guaranteeSSL) {
    if (guaranteeSSL) {
        // added this to attempt to force the SSL self signed certs to work
        Protocol myhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttps);
    }

    if (httpClientWrapper == null || httpClientWrapper.getHttpClient() == null) {
        httpClientWrapper = makeReusableHttpClient(false, 0, null);
    }

    HttpMethod httpMethod = null;
    if (method.equals(Method.GET)) {
        GetMethod gm = new GetMethod(URL);
        // put params into query string
        gm.setQueryString(mergeQueryStringWithParams(gm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in GET requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        gm.setFollowRedirects(true);
        httpMethod = gm;
    } else if (method.equals(Method.POST)) {
        PostMethod pm = new PostMethod(URL);
        // special handling for post params
        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                if (entry.getKey() == null || entry.getValue() == null) {
                    System.out.println("WARN: null value supplied for param name (" + entry.getKey()
                            + ") or value (" + entry.getValue()
                            + ") (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
                }
                pm.addParameter(entry.getKey(), entry.getValue());
            }
        }
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.PUT)) {
        PutMethod pm = new PutMethod(URL);
        // put params into query string
        pm.setQueryString(mergeQueryStringWithParams(pm.getQueryString(), params));
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.DELETE)) {
        DeleteMethod dm = new DeleteMethod(URL);
        // put params into query string
        dm.setQueryString(mergeQueryStringWithParams(dm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in DELETE requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        httpMethod = dm;
    } else {
        throw new IllegalArgumentException("Cannot handle method: " + method);
    }
    // set the headers for the request
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            httpMethod.addRequestHeader(entry.getKey(), entry.getValue());
        }
    }

    HttpResponse response = null;
    try {
        int responseCode = httpClientWrapper.getHttpClient().executeMethod(httpMethod);
        response = new HttpResponse(responseCode);

        // Avoid DOS because of large responses using up all memory in the system - https://jira.sakaiproject.org/browse/SAK-20405
        InputStream is = httpMethod.getResponseBodyAsStream();
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = is.read(b)) != -1;) {
            out.append(new String(b, 0, n));
            if (out.length() > MAX_RESPONSE_SIZE_CHARS) {
                // die if the response exceeds the maximum chars allowed
                throw new HttpRequestException("Response size (" + out.length() + " chars) from url (" + URL
                        + ") exceeded the maximum allowed batch response size (" + MAX_RESPONSE_SIZE_CHARS
                        + " chars) while processing the response");
            }
        }
        String body = out.toString();

        //String body = httpMethod.getResponseBodyAsString();
        //         byte[] responseBody = httpMethod.getResponseBody();
        //         if (responseBody != null) {
        //            body = new String(responseBody, "UTF-8");
        //         }
        response.setResponseBody(body);
        response.setResponseMessage(httpMethod.getStatusText());
        // now get the headers
        HashMap<String, String[]> responseHeaders = new HashMap<String, String[]>();
        Header[] respHeaders = httpMethod.getResponseHeaders();
        for (int i = 0; i < respHeaders.length; i++) {
            Header header = respHeaders[i];
            // now we convert the headers from these odd pairs into something more like servlets expect
            HeaderElement[] elements = header.getElements();
            if (elements == null || elements.length == 0) {
                continue;
            } else if (elements.length >= 1) {
                String[] values = new String[elements.length];
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < elements.length; j++) {
                    sb.setLength(0); // clear the StringBuilder
                    sb.append(elements[j].getName());
                    if (elements[j].getValue() != null) {
                        sb.append("=");
                        sb.append(elements[j].getValue());
                    }
                    values[j] = sb.toString();
                }
                responseHeaders.put(header.getName(), values);
            }
        }
        response.setResponseHeaders(responseHeaders);
    } catch (HttpException he) {
        // error contained in he.getMessage()
        throw new HttpRequestException(
                "Fatal HTTP Request Error: " + "Could not sucessfully fire request to url (" + URL
                        + ") using method (" + method + ")  :: " + he.getMessage(),
                he);
    } catch (IOException ioe) {
        // other exception
        throw new HttpIOException(
                "IOException (transport/connection) Error: " + "Could not sucessfully fire request to url ("
                        + URL + ") using method (" + method + ")  :: " + ioe.getMessage(),
                ioe);
    } finally {
        httpMethod.releaseConnection();
    }
    return response;
}