Example usage for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity

List of usage examples for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity

Introduction

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

Prototype

public StringRequestEntity(String paramString) 

Source Link

Usage

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

/**
 * @param args/*from  w  w w  .  j  a v a 2s  .co 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.cloud.ucs.manager.UcsHttpClient.java

public String call(String xml) {
    PostMethod post = new PostMethod(url);
    post.setRequestEntity(new StringRequestEntity(xml));
    post.setRequestHeader("Content-type", "text/xml");
    //post.setFollowRedirects(true);
    try {//from   ww w.j  av  a  2  s.c o m
        int result = client.executeMethod(post);
        if (result == 302) {
            // Handle HTTPS redirect
            // Ideal way might be to configure from add manager API
            // for using either HTTP / HTTPS
            // Allow only one level of redirect
            String redirectLocation;
            Header locationHeader = post.getResponseHeader("location");
            if (locationHeader != null) {
                redirectLocation = locationHeader.getValue();
            } else {
                throw new CloudRuntimeException("Call failed: Bad redirect from UCS Manager");
            }
            post.setURI(new URI(redirectLocation));
            result = client.executeMethod(post);
        }
        // Check for errors
        if (result != 200) {
            throw new CloudRuntimeException("Call failed: " + post.getResponseBodyAsString());
        }
        String res = post.getResponseBodyAsString();
        if (res.contains("errorCode")) {
            String err = String.format("ucs call failed:\nsubmitted doc:%s\nresponse:%s\n", xml, res);
            throw new CloudRuntimeException(err);
        }
        return res;
    } catch (Exception e) {
        throw new CloudRuntimeException(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
}

From source file:com.thoughtworks.go.remote.work.RemoteConsoleAppender.java

public void append(String content) throws IOException {
    PutMethod putMethod = new PutMethod(consoleUri);
    try {/*from  ww w  . j av  a  2 s.  c o m*/
        HttpClient httpClient = httpService.httpClient();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Appending console to URL -> " + consoleUri);
        }
        putMethod.setRequestEntity(new StringRequestEntity(content));

        HttpClientParams clientParams = new HttpClientParams();
        clientParams.setParameter("agentId", agentIdentifier.getUuid());
        HttpService.setSizeHeader(putMethod, content.getBytes().length);
        putMethod.setParams(clientParams);
        httpClient.executeMethod(putMethod);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Got " + putMethod.getStatusCode());
        }
    } finally {
        putMethod.releaseConnection();
    }
}

From source file:at.ac.tuwien.auto.sewoa.http.HttpRetrieverImpl.java

public byte[] postData(String url, String data) {
    byte[] result = new byte[] {};
    HttpClient httpClient = httpClientFactory.createClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.setRequestEntity(new StringRequestEntity(data));

    HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams();
    params.setConnectionTimeout((int) TimeUnit.SECONDS.toMillis(CONNECTION_TO));
    params.setSoTimeout((int) TimeUnit.SECONDS.toMillis(SOCKET_TO));
    postMethod.addRequestHeader("Content-Type", "application/xml");
    postMethod.addRequestHeader("Accept", "application/xml");

    try {//from w  ww.  j a v  a 2  s.c  o m
        result = send(httpClient, postMethod);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.owncloud.android.operations.CommentFileOperation.java

/**
 * Performs the operation.//from   ww w.  j a va  2  s  . c o m
 *
 * @param client Client object to communicate with the remote ownCloud server.
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {

    RemoteOperationResult result;
    try {
        String url = client.getNewWebdavUri() + "/comments/files/" + fileId;
        PostMethod postMethod = new PostMethod(url);
        postMethod.addRequestHeader("Content-type", "application/json");

        Map<String, String> values = new HashMap<>();
        values.put(ACTOR_ID, userId);
        values.put(ACTOR_TYPE, ACTOR_TYPE_VALUE);
        values.put(VERB, VERB_VALUE);
        values.put(MESSAGE, message);

        String json = new GsonBuilder().create().toJson(values, Map.class);

        postMethod.setRequestEntity(new StringRequestEntity(json));

        int status = client.executeMethod(postMethod, POST_READ_TIMEOUT, POST_CONNECTION_TIMEOUT);

        result = new RemoteOperationResult(isSuccess(status), postMethod);

        client.exhaustResponse(postMethod.getResponseBodyAsStream());
    } catch (IOException e) {
        result = new RemoteOperationResult(e);
        Log.e(TAG, "Post comment to file with id " + fileId + " failed: " + result.getLogMessage(), e);
    }

    return result;
}

From source file:com.rallydev.integration.build.rest.RallyRestServiceTest.java

protected void setUp() throws Exception {
    rallyRestService = new RallyRestService("user", "password", "host", "Build Plugin",
            RallyRestService.WSAPI_VERSION);
    httpClientMockControl = MockClassControl.createControl(HttpClient.class);
    httpClientMock = (HttpClient) httpClientMockControl.getMock();
    postMethodMockControl = MockClassControl.createControl(PostMethod.class);
    postMethodMock = (PostMethod) postMethodMockControl.getMock();
    httpStateMockControl = MockClassControl.createControl(HttpState.class);
    httpStateMock = (HttpState) httpStateMockControl.getMock();
    hostConfigurationMockControl = MockClassControl.createControl(HostConfiguration.class);
    hostConfigurationMock = (HostConfiguration) hostConfigurationMockControl.getMock();
    statusLineMockControl = MockClassControl.createControl(StatusLine.class);
    statusLineMock = (StatusLine) statusLineMockControl.getMock();
    httpClientMockControl.expectAndReturn(httpClientMock.getState(), httpStateMock);
    postMethodMock.setRequestHeader("foo", "foo");
    postMethodMockControl.setMatcher(MockControl.ALWAYS_MATCHER);
    postMethodMockControl.setVoidCallable(6);
    httpStateMock.setCredentials(new AuthScope("host", -1, null),
            new UsernamePasswordCredentials("user", "password"));
    postMethodMock.setRequestEntity(new StringRequestEntity(""));
    postMethodMockControl.setMatcher(MockControl.ALWAYS_MATCHER);
    httpStateMockControl.replay();//from  w  ww . j  a  va 2  s  .c o  m
}

From source file:at.ac.tuwien.auto.sewoa.http.HttpRetrieverImpl.java

public byte[] putData(String url, String data) {
    byte[] result = new byte[] {};
    HttpClient httpClient = httpClientFactory.createClient();
    PutMethod putmethod = new PutMethod(url);
    putmethod.setRequestEntity(new StringRequestEntity(data));

    HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams();
    params.setConnectionTimeout((int) TimeUnit.SECONDS.toMillis(CONNECTION_TO));
    params.setSoTimeout((int) TimeUnit.SECONDS.toMillis(SOCKET_TO));
    putmethod.addRequestHeader("Content-Type", "application/xml");
    putmethod.addRequestHeader("Accept", "application/xml");

    try {/* ww w . ja v  a  2  s .co m*/
        result = send(httpClient, putmethod);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

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

@SuppressWarnings("deprecation")
public Boolean createUserGroups() {
    String userGroupName = Util.input("Name of the UserGroup to create: ");
    String userGroupLabel = Util.input("Label of the UserGroup to create: ");
    Document responseXML = null;/*from w  ww . j  a  va 2  s.com*/
    if (this.USER_HANDLE != null) {
        PutMethod put = new PutMethod(this.FRAMEWORK_URL + "/aa/user-group");
        put.setRequestHeader("Cookie", "escidocCookie=" + this.USER_HANDLE);
        try {
            System.out.println("Request body sent to Server: ");
            put.setRequestEntity(new StringRequestEntity(Util.getCreateXml(userGroupName, userGroupLabel)));
            this.client.executeMethod(put);
            if (put.getStatusCode() != 200) {
                System.out.println("Server StatusCode: " + put.getStatusCode());
                return false;
            }
            System.out.println("Server response: ");
            responseXML = Util.inputStreamToXmlDocument(put.getResponseBodyAsStream());
            Util.xmlToString(responseXML);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("Error in creatUserGroup: No userHandle available");
    }
    return true;
}

From source file:ccc.api.http.SiteBrowserImpl.java

/** {@inheritDoc} */
@Override/*from   w  w  w.  j ava 2 s . c o  m*/
public String postUrlEncoded(final ResourceSummary rs, final Map<String, String[]> params) {
    /* This method deliberately elides charset values to replicate the
     * behaviour of a typical browser.                                    */

    final PostMethod post = new PostMethod(_hostUrl + rs.getAbsolutePath());
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    final List<NameValuePair> qParams = new ArrayList<NameValuePair>();
    for (final Map.Entry<String, String[]> param : params.entrySet()) {
        for (final String value : param.getValue()) {
            final NameValuePair qParam = new NameValuePair(param.getKey(), value);
            qParams.add(qParam);
        }
    }

    final StringBuilder buffer = createQueryString(qParams);
    post.setRequestEntity(new StringRequestEntity(buffer.toString()));

    return invoke(post);
}

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);/*from w  ww .  jav  a2  s  .  c  om*/
        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);
}