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:com.clarkparsia.sbol.editor.sparql.StardogEndpoint.java

@Override
public void addData(RDFInput input, String namedGraph) throws Exception {
    String txId = startTransaction();

    RequestEntity entity = createEntity(input);
    PostMethod post = new PostMethod(url + "/" + txId + "/add");
    if (namedGraph != null) {
        post.setQueryString(new NameValuePair[] { new NameValuePair("graph-uri", namedGraph) });
    }//from   w  w  w .j a  v a  2 s.c  o  m
    post.setRequestEntity(entity);

    execute(post);

    commitTransaction(txId);
}

From source file:com.denimgroup.threadfix.importer.impl.remoteprovider.utils.DefaultRequestConfigurer.java

@Override
public void configure(HttpMethodBase method) {
    if (username != null && password != null) {
        String login = username + ":" + password;
        String encodedLogin = DatatypeConverter.printBase64Binary(login.getBytes());

        method.setRequestHeader("Authorization", "Basic " + encodedLogin);
    }/*  ww w  . j av  a 2s .  c o  m*/

    method.setRequestHeader("Content-type", contentType);

    if (headerNames != null && headerVals != null && headerNames.length == headerVals.length) {
        for (int i = 0; i < headerNames.length; i++) {
            method.setRequestHeader(headerNames[i], headerVals[i]);
        }
    }

    if (method instanceof PostMethod) {
        PostMethod postVersion = (PostMethod) method;
        if (parameterNames != null && parameterVals != null && parameterNames.length == parameterVals.length) {
            for (int i = 0; i < parameterNames.length; i++) {
                postVersion.setParameter(parameterNames[i], parameterVals[i]);
            }
        }

        if (requestBody != null) {
            postVersion.setRequestEntity(getRequestEntity());
        }
    } // if it's a get then the parameters should be in the URL
}

From source file:ca.uvic.chisel.logging.eclipse.internal.network.LogUploadRunnable.java

public void run(IProgressMonitor sendMonitor) throws InterruptedException, InvocationTargetException {
    File[] filesToUpload = log.getCategory().getFilesToUpload();
    sendMonitor.beginTask("Uploading Log " + log.getCategory().getName(), filesToUpload.length);
    LoggingCategory category = log.getCategory();
    IMemento memento = category.getMemento();
    for (File file : filesToUpload) {
        if (sendMonitor.isCanceled()) {
            throw new InterruptedException();
        }/*from w w  w  .j a v a 2 s .  com*/
        PostMethod post = new PostMethod(category.getURL().toString());

        try {
            Part[] parts = { new StringPart("KIND", "workbench-log"),
                    new StringPart("CATEGORY", category.getCategoryID()),
                    new StringPart("USER", WorkbenchLoggingPlugin.getDefault().getLocalUser()),
                    new FilePart("WorkbenchLogger", file.getName(), file, "application/zip", null) };
            post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
            HttpClient client = new HttpClient();
            int status = client.executeMethod(post);
            String resp = getData(post.getResponseBodyAsStream());
            if (status != 200 || !resp.startsWith("Status: 200 Success")) {
                IOException ex = new IOException(resp);
                throw (ex);
            }
            memento.putString("lastUpload", file.getName());
            file.delete();
        } catch (IOException e) {
            throw new InvocationTargetException(e);
        } finally {
            sendMonitor.worked(1);
        }
    }
    sendMonitor.done();
}

From source file:com.bbva.arq.devops.ae.mirrorgate.jenkins.plugin.utils.RestCall.java

public MirrorGateResponse makeRestCallPost(String url, String jsonString, String user, String password) {

    MirrorGateResponse response;//from  w  w w  .j a  va  2  s .c o m
    PostMethod post = new PostMethod(url);
    try {
        HttpClient client = getHttpClient();

        if (user != null && password != null) {
            client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
            post.setDoAuthentication(true);
        }

        StringRequestEntity requestEntity = new StringRequestEntity(jsonString, "application/json", "UTF-8");
        post.setRequestEntity(requestEntity);
        int responseCode = client.executeMethod(post);
        String responseString = post.getResponseBodyAsStream() != null
                ? getResponseString(post.getResponseBodyAsStream())
                : "";
        response = new MirrorGateResponse(responseCode, responseString);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "MirrorGate: Error posting to MirrorGate", e);
        response = new MirrorGateResponse(HttpStatus.SC_BAD_REQUEST, "");
    } finally {
        post.releaseConnection();
    }
    return response;
}

From source file:com.sa.npopa.samples.hbase.rest.client.Client.java

/**
 * Send a POST request/*from  www. ja  va 2  s.co  m*/
 * @param cluster the cluster definition
 * @param path the path or URI
 * @param headers the HTTP headers to include, <tt>Content-Type</tt> must be
 * supplied
 * @param content the content bytes
 * @return a Response object with response detail
 * @throws IOException
 */
public Response post(Cluster cluster, String path, Header[] headers, byte[] content) throws IOException {
    PostMethod method = new PostMethod();
    try {
        method.setRequestEntity(new ByteArrayRequestEntity(content));
        int code = execute(cluster, method, headers, path);
        headers = method.getResponseHeaders();
        content = method.getResponseBody();
        return new Response(code, headers, content);
    } finally {
        method.releaseConnection();
    }
}

From source file:eu.learnpad.core.impl.sim.XwikiBridgeInterfaceRestResource.java

@Override
public Collection<String> addProcessDefinition(String processDefinitionFileURL, String modelSetId)
        throws LpRestException {
    HttpClient httpClient = this.getAnonymousClient();
    String uri;//from  w w  w.j av  a2s .co  m
    if (modelSetId != null) {
        uri = String.format("%s/learnpad/sim/bridge/processes?modelsetartifactid=%s", this.restPrefix,
                modelSetId);
    } else {
        uri = String.format("%s/learnpad/sim/bridge/processes", this.restPrefix);
    }

    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader("Content-Type", "application/json");

    try {
        RequestEntity requestEntity = new StringRequestEntity(processDefinitionFileURL, "application/json",
                "UTF-8");
        postMethod.setRequestEntity(requestEntity);

        httpClient.executeMethod(postMethod);

        // Not fully tested, but is looks working for our purposes -- Gulyx
        return this.objectReaderCollection.readValue(postMethod.getResponseBodyAsStream());
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:com.clarkparsia.sbol.editor.sparql.StardogEndpoint.java

@Override
public void removeData(RDFInput input, String namedGraph) throws Exception {
    String txId = startTransaction();

    RequestEntity entity = createEntity(input);
    PostMethod post = new PostMethod(url + "/" + txId + "/remove");
    if (namedGraph != null) {
        post.setQueryString(new NameValuePair[] { new NameValuePair("graph-uri", namedGraph) });
    }/*w  w w .  java2  s  .c om*/
    post.setRequestEntity(entity);

    execute(post);

    commitTransaction(txId);
}

From source file:com.zimbra.examples.extns.samlprovider.SamlAuthProvider.java

/**
 * Returns an AuthToken by auth data in SOAP request.
 * <p/>//www.  j  a v a2s.c o  m
 * Should never return null.
 *
 * @param soapCtxt soap context element
 * @param engineCtxt soap engine context
 * @return auth token
 * @throws AuthTokenException if auth data for the provider is not present
 * @throws AuthProviderException if auth data for the provider is present but cannot be resolved into a valid AuthToken
 */
protected AuthToken authToken(Element soapCtxt, Map engineCtxt)
        throws AuthProviderException, AuthTokenException {

    if (soapCtxt == null)
        throw AuthProviderException.NO_AUTH_DATA();

    Element authTokenElt;
    String type;
    try {
        authTokenElt = soapCtxt.getElement("authToken");
        if (authTokenElt == null)
            throw AuthProviderException.NO_AUTH_DATA();
        type = authTokenElt.getAttribute("type");
    } catch (AuthProviderException ape) {
        throw ape;
    } catch (ServiceException se) {
        ZimbraLog.extensions.error(SystemUtil.getStackTrace(se));
        throw AuthProviderException.NO_AUTH_DATA();
    }
    if (!"SAML_AUTH_PROVIDER".equals(type)) {
        throw AuthProviderException.NOT_SUPPORTED();
    }

    String samlAssertionId = authTokenElt.getTextTrim();
    if (samlAssertionId == null || "".equals(samlAssertionId))
        throw AuthProviderException.NO_AUTH_DATA();

    String samlAuthorityUrl = LC.get("saml_authority_url");
    if (samlAuthorityUrl == null)
        throw new AuthTokenException("SAML authority URL has not been specified in localconfig.zml");

    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(samlAuthorityUrl);
    Element samlAssertionReq = getSamlAssertionRequest(samlAssertionId);
    String samlAssertionReqStr = samlAssertionReq.toString();
    if (ZimbraLog.extensions.isDebugEnabled()) {
        ZimbraLog.extensions.debug("SAML assertion request: " + samlAssertionReqStr);
    }
    try {
        post.setRequestEntity(new StringRequestEntity(samlAssertionReqStr, "text/xml", "utf-8"));
        client.executeMethod(post);
        Element samlResp = Element.parseXML(post.getResponseBodyAsStream());
        Element soapBody = samlResp.getElement("Body");
        Element responseElt = soapBody.getElement("Response");
        Element samlAssertionElt = responseElt.getElement("Assertion");
        if (samlAssertionElt == null) {
            throw new AuthTokenException("SAML response does not contain a SAML token");
        }
        return new SamlAuthToken(samlAssertionElt);
    } catch (AuthTokenException ate) {
        throw ate;
    } catch (Exception e) {
        ZimbraLog.extensions.error(SystemUtil.getStackTrace(e));
        throw new AuthTokenException("Exception in executing SAML assertion request", e);
    }
}

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

/**
 * Performs the operation.//from ww  w  .java2s .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:de.mpg.escidoc.services.edoc.PubManImport.java

private String assignObjectPid(String id, String lastModificationDate) throws Exception {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(CORESERVICES_URL + "/ir/item/" + id + "/assign-object-pid");
    postMethod.addRequestHeader("Cookie", "escidocCookie=" + userHandle);
    String body = "<param last-modification-date=\"" + lastModificationDate
            + "\"><url>http://localhost:8080/album/core/ir/item/" + id + "</url></param>";

    postMethod.setRequestEntity(new StringRequestEntity(body));
    ProxyHelper.executeMethod(httpClient, postMethod);

    String response = postMethod.getResponseBodyAsString();

    if (postMethod.getStatusCode() != 200) {
        throw new RuntimeException(response);
    }/*from  w w  w . j  a va  2s.c  o  m*/

    return response;
}