Example usage for org.apache.commons.httpclient.methods PostMethod setRequestEntity

List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity

Introduction

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

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:de.mpg.escidoc.services.edoc.BatchUpdate.java

/**
 * @param args//from   w  w w  .j a  v a  2  s  .  c  o m
 */
public static void main(String[] args) throws Exception {
    CORESERVICES_URL = PropertyReader.getProperty("escidoc.framework_access.framework.url");

    String userHandle = AdminHelper.loginUser("import_user", "");

    logger.info("Querying core-services...");
    HttpClient httpClient = new HttpClient();
    String filter = "<param><filter name=\"http://escidoc.de/core/01/structural-relations/context\">"
            + IMPORT_CONTEXT
            + "</filter><order-by>http://escidoc.de/core/01/properties/creation-date</order-by><limit>0</limit></param>";

    logger.info("Filter: " + filter);

    PostMethod postMethod = new PostMethod(CORESERVICES_URL + "/ir/items/filter");

    postMethod.setRequestBody(filter);

    ProxyHelper.executeMethod(httpClient, postMethod);

    //        GetMethod getMethod = new GetMethod(CORESERVICES_URL + "/ir/item/escidoc:100220");
    //        getMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle)ProxyHelper.executeMethod(httpClient, getMethod)hod(httpClient, getMethod);

    String response = postMethod.getResponseBodyAsString();
    logger.info("...done!");

    System.out.println(response);

    while (response.contains("<escidocItem:item")) {

        int startPos = response.indexOf("<escidocItem:item");
        int endPos = response.indexOf("</escidocItem:item>");

        String item = response.substring(startPos, endPos + 19);

        response = response.substring(endPos + 19);

        startPos = item.indexOf("xlink:href=\"");
        endPos = item.indexOf("\"", startPos + 12);

        String objId = item.substring(startPos + 12, endPos);

        System.out.print(objId);

        if (item.contains("escidoc:22019")) {
            item = item.replaceAll("escidoc:22019", "escidoc:55222");

            PutMethod putMethod = new PutMethod(CORESERVICES_URL + objId);

            putMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
            putMethod.setRequestEntity(new StringRequestEntity(item));
            ProxyHelper.executeMethod(httpClient, putMethod);

            String result = putMethod.getResponseBodyAsString();

            //System.out.println(item);

            startPos = result.indexOf("last-modification-date=\"");
            endPos = result.indexOf("\"", startPos + 24);
            String modDate = result.substring(startPos + 24, endPos);
            //System.out.println("modDate: " + modDate);
            String param = "<param last-modification-date=\"" + modDate
                    + "\"><url>http://pubman.mpdl.mpg.de/pubman/item/" + objId.substring(4) + "</url></param>";
            postMethod = new PostMethod(CORESERVICES_URL + objId + "/assign-version-pid");
            postMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
            postMethod.setRequestEntity(new StringRequestEntity(param));
            ProxyHelper.executeMethod(httpClient, postMethod);
            result = postMethod.getResponseBodyAsString();
            //System.out.println("Result: " + result);

            startPos = result.indexOf("last-modification-date=\"");
            endPos = result.indexOf("\"", startPos + 24);
            modDate = result.substring(startPos + 24, endPos);
            //System.out.println("modDate: " + modDate);
            param = "<param last-modification-date=\"" + modDate
                    + "\"><comment>Batch repair of organizational unit identifier</comment></param>";
            postMethod = new PostMethod(CORESERVICES_URL + objId + "/submit");
            postMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
            postMethod.setRequestEntity(new StringRequestEntity(param));
            ProxyHelper.executeMethod(httpClient, postMethod);
            result = postMethod.getResponseBodyAsString();
            //System.out.println("Result: " + result);

            startPos = result.indexOf("last-modification-date=\"");
            endPos = result.indexOf("\"", startPos + 24);
            modDate = result.substring(startPos + 24, endPos);
            //System.out.println("modDate: " + modDate);
            param = "<param last-modification-date=\"" + modDate
                    + "\"><comment>Batch repair of organizational unit identifier</comment></param>";
            postMethod = new PostMethod(CORESERVICES_URL + objId + "/release");
            postMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
            postMethod.setRequestEntity(new StringRequestEntity(param));
            ProxyHelper.executeMethod(httpClient, postMethod);
            result = postMethod.getResponseBodyAsString();
            //System.out.println("Result: " + result);
            System.out.println("...changed");
        } else {
            System.out.println("...not affected");
        }
    }

}

From source file:com.mycompany.semconsolewebapp.FileUpload.java

public static void uploadImage(String urlString, Part[] parts) throws FileNotFoundException, IOException {
    PostMethod postMessage = new PostMethod(urlString);
    postMessage.setRequestEntity(new MultipartRequestEntity(parts, postMessage.getParams()));
    HttpClient client = new HttpClient();

    int status = client.executeMethod(postMessage);
    System.out.println("Got status message " + status);
}

From source file:com.ebay.pulsar.collector.Simulator.java

private static void sendMessage() throws IOException, JsonProcessingException, JsonGenerationException,
        JsonMappingException, UnsupportedEncodingException, HttpException {
    ObjectMapper mapper = new ObjectMapper();

    Map<String, Object> m = new HashMap<String, Object>();

    m.put("si", "12345");
    m.put("ct", System.currentTimeMillis());

    String payload = mapper.writeValueAsString(m);
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod("http://localhost:8080/tracking/ingest/PulsarRawEvent");
    //      method.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
    method.setRequestEntity(new StringRequestEntity(payload, "application/json", "UTF-8"));
    int status = client.executeMethod(method);
    System.out.println(Arrays.toString(method.getResponseHeaders()));
    System.out.println("Status code: " + status + ", Body: " + method.getResponseBodyAsString());
}

From source file:be.fedict.trust.service.util.ClockDriftUtil.java

public static Date executeTSP(ClockDriftConfigEntity clockDriftConfig, NetworkConfig networkConfig)
        throws IOException, TSPException {

    LOG.debug("clock drift detection: " + clockDriftConfig.toString());

    TimeStampRequestGenerator requestGen = new TimeStampRequestGenerator();

    TimeStampRequest request = requestGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100));
    byte[] requestData = request.getEncoded();

    HttpClient httpClient = new HttpClient();

    if (null != networkConfig) {
        httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort());
    }//w  w w .  j av a2s. co m

    PostMethod postMethod = new PostMethod(clockDriftConfig.getServer());
    postMethod.setRequestEntity(new ByteArrayRequestEntity(requestData, "application/timestamp-query"));

    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode != HttpStatus.SC_OK) {
        throw new TSPException("Error contacting TSP server " + clockDriftConfig.getServer());
    }

    TimeStampResponse tspResponse = new TimeStampResponse(postMethod.getResponseBodyAsStream());
    postMethod.releaseConnection();

    return tspResponse.getTimeStampToken().getTimeStampInfo().getGenTime();
}

From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.ServiceInvoker.java

/**
 * /*from  w  w  w.  j av a  2 s  .  c  o m*/
 * 
 */
public static int invoke(URL url, String userName, String password, Map<String, String> headers,
        InputStream input, HttpServletResponse output, OutputStream errorOut, int connectionTimeout,
        int soTimeout) throws IOException, SocketTimeoutException {
    HttpClient client = HttpClientUtil.createHttpClientWithHostConfig(url);
    SimpleHttpConnectionManager manager = new SimpleHttpConnectionManager(true);
    manager.getParams().setConnectionTimeout(connectionTimeout);
    manager.getParams().setSoTimeout(soTimeout);
    manager.getParams().setMaxConnectionsPerHost(client.getHostConfiguration(), 2);
    client.setHttpConnectionManager(manager);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));

    PostMethod method = new PostMethod(url.getFile());
    method.setRequestEntity(new InputStreamRequestEntity(input));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        method.addRequestHeader(e.getKey(), e.getValue());
    }
    if (!headers.containsKey("Content-Type"))
        method.addRequestHeader("Content-Type", "text/xml; charset=utf-8");
    if (!headers.containsKey("Accept"))
        method.addRequestHeader("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
    if (!headers.containsKey("SOAPAction"))
        method.addRequestHeader("SOAPAction", "\"\"");
    if (!headers.containsKey("User-Agent"))
        method.addRequestHeader("User-Agent", "Langrid Service Invoker/1.0");
    if (userName != null) {
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
            if (port == -1) {
                port = 80;
            }
        }
        if (password == null) {
            password = "";
        }
        client.getState().setCredentials(new AuthScope(url.getHost(), port, null),
                new UsernamePasswordCredentials(userName, password));
        client.getParams().setAuthenticationPreemptive(true);
        method.setDoAuthentication(true);
    }

    try {
        int status;
        try {
            status = client.executeMethod(method);
        } catch (SocketTimeoutException e) {
            status = HttpServletResponse.SC_REQUEST_TIMEOUT;
        }
        output.setStatus(status);
        if (status == 200) {
            for (Header h : method.getResponseHeaders()) {
                String name = h.getName();
                if (name.startsWith("X-Langrid") || (!throughHeaders.contains(name.toLowerCase())))
                    continue;
                String value = h.getValue();
                output.addHeader(name, value);
            }
            OutputStream os = output.getOutputStream();
            StreamUtil.transfer(method.getResponseBodyAsStream(), os);
            os.flush();
        } else if (status == HttpServletResponse.SC_REQUEST_TIMEOUT) {
        } else {
            StreamUtil.transfer(method.getResponseBodyAsStream(), errorOut);
        }
        return status;
    } finally {
        manager.shutdown();
    }
}

From source file:edu.uci.ics.external.connector.asterixdb.ConnectorUtils.java

public static void cleanDataset(StorageParameter storageParameter, DatasetInfo datasetInfo) throws Exception {
    // DDL service URL.
    String url = storageParameter.getServiceURL() + "/ddl";
    // Builds the DDL string to delete and (re-)create the sink datset.
    StringBuilder ddlBuilder = new StringBuilder();
    // use dataverse statement.
    ddlBuilder.append("use dataverse ");
    ddlBuilder.append(storageParameter.getDataverseName());
    ddlBuilder.append(";");

    // drop dataset statement.
    ddlBuilder.append("drop dataset ");
    ddlBuilder.append(storageParameter.getDatasetName());
    ddlBuilder.append(";");

    // create datset statement.
    ddlBuilder.append("create temporary dataset ");
    ddlBuilder.append(storageParameter.getDatasetName());
    ddlBuilder.append("(");
    ddlBuilder.append(datasetInfo.getRecordType().getTypeName());
    ddlBuilder.append(")");
    ddlBuilder.append(" primary key ");
    for (String primaryKey : datasetInfo.getPrimaryKeyFields()) {
        ddlBuilder.append(primaryKey);//  ww  w . ja v a  2 s  .  com
        ddlBuilder.append(",");
    }
    ddlBuilder.delete(ddlBuilder.length() - 1, ddlBuilder.length());
    ddlBuilder.append(";");

    // Create a method instance.
    PostMethod method = new PostMethod(url);
    method.setRequestEntity(new StringRequestEntity(ddlBuilder.toString()));
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    executeHttpMethod(method);
}

From source file:com.urswolfer.intellij.plugin.gerrit.rest.GerritApiUtil.java

@NotNull
private static HttpMethod doREST(@NotNull String host, @Nullable String login, @Nullable String password,
        @NotNull String path, @Nullable final String requestBody, final boolean post) throws IOException {
    HttpClient client = getHttpClient(login, password);
    String uri = host + path;//  w w w. ja  v a  2  s  . c  om
    return SslSupport.getInstance().executeSelfSignedCertificateAwareRequest(client, uri,
            new ThrowableConvertor<String, HttpMethod, IOException>() {
                @Override
                public HttpMethod convert(String uri) throws IOException {
                    if (post) {
                        PostMethod method = new PostMethod(uri);
                        if (requestBody != null) {
                            method.setRequestEntity(
                                    new StringRequestEntity(requestBody, "application/json", "UTF-8"));
                        }
                        return method;
                    }
                    return new GetMethod(uri);
                }
            });
}

From source file:com.google.appsforyourdomain.provisioning.AppsUtil.java

/**
 * Posts the specified postContent to the urlString and
 * returns a JDOM Document object containing the XML response.
 * /*w  w w . j a v  a2  s  .co m*/
 * @param urlString URL destination
 * @param postContent XML request
 * @return a JDOM Document object containing the XML response
 */
public static Document postHttpRequest(String urlString, String postContent) throws AppsForYourDomainException {
    try {

        // Send content
        final HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(urlString);
        StringRequestEntity sre = new StringRequestEntity(postContent, "text/xml", "UTF-8");
        method.setRequestEntity(sre);
        client.executeMethod(method);

        // Get response
        final SAXBuilder builder = new SAXBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        final Document doc = builder.build(rd);
        return doc;
    } catch (IOException e) {

        // error in URL Connection or reading response
        throw new ConnectionException(e.getMessage());
    } catch (JDOMException e) {

        // error in converting to JDOM Document
        throw new ParseException(e.getMessage());
    }
}

From source file:fr.eurecom.nerd.core.proxy.ExtractivClient.java

private static PostMethod getExtractivProcessString(final URI extractivURI, final String content,
        final String serviceKey) throws FileNotFoundException {

    final PartBase filePart = new StringPart("content", content, null);

    // bytes to upload
    final ArrayList<Part> message = new ArrayList<Part>();
    message.add(filePart);/*from   ww  w  .j a va2  s.  c o  m*/
    message.add(new StringPart("formids", "content"));
    message.add(new StringPart("output_format", "JSON"));
    message.add(new StringPart("api_key", serviceKey));

    final Part[] messageArray = message.toArray(new Part[0]);

    // Use a Post for the file upload
    final PostMethod postMethod = new PostMethod(extractivURI.toString());
    postMethod.setRequestEntity(new MultipartRequestEntity(messageArray, postMethod.getParams()));
    postMethod.addRequestHeader("Accept-Encoding", "gzip"); // Request the response be compressed (this is highly recommended)

    return postMethod;
}

From source file:com.infosupport.service.LPRServiceCaller.java

public static void postData(String urlString, File file) {
    try {//  w w  w .ja v a 2  s  .  c  o  m
        PostMethod postMessage = new PostMethod(urlString);
        Part[] parts = { new FilePart("lpimage", file), new StringPart("country", "eu"),
                new StringPart("nonce", "123456789") };
        postMessage.setRequestEntity(new MultipartRequestEntity(parts, postMessage.getParams()));
        HttpClient client = new HttpClient();
        client.executeMethod(postMessage);
    } catch (IOException e) {
        Log.w(TAG, "IOException, waarschijnlijk geen internet connectie aanwezig...");
    }
}