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

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

Introduction

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

Prototype

public FilePart(String paramString, PartSource paramPartSource) 

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   w  w w.  ja v  a 2 s  .  c  o 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.andrewberman.sync.PDFDownloader.java

/**
 * Uploads and downloads the bibtex library file, to synchronize library
 * changes./*www  .j a  va  2  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 {
    /*// w  ww .  java2s  .  co  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;//from ww w  .  ja v a  2 s .com
    }

    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   www . j  a  va  2  s .c om*/
 *
 * @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);/*from  ww w  .j  a v  a 2  s.  co  m*/

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

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

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

@Test
public void testSendMultiPartForm() throws Exception {
    HttpClient httpclient = new HttpClient();

    File file = new File("src/main/resources/META-INF/NOTICE.txt");

    PostMethod httppost = new PostMethod("http://localhost:" + getPort() + "/test");
    Part[] parts = { new StringPart("comment", "A binary file of some kind"),
            new FilePart(file.getName(), file) };

    MultipartRequestEntity reqEntity = new MultipartRequestEntity(parts, httppost.getParams());
    httppost.setRequestEntity(reqEntity);

    int status = httpclient.executeMethod(httppost);

    assertEquals("Get a wrong response status", 200, status);
    String result = httppost.getResponseBodyAsString();

    assertEquals("Get a wrong result", "A binary file of some kind", result);

}

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

@Test
public void testSendMultiPartForm() throws Exception {
    HttpClient httpclient = new HttpClient();
    File file = new File("src/main/resources/META-INF/NOTICE.txt");
    PostMethod httppost = new PostMethod("http://localhost:9080/test");
    Part[] parts = { new StringPart("comment", "A binary file of some kind"),
            new FilePart(file.getName(), file) };

    MultipartRequestEntity reqEntity = new MultipartRequestEntity(parts, httppost.getParams());
    httppost.setRequestEntity(reqEntity);

    int status = httpclient.executeMethod(httppost);

    assertEquals("Get a wrong response status", 200, status);

    String result = httppost.getResponseBodyAsString();
    assertEquals("Get a wrong result", "A binary file of some kind", result);
    assertNotNull("Did not use custom multipart filter", httppost.getResponseHeader("MyMultipartFilter"));
}

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

@Test
public void testSendMultiPartFormOverrideEnableMultpartFilterFalse() throws Exception {
    HttpClient httpclient = new HttpClient();

    File file = new File("src/main/resources/META-INF/NOTICE.txt");

    PostMethod httppost = new PostMethod("http://localhost:9080/test2");
    Part[] parts = { new StringPart("comment", "A binary file of some kind"),
            new FilePart(file.getName(), file) };

    MultipartRequestEntity reqEntity = new MultipartRequestEntity(parts, httppost.getParams());
    httppost.setRequestEntity(reqEntity);

    int status = httpclient.executeMethod(httppost);

    assertEquals("Get a wrong response status", 200, status);
    assertNotNull("Did not use custom multipart filter", httppost.getResponseHeader("MyMultipartFilter"));
}

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

@Test
public void testSendMultiPartForm() throws Exception {
    HttpClient httpclient = new HttpClient();
    File file = new File("src/main/resources/META-INF/NOTICE.txt");
    PostMethod httppost = new PostMethod("http://localhost:" + getPort() + "/test");
    Part[] parts = { new StringPart("comment", "A binary file of some kind"),
            new FilePart(file.getName(), file) };

    MultipartRequestEntity reqEntity = new MultipartRequestEntity(parts, httppost.getParams());
    httppost.setRequestEntity(reqEntity);

    int status = httpclient.executeMethod(httppost);

    assertEquals("Get a wrong response status", 200, status);

    String result = httppost.getResponseBodyAsString();
    assertEquals("Get a wrong result", "A binary file of some kind", result);
    assertNotNull("Did not use custom multipart filter", httppost.getResponseHeader("MyMultipartFilter"));
}