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.alfresco.httpclient.AbstractHttpClient.java

protected HttpMethod createMethod(Request req) throws IOException {
    StringBuilder url = new StringBuilder(128);
    url.append(baseUrl);/*from www  .  j  a v  a2  s .  c  o m*/
    url.append("/service/");
    url.append(req.getFullUri());

    // construct method
    HttpMethod httpMethod = null;
    String method = req.getMethod();
    if (method.equalsIgnoreCase("GET")) {
        GetMethod get = new GetMethod(url.toString());
        httpMethod = get;
        httpMethod.setFollowRedirects(true);
    } else if (method.equalsIgnoreCase("POST")) {
        PostMethod post = new PostMethod(url.toString());
        httpMethod = post;
        ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(req.getBody(), req.getType());
        if (req.getBody().length > DEFAULT_SAVEPOST_BUFFER) {
            post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        }
        post.setRequestEntity(requestEntity);
        // Note: not able to automatically follow redirects for POST, this is handled by sendRemoteRequest
    } else if (method.equalsIgnoreCase("HEAD")) {
        HeadMethod head = new HeadMethod(url.toString());
        httpMethod = head;
        httpMethod.setFollowRedirects(true);
    } else {
        throw new AlfrescoRuntimeException("Http Method " + method + " not supported");
    }

    if (req.getHeaders() != null) {
        for (Map.Entry<String, String> header : req.getHeaders().entrySet()) {
            httpMethod.setRequestHeader(header.getKey(), header.getValue());
        }
    }

    return httpMethod;
}

From source file:org.alfresco.repo.search.impl.solr.SolrQueryHTTPClient.java

protected JSONObject postQuery(HttpClient httpClient, String url, JSONObject body)
        throws UnsupportedEncodingException, IOException, HttpException, URIException, JSONException {
    PostMethod post = new PostMethod(url);
    if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER) {
        post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    }//from  www  . ja  va 2 s.c  om
    post.setRequestEntity(new ByteArrayRequestEntity(body.toString().getBytes("UTF-8"), "application/json"));

    try {
        httpClient.executeMethod(post);

        if (post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            Header locationHeader = post.getResponseHeader("location");
            if (locationHeader != null) {
                String redirectLocation = locationHeader.getValue();
                post.setURI(new URI(redirectLocation, true));
                httpClient.executeMethod(post);
            }
        }

        if (post.getStatusCode() != HttpServletResponse.SC_OK) {
            throw new LuceneQueryParserException(
                    "Request failed " + post.getStatusCode() + " " + url.toString());
        }

        Reader reader = new BufferedReader(
                new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet()));
        // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
        JSONObject json = new JSONObject(new JSONTokener(reader));

        if (json.has("status")) {
            JSONObject status = json.getJSONObject("status");
            if (status.getInt("code") != HttpServletResponse.SC_OK) {
                throw new LuceneQueryParserException("SOLR side error: " + status.getString("message"));
            }
        }
        return json;
    } finally {
        post.releaseConnection();
    }
}

From source file:org.apache.abdera.protocol.client.util.MethodHelper.java

public static HttpMethod createMethod(String method, String uri, RequestEntity entity, RequestOptions options) {
    if (method == null)
        return null;
    Method m = Method.fromString(method);
    Method actual = null;//www .j  a  va2  s  .co m
    HttpMethod httpMethod = null;
    if (options.isUsePostOverride()) {
        if (m.equals(Method.PUT)) {
            actual = m;
        } else if (m.equals(Method.DELETE)) {
            actual = m;
        }
        if (actual != null)
            m = Method.POST;
    }
    switch (m) {
    case GET:
        httpMethod = new GetMethod(uri);
        break;
    case POST:
        httpMethod = getMethod(new PostMethod(uri), entity);
        break;
    case PUT:
        httpMethod = getMethod(new PutMethod(uri), entity);
        break;
    case DELETE:
        httpMethod = new DeleteMethod(uri);
        break;
    case HEAD:
        httpMethod = new HeadMethod(uri);
        break;
    case OPTIONS:
        httpMethod = new OptionsMethod(uri);
        break;
    case TRACE:
        httpMethod = new TraceMethod(uri);
        break;
    default:
        httpMethod = getMethod(new ExtensionMethod(method, uri), entity);
    }
    if (actual != null) {
        httpMethod.addRequestHeader("X-HTTP-Method-Override", actual.name());
    }
    initHeaders(options, httpMethod);

    // by default use expect-continue is enabled on the client
    // only disable if explicitly disabled
    if (!options.isUseExpectContinue())
        httpMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

    // should we follow redirects, default is true
    if (!(httpMethod instanceof EntityEnclosingMethod))
        httpMethod.setFollowRedirects(options.isFollowRedirects());

    return httpMethod;
}

From source file:org.apache.axis.transport.http.CommonsHTTPSender.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 the messsage context
 *
 * @throws AxisFault/*from   www  .  ja va 2  s . co m*/
 */
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")
                && ((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);

            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);
        if (contentEncoding != null) {
            if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);
            } else {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
                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 (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.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 (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:org.apache.http.client.benchmark.TestHttpClient3.java

public TestHttpClient3() {
    super();//from  w  ww .j  a v  a 2 s.  co  m
    this.mgr = new MultiThreadedHttpConnectionManager();
    this.httpclient = new HttpClient(this.mgr);
    this.httpclient.getParams().setVersion(HttpVersion.HTTP_1_1);
    this.httpclient.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    this.httpclient.getHttpConnectionManager().getParams().setStaleCheckingEnabled(false);
    this.httpclient.getParams().setSoTimeout(15000);

    HttpMethodRetryHandler retryhandler = new HttpMethodRetryHandler() {

        public boolean retryMethod(final HttpMethod httpmethod, final IOException ex, int count) {
            return false;
        }

    };
    this.httpclient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);
}

From source file:org.bibsonomy.rest.client.worker.impl.PostWorker.java

public Reader perform(final String url, final File file) throws ErrorPerformingRequestException {
    LOGGER.debug("POST Multipart: URL: " + url);

    if (this.proxyHost != null) {
        this.getHttpClient().getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
    }/* w  ww.  j  av a 2  s.c om*/

    // TODO: remove deprecated method
    final MultipartPostMethod post = new MultipartPostMethod(url);

    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    post.addRequestHeader(HeaderUtils.HEADER_AUTHORIZATION,
            HeaderUtils.encodeForAuthorization(this.username, this.apiKey));
    post.addRequestHeader("Content-Type", "multipart/form-data");

    try {
        post.addParameter("file", file);

        this.getHttpClient().getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        this.httpResult = this.getHttpClient().executeMethod(post);
        LOGGER.debug("HTTP result: " + this.httpResult);
        LOGGER.debug("response:\n" + post.getResponseBodyAsString());
        LOGGER.debug("===================================================");
        return new StringReader(post.getResponseBodyAsString());
    } catch (final IOException e) {
        LOGGER.debug(e.getMessage(), e);
        throw new ErrorPerformingRequestException(e);
    } finally {
        post.releaseConnection();
    }
}

From source file:org.craftercms.cstudio.alfresco.preview.PreviewDeployer.java

protected void remoteDeploy(String path, InputStream content, Properties metaData, boolean delete)
        throws Exception {
    String server = this.deployServer;
    int port = this.deployPort;
    String password = this.deployPassword;
    String target = this.deployTarget;

    //int siteStartPos = path.indexOf("/wem-projects")+13;
    String site = "";
    String relativePath = "";
    Matcher matcher = DM_REPO_PATH_PATTERN_STRING.matcher(path);
    if (matcher.matches()) {
        site = matcher.group(3);//from  ww w.j  a v a2  s.c o  m
        relativePath = matcher.group(5).length() != 0 ? matcher.group(5) : "/";
    }

    //boolean publishMetadata = true;
    URL requestUrl = null;
    //String origPath = path;
    //path = path.substring(path.indexOf("/site"));

    try {
        String url = DEPLOYER_SERVLET_URL;
        requestUrl = new URL("http", server, port, url);

        List<Part> formParts = new FastList<Part>();
        formParts.add(new StringPart(DEPLOYER_PASSWORD_PARAM, password));
        formParts.add(new StringPart(DEPLOYER_TARGET_PARAM, target));

        if (delete == true) {
            formParts.add(new StringPart(DEPLOYER_DELETED_FILES_PARAM, relativePath));
        }

        if (content != null) {
            ByteArrayPartSource baps = null;
            byte[] byteArray = null;
            byteArray = IOUtils.toByteArray(content);

            baps = new ByteArrayPartSource(relativePath, byteArray);
            formParts.add(new FilePart(DEPLOYER_CONTENT_FILE_PARAM, baps));
        }

        if (metaData != null) {
            StringWriter writer = new StringWriter();
            metaData.store(writer, null);
            PartSource metadataPart = new ByteArrayPartSource(relativePath + ".meta",
                    writer.getBuffer().toString().getBytes());
            formParts.add(new FilePart(DEPLOYER_METADATA_FILE_PARAM, metadataPart));
        }

        formParts.add(new StringPart(DEPLOYER_CONTENT_LOCATION_PARAM, relativePath));
        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) {
        throw new Exception("error while preview deploying '" + path + "'" + err);
    }
}

From source file:org.craftercms.cstudio.impl.service.deployment.PublishingManagerImpl.java

@Override
public void deployItemsToTarget(String site, List<PublishingSyncItem> filteredItems,
        PublishingTargetItem target) throws ContentNotFoundForPublishingException, UploadFailedException {
    LOGGER.debug("Start deploying items for site \"{0}\", target \"{1}\", number of items \"{2}\"", site,
            target.getName(), filteredItems.size());
    URL requestUrl = null;/*from  w  ww.  j  a  v  a 2 s  .c  om*/
    try {
        requestUrl = new URL(target.getServerUrl());
    } catch (MalformedURLException e) {
        LOGGER.error("Invalid server URL for target {0}", target.getName());
        throw new UploadFailedException(site, target.getName(), target.getServerUrl(), e);
    }

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

    int numberOfBuckets = filteredItems.size() / target.getBucketSize() + 1;
    Iterator<PublishingSyncItem> iter = filteredItems.iterator();
    LOGGER.debug("Divide all deployment items into {0} bucket(s) for  target {1}", numberOfBuckets,
            target.getName());
    List<DeploymentEventItem> eventItems = new ArrayList<DeploymentEventItem>();
    for (int bucketIndex = 0; bucketIndex < numberOfBuckets; bucketIndex++) {
        int cntFiles = 0;
        StringBuilder sbDeletedFiles = new StringBuilder();
        List<Part> formParts = new ArrayList<Part>();

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

        LOGGER.debug("Preparing deployment items (bucket {0}) for target {1}", bucketIndex + 1,
                target.getName());

        int loopSize = (filteredItems.size() - (bucketIndex * target.getBucketSize()) > target.getBucketSize())
                ? target.getBucketSize()
                : filteredItems.size() - bucketIndex * target.getBucketSize();
        for (int j = 0; j < loopSize; j++) {
            if (iter.hasNext()) {

                PublishingSyncItem item = iter.next();
                LOGGER.debug("Parsing \"{0}\" , site \"{1}\"; for publishing on target \"{2}\"", item.getPath(),
                        item.getSite(), target.getName());
                DeploymentEventItem eventItem = new DeploymentEventItem();
                eventItem.setSite(item.getSite());
                eventItem.setPath(item.getPath());
                eventItem.setUser(item.getUser());
                eventItem.setDateTime(new Date());

                if (item.getAction() == PublishingSyncItem.Action.DELETE) {
                    eventItem.setState(DeploymentEventItem.STATE_DELETED);
                    if (sbDeletedFiles.length() > 0) {
                        sbDeletedFiles.append(FILES_SEPARATOR).append(item.getPath());
                    } else {
                        sbDeletedFiles.append(item.getPath());
                    }
                    if (item.getPath().endsWith("/" + _indexFile)) {
                        sbDeletedFiles.append(FILES_SEPARATOR)
                                .append(item.getPath().replace("/" + _indexFile, ""));
                    }
                } else {

                    if (item.getAction() == PublishingSyncItem.Action.NEW) {
                        eventItem.setState(DeploymentEventItem.STATE_NEW);
                    } else if (item.getAction() == PublishingSyncItem.Action.MOVE) {
                        eventItem.setState(DeploymentEventItem.STATE_MOVED);
                    } else {
                        eventItem.setState(DeploymentEventItem.STATE_UPDATED);
                    }

                    LOGGER.debug("Get content for \"{0}\" , site \"{1}\"", item.getPath(), item.getSite());
                    InputStream input = _contentRepository.getContent(site, null, LIVE_ENVIRONMENT,
                            item.getPath());
                    try {
                        if (input == null || input.available() < 0) {
                            if (!_contentRepository.isFolder(site, item.getPath())
                                    && _contentRepository.contentExists(site, item.getPath())) {
                                baps = null;
                                stringPart = null;
                                filePart = null;
                                formParts = null;
                                throw new ContentNotFoundForPublishingException(site, target.getName(),
                                        item.getPath());
                            } else {
                                // Content does not exist - skip deploying file
                                continue;
                            }
                        }
                    } catch (IOException err) {
                        LOGGER.error("Error reading input stream for content at path: " + item.getPath()
                                + " site: " + item.getSite());
                        if (_contentRepository.contentExists(site, item.getPath())) {
                            baps = null;
                            stringPart = null;
                            filePart = null;
                            formParts = null;
                            throw new ContentNotFoundForPublishingException(site, target.getName(),
                                    item.getPath());
                        } else {
                            // Content does not exist - skip deploying file
                            continue;
                        }
                    }
                    String fileName = _contentRepository.getFilename(site, item.getPath());

                    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;
                        if (_contentRepository.contentExists(site, item.getPath())) {
                            throw new ContentNotFoundForPublishingException(site, target.getName(),
                                    item.getPath());
                        } else {
                            // Content does not exist - skip deploying file
                            continue;
                        }
                    } 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}\"",
                            item.getPath(), item.getSite(), target.getName());
                    int idx = item.getPath().lastIndexOf("/");
                    String relativePath = item.getPath().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, ""));
                            }
                        }
                    }

                    if (target.isSendMetadata()) {
                        LOGGER.debug("Adding meta data for content \"{0}\" site \"{0}\"", item.getPath(),
                                item.getSite());
                        InputStream metadataStream = null;
                        try {
                            metadataStream = _contentRepository.getMetadataStream(site, item.getPath());
                            metadataPart = new ByteArrayPartSource(fileName + ".meta",
                                    IOUtils.toByteArray(metadataStream));
                            formParts.add(
                                    new FilePart(METADATA_FILE_REQUEST_PARAMETER + cntFiles, metadataPart));
                        } catch (IOException e) {
                            LOGGER.error("Error while creating input stream with content metadata", e);
                            baps = null;
                            stringPart = null;
                            filePart = null;
                            formParts = null;
                        } finally {
                            IOUtils.closeQuietly(metadataStream);
                            metadataPart = null;
                        }
                    }
                }
                cntFiles++;
                eventItems.add(eventItem);
            }
        }

        if (sbDeletedFiles.length() > 0) {
            formParts.add(new StringPart(DELETED_FILES_REQUEST_PARAMETER, sbDeletedFiles.toString()));
        }
        LOGGER.debug("Create http request to deploy bucket {0} for target {1}", bucketIndex + 1,
                target.getName());

        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 bucket number {0} on target {1}", bucketIndex + 1,
                        target.getName());
            } else {
                LOGGER.error(
                        "Deployment failed for bucket number {0} on target {1}. Deployment agent returned status {2}",
                        bucketIndex + 1, target.getName(), HttpStatus.getStatusText(status));
                throw new UploadFailedException(site, target.getName(), target.getServerUrl());
            }
        } catch (HttpException e) {
            LOGGER.error("Publish failed for target {0} due to http protocol exception", target.getName());
            throw new UploadFailedException(site, target.getName(), target.getServerUrl(), e);
        } catch (IOException e) {
            LOGGER.error("Publish failed for target {0} due to I/O (transport) exception", target.getName());
            throw new UploadFailedException(site, target.getName(), target.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(),
            eventItems.size());
    _contentRepository.publishDeployEvent(target.getName(), eventItems);

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

From source file:org.craftercms.cstudio.share.service.impl.WcmWorkflowServiceImpl.java

private String callRESTService(final String targetURI, final String xmlString) throws Exception {
    String xmlResponseString = "";
    int result = -1;

    //TODO: Use Alfresco Endpoint instead of httpclient

    PostMethod postMethod = null;/*from  ww  w . ja v  a  2 s  .com*/
    BufferedReader br = null;
    HttpClient httpClient = new HttpClient();

    // PRECONDITIONS
    assert targetURI != null && targetURI.trim().length() > 0 : "path must not be null, empty or blank.";

    // Body
    postMethod = new PostMethod(targetURI);
    postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    // Get the Alfresco Ticket       
    SeamlessAppContext context = SeamlessAppContext.currentApplicationContext();
    String alfTicketCookie = (String) cookieManager.getCookieValue(context.getRequest(),
            this.COOKIE_ALFRESCO_TICKET);

    // Set the Parameter
    //getMethod.setQueryString(new NameValuePair[] {new NameValuePair("formId", formId)});
    postMethod.setQueryString("?xml=" + xmlString + "&" + COOKIE_ALFRESCO_TICKET + "=" + alfTicketCookie);

    try {
        result = httpClient.executeMethod(postMethod);

        if (result == HttpStatus.SC_NOT_IMPLEMENTED) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("The POST method is not implemented by this URI");
                throw new Exception("The POST method is not implemented by this URI");
            }
            // still consume the response body
            xmlResponseString = postMethod.getResponseBodyAsString();
        } else {
            if (result == HttpStatus.SC_OK) {
                br = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream()));

                String readLine;
                while (((readLine = br.readLine()) != null)) {
                    xmlResponseString = xmlString + readLine;
                }
            } else {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("Push to Alfresco Service Failed: " + HttpStatus.getStatusText(result));
                    throw new Exception("Push to Alfresco Service Failed: " + HttpStatus.getStatusText(result));
                }
            }
        }
    } catch (HttpException he) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Push to Alfresco Service Failed due to HttpException: " + he.getMessage(), he);
            throw he;
        }
    } catch (IOException ie) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Push to Alfresco Service Failed due to IOException: " + ie.getMessage(), ie);
        }
    } finally {
        postMethod.releaseConnection();
        if (br != null)
            try {
                br.close();
            } catch (Exception fe) {
            }
    }

    return (xmlResponseString);
}

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

@Override
public void deployFile(String site, String path) {
    DeploymentEndpointConfigTO deploymentEndpointConfigTO = siteService.getPreviewDeploymentEndpoint(site);
    URL requestUrl = null;//from   w w w.j a  v  a  2 s .  c o m

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

        InputStream content = contentService.getContent(site, path);
        if (content != null) {
            ByteArrayPartSource baps = null;
            byte[] byteArray = null;
            byteArray = IOUtils.toByteArray(content);

            baps = new ByteArrayPartSource(path, byteArray);
            formParts.add(new FilePart(DEPLOYER_CONTENT_FILE_PARAM, baps));
        }

        formParts.add(new StringPart(DEPLOYER_CONTENT_LOCATION_PARAM, path));
        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);
    }
}