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.alfresco.repo.transfer.HttpClientTransmitterImpl.java

public void sendManifest(Transfer transfer, File manifest, OutputStream result) throws TransferException {
    TransferTarget target = transfer.getTransferTarget();
    PostMethod postSnapshotRequest = getPostMethod();
    MultipartRequestEntity requestEntity;

    if (log.isDebugEnabled()) {
        log.debug("does manifest exist? " + manifest.exists());
        log.debug("sendManifest file : " + manifest.getAbsoluteFile());
    }/*from   ww w .  j a  va  2  s. co m*/

    try {
        HostConfiguration hostConfig = getHostConfig(target);
        HttpState httpState = getHttpState(target);

        try {
            postSnapshotRequest.setPath(target.getEndpointPath() + "/post-snapshot");

            //Put the transferId on the query string
            postSnapshotRequest.setQueryString(
                    new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) });

            //TODO encapsulate the name of the manifest part
            //And add the manifest file as a "part"
            Part file = new FilePart(TransferCommons.PART_NAME_MANIFEST, manifest);
            requestEntity = new MultipartRequestEntity(new Part[] { file }, postSnapshotRequest.getParams());
            postSnapshotRequest.setRequestEntity(requestEntity);

            int responseStatus = httpClient.executeMethod(hostConfig, postSnapshotRequest, httpState);
            checkResponseStatus("sendManifest", responseStatus, postSnapshotRequest);

            InputStream is = postSnapshotRequest.getResponseBodyAsStream();

            final ReadableByteChannel inputChannel = Channels.newChannel(is);
            final WritableByteChannel outputChannel = Channels.newChannel(result);
            try {
                // copy the channels
                channelCopy(inputChannel, outputChannel);
            } finally {
                inputChannel.close();
                outputChannel.close();
            }

            return;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            String error = "Failed to execute HTTP request to target";
            log.debug(error, e);
            throw new TransferException(MSG_HTTP_REQUEST_FAILED,
                    new Object[] { "sendManifest", target.toString(), e.toString() }, e);
        }
    } finally {
        postSnapshotRequest.releaseConnection();
    }
}

From source file:org.alfresco.repo.transfer.HttpClientTransmitterImpl.java

/**
 *
 *///ww  w.  j  a  v  a  2s. co  m
public void sendContent(Transfer transfer, Set<ContentData> data) throws TransferException {
    if (log.isDebugEnabled()) {
        log.debug("send content to transfer:" + transfer);
    }

    TransferTarget target = transfer.getTransferTarget();
    PostMethod postContentRequest = getPostMethod();

    try {
        HostConfiguration hostConfig = getHostConfig(target);
        HttpState httpState = getHttpState(target);

        try {
            postContentRequest.setPath(target.getEndpointPath() + "/post-content");
            //Put the transferId on the query string
            postContentRequest.setQueryString(
                    new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) });

            //Put the transferId on the query string
            postContentRequest.setQueryString(
                    new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) });

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

            int index = 0;
            for (ContentData content : data) {
                String contentUrl = content.getContentUrl();
                String fileName = TransferCommons.URLToPartName(contentUrl);
                log.debug("content partName: " + fileName);

                parts[index++] = new ContentDataPart(getContentService(), fileName, content);
            }

            MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts,
                    postContentRequest.getParams());
            postContentRequest.setRequestEntity(requestEntity);

            int responseStatus = httpClient.executeMethod(hostConfig, postContentRequest, httpState);
            checkResponseStatus("sendContent", responseStatus, postContentRequest);

            if (log.isDebugEnabled()) {
                log.debug("sent content");
            }

        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            String error = "Failed to execute HTTP request to target";
            log.debug(error, e);
            throw new TransferException(MSG_HTTP_REQUEST_FAILED,
                    new Object[] { "sendContent", target.toString(), e.toString() }, e);
        }
    } finally {
        postContentRequest.releaseConnection();
    }
}

From source file:org.alfresco.repo.web.scripts.custommodel.CustomModelImportTest.java

public PostRequest buildMultipartPostRequest(File file) throws IOException {
    Part[] parts = { new FilePart("filedata", file.getName(), file, "application/zip", null) };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new HttpMethodParams());

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    multipartRequestEntity.writeRequest(os);

    PostRequest postReq = new PostRequest(UPLOAD_URL, os.toByteArray(),
            multipartRequestEntity.getContentType());
    return postReq;
}

From source file:org.alfresco.rest.api.tests.util.MultiPartBuilder.java

public MultiPartRequest build() throws IOException {
    List<Part> parts = new ArrayList<>();

    if (fileData != null) {
        FilePart fp = new FilePart("filedata", fileData.getFileName(), fileData.getFile(),
                fileData.getMimetype(), null);
        // Get rid of the default values added upon FilePart instantiation
        fp.setCharSet(fileData.getEncoding());
        fp.setContentType(fileData.getMimetype());
        parts.add(fp);//from   w  ww .  j  a  v  a2s.  c  om
        addPartIfNotNull(parts, "name", fileData.getFileName());
    }
    addPartIfNotNull(parts, "relativepath", relativePath);
    addPartIfNotNull(parts, "updatenoderef", updateNodeRef);
    addPartIfNotNull(parts, "description", description);
    addPartIfNotNull(parts, "contenttype", contentTypeQNameStr);
    addPartIfNotNull(parts, "aspects", getCommaSeparated(aspects));
    addPartIfNotNull(parts, "majorversion", majorVersion);
    addPartIfNotNull(parts, "overwrite", overwrite);
    addPartIfNotNull(parts, "autorename", autoRename);
    addPartIfNotNull(parts, "nodetype", nodeType);
    addPartIfNotNull(parts, "renditions", getCommaSeparated(renditionIds));

    if (!properties.isEmpty()) {
        for (Entry<String, String> prop : properties.entrySet()) {
            parts.add(new StringPart(prop.getKey(), prop.getValue()));
        }
    }

    MultipartRequestEntity req = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]),
            new HttpMethodParams());

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    req.writeRequest(os);

    return new MultiPartRequest(os.toByteArray(), req.getContentType(), req.getContentLength());
}

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

/**
 * @inheritDoc/*from w w  w  .j  a  v  a2s  .c  o m*/
 */
@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

/**
 * Uploads and downloads the bibtex library file, to synchronize library
 * changes.//from   w  w w . jav a2 s  .  c  o  m
 */
void syncBibTex() throws Exception {
    String base = baseDir.getCanonicalPath() + sep;
    itemMax = -1;
    final File bibFile = new File(base + username + ".bib");
    //      final File md5File = new File(base + ".md5s.txt");
    final File dateFile = new File(base + "sync_info.txt");
    // Check the MD5s, if the .md5s.txt file exists.

    long bibModified = bibFile.lastModified();
    long lastDownload = 0;

    boolean download = true;
    boolean upload = true;
    if (dateFile.exists()) {
        String fileS = readFile(dateFile);
        String[] props = fileS.split("\n");
        for (String prop : props) {
            String[] keyval = prop.split("=");
            if (keyval[0].equals("date")) {
                lastDownload = Long.valueOf(keyval[1]);
            }
        }
    }

    if (lastDownload >= bibModified) {
        upload = false;
    }

    boolean uploadSuccess = false;
    if (bibFile.exists() && uploadNewer && upload) {
        BufferedReader br = null;
        try {
            status("Uploading BibTex file...");
            FilePartSource fsrc = new FilePartSource(bibFile);
            FilePart fp = new FilePart("file", fsrc);
            br = new BufferedReader(new FileReader(bibFile));
            StringBuffer sb = new StringBuffer();
            String s;
            while ((s = br.readLine()) != null) {
                sb.append(s + "\n");
            }
            String str = sb.toString();

            final Part[] parts = new Part[] { new StringPart("btn_bibtex", "Import BibTeX file..."),
                    new StringPart("to_read", "2"), new StringPart("tag", ""), new StringPart("private", "t"),
                    new StringPart("update_allowed", "t"), new StringPart("update_id", "cul-id"),
                    new StringPart("replace_notes", "t"), new StringPart("replace_tags", "t"), fp };
            waitOrExit();
            PostMethod filePost = new PostMethod(BASE_URL + "/profile/" + username + "/import_do");
            try {
                filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
                httpclient.executeMethod(filePost);
                String response = filePost.getResponseBodyAsString();
                //            System.out.println(response);
                uploadSuccess = true;
                System.out.println("Bibtex upload success!");
            } finally {
                filePost.releaseConnection();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null)
                br.close();
        }
    }

    if (download || upload) {
        status("Downloading BibTeX file...");
        String pageURL = BASE_URL + "bibtex/user/" + username + "";
        FileWriter fw = new FileWriter(bibFile);
        try {
            GetMethod get = new GetMethod(pageURL);
            httpclient.executeMethod(get);
            InputStreamReader read = new InputStreamReader(get.getResponseBodyAsStream());
            int c;
            while ((c = read.read()) != -1) {
                waitOrExit();
                fw.write(c);
            }
            read.close();
        } finally {
            fw.close();
        }
    }

    // Store the checksums.
    if (uploadSuccess) {
        //         if (fileChecksum == null)
        //         {
        //            fileChecksum = getMd5(bibFile);
        //            remoteChecksum = get(BASE_URL + "bibtex/user/" + username + "?md5=true");
        //         }
        //         String md5S = fileChecksum + "\n" + remoteChecksum;
        //         writeFile(md5File, md5S);
        String dateS = "date=" + Calendar.getInstance().getTimeInMillis();
        writeFile(dateFile, dateS);
    }
}

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

private void uploadPDF(String id, File file) throws Exception {
    /*/*from   w  ww  .j  a  va  2  s  .c  om*/
     * 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;//from  w  w w  .  java2  s.  co  m
    }

    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.axis2.maven2.aar.DeployAarMojo.java

/**
 * Deploys the AAR.//from  ww  w.  j ava  2s. c  o  m
 *
 * @param aarFile the target AAR file
 * @throws MojoExecutionException
 * @throws HttpException
 * @throws IOException
 */
private void deploy(File aarFile) throws MojoExecutionException, IOException, HttpException {
    if (axis2AdminConsoleURL == null) {
        throw new MojoExecutionException("No Axis2 administrative console URL provided.");
    }

    // TODO get name of web service mount point
    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpClientParams.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    // log into Axis2 administration console
    URL axis2AdminConsoleLoginURL = new URL(axis2AdminConsoleURL.toString() + "/login");
    getLog().debug("Logging into Axis2 Admin Web Console " + axis2AdminConsoleLoginURL + " using user ID "
            + axis2AdminUser);

    PostMethod post = new PostMethod(axis2AdminConsoleLoginURL.toString());
    NameValuePair[] nvps = new NameValuePair[] { new NameValuePair("userName", axis2AdminUser),
            new NameValuePair("password", axis2AdminPassword) };
    post.setRequestBody(nvps);

    int status = client.executeMethod(post);
    if (status != 200) {
        throw new MojoExecutionException("Failed to log in");
    }
    if (post.getResponseBodyAsString().indexOf(LOGIN_FAILED_ERROR_MESSAGE) != -1) {
        throw new MojoExecutionException(
                "Failed to log into Axis2 administration web console using credentials");
    }

    // deploy AAR web service
    URL axis2AdminConsoleUploadURL = new URL(axis2AdminConsoleURL.toString() + "/upload");
    getLog().debug("Uploading AAR to Axis2 Admin Web Console " + axis2AdminConsoleUploadURL);

    post = new PostMethod(axis2AdminConsoleUploadURL.toString());
    Part[] parts = { new FilePart(project.getArtifact().getFile().getName(), project.getArtifact().getFile()) };
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

    status = client.executeMethod(post);
    if (status != 200) {
        throw new MojoExecutionException("Failed to log in");
    }

    // log out of web console
    URL axis2AdminConsoleLogoutURL = new URL(axis2AdminConsoleURL.toString() + "/logout");
    getLog().debug("Logging out of Axis2 Admin Web Console " + axis2AdminConsoleLogoutURL);

    GetMethod get = new GetMethod(axis2AdminConsoleLogoutURL.toString());
    status = client.executeMethod(get);
    if (status != 200) {
        throw new MojoExecutionException("Failed to log out");
    }

}

From source file:org.apache.camel.component.jetty.HttpBridgeMultipartRouteTest.java

@Test
public void testHttpClient() throws Exception {
    File jpg = new File("src/test/resources/java.jpg");
    String body = "TEST";
    Part[] parts = new Part[] { new StringPart("body", body), new FilePart(jpg.getName(), jpg) };

    PostMethod method = new PostMethod("http://localhost:" + port2 + "/test/hello");
    MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, method.getParams());
    method.setRequestEntity(requestEntity);

    HttpClient client = new HttpClient();
    client.executeMethod(method);/*  w w  w.  j ava  2  s . c  om*/

    String responseBody = method.getResponseBodyAsString();
    assertEquals(body, responseBody);

    String numAttachments = method.getResponseHeader("numAttachments").getValue();
    assertEquals(numAttachments, "1");
}