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.utest.domain.service.util.FileUploadUtil.java

public static void uploadFile(final File targetFile, final String targetURL, final String targerFormFieldName_)
        throws Exception {
    final PostMethod filePost = new PostMethod(targetURL);
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    filePost.addRequestHeader("X-Atlassian-Token", "no-check");
    try {//  www  .  ja va  2s .  c om
        final FilePart fp = new FilePart(targerFormFieldName_, targetFile);
        fp.setTransferEncoding(null);
        final Part[] parts = { fp };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        final HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        final int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            Logger.getLogger(FileUploadUtil.class)
                    .info("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            Logger.getLogger(FileUploadUtil.class)
                    .info("Upload failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (final Exception ex) {
        Logger.getLogger(FileUploadUtil.class)
                .error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage(), ex);
        throw ex;
    } finally {
        Logger.getLogger(FileUploadUtil.class).debug(new String(filePost.getResponseBody()));
        filePost.releaseConnection();
    }

}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpSettingsRequestFilter.java

public void filterAbstractHttpRequest(SubmitContext context, AbstractHttpRequest<?> httpRequest) {
    ExtendedHttpMethod httpMethod = (ExtendedHttpMethod) context
            .getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    // set maxsize
    Settings settings = httpRequest.getSettings();

    // close connections?
    if (settings.getBoolean(HttpSettings.CLOSE_CONNECTIONS)) {
        httpMethod.setRequestHeader("Connection", "close");
    }//from w w  w .ja va  2 s.  c  o m

    // close connections?
    if (settings.getBoolean(HttpSettings.EXPECT_CONTINUE) && httpMethod instanceof EntityEnclosingMethod) {
        httpMethod.getParams().setParameter(HttpMethodParams.USE_EXPECT_CONTINUE, Boolean.TRUE);
    }

    // compress request?
    String compressionAlg = settings.getString(HttpSettings.REQUEST_COMPRESSION, "None");
    if (!"None".equals(compressionAlg))
        httpMethod.setRequestHeader("Content-Encoding", compressionAlg);

    // accept compressed responses?
    if (settings.getBoolean(HttpSettings.RESPONSE_COMPRESSION)) {
        httpMethod.setRequestHeader("Accept-Encoding", CompressionSupport.getAvailableAlgorithms(","));
    }

    String httpVersion = settings.getString(HttpSettings.HTTP_VERSION, "1.1");
    if (httpVersion.equals(HttpSettings.HTTP_VERSION_1_1)) {
        httpMethod.getParams().setVersion(HttpVersion.HTTP_1_1);
    } else if (httpVersion.equals(HttpSettings.HTTP_VERSION_1_0)) {
        httpMethod.getParams().setVersion(HttpVersion.HTTP_1_0);
    } else if (httpVersion.equals(HttpSettings.HTTP_VERSION_0_9)) {
        httpMethod.getParams().setVersion(HttpVersion.HTTP_1_1);
    }

    // max size..
    long maxSize = httpRequest.getMaxSize();
    if (maxSize == 0)
        maxSize = settings.getLong(HttpSettings.MAX_RESPONSE_SIZE, 0);
    if (maxSize > 0)
        httpMethod.setMaxSize(maxSize);

    // follow redirects is false; handled in transport
    httpMethod.setFollowRedirects(false);

    // apply global settings
    HttpClientSupport.applyHttpSettings(httpMethod, settings);

    String timeout = context.expand(httpRequest.getTimeout());
    if (StringUtils.hasContent(timeout)) {
        try {
            httpMethod.getParams().setSoTimeout(Integer.parseInt(timeout));
        } catch (NumberFormatException e) {
            SoapUI.logError(e);
        }
    }
}

From source file:colt.nicity.performance.agent.LatentHttpPump.java

private org.apache.commons.httpclient.HttpClient createApacheClient(String host, int port, int maxConnections,
        int socketTimeoutInMillis) {

    HttpConnectionManager connectionManager = createConnectionManager(maxConnections);

    org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(
            connectionManager);//w w  w  . j  a v a2  s.  c o m
    client.getParams().setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109);
    client.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    client.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    client.getParams().setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, true);
    client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
            socketTimeoutInMillis > 0 ? socketTimeoutInMillis : 0);
    client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,
            socketTimeoutInMillis > 0 ? socketTimeoutInMillis : 0);

    HostConfiguration hostConfiguration = new HostConfiguration();
    configureSsl(hostConfiguration, host, port);
    configureProxy(hostConfiguration);

    client.setHostConfiguration(hostConfiguration);
    return client;

}

From source file:mercury.UploadController.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        try {//from ww w  . j  ava2 s  .  c o m
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String targetUrl = Config.getConfigProperty(ConfigurationEnum.DIGITAL_MEDIA);
                    if (StringUtils.isBlank(targetUrl)) {
                        targetUrl = request.getRequestURL().toString();
                        targetUrl = targetUrl.substring(0, targetUrl.lastIndexOf('/'));
                    }
                    targetUrl += "/DigitalMediaController";
                    PostMethod filePost = new PostMethod(targetUrl);
                    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
                    UploadPartSource src = new UploadPartSource(item.getName(), item.getSize(),
                            item.getInputStream());
                    Part[] parts = new Part[1];
                    parts[0] = new FilePart(item.getName(), src, item.getContentType(), null);
                    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) {
                        String data = filePost.getResponseBodyAsString();
                        JSONObject json = new JSONObject(data);
                        if (json.has("id")) {
                            JSONObject responseJson = new JSONObject();
                            responseJson.put("success", true);
                            responseJson.put("id", json.getString("id"));
                            responseJson.put("uri", targetUrl + "?id=" + json.getString("id"));
                            response.getWriter().write(responseJson.toString());
                        }
                    }
                    filePost.releaseConnection();
                    return;
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (JSONException je) {
            je.printStackTrace();
        }
    }
    response.getWriter().write("{success: false}");
}

From source file:com.jivesoftware.os.jive.utils.http.client.HttpClientFactoryProvider.java

public HttpClientFactory createHttpClientFactory(final Collection<HttpClientConfiguration> configurations) {
    return new HttpClientFactory() {
        @Override//w  w  w.ja v a 2 s  . c  o  m
        public HttpClient createClient(String host, int port) {

            ApacheHttpClient31BackedHttpClient httpClient = createApacheClient();

            HostConfiguration hostConfiguration = new HostConfiguration();
            configureSsl(hostConfiguration, host, port, httpClient);
            configureProxy(hostConfiguration, httpClient);

            httpClient.setHostConfiguration(hostConfiguration);
            configureOAuth(httpClient);
            return httpClient;
        }

        private ApacheHttpClient31BackedHttpClient createApacheClient() {
            HttpClientConfig httpClientConfig = locateConfig(HttpClientConfig.class,
                    HttpClientConfig.newBuilder().build());

            HttpConnectionManager connectionManager = createConnectionManager(httpClientConfig);

            org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(
                    connectionManager);
            client.getParams().setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109);
            client.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            client.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
            client.getParams().setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, true);
            client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                    httpClientConfig.getSocketTimeoutInMillis() > 0
                            ? httpClientConfig.getSocketTimeoutInMillis()
                            : 0);
            client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,
                    httpClientConfig.getSocketTimeoutInMillis() > 0
                            ? httpClientConfig.getSocketTimeoutInMillis()
                            : 0);

            return new ApacheHttpClient31BackedHttpClient(client,
                    httpClientConfig.getCopyOfHeadersForEveryRequest());

        }

        @SuppressWarnings("unchecked")
        private <T> T locateConfig(Class<? extends T> _class, T defaultConfiguration) {
            for (HttpClientConfiguration configuration : configurations) {
                if (_class.isInstance(configuration)) {
                    return (T) configuration;
                }
            }
            return defaultConfiguration;
        }

        private boolean hasValidProxyUsernameAndPasswordSettings(HttpClientProxyConfig httpClientProxyConfig) {
            return StringUtils.isNotBlank(httpClientProxyConfig.getProxyUsername())
                    && StringUtils.isNotBlank(httpClientProxyConfig.getProxyPassword());
        }

        private HttpConnectionManager createConnectionManager(HttpClientConfig config) {
            MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
            if (config.getMaxConnectionsPerHost() > 0) {
                connectionManager.getParams()
                        .setDefaultMaxConnectionsPerHost(config.getMaxConnectionsPerHost());
            } else {
                connectionManager.getParams().setDefaultMaxConnectionsPerHost(Integer.MAX_VALUE);
            }
            if (config.getMaxConnections() > 0) {
                connectionManager.getParams().setMaxTotalConnections(config.getMaxConnections());
            }
            return connectionManager;
        }

        private void configureOAuth(ApacheHttpClient31BackedHttpClient httpClient) {
            HttpClientOAuthConfig httpClientOAuthConfig = locateConfig(HttpClientOAuthConfig.class, null);
            if (httpClientOAuthConfig != null) {
                String serviceName = httpClientOAuthConfig.getServiceName();
                HttpClientConsumerKeyAndSecretProvider consumerKeyAndSecretProvider = httpClientOAuthConfig
                        .getConsumerKeyAndSecretProvider();
                String consumerKey = consumerKeyAndSecretProvider.getConsumerKey(serviceName);
                if (StringUtils.isEmpty(consumerKey)) {
                    throw new RuntimeException(
                            "could create oauth client because consumerKey is null or empty for service:"
                                    + serviceName);
                }
                String consumerSecret = consumerKeyAndSecretProvider.getConsumerSecret(serviceName);
                if (StringUtils.isEmpty(consumerSecret)) {
                    throw new RuntimeException(
                            "could create oauth client because consumerSecret is null or empty for service:"
                                    + serviceName);
                }

                httpClient.setConsumerTokens(consumerKey, consumerSecret);
            }
        }

        private void configureProxy(HostConfiguration hostConfiguration,
                ApacheHttpClient31BackedHttpClient httpClient) {
            HttpClientProxyConfig httpClientProxyConfig = locateConfig(HttpClientProxyConfig.class, null);
            if (httpClientProxyConfig != null) {
                hostConfiguration.setProxy(httpClientProxyConfig.getProxyHost(),
                        httpClientProxyConfig.getProxyPort());
                if (hasValidProxyUsernameAndPasswordSettings(httpClientProxyConfig)) {
                    HttpState state = new HttpState();
                    state.setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(httpClientProxyConfig.getProxyUsername(),
                                    httpClientProxyConfig.getProxyPassword()));
                    httpClient.setState(state);
                }
            }
        }

        private void configureSsl(HostConfiguration hostConfiguration, String host, int port,
                ApacheHttpClient31BackedHttpClient httpClient) throws IllegalStateException {
            HttpClientSSLConfig httpClientSSLConfig = locateConfig(HttpClientSSLConfig.class, null);
            if (httpClientSSLConfig != null) {
                Protocol sslProtocol;
                if (httpClientSSLConfig.getCustomSSLSocketFactory() != null) {
                    sslProtocol = new Protocol(HTTPS_PROTOCOL, new CustomSecureProtocolSocketFactory(
                            httpClientSSLConfig.getCustomSSLSocketFactory()), SSL_PORT);
                } else {
                    sslProtocol = Protocol.getProtocol(HTTPS_PROTOCOL);
                }
                hostConfiguration.setHost(host, port, sslProtocol);
                httpClient.setUsingSSL();
            } else {
                hostConfiguration.setHost(host, port);
            }
        }
    };
}

From source file:com.utest.webservice.client.rest.RestClient.java

public HttpMethod createPost(String service, String path, Map<String, Object> parameters) {
    final PostMethod post = new PostMethod(baseUrl + servicePath + service + "/" + path);
    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    for (final Map.Entry<String, Object> param : parameters.entrySet()) {
        post.addParameter(param.getKey(), (param.getValue() == null) ? "" : param.getValue().toString());
    }//from  w  ww  .  j ava 2s.co  m
    setHeader(post);
    return post;
}

From source file:com.globalsight.everest.webapp.applet.admin.customer.FileSystemApplet.java

/**
 * Zip the selected files and send the zip to the server.
 * @param p_filesToBeZipped - A list of selected files to be uploaded.
 * @param p_targetURL - The target URL representing server URL.
 * @param p_targetLocation - A string representing the link to the next page.
 *///from   ww  w  . j a  va2 s  . c  o  m
public void sendZipFile(File[] p_filesToBeZipped, String p_targetURL, final String p_targetLocation)
        throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.append("GS_");
    sb.append(System.currentTimeMillis());
    sb.append(".zip");

    File targetFile = getFile(sb.toString());
    ZipIt.addEntriesToZipFile(targetFile, p_filesToBeZipped);
    m_progressBar.setValue(30);

    PostMethod filePost = new PostMethod(p_targetURL + "&doPost=true");
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    filePost.setDoAuthentication(true);
    try {
        Part[] parts = { new FilePart(targetFile.getName(), targetFile) };

        m_progressBar.setValue(40);
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        HttpClient client = new HttpClient();
        setUpClientForProxy(client);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        m_progressBar.setValue(50);
        int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            //no need to ask for auth again since the first upload was fine
            s_authPrompter.setAskForAuthentication(false);

            m_progressBar.setValue(60);
            InputStream is = filePost.getResponseBodyAsStream();
            m_progressBar.setValue(70);
            ObjectInputStream inputStreamFromServlet = new ObjectInputStream(is);
            Vector incomingData = (Vector) inputStreamFromServlet.readObject();

            inputStreamFromServlet.close();
            if (incomingData != null) {
                if (incomingData.elementAt(0) instanceof ExceptionMessage) {
                    resetProgressBar();
                    AppletHelper.displayErrorPage((ExceptionMessage) incomingData.elementAt(0), this);
                }
            } else {
                boolean deleted = targetFile.delete();
                m_progressBar.setValue(100);
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
                // now move to some other page...
                goToTargetPage(p_targetLocation);
            }
        } else {
            //authentication may have failed, reset the need to ask
            s_authPrompter.setAskForAuthentication(true);
            resetProgressBar();
            String errorMessage = "Upload failed because: (" + status + ") " + HttpStatus.getStatusText(status);
            if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                errorMessage = "Incorrect NTDomain\\username or password entered. Hit 'upload' again to re-try.";
            }
            AppletHelper.getErrorDlg(errorMessage, null);
        }
    } catch (Exception ex) {
        //authentication may have failed, reset the need to ask
        s_authPrompter.setAskForAuthentication(true);

        resetProgressBar();
        System.err.println(ex);
        AppletHelper.getErrorDlg(ex.getMessage(), null);
    } finally {
        filePost.releaseConnection();
    }

}

From source file:edu.caltech.ipac.firefly.server.WorkspaceManager.java

public boolean davPut(File upload, String toPath) {
    try {/*from ww w .  ja  va 2  s  .c  o  m*/
        PutMethod put = new PutMethod(getResourceUrl(toPath));
        RequestEntity requestEntity = new InputStreamRequestEntity(
                new BufferedInputStream(new FileInputStream(upload), HttpServices.BUFFER_SIZE),
                upload.length());
        put.setRequestEntity(requestEntity);
        /** is to allow a client that is sending a request message with a request body
         *  to determine if the origin server is willing to accept the request
         * (based on the request headers) before the client sends the request body.
         * this require server supporting HTTP/1.1 protocol.
         */
        put.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

        if (!executeMethod(put)) {
            // handle error
            System.out.println("Unable to upload file:" + toPath + " -- " + put.getStatusText());
            return false;
        }

        return true;
    } catch (Exception e) {
        LOG.error(e, "Error while uploading file:" + upload.getPath());
    }
    return false;
}

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

/**
* invoke creates a socket connection, sends the request SOAP message and
* then reads the response SOAP message back from the SOAP server
* 
* @param msgContext/*from ww w  . j a  v a2s  . c  om*/
*            the messsage context
* 
* @throws AxisFault
*/
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    log.debug(Messages.getMessage("enter00", "CommonsHttpSender::invoke"));
    try {
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // no need to retain these, as the cookies/credentials are
        // stored in the message context across multiple requests.
        // the underlying connection manager, however, is retained
        // so sockets get recycled when possible.
        HttpClient httpClient = new HttpClient(this.connectionManager);

        // the timeout value for allocation of connections from the pool
        httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL);

        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null)
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
        }

        if (posting) {
            Message reqMessage = msgContext.getRequestMessage();
            method = new PostMethod(targetURL.toString());
            log.info("POST message created with target [" + targetURL.toString() + "]");
            TransactionContext transactionContext = TransactionContextFactory.get();
            transactionContext
                    .addDebugInformation("POST message created with target [" + targetURL.toString() + "]");

            // set false as default, addContetInfo can overwrite
            method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

            addContextInfo(method, httpClient, msgContext, targetURL);

            Credentials cred = httpClient.getState().getCredentials(AuthScope.ANY);
            if (cred instanceof UsernamePasswordCredentials) {
                log.trace("POST message created on client with credentials ["
                        + ((UsernamePasswordCredentials) cred).getUserName() + ", "
                        + ((UsernamePasswordCredentials) cred).getPassword() + "].");
            }

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
                log.info("HTTPCommonsSender - zipping request.");
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
                log.info("HTTPCommonsSender - not zipping request");
            }
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            log.info("GET message created with target [" + targetURL.toString() + "]");
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP))
            log.info("HTTPCommonsSender - accepting GZIP");
        else
            log.info("HTTPCommonsSender - NOT accepting GZIP");

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null && httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10))
            method.getParams().setVersion(HttpVersion.HTTP_1_0);

        // don't forget the cookies!
        // Cookies need to be set on HttpState, since HttpMethodBase
        // overwrites the cookies from HttpState
        if (msgContext.getMaintainSession()) {
            HttpState state = httpClient.getState();
            method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            String host = hostConfiguration.getHost();
            String path = targetURL.getPath();

            boolean secure = hostConfiguration.getProtocol().isSecure();
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure);
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure);
            httpClient.setState(state);
        }

        // add HTTP header fields that the application thinks are "interesting"
        // the expectation is that these would be non-standard HTTP headers, 
        // by convention starting with "xxx-"
        VistaRealmPrincipal principal = VistaRealmSecurityContext.get();

        if (principal != null) {
            log.info("SecurityContext credentials for '" + principal.getAccessCode() + "' are available.");
            String duz = principal.getDuz();
            if (duz != null && duz.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderDuz, duz);

            String fullname = principal.getFullName();
            if (fullname != null && fullname.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderFullName, fullname);

            String sitename = principal.getSiteName();
            if (sitename != null && sitename.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteName, sitename);

            String sitenumber = principal.getSiteNumber();
            if (sitenumber != null && sitenumber.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteNumber, sitenumber);

            String ssn = principal.getSsn();
            if (ssn != null && ssn.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSSN, ssn);

            String securityToken = principal.getSecurityToken();
            if (securityToken != null && securityToken.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderBrokerSecurityTokenId,
                        securityToken);

            String cacheLocationId = principal.getCacheLocationId();
            if (cacheLocationId != null && cacheLocationId.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderCacheLocationId,
                        cacheLocationId);

            String userDivision = principal.getUserDivision();
            if (userDivision != null && userDivision.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderUserDivision, userDivision);
        } else
            log.debug("SecurityContext credentials are NOT available.");

        method.addRequestHeader(HTTPConstants.HEADER_CACHE_CONTROL, "no-cache,no-store");
        method.addRequestHeader(HTTPConstants.HEADER_PRAGMA, "no-cache");

        try {
            log.info("Executing method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                    + "]");
        } catch (IllegalStateException isX) {
        }

        // send the HTTP request and wait for a response 
        int returnCode = httpClient.executeMethod(hostConfiguration, method, null);

        TransactionContext transactionContext = TransactionContextFactory.get();
        // don't set the response code here - this is not the response code we send out, but the resposne code we get back from the data source
        //transactionContext.setResponseCode (String.valueOf (returnCode));

        // How many bytes received?
        transactionContext.setDataSourceBytesReceived(method.getBytesReceived());

        // How long did it take to start getting a response coming back?
        Long timeSent = method.getTimeRequestSent();
        Long timeReceived = method.getTimeFirstByteReceived();
        if (timeSent != null && timeReceived != null) {
            long timeTook = timeReceived.longValue() - timeSent.longValue();
            transactionContext.setTimeToFirstByte(new Long(timeTook));
        }

        // Looks like it wasn't found in cache - is there a place to set this to true if it was?
        transactionContext.setItemCached(Boolean.FALSE);

        // extract the basic HTTP header fields for content type, location and length
        String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE);
        String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION);
        String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH);

        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html")
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
        } else {
            String statusMessage = method.getStatusText();
            try {
                log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                        + "] failed - '" + statusMessage + "'.");
            } catch (IllegalStateException isX) {
            }

            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            try {
                fault.setFaultDetailString(
                        Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString()));
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } finally {
                method.releaseConnection(); // release connection back to
                // pool.
            }
        }

        // wrap the response body stream so that close() also releases
        // the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method);

        Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
        log.info("HTTPCommonsSender - " + HTTPConstants.HEADER_CONTENT_ENCODING + "="
                + (contentEncoding == null ? "null" : contentEncoding.getValue()));

        if (contentEncoding != null) {
            if (HTTPConstants.COMPRESSION_GZIP.equalsIgnoreCase(contentEncoding.getValue())) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);

                log.debug("HTTPCommonsSender - receiving gzipped stream.");
            } else if (ENCODING_DEFLATE.equalsIgnoreCase(contentEncoding.getValue())) {
                releaseConnectionOnCloseStream = new java.util.zip.InflaterInputStream(
                        releaseConnectionOnCloseStream);

                log.debug("HTTPCommonsSender - receiving 'deflated' stream.");
            } else {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
                log.warn(fault.getMessage());
                throw fault;
            }

        }
        try {
            log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                    + "] succeeded, parsing response.");
        } catch (IllegalStateException isX) {
        }

        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP
        // message
        Header[] responseHeaders = method.getResponseHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }
        outMsg.setMessageType(Message.RESPONSE);
        msgContext.setResponseMessage(outMsg);
        if (log.isTraceEnabled()) {
            if (null == contentLength)
                log.trace("\n" + Messages.getMessage("no00", "Content-Length"));
            log.trace("\n" + Messages.getMessage("xmlRecd00"));
            log.trace("-----------------------------------------------");
            log.trace(outMsg.getSOAPPartAsString());
        }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();

            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext);
                } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext);
                }
            }
        }

        // always release the connection back to the pool if
        // it was one way invocation
        if (msgContext.isPropertyTrue("axis.one.way")) {
            method.releaseConnection();
        }

    } catch (Exception e) {
        log.debug(e);
        throw AxisFault.makeFault(e);
    }

    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
    }
}

From source file:com.vmware.aurora.vc.VcFileManager.java

static private void uploadFileWork(String url, boolean isPost, File file, String contentType, String cookie,
        ProgressListener listener) throws Exception {
    EntityEnclosingMethod method;/*w  w w.  j  a  va  2 s. c o m*/
    final RequestEntity entity = new ProgressListenerRequestEntity(file, contentType, listener);
    if (isPost) {
        method = new PostMethod(url);
        method.setContentChunked(true);
    } else {
        method = new PutMethod(url);
        method.addRequestHeader("Cookie", cookie);
        method.setContentChunked(false);
        HttpMethodParams params = new HttpMethodParams();
        params.setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        method.setParams(params);
    }
    method.setRequestEntity(entity);

    logger.info("upload " + file + " to " + url);
    long t1 = System.currentTimeMillis();
    boolean ok = false;
    try {
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(method);
        String response = method.getResponseBodyAsString(100);
        logger.debug("status: " + statusCode + " response: " + response);
        if (statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_OK) {
            throw new Exception("Http post failed");
        }
        method.releaseConnection();
        ok = true;
    } finally {
        if (!ok) {
            method.abort();
        }
    }
    long t2 = System.currentTimeMillis();
    logger.info("upload " + file + " done in " + (t2 - t1) + " ms");
}