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

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

Introduction

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

Prototype

public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException 

Source Link

Usage

From source file:org.roda.wui.filter.CasClient.java

/**
 * Get a <strong>Service Ticket</strong> from the CAS server for the specified
 * <strong>Ticket Granting Ticket</strong> and <strong>service</strong>.
 * /* ww  w.j a  va  2 s  . c om*/
 * @param ticketGrantingTicket
 *          the <strong>Ticket Granting Ticket</strong>.
 * @param service
 *          the service URL.
 * @return the <strong>Service Ticket</strong>.
 * @throws GenericException
 *           if some error occurred.
 */
public String getServiceTicket(final String ticketGrantingTicket, final String service)
        throws GenericException {
    final HttpClient client = new HttpClient();
    final PostMethod post = new PostMethod(
            String.format("%s/v1/tickets/%s", casServerUrlPrefix, ticketGrantingTicket));
    post.setRequestBody(new NameValuePair[] { new NameValuePair("service", service) });
    try {
        client.executeMethod(post);
        final String response = post.getResponseBodyAsString();
        if (post.getStatusCode() == HttpStatus.SC_OK) {
            return response;
        } else {
            LOGGER.warn(invalidResponseMessage(post));
            throw new GenericException(invalidResponseMessage(post));
        }
    } catch (final IOException e) {
        throw new GenericException(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
}

From source file:org.sakaiproject.kernel.mailman.impl.MailmanManagerImpl.java

public void createList(String listName, String ownerEmail, String password) throws MailmanException {
    HttpClient client = new HttpClient(proxyClientService.getHttpConnectionManager());
    PostMethod post = new PostMethod(getMailmanUrl("/create"));
    NameValuePair[] parametersBody = new NameValuePair[] { new NameValuePair("listname", listName),
            new NameValuePair("owner", ownerEmail), new NameValuePair("password", password),
            new NameValuePair("confirm", password),
            new NameValuePair("auth", configMap.get(LIST_ADMIN_PASSWORD)), new NameValuePair("langs", "en"),
            new NameValuePair("notify", "1"), new NameValuePair("autogen", "0"),
            new NameValuePair("moderate", "0"), new NameValuePair("doit", "Create List") };
    post.setRequestBody(parametersBody);
    try {// w w w  .  j  a  v a  2  s  . co  m
        int result = client.executeMethod(post);
        if (result != HttpServletResponse.SC_OK) {
            throw new MailmanException("Unable to create list");
        }
    } catch (HttpException e) {
        throw new MailmanException("HTTP Exception communicating with mailman server", e);
    } catch (IOException e) {
        throw new MailmanException("IOException communicating with mailman server", e);
    } finally {
        post.releaseConnection();
    }
}

From source file:org.sakaiproject.kernel.mailman.impl.MailmanManagerImpl.java

public void deleteList(String listName, String listPassword) throws MailmanException {
    HttpClient client = new HttpClient(proxyClientService.getHttpConnectionManager());
    PostMethod post = new PostMethod(getMailmanUrl("/rmlist/" + listName));
    NameValuePair[] parametersBody = new NameValuePair[] { new NameValuePair("password", listPassword),
            new NameValuePair("delarchives", "0"), new NameValuePair("doit", "Delete this list") };
    post.setRequestBody(parametersBody);
    try {/*from   w w  w  .jav  a 2s .  co m*/
        int result = client.executeMethod(post);
        if (result != HttpServletResponse.SC_OK) {
            throw new MailmanException("Unable to create list");
        }
    } catch (HttpException e) {
        throw new MailmanException("HTTP Exception communicating with mailman server", e);
    } catch (IOException e) {
        throw new MailmanException("IOException communicating with mailman server", e);
    } finally {
        post.releaseConnection();
    }
}

From source file:org.sakaiproject.nakamura.mailman.impl.MailmanManagerImpl.java

public void createList(String listName, String password) throws MailmanException {
    HttpClient client = new HttpClient(proxyClientService.getHttpConnectionManager());
    PostMethod post = new PostMethod(getMailmanUrl("/create"));
    NameValuePair[] parametersBody = new NameValuePair[] { new NameValuePair("listname", listName),
            new NameValuePair("owner",
                    configMap.get(MM_EMAIL_PREFIX) + listName + "@" + configMap.get(MM_HOST_NAME)),
            new NameValuePair("password", password), new NameValuePair("confirm", password),
            new NameValuePair("auth", configMap.get(LIST_ADMIN_PASSWORD)), new NameValuePair("langs", "en"),
            new NameValuePair("notify", "1"), new NameValuePair("autogen", "0"),
            new NameValuePair("moderate", "0"), new NameValuePair("doit", "Create List") };
    post.setRequestBody(parametersBody);
    int result = 0;
    try {/*  w w w  .  j  ava2  s .co m*/
        result = client.executeMethod(post);
        if (result != HttpServletResponse.SC_OK) {
            throw new MailmanException("Unable to create list");
        }
    } catch (HttpException e) {
        throw new MailmanException("HTTP Exception communicating with mailman server", e);
    } catch (IOException e) {
        throw new MailmanException("IOException communicating with mailman server", e);
    } finally {
        post.releaseConnection();
    }
    setListSettings(listName, password);
}

From source file:org.sharegov.cirm.utils.GenUtils.java

@SuppressWarnings("deprecation")
public static String httpPost(String url, String data, String... headers) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    if (headers != null) {
        if (headers.length % 2 != 0)
            throw new IllegalArgumentException(
                    "Odd number of headers argument, specify HTTP headers in pairs: name then value, etc.");
        for (int i = 0; i < headers.length; i++)
            method.addRequestHeader(headers[i], headers[++i]);
    }/*  w  w  w . j  a  v  a2s  .com*/
    method.setRequestBody(data);
    try {
        // disable retries from within the HTTP client          
        client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(0, false));
        client.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 0);
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK)
            throw new RuntimeException(
                    "HTTP Error " + statusCode + " while post to " + url.toString() + ", body " + data);
        return method.getResponseBodyAsString();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor.java

/**
 * Set the given serialized remote invocation as request body.
 * <p>The default implementation simply sets the serialized invocation
 * as the PostMethod's request body. This can be overridden, for example,
 * to write a specific encoding and potentially set appropriate HTTP
 * request headers./*from   w  w  w .  j ava2 s. com*/
 * @param config the HTTP invoker configuration that specifies the target service
 * @param postMethod the PostMethod to set the request body on
 * @param baos the ByteArrayOutputStream that contains the serialized
 * RemoteInvocation object
 * @throws IOException if thrown by I/O methods
 * @see org.apache.commons.httpclient.methods.PostMethod#setRequestBody(java.io.InputStream)
 * @see org.apache.commons.httpclient.methods.PostMethod#setRequestEntity
 * @see org.apache.commons.httpclient.methods.InputStreamRequestEntity
 */
protected void setRequestBody(HttpInvokerClientConfiguration config, PostMethod postMethod,
        ByteArrayOutputStream baos) throws IOException {

    // Need to call setRequestBody for compatibility with Commons HttpClient 2.0
    postMethod.setRequestBody(new ByteArrayInputStream(baos.toByteArray()));
}

From source file:org.tizzit.util.spring.httpinvoker.StreamSupportingHttpInvokerRequestExecutor.java

/**
 * Execute a request to send the given serialized remote invocation.
 * <p>Implementations will usually call <code>readRemoteInvocationResult</code>
 * to deserialize a returned RemoteInvocationResult object.
 *
 * @param config the HTTP invoker configuration that specifies the target
 *               service/*w w w.java2  s. c om*/
 * @param baos   the ByteArrayOutputStream that contains the serialized
 *               RemoteInvocation object
 *
 * @return the RemoteInvocationResult object
 *
 * @throws IOException            if thrown by I/O operations
 * @throws ClassNotFoundException if thrown during deserialization
 * @see #readRemoteInvocationResult(java.io.InputStream, String)
 */
protected RemoteInvocationResult doExecuteRequest(final HttpInvokerClientConfiguration config,
        final ByteArrayOutputStream baos, final StreamSupportingRemoteInvocation invocation)
        throws IOException, ClassNotFoundException {
    final ByteArrayInputStream serializedInvocation = new ByteArrayInputStream(baos.toByteArray());

    final PostMethod postMethod;
    final InputStream body;

    if (invocation.getClientSideInputStream() != null) {
        // We don't want to close the client side input stream unless the remote
        // method closes the input stream, so we "shield" the close for now.
        body = new CompositeInputStream(new InputStream[] { serializedInvocation,
                new CloseShieldedInputStream(invocation.getClientSideInputStream()) });
        postMethod = createPostMethodForStreaming(config);
    } else {
        body = serializedInvocation;
        postMethod = createPostMethod(config);
    }

    boolean delayReleaseConnection = false;

    try {
        postMethod.setRequestBody(body);
        executePostMethod(config, getHttpClient(), postMethod);

        HttpState state = getHttpClient().getState();
        /*postMethod.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        String host = targetURL.getHost();
        String path = targetURL.getPath();
        boolean secure = ("https".equalsIgnoreCase(targetURL.getProtocol())) ? true : false; //$NON-NLS-1$
        String ck1 = (String) postMethod.getParams().g msgContext.getProperty(HTTPConstants.HEADER_COOKIE);
                
        String ck2 = (String) msgContext.getProperty(HTTPConstants.HEADER_COOKIE2);
        if (ck1 != null) {
           int index = ck1.indexOf('=');
           state.addCookie(new Cookie(host, ck1.substring(0, index), ck1.substring(index + 1), path, null, secure));
        }
        if (ck2 != null) {
           int index = ck2.indexOf('=');
           state.addCookie(new Cookie(host, ck2.substring(0, index), ck2.substring(index + 1), path, null, secure));
        }
        httpClient.setState(state);
        */

        final RemoteInvocationResult ret = readRemoteInvocationResult(postMethod.getResponseBodyAsStream(),
                config.getCodebaseUrl());
        if (ret instanceof StreamSupportingRemoteInvocationResult) {
            final StreamSupportingRemoteInvocationResult ssrir = (StreamSupportingRemoteInvocationResult) ret;

            // Close the local InputStream parameter if the remote method
            // explicitly closed the InputStream parameter on the other side.
            if (invocation.getClientSideInputStream() != null) {
                if (ssrir.getMethodClosedParamInputStream() != null) {
                    if (Boolean.TRUE.equals(ssrir.getMethodClosedParamInputStream())) {
                        invocation.getClientSideInputStream().close();
                    }
                } else {
                    warnInputStreamParameterStateNotSpecified(invocation);
                }
            }

            // If there is a return stream, then we need to leave the PostMethod
            // connection open until the return stream is closed, so augment the
            // return stream for this.
            if (ssrir.getHasReturnStream()) {
                final InputStream sourceRetIs = ssrir.getClientSideInputStream();
                if (sourceRetIs != null) {
                    ssrir.setClientSideInputStream(new FilterInputStream(sourceRetIs) {
                        public void close() throws IOException {
                            super.close();
                            postMethod.releaseConnection();
                        }
                    });
                    delayReleaseConnection = true;
                }
            }
        } else if (invocation.getClientSideInputStream() != null) {
            warnInputStreamParameterStateNotSpecified(invocation);
        }
        return ret;
    } finally {
        // need to explicitly release because it might be pooled
        if (!delayReleaseConnection) {
            postMethod.releaseConnection();
        }
    }
}

From source file:org.tranche.add.AddFileToolUtil.java

/**
 * /* w  w w  . j  a v  a  2  s. co  m*/
 * @param aft
 * @param report
 */
public static void registerUpload(final AddFileTool aft, final AddFileToolReport report) {
    final String logURL = ConfigureTranche.get(ConfigureTranche.CATEGORY_LOGGING,
            ConfigureTranche.PROP_LOG_UPLOAD_URL);
    if (logURL == null || logURL.equals("")) {
        return;
    }

    HttpClient c = new HttpClient();
    PostMethod pm = new PostMethod(logURL);
    try {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new NameValuePair("Title", aft.getTitle()));
        pairs.add(new NameValuePair("Description", aft.getDescription()));
        pairs.add(new NameValuePair("Timestamp", String.valueOf(report.getTimestampStart())));
        if (aft.getPassphrase() == null) {
            pairs.add(new NameValuePair("passphrase", ""));
        } else {
            pairs.add(new NameValuePair("passphrase", aft.getPassphrase()));
        }
        pairs.add(new NameValuePair("hash", report.getHash().toString()));
        pairs.add(new NameValuePair("uploadTime", String.valueOf(report.getTimeToFinish())));
        pairs.add(
                new NameValuePair("Submitted By", UserCertificateUtil.readUserName(aft.getUserCertificate())));
        pairs.add(new NameValuePair("Tranche:Files", String.valueOf(report.getOriginalFileCount())));
        pairs.add(new NameValuePair("Tranche:Size", String.valueOf(report.getOriginalBytesUploaded())));
        for (MetaDataAnnotation mda : aft.getMetaDataAnnotations()) {
            pairs.add(new NameValuePair(mda.getName(), mda.getValue()));
        }

        if (aft.getLicense() != null) {
            try {
                pairs.add(new NameValuePair("licenseText", aft.getLicense().getDescription()));
                pairs.add(new NameValuePair("licenseName", aft.getLicense().getTitle()));
                pairs.add(new NameValuePair("licenseShortName", aft.getLicense().getShortDescription()));
            } catch (Exception ex) {
                System.err.println(ex.getClass().getSimpleName()
                        + " happened while including license information: " + ex.getMessage());
                ex.printStackTrace(System.err);
            }
        }

        // create the pair array
        NameValuePair[] pairArray = new NameValuePair[pairs.size()];
        for (int i = 0; i < pairs.size(); i++) {
            pairArray[i] = pairs.get(i);
        }

        // set the values
        pm.setRequestBody(pairArray);

        // execute the method
        int statusCode = c.executeMethod(pm);

        // If registrar failed to send email, do so here...
        if (statusCode != 200 && ConfigureTranche.getAdminEmailAccounts().length != 0) {
            String message = "You are receiving this message from the AddFileTool because the the upload registrar returned an HTTP code of "
                    + statusCode + ".\n\n" + "Submitted by: "
                    + UserCertificateUtil.readUserName(aft.getUserCertificate()) + "\n" + "Hash: "
                    + report.getHash().toString() + "\n" + "Title: " + report.getTitle() + "\n"
                    + "Description: " + report.getDescription() + "\n";
            EmailUtil.safeSendEmail(
                    "[" + ConfigureTranche.get(ConfigureTranche.CATEGORY_GENERAL, ConfigureTranche.PROP_NAME)
                            + "] Upload Registration Failed @ "
                            + TextUtil.getFormattedDate(TimeUtil.getTrancheTimestamp()),
                    ConfigureTranche.getAdminEmailAccounts(), message);
        }
    } catch (Exception e) {
        DebugUtil.debugErr(AddFileToolUtil.class, e);
    } finally {
        pm.releaseConnection();
    }
}

From source file:org.tranche.get.GetFileToolUtil.java

/**
 * <p>Sends a notification via an HTTP POST to a web server that a successful download has occurred.</p>
 * <p>The URL to send the notification to must be set using the GetFileToolUtil.setURL(String url) method for this action to be performed.</p>
 * <p>A Thread with minimum priority is spawned to handle this event, so this method is asynchronous.</p>
 * @param gft/*  www . j a v  a  2s . c o  m*/
 * @param report
 */
public static void registerDownload(final GetFileTool gft, final GetFileToolReport report) {
    if (TestUtil.isTesting()) {
        return;
    }

    final String logURL = ConfigureTranche.get(ConfigureTranche.CATEGORY_LOGGING,
            ConfigureTranche.PROP_LOG_DOWNLOAD_URL);
    if (logURL == null || logURL.equals("")) {
        return;
    }

    // Notify server of download
    try {
        HttpClient c = new HttpClient();
        PostMethod pm = new PostMethod(logURL);

        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("hash", Base16.encode(gft.getHash().toByteArray())));
        params.add(new NameValuePair("downloadTime", String.valueOf(report.getTimeToFinish())));
        if (report.getBytesDownloaded() != 0) {
            params.add(new NameValuePair("uncompressedSize", String.valueOf(report.getBytesDownloaded())));
        }
        pm.setRequestBody(params.toArray(new NameValuePair[0]));

        // best effort, do not print anything
        c.executeMethod(pm);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.tranche.get.GetFileToolUtil.java

/**
 * <p>Registers a failed download only if configured to do so.</p>
 * @param gft/*  w w  w. j a  va  2  s . c  o m*/
 * @param report
 */
public static void registerFailedDownload(final GetFileTool gft, final GetFileToolReport report) {
    // no tests
    if (TestUtil.isTesting() || !report.isFailed()) {
        return;
    }

    try {
        String[] emailRecipients = ConfigureTranche.getAdminEmailAccounts();
        String subject = "["
                + ConfigureTranche.get(ConfigureTranche.CATEGORY_GENERAL, ConfigureTranche.PROP_NAME)
                + "] Failed Download @ " + TextUtil.getFormattedDate(TimeUtil.getTrancheTimestamp());

        StringBuffer message = new StringBuffer();
        message.append("A download failed @ " + TextUtil.getFormattedDate(TimeUtil.getTrancheTimestamp())
                + " on " + ConfigureTranche.get(ConfigureTranche.CATEGORY_GENERAL, ConfigureTranche.PROP_NAME)
                + "\n\n");
        message.append(
                "--------------------------------------------------------------------------------------------\n");
        for (PropagationExceptionWrapper pew : report.getFailureExceptions()) {
            message.append(pew.toString() + "\n");
            for (StackTraceElement ste : pew.exception.getStackTrace()) {
                message.append("    " + ste + "\n");
            }
            message.append("\n");
        }
        message.append(
                "--------------------------------------------------------------------------------------------\n");
        message.append("\n");
        if (gft.getMetaData() != null && gft.getMetaData().getDataSetName() != null) {
            message.append("Title: " + gft.getMetaData().getDataSetName() + "\n");
        }
        message.append("Hash: " + gft.getHash().toString() + "\n");
        message.append("Using passphrase?: " + String.valueOf(gft.getPassphrase() != null) + "\n");

        File tempFile = null;
        try {
            tempFile = LogUtil.getTroubleshootingInformationFile();

            if (gft.getFailedChunksListener() != null) {

                BufferedWriter writer = null;
                try {
                    writer = new BufferedWriter(new FileWriter(tempFile, true));
                    GetFileToolFailedChunksListener failedChunksListener = gft.getFailedChunksListener();

                    // Any missing meta data chunks
                    int missingMDSize = failedChunksListener.getMissingMetaDataChunks().size();
                    if (missingMDSize > 0) {
                        writer.write("* Data set missing " + missingMDSize + " meta chunk"
                                + (missingMDSize == 1 ? "" : "s") + ":");
                        writer.newLine();
                        for (BigHash metaHash : failedChunksListener.getMissingMetaDataChunks()) {
                            writer.write("    - " + metaHash);
                            writer.newLine();
                        }
                    } else {
                        writer.write("* Data set not missing any meta data chunks.");
                        writer.newLine();
                    }
                    writer.newLine();

                    // Any missing data chunks
                    int missingDataChunksSize = 0,
                            missingFromFiles = failedChunksListener.getMissingDataChunks().size();

                    if (missingFromFiles > 0) {
                        for (BigHash metaHash : failedChunksListener.getMissingDataChunks().keySet()) {
                            Set<BigHash> dataChunks = failedChunksListener.getMissingDataChunks().get(metaHash);
                            missingDataChunksSize += dataChunks.size();
                        }

                        writer.write("A total of " + missingDataChunksSize + " data chunks missing in "
                                + missingFromFiles + " files:");
                        writer.newLine();

                        for (BigHash metaHash : failedChunksListener.getMissingDataChunks().keySet()) {
                            Set<BigHash> dataChunks = failedChunksListener.getMissingDataChunks().get(metaHash);
                            writer.write("    - File: " + metaHash);
                            writer.newLine();

                            for (BigHash dataHash : dataChunks) {
                                writer.write("        -> " + dataHash);
                                writer.newLine();
                            }
                        }
                    } else {
                        writer.write(
                                "* No missing data chunks were reported. (Note: data chunks might be missing and not reported because associated meta data not found.)");
                        writer.newLine();
                    }

                    writer.newLine();
                    writer.newLine();

                } finally {
                    IOUtil.safeClose(writer);
                }
            }

            EmailUtil.sendEmailHttp(subject, emailRecipients, message.toString(), tempFile);
        } finally {
            IOUtil.safeDelete(tempFile);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    final String logFailureURL = ConfigureTranche.get(ConfigureTranche.CATEGORY_LOGGING,
            ConfigureTranche.PROP_LOG_DOWNLOAD_FAILURE);
    if (logFailureURL == null || logFailureURL.equals("")) {
        return;
    }

    try {
        // make a new client
        HttpClient c = new HttpClient();
        PostMethod pm = new PostMethod(logFailureURL);

        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("hash", Base16.encode(gft.getHash().toByteArray())));

        // TODO: remove these in the registration script
        params.add(new NameValuePair("username", ""));
        params.add(new NameValuePair("toolType", ""));

        // TODO: refactor registration script to allow for multiple exceptions
        String exceptionName = "";
        String exceptionMessage = "";
        String exceptionStack = "";
        if (!report.getFailureExceptions().isEmpty()) {
            for (PropagationExceptionWrapper pew : report.getFailureExceptions()) {
                exceptionName = pew.exception.getClass().getName();
                exceptionMessage = pew.exception.getMessage();
                for (StackTraceElement ste : pew.exception.getStackTrace()) {
                    exceptionStack = exceptionStack + ste.toString() + "\n";
                }
            }
        }

        params.add(new NameValuePair("exceptionName", exceptionName == null ? "" : exceptionName));
        params.add(new NameValuePair("exceptionMessage", exceptionMessage == null ? "" : exceptionMessage));
        params.add(new NameValuePair("exceptionStack", exceptionStack == null ? "" : exceptionStack));
        params.add(new NameValuePair("buildNumber", "@buildNumber"));
        params.add(new NameValuePair("timestamp", String.valueOf(report.getTimestampEnd())));
        pm.setRequestBody(params.toArray(new NameValuePair[0]));

        // best effort, do not print anything
        c.executeMethod(pm);
    } catch (Exception e) {
        e.printStackTrace();
    }
}