Example usage for org.apache.commons.httpclient.methods PutMethod setRequestBody

List of usage examples for org.apache.commons.httpclient.methods PutMethod setRequestBody

Introduction

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

Prototype

public void setRequestBody(InputStream paramInputStream) 

Source Link

Usage

From source file:net.bioclipse.opentox.api.Dataset.java

@SuppressWarnings("serial")
public static void addMolecules(String datasetURI, String sdFile, IProgressMonitor monitor) throws Exception {
    if (monitor == null)
        monitor = new NullProgressMonitor();

    HttpClient client = new HttpClient();
    datasetURI = normalizeURI(datasetURI);
    PutMethod method = new PutMethod(datasetURI);
    HttpMethodHelper.addMethodHeaders(method, new HashMap<String, String>() {
        {/*from  w  w w.  j  a v a2s. co  m*/
            put("Accept", "text/uri-list");
            put("Content-type", "chemical/x-mdl-sdfile");
        }
    });
    method.setRequestBody(sdFile);
    client.executeMethod(method);
    int status = method.getStatusCode();
    String dataset = "";
    String responseString = method.getResponseBodyAsString();
    logger.debug("Response: " + responseString);
    int tailing = 1;
    if (status == 200) {
        // OK, that was quick!
        dataset = method.getResponseBodyAsString();
        logger.debug("No Task, Data set: " + dataset);
    } else if (status == 202 || status == 201) {
        // OK, we got a task... let's wait until it is done
        String task = method.getResponseBodyAsString();
        Thread.sleep(1000); // let's be friendly, and wait 1 sec
        TaskState state = Task.getState(task);
        while (!state.isFinished() && !monitor.isCanceled()) {
            // let's be friendly, and wait 2 secs and a bit and increase
            // that time after each wait
            int waitingTime = andABit(2000 * tailing);
            logger.debug("Waiting " + waitingTime + "ms.");
            waitUnlessInterrupted(waitingTime, monitor);
            state = Task.getState(task);
            if (state.isRedirected()) {
                task = state.getResults();
                logger.debug("  new task, new task!!: " + task);
            }
            // but wait at most 20 secs and a bit
            if (tailing < 10)
                tailing++;
        }
        if (monitor.isCanceled())
            Task.delete(task);
        // OK, it should be finished now
        dataset = state.getResults();
    } else {
        logger.warn("Unexpected return code when adding molecules: " + status);
    }
    method.releaseConnection();
}

From source file:net.bioclipse.opentox.api.Dataset.java

public static void setMetadata(String datasetURI, String predicate, String value) throws Exception {
    HttpClient client = new HttpClient();
    PutMethod method = new PutMethod(normalizeURI(datasetURI) + "metadata");
    HttpMethodHelper.addMethodHeaders(method, new HashMap<String, String>() {
        {//from  w w  w.j  a  v a  2s .c  o  m
            put("Content-type", "text/n3");
        }
    });
    String triples = "<" + datasetURI + "> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> "
            + "<http://www.opentox.org/api/1.1#Dataset> .\n" + "<" + datasetURI + "> <" + predicate + "> "
            + value + " .";
    System.out.println("Triples:\n" + triples);
    method.setRequestBody(triples);
    client.executeMethod(method);
    int status = method.getStatusCode();
    if (status == 200) {
        // OK, that was quick!
        String response = method.getResponseBodyAsString();
        System.out.println("Set value response: " + response);
    } else if (status == 202) {
        // OK, we got a task... let's wait until it is done
        String task = method.getResponseBodyAsString();
        Thread.sleep(1000); // let's be friendly, and wait 1 sec
        TaskState state = Task.getState(task);
        while (!state.isFinished()) {
            Thread.sleep(3000); // let's be friendly, and wait 3 sec
            state = Task.getState(task);
            if (state.isRedirected()) {
                task = state.getResults();
            }
        }
        // OK, it should be finished now
        String dataset = state.getResults();
    } else {
        throw new BioclipseException("Status : " + status);
    }
    method.releaseConnection();
}

From source file:edu.stanford.epad.epadws.queries.XNATQueries.java

public static int setXNATSubjectField(String sessionID, String subjectID, String fieldName, String fieldValue) {
    HttpClient client = new HttpClient();
    //HttpPut httpput = new HttpPut(XNATQueryUtil.buildSubjectURL(subjectID));
    PutMethod method = new PutMethod(XNATQueryUtil.buildSubjectURL(subjectID));
    int xnatStatusCode;

    method.setRequestHeader("Cookie", "JSESSIONID=" + sessionID);

    try {//from   www . j  av a2s .c  o  m
        //httpput.setHeader("Cookie", "JSESSIONID=" + sessionID);
        //httpput.setEntity(new StringEntity(, "text/xml", "utf8"));
        method.setRequestBody(XNATQueryUtil.buildSubjectFieldXML(fieldName, fieldValue));
        //HttpResponse response = client.execute(httpput);
        xnatStatusCode = client.executeMethod(method);
    } catch (IOException e) {
        log.warning("Warning: error performing XNAT subject query " + XNATQueryUtil.buildSubjectURL(subjectID),
                e);
        xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    } finally {
        method.releaseConnection();
    }
    return xnatStatusCode;
}

From source file:com.cellbots.remoteEyes.RemoteEyesActivity.java

private void uploadImage(byte[] imageData) {
    try {//from w  ww. j a v a2s  .  c  o m
        YuvImage yuvImage = new YuvImage(imageData, previewFormat, previewWidth, previewHeight, null);
        yuvImage.compressToJpeg(r, 20, out); // Tweak the quality here - 20
        // seems pretty decent for
        // quality + size.
        PutMethod put = new PutMethod(putUrl);
        put.setRequestBody(new ByteArrayInputStream(out.toByteArray()));
        put.execute(mHttpState, mConnection);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
        resetConnection();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        resetConnection();
    } catch (IOException e) {
        e.printStackTrace();
        resetConnection();
    } finally {
        out.reset();
        if (mCamera != null) {
            mCamera.addCallbackBuffer(mCallbackBuffer);
        }
        isUploading = false;
    }

}

From source file:com.mercatis.lighthouse3.commons.commons.HttpRequest.java

/**
 * This method performs an HTTP request against an URL.
 *
 * @param url         the URL to call//from   ww w.  j  a  va  2  s . co  m
 * @param method      the HTTP method to execute
 * @param body        the body of a POST or PUT request, can be <code>null</code>
 * @param queryParams a Hash with the query parameter, can be <code>null</code>
 * @return the data returned by the web server
 * @throws HttpException in case a communication error occurred.
 */
@SuppressWarnings("deprecation")
public String execute(String url, HttpRequest.HttpMethod method, String body, Map<String, String> queryParams) {

    NameValuePair[] query = null;

    if (queryParams != null) {
        query = new NameValuePair[queryParams.size()];

        int counter = 0;
        for (Entry<String, String> queryParam : queryParams.entrySet()) {
            query[counter] = new NameValuePair(queryParam.getKey(), queryParam.getValue());
            counter++;
        }
    }

    org.apache.commons.httpclient.HttpMethod request = null;

    if (method == HttpMethod.GET) {
        request = new GetMethod(url);
    } else if (method == HttpMethod.POST) {
        PostMethod postRequest = new PostMethod(url);
        if (body != null) {
            postRequest.setRequestBody(body);
        }
        request = postRequest;
    } else if (method == HttpMethod.PUT) {
        PutMethod putRequest = new PutMethod(url);
        if (body != null) {
            putRequest.setRequestBody(body);
        }
        request = putRequest;
    } else if (method == HttpMethod.DELETE) {
        request = new DeleteMethod(url);
    }

    request.setRequestHeader("Content-type", "application/xml;charset=utf-8");
    if (query != null) {
        request.setQueryString(query);
    }

    int resultCode = 0;
    StringBuilder resultBodyBuilder = new StringBuilder();

    try {
        resultCode = this.httpClient.executeMethod(request);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(request.getResponseBodyAsStream(), Charset.forName("UTF-8")));
        String line = null;
        while ((line = reader.readLine()) != null) {
            resultBodyBuilder.append(line);
        }

        if (resultCode != 200) {
            throw new HttpException(resultBodyBuilder.toString(), null);
        }
    } catch (HttpException httpException) {
        throw new HttpException("HTTP request failed", httpException);
    } catch (IOException ioException) {
        throw new HttpException("HTTP request failed", ioException);
    } catch (NullPointerException npe) {
        throw new HttpException("HTTP request failed", npe);
    } finally {
        request.releaseConnection();
    }

    return resultBodyBuilder.toString();
}

From source file:gov.va.vinci.leo.tools.JamService.java

/**
 * Given a queuename and broker, do an immediate gather of stats.
 * @param queueName the queue name of the service.
 * @param brokerUrl  the broker url for the service.
 * @throws IOException  if any communication exception occurs.
 *//*  w  w w  . j  a v a 2  s  .  co  m*/
public void runGather(final String queueName, final String brokerUrl) throws IOException {
    String requestBody = getServiceQueueExistRequestBody(queueName, brokerUrl);
    PutMethod method = new PutMethod(jamServerBaseUrl + "webservice/runGather");
    method.setRequestBody(requestBody);
    doHttpCall(method);
}

From source file:gov.va.vinci.leo.tools.JamService.java

/**
 * A web service that add a server to an existing service queue.
 *
 * @param queueName the name of the queue to add this host to.
 * @param host      the host name to add to the service queue
 * @param port      the port on the host that is added to the service queue
 * @param brokerUrl  the broker url this service is using.
 * @throws IOException if any communication exception occurs.
 *///from  www .  j av  a2  s. co m
public void addServerToServiceQueue(final String queueName, final String brokerUrl, final String host,
        final int port) throws IOException {
    String requestBody = createJmxServerXml(queueName, brokerUrl, host, port);
    PutMethod method = new PutMethod(jamServerBaseUrl + "webservice/addServerToServiceQueue");
    method.setRequestBody(requestBody);
    doHttpCall(method);
}

From source file:gov.va.vinci.leo.tools.JamService.java

/**
 * Registers a new service queue in Jam. Note: Service queue names MUST be unique in the jam system.
 *
 * @param queueName the name of the queue to register with.
 * @param brokerUrl the broker url this service is using.
 * @param queryIntervalInSeconds the interval in seconds to query the running service for metrics.
 * @param resetStatisticsAfterQuery if true, statistics are reset to 0 after each gather. If false, statistics are
 *                                  cumulative.
 * @param profileEnabled if true the profile is enabled for gathering, if false, it is registered, but not enabled
 *                       for gathering./*from   w w w.j  av  a 2s .  c  om*/
 * @throws IOException  if any communication exception occurs.
 */
public void registerServiceQueue(final String queueName, final String brokerUrl,
        final int queryIntervalInSeconds, final boolean resetStatisticsAfterQuery, final boolean profileEnabled)
        throws IOException {
    String requestBody = getRegisterServiceRequestBody(queueName, brokerUrl, queryIntervalInSeconds,
            resetStatisticsAfterQuery, profileEnabled);

    PutMethod method = new PutMethod(jamServerBaseUrl + "webservice/registerServiceQueue");
    method.setRequestBody(requestBody);
    doHttpCall(method);
}

From source file:gov.va.vinci.leo.tools.JamService.java

/**
 * Given a queue name, determine if it already exists.
 *
 * @param queueName the ServiceQueue.queueName to check for
 * @param brokerUrl the broker url this service is using.
 * @return returns TRUE if the service queue name exists, or false if it does not.
 * @throws IOException if any communication exception occurs.
 *//*ww  w.  j a v  a 2  s . c om*/
public boolean doesServiceQueueExist(final String queueName, final String brokerUrl) throws IOException {
    PutMethod method = new PutMethod(jamServerBaseUrl + "webservice/doesServiceQueueExist");

    method.setRequestBody(getServiceQueueExistRequestBody(queueName, brokerUrl));

    String result = doHttpCall(method);
    return "TRUE".equals(result);

}

From source file:gov.va.vinci.leo.tools.JamService.java

/**
 * Remove a host/port from a service queue.
 * <p/>//from   w  w  w  .  ja  v a  2  s  .com
 * If the host is not part of the service queue, no-op. If it is
 * part of the Service Queue, it is removed.
 * @param queueName the name of the queue to remove.
 * @param brokerUrl the broker url this service is using.
 * @param host the host the service is running on.
 * @param port the port the service is running on.
 *
 * @throws IOException if any communication exception occurs.
 */
public void removeServerFromServiceQueue(final String queueName, final String brokerUrl, final String host,
        final int port) throws IOException {
    String requestBody = createJmxServerXml(queueName, brokerUrl, host, port);
    PutMethod method = new PutMethod(jamServerBaseUrl + "webservice/removeServerFromServiceQueue");
    method.setRequestBody(requestBody);
    doHttpCall(method);
}