Example usage for org.apache.commons.httpclient.params HttpMethodParams USE_EXPECT_CONTINUE

List of usage examples for org.apache.commons.httpclient.params HttpMethodParams USE_EXPECT_CONTINUE

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpMethodParams USE_EXPECT_CONTINUE.

Prototype

String USE_EXPECT_CONTINUE

To view the source code for org.apache.commons.httpclient.params HttpMethodParams USE_EXPECT_CONTINUE.

Click Source Link

Usage

From source file:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java

/**
 * @param cookies//from ww w .ja  v a  2  s . c  o m
 *            the previous request response existing cookies to keep the
 *            session information.
 * @throws MojoExecutionException
 *             in case of any errors during this process.
 */
@SuppressWarnings("deprecation")
private void installPackage(final Cookie[] cookies) throws MojoExecutionException {
    File file = new File(jarfile);
    String url = crxPath + "/packmgr/unpack.jsp?Path=" + getPackagePath(file)
            + (aclIgnore ? "" : "&acHandling=overwrite");

    GetMethod loginPost = new GetMethod(url);
    loginPost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    try {
        getLog().info("installing: " + url);
        HttpClient client = new HttpClient();
        client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY);
        client.getState().addCookies(cookies);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_DEFAULT_TIMEOUT);
        int status = client.executeMethod(loginPost);
        // log the status
        getLog().info(
                "Response status: " + status + ", statusText: " + HttpStatus.getStatusText(status) + "\r\n");
        // if it's ok, proceed
        if (status == HttpStatus.SC_OK) {
            InputStream response = loginPost.getResponseBodyAsStream();
            if (response != null) {
                String responseBody = IOUtils.toString(response);
                if (responseBody.contains("Package installed in")) {
                    getLog().info("Install successful");
                } else {
                    logResponseDetails(loginPost);
                    throw new MojoExecutionException("Error installing package on crx");
                }
            } else {
                throw new MojoExecutionException("Null response when installing package on crx");
            }
        } else {
            logResponseDetails(loginPost);
            throw new MojoExecutionException("Installation failed");
        }
    } catch (Exception ex) {
        getLog().error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage());
        throw new MojoExecutionException(ex.getMessage());
    } finally {
        loginPost.releaseConnection();
    }
}

From source file:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java

/**
 * @param cookies/*from  ww  w.  ja va2  s  .co  m*/
 *            the previous request response existing cookies to keep the
 *            session information.
 * @param path
 *            the node path to delete.
 * @throws MojoExecutionException
 *             in case of any errors during this process.
 */
@SuppressWarnings("deprecation")
private void deleteNode(final Cookie[] cookies, final String pathInput) throws MojoExecutionException {
    String[] pathes = pathInput.split(",");

    for (String path : pathes) {
        GetMethod removeCall = new GetMethod(
                crxPath + "/browser/delete_recursive.jsp?Path=" + path + "&action=delete");
        removeCall.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        try {
            getLog().info("removing " + path);
            getLog().info(crxPath + "/browser/delete_recursive.jsp?Path=" + path + "&action=delete");

            HttpClient client = new HttpClient();
            client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY);
            client.getState().addCookies(cookies);
            client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_DEFAULT_TIMEOUT);
            removeCall.setFollowRedirects(false);

            if (isVersionable(cookies, path, client)) {
                getLog().info("Node at : " + path + " is mix:versionable.");
                checkout(cookies, path, client);
            }

            else {

                getLog().info("removing " + path);
                getLog().info(crxPath + "/browser/delete_recursive.jsp?Path=" + path + "&action=delete");

                int status = client.executeMethod(removeCall);

                if (status == HttpStatus.SC_OK) {
                    getLog().info("Node deleted");
                    // log the status
                    getLog().info("Response status: " + status + ", statusText: "
                            + HttpStatus.getStatusText(status) + "\r\n");
                } else {
                    logResponseDetails(removeCall);
                    throw new MojoExecutionException(
                            "Removing node " + path + " failed, response=" + HttpStatus.getStatusText(status));
                }
                getLog().info("Response status: " + status + ", statusText: " + HttpStatus.getStatusText(status)
                        + "\r\n");
            }
        } catch (Exception ex) {
            getLog().error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage());
            throw new MojoExecutionException(ex.getMessage());
        } finally {
            removeCall.releaseConnection();
        }
    }

}

From source file:my.swingconnect.SwingConnectUI.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    {/*from w ww  . ja v a2 s. c  om*/

        int i = 0;
        while (i < results.size()) {
            String path = results.get(i);
            System.out.println("Printing path" + path);
            targetFile1 = new File(path);

            //                    String targetURL = jTextField3.getSelectedItem().toString();
            //                String targetURL = jTextField3.getSelectedText();
            String targetURL = "http://photo-drop.com/uploader.php";

            //                    if (!targetURL
            //
            //                            .equals(
            //
            //                            cmbURLModel.getElementAt(
            //
            //                            cmbURL.getSelectedIndex()))) {
            //
            //                        cmbURLModel.addElement(targetURL);
            //
            //                    }

            System.out.println(targetURL);
            //From the apache package: the class that implements POST method

            PostMethod filePost = new PostMethod(targetURL);

            filePost.getParams().setBooleanParameter(

                    HttpMethodParams.USE_EXPECT_CONTINUE,

                    jCheckBox1.isSelected());
            try {

                System.out.println("Uploading " + targetFile1.getName() + " to " + targetURL);
                jTextArea2.append("Uploading " + targetFile1.getName() + " to " + targetURL);
                filename = targetFile1.toString();
                System.out.println(filename);
                javapostmethod f = new javapostmethod();
                f.sendPost(filename);

                Part[] parts = {

                        new FilePart(targetFile1.getName(), targetFile1)

                };

                filePost.setRequestEntity(

                        new MultipartRequestEntity(parts,

                                filePost.getParams())

                );

                HttpClient client = new HttpClient();

                client.getHttpConnectionManager().

                        getParams().setConnectionTimeout(5000);

                int status = client.executeMethod(filePost);
                if (status == HttpStatus.SC_OK) {
                    jTextArea2.append("Upload complete, response=" + filePost.getResponseBodyAsString());
                    jTextArea2.append("Uploaded from:" + filename);
                } else {
                    jTextArea2.append("Upload failed, response=" + HttpStatus.getStatusText(status));
                }
            } catch (Exception ex) {
                jTextArea2.append("Error: " + ex.getMessage());
                ex.printStackTrace();
            } finally {
                filePost.releaseConnection();
            }

            i++;

        }

        //

    }

}

From source file:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java

/**
 * @param cookies/*from  w  w  w . j  a v  a 2s .  co  m*/
 *            the previous request response existing cookies to keep the
 *            session information.
 * @throws MojoExecutionException
 *             in case of any errors during this process.
 */
@SuppressWarnings("deprecation")
private void saveAll(final Cookie[] cookies) throws MojoExecutionException {
    GetMethod savePost = new GetMethod(crxPath + "/browser/content.jsp?Path=/&action_ops=saveAll");
    savePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    try {
        getLog().info("save all changes");
        HttpClient client = new HttpClient();
        client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY);
        client.getState().addCookies(cookies);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_DEFAULT_TIMEOUT);
        int status = client.executeMethod(savePost);
        // log the status
        getLog().info(
                "Response status: " + status + ", statusText: " + HttpStatus.getStatusText(status) + "\r\n");
        if (status == HttpStatus.SC_OK) {
            getLog().info("All changes saved");
        } else {
            logResponseDetails(savePost);
            throw new MojoExecutionException(
                    "save all changes failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        getLog().error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage());
        throw new MojoExecutionException(ex.getMessage());
    } finally {
        savePost.releaseConnection();
    }
}

From source file:com.polarion.alm.ws.client.internal.connection.CommonsHTTPSender.java

/**
 * Extracts info from message context.// w  w w  .  ja va  2  s. c o m
 * 
 * @param method
 *            Post method
 * @param httpClient
 *            The client used for posting
 * @param msgContext
 *            the message context
 * @param tmpURL
 *            the url to post to.
 * 
 * @throws Exception
 */
private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL)
        throws Exception {

    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /*
         * ISSUE: these are not the same, but MessageContext has only one
         * definition of timeout
         */
        // SO_TIMEOUT -- timeout for blocking reads
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\""));
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
    }

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            // Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addRequestHeader(key, value);
            }
        }
    }
}

From source file:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java

@SuppressWarnings("deprecation")
private void backUp(final Cookie[] cookies) throws MojoExecutionException {
    checkBackupFolder();//w  ww  .  j a  v  a2  s .  c om
    File file = new File(jarfile);
    GetMethod backupPost = new GetMethod(crxPath + "/packmgr/service.jsp?cmd=get&_charset_=utf8&name="
            + FilenameUtils.getBaseName(file.getName()));
    backupPost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    try {
        getLog().info("backing up /etc/packages/" + file.getName());
        HttpClient client = new HttpClient();
        client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY);
        client.getState().addCookies(cookies);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_DEFAULT_TIMEOUT);
        int status = client.executeMethod(backupPost);
        // log the status
        getLog().info(
                "Response status: " + status + ", statusText: " + HttpStatus.getStatusText(status) + "\r\n");

        String backUpFileName = formatbackUpFileName(file);

        File backupFile = new File(backUpFileName);

        if (status == HttpStatus.SC_OK) {
            copyStreamToFile(backupPost.getResponseBodyAsStream(), backupFile);
            getLog().info("Back-up succesfull. The backup is " + backupFile.getAbsolutePath());
        } else {
            logResponseDetails(backupPost);
            throw new MojoExecutionException("Back-up failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        getLog().error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage());
        throw new MojoExecutionException(ex.getMessage());
    } finally {
        backupPost.releaseConnection();
    }
}

From source file:com.jaspersoft.ireport.jasperserver.ws.CommonsHTTPSender.java

/**
 * Extracts info from message context./*from w  w  w. j  ava2 s .  co  m*/
 *
 * @param method Post method
 * @param httpClient The client used for posting
 * @param msgContext the message context
 * @param tmpURL the url to post to.
 *
 * @throws Exception
 */
private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL)
        throws Exception {

    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /* ISSUE: these are not the same, but MessageContext has only one
              definition of timeout */
        // SO_TIMEOUT -- timeout for blocking reads
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\""));
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
    }

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers. 
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            //HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            //Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addRequestHeader(key, value);
            }
        }
    }
}

From source file:edu.unc.lib.dl.fedora.ManagementClient.java

public String upload(File file, boolean retry) {
    String result = null;//  w w  w .  ja v a 2  s . c om
    String uploadURL = this.getFedoraContextUrl() + "/upload";
    PostMethod post = new PostMethod(uploadURL);
    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    log.debug("Uploading file with forwarded groups: " + GroupsThreadStore.getGroupString());
    post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());
    try {
        log.debug("Uploading to " + uploadURL);
        Part[] parts = { new FilePart("file", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        int status = httpClient.executeMethod(post);

        StringWriter sw = new StringWriter();
        try (InputStream in = post.getResponseBodyAsStream(); PrintWriter pw = new PrintWriter(sw)) {
            int b;
            while ((b = in.read()) != -1) {
                pw.write(b);
            }
        }

        switch (status) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_CREATED:
        case HttpStatus.SC_ACCEPTED:
            result = sw.toString().trim();
            log.info("Upload complete, response=" + result);
            break;
        case HttpStatus.SC_FORBIDDEN:
            log.warn("Authorization to Fedora failed, attempting to reestablish connection.");
            try {
                this.initializeConnections();
                return upload(file, false);
            } catch (Exception e) {
                log.error("Failed to reestablish connection to Fedora", e);
            }
            break;
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
            throw new FedoraTimeoutException("Fedora service unavailable, upload failed");
        default:
            log.warn("Upload failed, response=" + HttpStatus.getStatusText(status));
            log.debug(sw.toString().trim());
            break;
        }
    } catch (ServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ServiceException(ex);
    } finally {
        post.releaseConnection();
    }
    return result;
}

From source file:edu.unc.lib.dl.fedora.ManagementClient.java

public String upload(byte[] bytes, String fileName) {
    String result = null;// www .jav a 2 s  . c  o m
    // construct a post request to Fedora upload service
    String uploadURL = this.getFedoraContextUrl() + "/upload";
    PostMethod post = new PostMethod(uploadURL);
    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    log.debug("Uploading XML with forwarded groups: " + GroupsThreadStore.getGroupString());
    post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());
    try {
        log.debug("Uploading to " + uploadURL);
        Part[] parts = { new FilePart("file", new ByteArrayPartSource(fileName, bytes)) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        int status = httpClient.executeMethod(post);

        StringWriter sw = new StringWriter();
        try (InputStream in = post.getResponseBodyAsStream(); PrintWriter pw = new PrintWriter(sw)) {
            int b;
            while ((b = in.read()) != -1) {
                pw.write(b);
            }
        }
        if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_ACCEPTED) {
            result = sw.toString().trim();
            log.debug("Upload complete, response=" + result);
        } else {
            log.warn("Upload failed, response=" + HttpStatus.getStatusText(status));
            log.debug(sw.toString().trim());
        }
    } catch (Exception ex) {
        log.error("Upload failed due to error", ex);
        throw new ServiceException(ex);
    } finally {
        post.releaseConnection();
    }
    return result;
}

From source file:gov.va.med.imaging.proxy.ImageXChangeHttpCommonsSender.java

/**
* Extracts info from message context./*from  w ww . j a v a 2s  . c  o m*/
* 
* @param method
*            Post method
* @param httpClient
*            The client used for posting
* @param msgContext
*            the message context
* @param tmpURL
*            the url to post to.
* 
* @throws Exception
*/
private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL)
        throws Exception {

    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /*
        * ISSUE: these are not the same, but MessageContext has only one
        * definition of timeout
        */
        // SO_TIMEOUT -- timeout for blocking reads
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\""));
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
    //method.setRequestHeader(
    //   new Header(HTTPConstants.HEADER_USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.5072)")
    //);

    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();
    //System.out.println("ImageXChangeHttpCommonsSender setting credentials = '" + userID + ". " + passwd + "'");

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
        //System.out.println("ImageXChangeHttpCommonsSender setting credentials = '" + userID + ". " + passwd + "'");
    }

    // add compression headers if needed
    // if we accept GZIP then add the accept-encoding header
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        // accept both gzip and deflate if the gzip property is set
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING,
                HTTPConstants.COMPRESSION_GZIP + "," + COMPRESSION_DEFLATE);
        //method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, COMPRESSION_DEFLATE);
    }

    // if we will gzip the request then add the content-encoding header
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            // Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION))
                continue;
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addRequestHeader(key, value);
            }
        }
    }
}