Example usage for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity

List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity MultipartRequestEntity

Introduction

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

Prototype

public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams) 

Source Link

Usage

From source file:org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.java

public NamedList<Object> request(final SolrRequest request, ResponseParser processor)
        throws SolrServerException, IOException {
    HttpMethod method = null;//  w w  w  .j a v  a 2  s .  c  o m
    InputStream is = null;
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = "/select";
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = _parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original params
    ModifiableSolrParams wparams = new ModifiableSolrParams();
    wparams.set(CommonParams.WT, parser.getWriterType());
    wparams.set(CommonParams.VERSION, parser.getVersion());
    if (params == null) {
        params = wparams;
    } else {
        params = new DefaultSolrParams(wparams, params);
    }

    if (_invariantParams != null) {
        params = new DefaultSolrParams(_invariantParams, params);
    }

    int tries = _maxRetries + 1;
    try {
        while (tries-- > 0) {
            // Note: since we aren't do intermittent time keeping
            // ourselves, the potential non-timeout latency could be as
            // much as tries-times (plus scheduling effects) the given
            // timeAllowed.
            try {
                if (SolrRequest.METHOD.GET == request.getMethod()) {
                    if (streams != null) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
                    }
                    method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false));
                } else if (SolrRequest.METHOD.POST == request.getMethod()) {

                    String url = _baseURL + path;
                    boolean isMultipart = (streams != null && streams.size() > 1);

                    if (streams == null || isMultipart) {
                        PostMethod post = new PostMethod(url);
                        post.getParams().setContentCharset("UTF-8");
                        if (!this.useMultiPartPost && !isMultipart) {
                            post.addRequestHeader("Content-Type",
                                    "application/x-www-form-urlencoded; charset=UTF-8");
                        }

                        List<Part> parts = new LinkedList<Part>();
                        Iterator<String> iter = params.getParameterNamesIterator();
                        while (iter.hasNext()) {
                            String p = iter.next();
                            String[] vals = params.getParams(p);
                            if (vals != null) {
                                for (String v : vals) {
                                    if (this.useMultiPartPost || isMultipart) {
                                        parts.add(new StringPart(p, v, "UTF-8"));
                                    } else {
                                        post.addParameter(p, v);
                                    }
                                }
                            }
                        }

                        if (isMultipart) {
                            int i = 0;
                            for (ContentStream content : streams) {
                                final ContentStream c = content;

                                String charSet = null;
                                PartSource source = new PartSource() {
                                    public long getLength() {
                                        return c.getSize();
                                    }

                                    public String getFileName() {
                                        return c.getName();
                                    }

                                    public InputStream createInputStream() throws IOException {
                                        return c.getStream();
                                    }
                                };

                                parts.add(new FilePart(c.getName(), source, c.getContentType(), charSet));
                            }
                        }
                        if (parts.size() > 0) {
                            post.setRequestEntity(new MultipartRequestEntity(
                                    parts.toArray(new Part[parts.size()]), post.getParams()));
                        }

                        method = post;
                    }
                    // It is has one stream, it is the post body, put the params in the URL
                    else {
                        String pstr = ClientUtils.toQueryString(params, false);
                        PostMethod post = new PostMethod(url + pstr);
                        //              post.setRequestHeader("connection", "close");

                        // Single stream as body
                        // Using a loop just to get the first one
                        final ContentStream[] contentStream = new ContentStream[1];
                        for (ContentStream content : streams) {
                            contentStream[0] = content;
                            break;
                        }
                        if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                            post.setRequestEntity(new RequestEntity() {
                                public long getContentLength() {
                                    return -1;
                                }

                                public String getContentType() {
                                    return contentStream[0].getContentType();
                                }

                                public boolean isRepeatable() {
                                    return false;
                                }

                                public void writeRequest(OutputStream outputStream) throws IOException {
                                    ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream);
                                }
                            });

                        } else {
                            is = contentStream[0].getStream();
                            post.setRequestEntity(
                                    new InputStreamRequestEntity(is, contentStream[0].getContentType()));
                        }
                        method = post;
                    }
                } else {
                    throw new SolrServerException("Unsupported method: " + request.getMethod());
                }
            } catch (NoHttpResponseException r) {
                // This is generally safe to retry on
                method.releaseConnection();
                method = null;
                if (is != null) {
                    is.close();
                }
                // If out of tries then just rethrow (as normal error).
                if ((tries < 1)) {
                    throw r;
                }
                //log.warn( "Caught: " + r + ". Retrying..." );
            }
        }
    } catch (IOException ex) {
        log.error("####request####", ex);
        throw new SolrServerException("error reading streams", ex);
    }

    method.setFollowRedirects(_followRedirects);
    method.addRequestHeader("User-Agent", AGENT);
    if (_allowCompression) {
        method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate"));
    }
    //    method.setRequestHeader("connection", "close");

    try {
        // Execute the method.
        //System.out.println( "EXECUTE:"+method.getURI() );

        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            StringBuilder msg = new StringBuilder();
            msg.append(method.getStatusLine().getReasonPhrase());
            msg.append("\n\n");
            msg.append(method.getStatusText());
            msg.append("\n\n");
            msg.append("request: " + method.getURI());
            throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8"));
        }

        // Read the contents
        String charset = "UTF-8";
        if (method instanceof HttpMethodBase) {
            charset = ((HttpMethodBase) method).getResponseCharSet();
        }
        InputStream respBody = method.getResponseBodyAsStream();
        // Jakarta Commons HTTPClient doesn't handle any
        // compression natively.  Handle gzip or deflate
        // here if applicable.
        if (_allowCompression) {
            Header contentEncodingHeader = method.getResponseHeader("Content-Encoding");
            if (contentEncodingHeader != null) {
                String contentEncoding = contentEncodingHeader.getValue();
                if (contentEncoding.contains("gzip")) {
                    //log.debug( "wrapping response in GZIPInputStream" );
                    respBody = new GZIPInputStream(respBody);
                } else if (contentEncoding.contains("deflate")) {
                    //log.debug( "wrapping response in InflaterInputStream" );
                    respBody = new InflaterInputStream(respBody);
                }
            } else {
                Header contentTypeHeader = method.getResponseHeader("Content-Type");
                if (contentTypeHeader != null) {
                    String contentType = contentTypeHeader.getValue();
                    if (contentType != null) {
                        if (contentType.startsWith("application/x-gzip-compressed")) {
                            //log.debug( "wrapping response in GZIPInputStream" );
                            respBody = new GZIPInputStream(respBody);
                        } else if (contentType.startsWith("application/x-deflate")) {
                            //log.debug( "wrapping response in InflaterInputStream" );
                            respBody = new InflaterInputStream(respBody);
                        }
                    }
                }
            }
        }
        return processor.processResponse(respBody, charset);
    } catch (HttpException e) {
        throw new SolrServerException(e);
    } catch (IOException e) {
        throw new SolrServerException(e);
    } finally {
        method.releaseConnection();
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.apache.wookie.tests.helpers.WidgetUploader.java

/**
 * Upload a widget//  www  .ja  v  a2  s  . c o  m
 * @param file
 * @return
 * @throws IOException
 */
public static String uploadWidget(File file) throws IOException {
    HttpClient httpclient = new HttpClient();
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, "wookie"),
            new UsernamePasswordCredentials("java", "java"));
    PostMethod post = new PostMethod(SERVICE_URL);
    Part[] parts = { new FilePart(file.getName(), file) };
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
    int status = httpclient.executeMethod(post);
    if (status != 200 && status != 201) {
        fail("problem with upload");
    }
    String response = IOUtils.toString(post.getResponseBodyAsStream());
    post.releaseConnection();
    return getError(response);
}

From source file:org.avalonmediasystem.AvalonWorkflowListener.java

private void pingAvalon(String pid, long workflowId) {
    logger.trace("Starting to ping Avalon: " + pid + " " + workflowId);
    try {//from w w  w . ja  v  a 2s .  com
        String url = UrlSupport.concat(new String[] { avalonUrl, "master_files", pid });
        MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
        HttpClient client = new HttpClient(mgr);

        PutMethod put = new PutMethod(url);

        Part[] parts = { new StringPart("workflow_id", String.valueOf(workflowId)), };
        put.setRequestEntity(new MultipartRequestEntity(parts, put.getParams()));
        logger.trace("About to ping Avalon");
        int status = client.executeMethod(put);
        logger.debug("Got status: " + status);
        logger.trace("Got response body: " + put.getResponseBodyAsString());
    } catch (Exception e) {
        logger.debug("Exception pinging Avalon: " + e.getCause(), e);
    }
}

From source file:org.carrot2.dcs.HttpClientPostProvider.java

public InputStream post(URI dcsURI, Map<String, String> attributes) throws IOException {
    final HttpClient client = new HttpClient();
    final PostMethod post = new PostMethod(dcsURI.toString());
    final List<Part> parts = new ArrayList<Part>();
    for (Map.Entry<String, String> entry : attributes.entrySet()) {
        parts.add(new StringPart(entry.getKey(), entry.getValue()));
    }//from ww  w.  j  a va  2s .  c  om
    post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));

    try {
        if (client.executeMethod(post) != HttpStatus.SC_OK) {
            throw new IOException(
                    "Unexpected DCS response: " + post.getStatusCode() + ": " + post.getStatusText());
        }

        final byte[] body = StreamUtils.readFullyAndClose(post.getResponseBodyAsStream());
        return new ByteArrayInputStream(body);
    } finally {
        post.releaseConnection();
    }
}

From source file:org.cellprofiler.subimager.TestImageJHandlerBase.java

protected Response post(Request request, Map<String, NDImage> ndimagesIn, Map<String, NDImage> ndimagesOut) {
    StringWriter writer = new StringWriter();
    try {//from ww  w.  j  a  va 2s .  com
        Marshaller marshaller = new Marshaller(writer);
        marshaller.marshal(request);
    } catch (MarshalException e2) {
        throw new AssertionError(e2.getMessage());
    } catch (ValidationException e2) {
        throw new AssertionError(e2.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        throw new AssertionError(e.getMessage());
    }
    String xml = writer.toString();

    ArrayList<Part> parts = new ArrayList<Part>();
    parts.add(new StringPart(ImageJHandler.NAME_REQUEST, xml));
    String sURL = String.format("http://localhost:%d/imagej", getPort());
    final PostMethod post = new PostMethod(sURL);
    for (Map.Entry<String, NDImage> entry : ndimagesIn.entrySet()) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            entry.getValue().encode(bos);
        } catch (IOException e1) {
            e1.printStackTrace();
            throw new AssertionError("Failed to encode image: " + e1.getMessage());
        }
        ByteArrayPartSource src = new ByteArrayPartSource(entry.getKey(), bos.toByteArray());
        FilePart filePart = new FilePart(entry.getKey(), src, "application/octet-stream", "binary");
        parts.add(filePart);
    }
    post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), post.getParams()));
    HttpClient client = new HttpClient();
    int responseCode;
    try {
        responseCode = client.executeMethod(post);
    } catch (HttpException e) {
        throw new AssertionError(e.getMessage());
    } catch (IOException e) {
        throw new AssertionError(e.getMessage());
    }
    assertEquals(HttpURLConnection.HTTP_OK, responseCode);
    final String contentType = post.getResponseHeader("Content-Type").getValue();
    assertTrue(contentType.startsWith("multipart/form-data"));
    final long contentLength = post.getResponseContentLength();
    try {
        final InputStream responseBodyStream = post.getResponseBodyAsStream();
        FileUpload upload = new FileUpload();
        FileItemIterator fileItemIterator;
        fileItemIterator = upload.getItemIterator(new RequestContext() {

            public String getCharacterEncoding() {
                if (post.getResponseHeader("Content-Encoding") == null)
                    return null;
                return post.getResponseHeader("Content-Encoding").getValue();
            }

            public String getContentType() {
                return contentType;
            }

            public int getContentLength() {
                return (int) contentLength;
            }

            InputStream tmpStream = null;

            public InputStream getInputStream() throws IOException {
                if (tmpStream == null) {
                    byte[] buf = new byte[(int) contentLength];
                    int offset = 0;
                    while (offset < buf.length) {
                        offset += responseBodyStream.read(buf, offset, buf.length - offset);
                    }
                    tmpStream = new ByteArrayInputStream(buf);
                }
                return tmpStream;
            }
        });
        assertTrue(fileItemIterator.hasNext());
        FileItemStream fis = fileItemIterator.next();
        assertEquals(fis.getFieldName(), ImageJHandler.NAME_RESPONSE);
        Reader rdr = new InputStreamReader(fis.openStream(), "utf-8");
        Unmarshaller unmarshaller = new Unmarshaller(Response.class);
        unmarshaller.setProperty(XMLProperties.LENIENT_INTEGER_VALIDATION, "true");
        Object oresponse = unmarshaller.unmarshal(rdr);
        assertTrue(oresponse instanceof Response);
        Response response = (Response) oresponse;
        while (fileItemIterator.hasNext()) {
            fis = fileItemIterator.next();
            String name = fis.getFieldName();
            NDImage ndimage = NDImage.decode(fis.openStream());
            ndimagesOut.put(name, ndimage);
        }
        return response;
    } catch (IOException e) {
        e.printStackTrace();
        throw new AssertionError(e.getMessage());
    } catch (FileUploadException e) {
        e.printStackTrace();
        throw new AssertionError(e.getMessage());
    } catch (MarshalException e) {
        e.printStackTrace();
        throw new AssertionError(e.getMessage());
    } catch (ValidationException e) {
        e.printStackTrace();
        throw new AssertionError(e.getMessage());
    } catch (FormatException e) {
        e.printStackTrace();
        throw new AssertionError(e.getMessage());
    }

}

From source file:org.codeartisans.proxilet.Proxilet.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST data as was sent in the given
 * {@link HttpServletRequest}./*from  w  w w .  ja v a  2 s.  c o m*/
 *
 * @param postMethodProxyRequest    The {@link PostMethod} that we are configuring to send a multipart POST request
 * @param httpServletRequest    The {@link HttpServletRequest} that contains the mutlipart POST data to be sent via the {@link PostMethod}
 */
@SuppressWarnings("unchecked")
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(maxFileUploadSize);
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(HEADER_CONTENT_TYPE, multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:org.codinjutsu.tools.jenkins.security.DefaultSecurityClient.java

private PostMethod addFiles(PostMethod post) {
    if (files.size() > 0) {
        ArrayList<Part> parts = new ArrayList<Part>();
        int i = 0;
        for (String key : files.keySet()) {
            VirtualFile virtualFile = files.get(key);
            parts.add(new StringPart("name", key));
            parts.add(new StringPart("json", "{\"parameter\":{\"name\":\"" + key + "\",\"file\":\""
                    + String.format("file%d", i) + "\"}}"));
            parts.add(new FilePart(String.format("file%d", i), new VirtualFilePartSource(virtualFile)));
            i++;/*w w w . java  2 s.c  o m*/
        }
        post.setRequestEntity(
                new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));
        files.clear();
    }

    return post;
}

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  w ww  .  j a v a2s .  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;/*ww w.  j av  a  2 s .co  m*/
    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.studio.impl.v1.deployment.PreviewDeployer.java

@Override
public void deployFile(String site, String path) {
    DeploymentEndpointConfigTO deploymentEndpointConfigTO = siteService.getPreviewDeploymentEndpoint(site);
    URL requestUrl = null;/*from  w ww.  j  av 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);
    }
}