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

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

Introduction

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

Prototype

public ByteArrayPartSource(String paramString, byte[] paramArrayOfByte) 

Source Link

Usage

From source file:com.zimbra.client.ZMailbox.java

/**
 * Uploads a byte array to <tt>FileUploadServlet</tt>.
 * @return the attachment id//from  ww w  .  j  a v  a2  s  .  co m
 */
public String uploadAttachment(String name, byte[] content, String contentType, int msTimeout)
        throws ServiceException {
    FilePart part = new FilePart(name, new ByteArrayPartSource(name, content));
    part.setContentType(contentType);

    return uploadAttachments(new Part[] { part }, msTimeout);
}

From source file:com.zimbra.client.ZMailbox.java

/**
 * Creates an <tt>HttpClient FilePart</tt> from the given filename and content.
 *//*w  w  w .j  a  va 2 s .  c  om*/
public FilePart createAttachmentPart(String filename, byte[] content) {
    FilePart part = new FilePart(filename, new ByteArrayPartSource(filename, content));
    String contentType = URLConnection.getFileNameMap().getContentTypeFor(filename);
    part.setContentType(contentType);
    return part;
}

From source file:no.sws.client.SwsClient.java

private PostMethod createPostMethod(final NameValuePair[] httpParams, final String swsXml) {

    final PostMethod result = new PostMethod(this.BUTLER_PATH);

    // set the given http params on PostMethod
    result.setQueryString(httpParams);/*  w  w w.  j  a  va2 s. com*/

    // legger til en "fil" Dette er egentlig bare en String som ligger lagret i minne.
    ByteArrayPartSource xml;
    try {
        xml = new ByteArrayPartSource("sws.xml", swsXml.getBytes("UTF-8"));
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    final Part[] parts = { new FilePart("xml", xml, "text/xml", "UTF-8") };

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

    return result;
}

From source file:org.ambraproject.service.search.SolrHttpServiceImpl.java

/**
 * @inheritDoc// w  w  w.j  a v a2 s  .com
 */
@Override
public void makeSolrPostRequest(Map<String, String> params, String data, boolean isCSV) throws SolrException {
    String postUrl = config.getString(URL_CONFIG_PARAM);

    String queryString = "?";
    for (String param : params.keySet()) {
        String value = params.get(param);
        if (queryString.length() > 1) {
            queryString += "&";
        }
        queryString += (cleanInput(param) + "=" + cleanInput(value));
    }

    String filename;
    String contentType;

    if (isCSV) {
        postUrl = postUrl + "/update/csv" + queryString;
        filename = "data.csv";
        contentType = "text/plain";
    } else {
        postUrl = postUrl + "/update" + queryString;
        filename = "data.xml";
        contentType = "text/xml";
    }

    log.debug("Making Solr http post request to " + postUrl);

    PostMethod filePost = new PostMethod(postUrl);

    try {
        filePost.setRequestEntity(new MultipartRequestEntity(new Part[] { new FilePart(filename,
                new ByteArrayPartSource(filename, data.getBytes("UTF-8")), contentType, "UTF-8") },
                filePost.getParams()));
    } catch (UnsupportedEncodingException ex) {
        throw new SolrException(ex);
    }

    try {
        int response = httpClient.executeMethod(filePost);

        if (response == 200) {
            log.info("Request Complete: {}", response);

            //Confirm SOLR result status is 0

            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource source = new InputSource(filePost.getResponseBodyAsStream());

            Document doc = db.parse(source);

            String result = xPathUtil.evaluate(doc, "//int[@name=\'status\']");

            if (!"0".equals(result)) {
                log.error("SOLR Returned non zero result: {}", result);
                throw new SolrException("SOLR Returned non zero result: " + result);
            }
        } else {
            log.error("Request Failed: {}", response);
            throw new SolrException("Request Failed: " + response);
        }
    } catch (IOException ex) {
        throw new SolrException(ex);
    } catch (ParserConfigurationException ex) {
        throw new SolrException(ex);
    } catch (SAXException ex) {
        throw new SolrException(ex);
    } catch (XPathExpressionException ex) {
        throw new SolrException(ex);
    }
}

From source file:org.andrewberman.sync.PDFDownloader.java

private void uploadPDF(String id, File file) throws Exception {
    /*/*w  ww  .  j a v a2 s  .c o m*/
     * Set up the Multipart POST file upload.
     */
    StringPart p1 = new StringPart("article_id", id);
    StringPart p2 = new StringPart("username", username);
    StringPart p3 = new StringPart("check", "v2");
    StringPart p4 = new StringPart("keep_name", "yes");

    // Read the file into a byte array.
    InputStream is = new FileInputStream(file);
    long length = file.length();
    byte[] bytes = new byte[(int) length];
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file " + file.getName());
    }
    // Close the input stream and return bytes
    is.close();

    ByteArrayPartSource source = new ByteArrayPartSource(file.getName(), bytes);
    FilePart fp = new FilePart("file", source);
    fp.setName("file");

    Part[] parts = new Part[] { p1, p2, p3, p4, fp };
    //      status("Uploading...");
    //      debug("Uploading...");

    waitOrExit();

    PostMethod filePost = new PostMethod(BASE_URL + "personal_pdf_upload");
    try {
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        httpclient.executeMethod(filePost);
        String response = filePost.getResponseBodyAsString();
        //         System.out.println(response);
        if (response.contains("didn't work"))
            throw new Exception("CiteULike thinks the PDF is invalid!");
    } finally {
        is.close();
        is = null;
        bytes = null;
        source = null;
        parts = null;
        filePost.releaseConnection();
    }
}

From source file:org.andrewberman.sync.PDFSearcher.java

public void startMe() throws Exception {
    if (username.length() == 0 || password.length() == 0) {
        status("Error: Username or password is blank. Try again.");
        return;// www.j  a  v a 2 s  . c om
    }

    initPatternArray();

    login();

    do {
        getArticleInfo();
        List<CiteULikeReference> articlesWithoutPDFs = getArticlesWithoutPDFs(this.refs);

        itemMax = articlesWithoutPDFs.size();
        itemNum = 0;

        utd += this.refs.size() - articlesWithoutPDFs.size();

        Thread.sleep(1000);

        for (int i = 0; i < articlesWithoutPDFs.size(); i++) {
            itemNum++;
            waitOrExit();

            cnt = String.valueOf(i + 1) + "/" + articlesWithoutPDFs.size();
            status("Searching...");

            /*
             * Set the timeout timer.
             */
            TimerTask task = new TimerTask() {
                public void run() {
                    skipToNext = true;
                }
            };
            timer.schedule(task, (long) timeout * 1000);

            try {
                CiteULikeReference ref = articlesWithoutPDFs.get(i);
                System.out.println(ref.href);
                setArticleLink("Current article ID: " + ref.article_id, ref.href);

                waitOrExit();

                GetMethod get = null;
                for (String linkOut : ref.linkouts) {
                    try {
                        get = pdfScrape(linkOut, 5);
                        if (get != null)
                            break;
                    } catch (Exception e) {
                        System.err.println("Error retrieving article: " + e.getMessage());
                        System.err.println("  Will continue to the next one...");
                        continue;
                    }
                }

                // Sorry, no PDF for you!
                if (get == null) {
                    throw new Exception("No PDF was found!");
                }

                /*
                 * Looks like we really found a PDF. Let's download it.
                 */
                try {
                    InputStream in = get.getResponseBodyAsStream();
                    ByteArrayOutputStream ba = new ByteArrayOutputStream();

                    waitOrExit();

                    status("Downloading...");
                    debug("Downloading...");
                    int j = 0;
                    int ind = 0;
                    long length = get.getResponseContentLength();
                    int starRatio = (int) length / 20;
                    int numStars = 0;
                    while ((j = in.read()) != -1) {
                        if (length != -1 && ind % starRatio == 0) {
                            status("Downloading..." + repeat(".", ++numStars));
                        }
                        if (ind % 1000 == 0) {
                            waitOrExit();
                        }
                        ba.write(j);
                        ind++;
                    }
                    /*
                     * Set up the Multipart POST file upload.
                     */
                    //               String id = url.substring(url.lastIndexOf("/") + 1, url
                    //                     .length());
                    StringPart p1 = new StringPart("article_id", ref.article_id);
                    StringPart p2 = new StringPart("username", username);
                    StringPart p3 = new StringPart("check", "v2");
                    ByteArrayPartSource source = new ByteArrayPartSource("temp.pdf", ba.toByteArray());
                    FilePart fp = new FilePart("file", source);
                    fp.setName("file");

                    Part[] parts = new Part[] { p1, p2, p3, fp };
                    status("Uploading...");
                    debug("Uploading...");

                    waitOrExit();

                    PostMethod filePost = new PostMethod(BASE_URL + "personal_pdf_upload");
                    try {
                        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
                        httpclient.executeMethod(filePost);
                        String response = filePost.getResponseBodyAsString();
                        System.out.println(response);
                        if (response.contains("didn't work"))
                            throw new Exception("CiteULike thinks the PDF is invalid!");
                    } finally {
                        ba = null;
                        source = null;
                        parts = null;
                        filePost.releaseConnection();
                    }

                } finally {
                    get.releaseConnection();
                }

                status("Done!");
                Thread.sleep(BETWEEN_SEARCH_ITEMS_SLEEP_TIME);
                dl++;
            } catch (Exception e) {
                if (isStopped()) {
                    throw e;
                } else if (skipToNext) {
                    err++;
                    status("Timed out.");
                    Thread.sleep(BETWEEN_SEARCH_ITEMS_SLEEP_TIME);
                    continue;
                } else if (e instanceof Exception) {
                    err++;
                    status(e.getMessage());
                    Thread.sleep(BETWEEN_SEARCH_ITEMS_SLEEP_TIME);
                    continue;
                } else {
                    err++;
                    e.printStackTrace();
                    status("Failed. See the Java console for more info.");
                    Thread.sleep(BETWEEN_SEARCH_ITEMS_SLEEP_TIME);
                    continue;
                }
            } finally {
                task.cancel();
                skipToNext = false;
            }
        }
    } while (this.refs.size() != 0);

    setArticleLink("", "");
    this.pageNum = 0;
    status("Finished. " + dl + " found, " + utd + " existing and " + err + " failed.");
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSMultipartTest.java

@Test
public void testMultipartRequestTooLarge() throws Exception {
    PostMethod post = new PostMethod("http://localhost:" + PORT + "/bookstore/books/image");
    String ct = "multipart/mixed";
    post.setRequestHeader("Content-Type", ct);
    Part[] parts = new Part[1];
    parts[0] = new FilePart("image", new ByteArrayPartSource("testfile.png", new byte[1024 * 11]), "image/png",
            null);//  w  ww.  j a va  2s .co  m
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

    HttpClient httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(post);
        assertEquals(413, result);
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSMultipartTest.java

@Test
public void testMultipartRequestTooLargeManyParts() throws Exception {
    PostMethod post = new PostMethod("http://localhost:" + PORT + "/bookstore/books/image");
    String ct = "multipart/mixed";
    post.setRequestHeader("Content-Type", ct);
    Part[] parts = new Part[2];
    parts[0] = new FilePart("image", new ByteArrayPartSource("testfile.png", new byte[1024 * 9]), "image/png",
            null);//from   w w w.j a va  2 s  . c  om
    parts[1] = new FilePart("image", new ByteArrayPartSource("testfile2.png", new byte[1024 * 11]), "image/png",
            null);
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

    HttpClient httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(post);
        assertEquals(413, result);
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}

From source file:org.apache.sling.ide.osgi.impl.HttpOsgiClient.java

@Override
public void installBundle(InputStream in, String fileName) throws OsgiClientException {

    if (in == null) {
        throw new IllegalArgumentException("in may not be null");
    }//from   w w  w. j a va2s  .c om

    if (fileName == null) {
        throw new IllegalArgumentException("fileName may not be null");
    }

    // append pseudo path after root URL to not get redirected for nothing
    final PostMethod filePost = new PostMethod(repositoryInfo.appendPath("system/console/install"));

    try {
        // set referrer
        filePost.setRequestHeader("referer", "about:blank");

        List<Part> partList = new ArrayList<>();
        partList.add(new StringPart("action", "install"));
        partList.add(new StringPart("_noredir_", "_noredir_"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(in, baos);
        PartSource partSource = new ByteArrayPartSource(fileName, baos.toByteArray());
        partList.add(new FilePart("bundlefile", partSource));
        partList.add(new StringPart("bundlestart", "start"));

        Part[] parts = partList.toArray(new Part[partList.size()]);

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

        int status = getHttpClient().executeMethod(filePost);
        if (status != 200) {
            throw new OsgiClientException("Method execution returned status " + status);
        }
    } catch (IOException e) {
        throw new OsgiClientException(e);
    } finally {
        filePost.releaseConnection();
    }
}

From source file:org.apache.sling.ide.osgi.impl.HttpOsgiClient.java

@Override
public void installLocalBundle(final InputStream jarredBundle, String sourceLocation)
        throws OsgiClientException {

    if (jarredBundle == null) {
        throw new IllegalArgumentException("jarredBundle may not be null");
    }//  w  w  w.  j  a  v a  2s .c  o m

    new LocalBundleInstaller(getHttpClient(), repositoryInfo) {

        @Override
        void configureRequest(PostMethod method) throws IOException {

            Part[] parts = new Part[] { new FilePart("bundle",
                    new ByteArrayPartSource("bundle.jar", IOUtils.toByteArray(jarredBundle))) };
            method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
        }
    }.installBundle();
}