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:org.craftercms.studio.impl.v1.deployment.PreviewDeployer.java

@Override
public void deleteFile(String site, String path) {

    DeploymentEndpointConfigTO deploymentEndpointConfigTO = siteService.getPreviewDeploymentEndpoint(site);
    URL requestUrl = null;/*w  ww . ja  v a 2 s .  com*/

    try {
        String url = DEPLOYER_SERVLET_URL;
        List<Part> formParts = new ArrayList<>();
        if (deploymentEndpointConfigTO != null) {
            requestUrl = new URL(deploymentEndpointConfigTO.getServerUrl());
            formParts.add(new StringPart(DEPLOYER_PASSWORD_PARAM, deploymentEndpointConfigTO.getPassword()));
            formParts.add(new StringPart(DEPLOYER_TARGET_PARAM, deploymentEndpointConfigTO.getTarget()));
        } else {
            requestUrl = new URL("http", defaultServer, defaultPort, url);
            formParts.add(new StringPart(DEPLOYER_PASSWORD_PARAM, defaultPassword));
            formParts.add(new StringPart(DEPLOYER_TARGET_PARAM, defaultTarget));
        }

        StringBuilder sbDeletedFiles = new StringBuilder(path);
        if (path.endsWith("/index.xml")) {
            RepositoryItem[] children = contentRepository.getContentChildren(
                    contentService.expandRelativeSitePath(site, path.replace("/index.xml", "")));
            if (!(children != null && children.length > 1)) {
                sbDeletedFiles.append(FILES_SEPARATOR).append(path.replace("/index.xml", ""));

            }
        }
        formParts.add(new StringPart(DEPLOYER_DELETED_FILES_PARAM, sbDeletedFiles.toString()));
        formParts.add(new StringPart(DEPLOYER_SITE_PARAM, site));

        PostMethod postMethod = new PostMethod(requestUrl.toString());
        postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

        Part[] parts = new Part[formParts.size()];

        for (int i = 0; i < formParts.size(); i++)
            parts[i] = formParts.get(i);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        HttpClient client = new HttpClient();
        int status = client.executeMethod(postMethod);
        postMethod.releaseConnection();
    } catch (Exception err) {
        logger.error("error while preview deploying '" + site + ":" + path + "'", err);
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.PreviewDeployer.java

protected void deleteSite(String site) {

    DeploymentEndpointConfigTO deploymentEndpointConfigTO = siteService.getPreviewDeploymentEndpoint(site);
    URL requestUrl = null;/*from   w w w. ja v  a 2s .com*/

    try {
        String url = DEPLOYER_SERVLET_URL;
        List<Part> formParts = new ArrayList<>();
        if (deploymentEndpointConfigTO != null) {
            requestUrl = new URL(deploymentEndpointConfigTO.getServerUrl());
            formParts.add(new StringPart(DEPLOYER_PASSWORD_PARAM, deploymentEndpointConfigTO.getPassword()));
            formParts.add(new StringPart(DEPLOYER_TARGET_PARAM, deploymentEndpointConfigTO.getTarget()));
        } else {
            requestUrl = new URL("http", defaultServer, defaultPort, url);
            formParts.add(new StringPart(DEPLOYER_PASSWORD_PARAM, defaultPassword));
            formParts.add(new StringPart(DEPLOYER_TARGET_PARAM, defaultTarget));
        }

        StringBuilder sbDeletedFiles = new StringBuilder("/");

        formParts.add(new StringPart(DEPLOYER_DELETED_FILES_PARAM, sbDeletedFiles.toString()));
        formParts.add(new StringPart(DEPLOYER_SITE_PARAM, site));

        PostMethod postMethod = new PostMethod(requestUrl.toString());
        postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

        Part[] parts = new Part[formParts.size()];

        for (int i = 0; i < formParts.size(); i++)
            parts[i] = formParts.get(i);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        HttpClient client = new HttpClient();
        int status = client.executeMethod(postMethod);
        postMethod.releaseConnection();
    } catch (Exception err) {
        logger.error("error while deleting site from preview: '" + site + "'", err);
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.SyncTargetDeployer.java

@Override
public void deployFiles(String site, List<String> paths, List<String> deletedFiles)
        throws ContentNotFoundForPublishingException, UploadFailedException {
    logger.debug("Start deploying items for site \"{0}\", target \"{1}\", number of items \"{2}\"", site,
            endpointConfig.getName(), paths.size());
    URL requestUrl = null;/* w  w  w  .ja  v  a2s.  c  o  m*/
    try {
        requestUrl = new URL(endpointConfig.getServerUrl());
    } catch (MalformedURLException e) {
        logger.error("Invalid server URL for target {0}", endpointConfig.getName());
        throw new UploadFailedException(site, endpointConfig.getName(), endpointConfig.getServerUrl(), e);
    }

    ByteArrayPartSource baps = null;
    PartSource metadataPart = null;
    StringPart stringPart = null;
    FilePart filePart = null;

    // TODO: implement reactor version of deployment events
    int cntFiles = 0;
    StringBuilder sbDeletedFiles = new StringBuilder();
    List<Part> formParts = new ArrayList<Part>();

    formParts.add(new StringPart(PASSWORD_REQUEST_PARAMETER, endpointConfig.getPassword()));
    formParts.add(new StringPart(TARGET_REQUEST_PARAMETER, endpointConfig.getTarget()));
    String siteId = endpointConfig.getSiteId();
    if (StringUtils.isEmpty(siteId)) {
        siteId = site;
    }
    formParts.add(new StringPart(SITE_REQUEST_PARAMETER, siteId));

    logger.debug("Preparing deployment items for target {0}", endpointConfig.getName());
    for (String path : paths) {
        logger.debug("Parsing \"{0}\" , site \"{1}\"; for publishing on target \"{2}\"", path, site,
                endpointConfig.getName());
        logger.debug("Get content for \"{0}\" , site \"{1}\", environment \"{2}\"", path, site, environment);
        File file = new File(getDestinationPath(site, path, environment));
        InputStream input = null;
        try {
            input = FileUtils.openInputStream(file);
            if (input == null || input.available() < 0) {
                if (file.exists() && !file.isDirectory()) {
                    baps = null;
                    stringPart = null;
                    filePart = null;
                    formParts = null;
                    throw new ContentNotFoundForPublishingException(site, endpointConfig.getName(), path);
                } else {
                    // Content does not exist - skip deploying file
                    continue;
                }
            }
        } catch (IOException err) {
            logger.error("Error reading input stream from envirnoment store for content at path: " + path
                    + " site: " + site + " environment: " + environment);
            if (!file.exists()) {
                logger.error("File expected, but does not exist at path: " + file.getAbsolutePath());
            }
            continue;
        }
        String fileName = file.getName();

        byte[] byteArray = null;

        try {
            byteArray = IOUtils.toByteArray(input);
        } catch (IOException e) {
            logger.error("Error while converting input stream to byte array", e);
            baps = null;
            stringPart = null;
            filePart = null;
            formParts = null;
        } finally {
            IOUtils.closeQuietly(input);
            input = null;
        }
        baps = new ByteArrayPartSource(fileName, byteArray);

        logger.debug("Create http request parameters for \"{0}\" , site \"{1}\"; publishing on target \"{2}\"",
                path, site, endpointConfig.getName());
        int idx = path.lastIndexOf("/");
        String relativePath = path.substring(0, idx + 1) + fileName;
        stringPart = new StringPart(CONTENT_LOCATION_REQUEST_PARAMETER + cntFiles, relativePath);
        formParts.add(stringPart);
        filePart = new FilePart(CONTENT_FILE_REQUEST_PARAMETER + cntFiles, baps);
        formParts.add(filePart);
        /*
        if (item.getAction() == PublishingSyncItem.Action.MOVE) {
        if (item.getOldPath() != null && !item.getOldPath().equalsIgnoreCase(item.getPath())) {
            LOGGER.debug("Add old path to be deleted for MOVE action (\"{0}\")", item.getOldPath());
            eventItem.setOldPath(item.getOldPath());
            if (sbDeletedFiles.length() > 0) {
                sbDeletedFiles.append(",").append(item.getOldPath());
            } else {
                sbDeletedFiles.append(item.getOldPath());
            }
            if (item.getOldPath().endsWith("/" + _indexFile)) {
                sbDeletedFiles.append(FILES_SEPARATOR).append(item.getOldPath().replace("/" + _indexFile, ""));
            }
        }
        }*/
        cntFiles++;

        // TODO: implement metadata transfer
    }

    for (int i = 0; i < deletedFiles.size(); i++) {
        if (i > 0) {
            sbDeletedFiles.append(FILES_SEPARATOR);
        }
        sbDeletedFiles.append(deletedFiles.get(i));
    }

    if (sbDeletedFiles.length() > 0) {
        formParts.add(new StringPart(DELETED_FILES_REQUEST_PARAMETER, sbDeletedFiles.toString()));
    }
    logger.debug("Create http request to deploy content for target {0} ({1})", endpointConfig.getName(),
            endpointConfig.getTarget());
    PostMethod postMethod = null;
    HttpClient client = null;
    try {
        logger.debug("Create HTTP Post Method");
        postMethod = new PostMethod(requestUrl.toString());
        postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        Part[] parts = new Part[formParts.size()];
        for (int i = 0; i < formParts.size(); i++)
            parts[i] = formParts.get(i);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        client = new HttpClient();

        logger.debug("Execute HTTP POST request \"{0}\"", postMethod.getURI());
        int status = client.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
            logger.info("Successfully deployed on target {0}", endpointConfig.getName());
        } else {
            logger.error("Deployment failed for on target {1}. Deployment agent returned status {2}",
                    endpointConfig.getName(), HttpStatus.getStatusText(status));
            throw new UploadFailedException(site, endpointConfig.getName(), endpointConfig.getServerUrl());
        }
    } catch (HttpException e) {
        logger.error("Publish failed for target {0} due to http protocol exception", endpointConfig.getName());
        throw new UploadFailedException(site, endpointConfig.getName(), endpointConfig.getServerUrl(), e);
    } catch (IOException e) {
        logger.error("Publish failed for target {0} due to I/O (transport) exception",
                endpointConfig.getName());
        throw new UploadFailedException(site, endpointConfig.getName(), endpointConfig.getServerUrl(), e);
    } finally {
        logger.debug("Release http connection and release resources");
        if (client != null) {
            HttpConnectionManager mgr = client.getHttpConnectionManager();
            if (mgr instanceof SimpleHttpConnectionManager) {
                ((SimpleHttpConnectionManager) mgr).shutdown();
            }
        }
        if (postMethod != null) {
            postMethod.releaseConnection();
            postMethod = null;
            client = null;
        }
        baps = null;
        stringPart = null;
        filePart = null;
        formParts = null;
    }

    //LOGGER.debug("Publishing deployment event for target \"{0}\" with \"{1}\" items.", target.getName(), 0/*eventItems.size()*/);
    //contentRepository.publishDeployEvent(target.getName(), eventItems);

    logger.info("Deployment successful on target {0}", endpointConfig.getName());
    logger.debug("Finished deploying items for site \"{0}\", target \"{1}\", number of items \"{2}\"", site,
            endpointConfig.getName(), paths.size());
}

From source file:org.eclipse.mylyn.internal.bugzilla.core.BugzillaClient.java

public void postAttachment(String bugReportID, String comment, AbstractTaskAttachmentSource source,
        TaskAttribute attachmentAttribute, IProgressMonitor monitor)
        throws HttpException, IOException, CoreException {
    monitor = Policy.monitorFor(monitor);
    String description = source.getDescription();
    String contentType = source.getContentType();
    String filename = source.getName();
    boolean isPatch = false;

    if (attachmentAttribute != null) {
        TaskAttachmentMapper mapper = TaskAttachmentMapper.createFrom(attachmentAttribute);

        if (mapper.getDescription() != null) {
            description = mapper.getDescription();
        }//from  w  w w  . j  ava 2  s.  co  m

        if (mapper.getContentType() != null) {
            contentType = mapper.getContentType();
        }

        if (mapper.getFileName() != null) {
            filename = mapper.getFileName();
        }

        if (mapper.isPatch() != null) {
            isPatch = mapper.isPatch();
        }
    }
    Assert.isNotNull(bugReportID);
    Assert.isNotNull(source);
    Assert.isNotNull(contentType);
    if (description == null) {
        throw new CoreException(new Status(IStatus.WARNING, BugzillaCorePlugin.ID_PLUGIN,
                Messages.BugzillaClient_description_required_when_submitting_attachments));
    }

    hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);
    authenticate(monitor);
    GzipPostMethod postMethod = null;

    try {
        postMethod = new GzipPostMethod(
                WebUtil.getRequestPath(repositoryUrl + IBugzillaConstants.URL_POST_ATTACHMENT_UPLOAD), true);
        // This option causes the client to first
        // check
        // with the server to see if it will in fact receive the post before
        // actually sending the contents.
        postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        List<PartBase> parts = new ArrayList<PartBase>();
        parts.add(new StringPart(IBugzillaConstants.POST_INPUT_ACTION, VALUE_ACTION_INSERT,
                getCharacterEncoding()));

        parts.add(new StringPart(IBugzillaConstants.POST_INPUT_BUGID, bugReportID, getCharacterEncoding()));
        if (description != null) {
            parts.add(new StringPart(IBugzillaConstants.POST_INPUT_DESCRIPTION, description,
                    getCharacterEncoding()));
        }
        if (comment != null) {
            parts.add(new StringPart(IBugzillaConstants.POST_INPUT_COMMENT, comment, getCharacterEncoding()));
        }
        parts.add(new BugzillaFilePart(source, filename, contentType, getCharacterEncoding()));

        if (isPatch) {
            parts.add(new StringPart(ATTRIBUTE_ISPATCH, VALUE_ISPATCH));
        } else {
            parts.add(new StringPart(ATTRIBUTE_CONTENTTYPEMETHOD, VALUE_CONTENTTYPEMETHOD_MANUAL));
            parts.add(new StringPart(ATTRIBUTE_CONTENTTYPEENTRY, contentType));
        }
        if (attachmentAttribute != null) {
            Collection<TaskAttribute> attributes = attachmentAttribute.getAttributes().values();
            Iterator<TaskAttribute> itr = attributes.iterator();
            while (itr.hasNext()) {
                TaskAttribute a = itr.next();
                if (a.getId().startsWith(BugzillaAttribute.KIND_FLAG_TYPE) && repositoryConfiguration != null) {
                    List<BugzillaFlag> flags = repositoryConfiguration.getFlags();
                    TaskAttribute requestee = a.getAttribute("requestee"); //$NON-NLS-1$
                    a = a.getAttribute("state"); //$NON-NLS-1$
                    String value = a.getValue();
                    String id = ""; //$NON-NLS-1$
                    if (value.equals(" ")) { //$NON-NLS-1$
                        continue;
                    }
                    String flagname = a.getMetaData().getLabel();
                    BugzillaFlag theFlag = null;
                    for (BugzillaFlag bugzillaFlag : flags) {
                        if (flagname.equals(bugzillaFlag.getName())) {
                            theFlag = bugzillaFlag;
                            break;
                        }
                    }
                    if (theFlag != null) {
                        int flagTypeNumber = theFlag.getFlagId();
                        id = "flag_type-" + flagTypeNumber; //$NON-NLS-1$
                        value = a.getValue();
                        if (value.equals("?") && requestee != null) { //$NON-NLS-1$
                            parts.add(new StringPart("requestee_type-" + flagTypeNumber, //$NON-NLS-1$
                                    requestee.getValue() != null ? requestee.getValue() : "")); //$NON-NLS-1$
                        }
                    }
                    parts.add(new StringPart(id, value != null ? value : "")); //$NON-NLS-1$
                } else if (a.getId().startsWith(BugzillaAttribute.KIND_FLAG)) {
                    TaskAttribute flagnumber = a.getAttribute("number"); //$NON-NLS-1$
                    TaskAttribute requestee = a.getAttribute("requestee"); //$NON-NLS-1$
                    a = a.getAttribute("state"); //$NON-NLS-1$
                    String id = "flag-" + flagnumber.getValue(); //$NON-NLS-1$
                    String value = a.getValue();
                    if (value.equals(" ") || value.equals("")) { //$NON-NLS-1$ //$NON-NLS-2$
                        value = "X"; //$NON-NLS-1$
                    }
                    if (value.equals("?") && requestee != null) { //$NON-NLS-1$
                        parts.add(new StringPart("requestee-" + flagnumber.getValue(), //$NON-NLS-1$
                                requestee.getValue() != null ? requestee.getValue() : "")); //$NON-NLS-1$
                    }
                    parts.add(new StringPart(id, value != null ? value : "")); //$NON-NLS-1$
                }
            }
        }
        String token = null;
        BugzillaVersion bugzillaVersion = null;
        if (repositoryConfiguration != null) {
            bugzillaVersion = repositoryConfiguration.getInstallVersion();
        } else {
            bugzillaVersion = BugzillaVersion.MIN_VERSION;
        }
        if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_4_0) > 0) {
            token = getTokenInternal(repositoryUrl + ENTER_ATTACHMENT_CGI + bugReportID, monitor);
        }
        if (token != null) {
            parts.add(new StringPart(BugzillaAttribute.TOKEN.getKey(), token));
        }

        postMethod.setRequestEntity(
                new MultipartRequestEntity(parts.toArray(new Part[1]), postMethod.getParams()));
        postMethod.setDoAuthentication(true);
        int status = WebUtil.execute(httpClient, hostConfiguration, postMethod, monitor);
        if (status == HttpStatus.SC_OK) {
            InputStream input = getResponseStream(postMethod, monitor);
            try {
                parsePostResponse(bugReportID, input);
            } finally {
                input.close();
            }

        } else {
            WebUtil.releaseConnection(postMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_NETWORK, repositoryUrl.toString(), "Http error: " //$NON-NLS-1$
                            + HttpStatus.getStatusText(status)));
            // throw new IOException("Communication error occurred during
            // upload. \n\n"
            // + HttpStatus.getStatusText(status));
        }
    } finally {
        if (postMethod != null) {
            WebUtil.releaseConnection(postMethod, monitor);
        }
    }
}

From source file:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and then reads the response SOAP message back
 * from the SOAP server/*from  w ww .  jav  a 2  s  .c o  m*/
 * 
 * @param msgContext
 *            the messsage context
 * @throws AxisFault
 */
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    //      if (log.isDebugEnabled()) {
    //         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());

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

            addContextInfo(method, httpClient, msgContext, targetURL);

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
            }
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null) {
            if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
                method.getParams().setVersion(HttpVersion.HTTP_1_0);
            }
            // assume 1.1
        }

        // 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);
        }

        int returnCode = httpClient.executeMethod(hostConfiguration, method, null);

        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") //$NON-NLS-1$
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
        } else {
            //            String statusMessage = method.getStatusText();
            //            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

            try {
                //               fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, //$NON-NLS-1$ //$NON-NLS-2$
                //                     method.getResponseBodyAsString()));
                //               fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                //               throw fault;
                throw AxisHttpFault.makeFault(method);
            } 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);
        if (contentEncoding != null) {
            if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);
            } else if (contentEncoding.getValue().equals("") //$NON-NLS-1$
                    && msgContext.isPropertyTrue(SoapHttpSender.ALLOW_EMPTY_CONTENT_ENCODING)) {
                // assume no encoding
            } else {
                AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" //$NON-NLS-1$ //$NON-NLS-2$
                        + contentEncoding.getValue() + "' found", null, null); //$NON-NLS-1$
                throw fault;
            }

        }
        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 (Header responseHeader : responseHeaders) {
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }
        outMsg.setMessageType(Message.RESPONSE);
        msgContext.setResponseMessage(outMsg);
        //         if (log.isDebugEnabled()) {
        //            if (null == contentLength) {
        //               log.debug("\n" + Messages.getMessage("no00", "Content-Length"));
        //            }
        //            log.debug("\n" + Messages.getMessage("xmlRecd00"));
        //            log.debug("-----------------------------------------------");
        //            log.debug(outMsg.getSOAPPartAsString());
        //         }

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

            for (Header header : headers) {
                if (header.getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE, header.getValue(), msgContext);
                } else if (header.getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE2, header.getValue(), msgContext);
                }
            }
        }

        // always release the connection back to the pool if 
        // it was one way invocation
        if (msgContext.isPropertyTrue("axis.one.way")) { //$NON-NLS-1$
            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:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java

/**
 * Extracts info from message context.//ww  w . j  av a  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
 */
protected 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() : ""; //$NON-NLS-1$

    if (action == null) {
        action = ""; //$NON-NLS-1$
    }

    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 + "\"")); //$NON-NLS-1$ //$NON-NLS-2$
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent"))); //$NON-NLS-1$
    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("\\"); //$NON-NLS-1$
        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 {
                // let plug-ins using SOAP be able to set their own user-agent header (i.e. for tracking purposes)
                if (HTTPConstants.HEADER_USER_AGENT.equalsIgnoreCase(key)) {
                    method.setRequestHeader(key, value);
                } else {
                    method.addRequestHeader(key, value);
                }
            }
        }
    }
}

From source file:org.pmedv.core.util.UploadUtils.java

public static boolean uploadFile(File sourceFile, String targetURL, UploadMonitor monitor) {

    log.info("uploading " + sourceFile + " to " + targetURL);

    PostMethod filePost = new PostMethod(targetURL);
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    filePost.getParams().setContentCharset("ISO-8859-15");

    try {/* w w  w.  j a  v a 2s .c  om*/

        Part[] parts = { new CustomizableFilePart(sourceFile.getName(), sourceFile, monitor) };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        client.getState().setCredentials(new AuthScope(hostname, port, AuthScope.ANY_REALM), defaultcreds);

        int status = client.executeMethod(filePost);

        if (status == HttpStatus.SC_OK) {
            log.info("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            log.info("Upload failed, response=" + HttpStatus.getStatusText(status));
            return false;
        }

    } catch (Exception ex) {
        log.error("An exception occured :");
        log.error(ResourceUtils.getStackTrace(ex));
        return false;
    } finally {
        filePost.releaseConnection();
    }

    return true;

}

From source file:org.pmedv.core.util.UploadUtils.java

public static boolean uploadFile(File sourceFile, String targetURL, UploadMonitor monitor,
        String requestParams) {//from   www .  java 2 s . c o m

    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("remoting.properties");
    Properties uploadProps = new Properties();

    try {
        uploadProps.load(is);
    } catch (IOException e) {
        log.info("Could not load upload.properties, is it in classpath?");
        return false;
    }

    log.info("uploading " + sourceFile + " to " + targetURL);

    PostMethod filePost = new PostMethod(targetURL + requestParams);

    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

    try {

        Part[] parts = { new CustomizableFilePart(sourceFile.getName(), sourceFile, monitor) };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        client.getState().setCredentials(new AuthScope(hostname, port, AuthScope.ANY_REALM), defaultcreds);

        int status = client.executeMethod(filePost);

        if (status == HttpStatus.SC_OK) {
            log.info("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            log.info("Upload failed, response=" + HttpStatus.getStatusText(status));
            return false;
        }

    } catch (Exception ex) {
        log.error("An exception occured :");
        log.error(ResourceUtils.getStackTrace(ex));
        return false;
    } finally {
        filePost.releaseConnection();
    }

    return true;

}

From source file:org.soaplab.gowlab.GowlabJob.java

/**************************************************************************
 * Fill 'httpMethod' with the user data (from 'formData',
 * 'queryString' and 'fileData') and execute it. It will do the
 * real data fetching.//  w  w w.j  a  v  a 2 s  . c om
 *
 * If the fetching finished successfully the 'httpMethod' has the
 * response.
 *************************************************************************/
protected void getResponse() throws SoaplabException {

    if (isGetUsed()) {

        // GET method...

        if (StringUtils.isNotEmpty(queryString)) {
            // ...from a query string
            try {
                httpMethod.setQueryString(URIUtil.encodeQuery(queryString));
            } catch (URIException e) {
                httpMethod.setQueryString(queryString);
            }

        } else {
            // ...from name-value pairs
            httpMethod.setQueryString(formData);
        }

    } else if (isPostUsed()) {

        // POST method...

        // ...from name-value pairs
        ((PostMethod) httpMethod).setRequestBody(formData);

        // ...files to be uploaded
        if (isMultipartUsed()) {
            httpMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            List<Part> parts = new ArrayList<Part>();
            for (IOData io : fileData) {
                if (!io.getDefinition().isRegularInput())
                    continue;
                File forUpload = io.getData();
                if (forUpload == null)
                    continue;
                try {
                    String tag = io.getDefinition().get(ParamDef.TAG);
                    if (StringUtils.isEmpty(tag))
                        tag = io.getDefinition().id;
                    parts.add(new FilePart(tag, forUpload));
                } catch (FileNotFoundException e) {
                    internalError("A file for uploading was not found: " + forUpload.getAbsolutePath());
                }
            }
            ((PostMethod) httpMethod).setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[] {}), httpMethod.getParams()));
        }
    }

    // finally, execute the method
    try {
        // instantiating an HttpClient
        new HttpClient().executeMethod(httpMethod);

    } catch (HttpException e) {
        internalError("Fatal protocol violation: " + e.getMessage());
    } catch (IOException e) {
        logAndThrow("Fatal transport error: " + e.getMessage());
    }

}

From source file:org.soitoolkit.commons.mule.mime.MimeUtil.java

public static String sendFileAsMultipartHttpPost(String targetURL, File targetFile, String partName,
        boolean expectHeader, int timeoutMs) {

    logger.debug("Send file {} to url {}", targetFile.getAbsolutePath(), targetURL);

    String response = null;/*  w  w w . ja  v a 2 s  .  c o m*/

    PostMethod filePost = new PostMethod(targetURL);

    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, expectHeader);

    try {

        Part[] parts = { new FilePart(partName, targetFile) };

        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(timeoutMs);

        int status = client.executeMethod(filePost);

        logger.debug("Send done, http status: {}", status);

        if (status == HttpStatus.SC_OK) {
            response = filePost.getResponseBodyAsString();
            logger.debug("Send done, http response: {}", response);
        } else {
            String errorText = HttpStatus.getStatusText(status);
            throw new RuntimeException("HTTP Error Code: " + status + "HTTP Error Text: " + errorText);
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        filePost.releaseConnection();
    }

    return response;
}