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 paramString1, String paramString2, File paramFile) throws FileNotFoundException 

Source Link

Usage

From source file:ca.uvic.cs.tagsea.wizards.TagNetworkSender.java

public static synchronized void send(String xml, IProgressMonitor sendMonitor, int id)
        throws InvocationTargetException {
    sendMonitor.beginTask("Uploading Tags", 100);
    sendMonitor.subTask("Saving Temporary file...");
    File location = TagSEAPlugin.getDefault().getStateLocation().toFile();
    File temp = new File(location, "tagsea.temp.file.txt");
    if (temp.exists()) {
        String message = "Unable to send tags. Unable to create temporary file.";
        IOException ex = new IOException(message);
        throw (new InvocationTargetException(ex, message));
    }/*from w ww . j  a  v a2 s  .c  om*/
    try {
        FileWriter writer = new FileWriter(temp);
        writer.write(xml);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }
    sendMonitor.worked(5);
    sendMonitor.subTask("Uploading Tags...");
    String uploadScript = "http://stgild.cs.uvic.ca/cgi-bin/tagSEAUpload.cgi";
    PostMethod post = new PostMethod(uploadScript);

    String fileName = getToday() + ".txt";
    try {
        Part[] parts = { new StringPart("KIND", "tag"), new FilePart("MYLAR" + id, fileName, temp) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        HttpClient client = new HttpClient();
        int status = client.executeMethod(post);
        String resp = getData(post.getResponseBodyAsStream());
        if (status != 200) {
            IOException ex = new IOException(resp);
            throw (ex);
        }
    } catch (IOException e) {
        throw new InvocationTargetException(e, e.getLocalizedMessage());
    } finally {
        sendMonitor.worked(90);
        sendMonitor.subTask("Deleting Temporary File");
        temp.delete();
        sendMonitor.done();
    }

}

From source file:net.morphbank.mbsvc3.test.SendImageTest.java

public void sendImage(String strURL, String id, String originalFileName, String imageFileName)
        throws Exception {
    File input = new File(imageFileName);
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);

    Part[] parts = { new StringPart("id", id), new StringPart("fileName", originalFileName),
            new FilePart("image", originalFileName, input) };
    RequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
    post.setRequestEntity(entity);//  w  w  w . j  a v a 2s  .  c  om
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {
        System.out.println("Trying post");
        int result = httpclient.executeMethod(post);
        // Display status code
        System.out.println("Response status code: " + result);
        // Display response
        System.out.println("Response body: ");
        InputStream response = post.getResponseBodyAsStream();
        // int j = response.read(); System.out.write(j);
        for (int i = response.read(); i != -1; i = response.read()) {
            System.out.write(i);
        }
        // System.out.flush();
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
}

From source file:ca.uvic.cs.tagsea.monitor.NetworkLogging.java

public synchronized boolean uploadForDate(Date d) throws IOException {
    File f = SimpleDayLog.findLogFileForDay(d);
    if (f.length() == 0)
        return true;

    PostMethod post = new PostMethod(uploadScript);
    Display disp = TagSEAMonitorPlugin.getDefault().getWorkbench().getDisplay();
    int id = getUID();
    if (id < 0) {
        //error getting the user id. Quit.
        return false;
    }/*w ww  .  ja va 2 s.  c  om*/
    Part[] parts = { new StringPart("KIND", "log"), new FilePart("MYLAR" + id, f.getName(), f) };
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
    HttpClient client = new HttpClient();
    int status = client.executeMethod(post);
    resp = getData(post.getResponseBodyAsStream());
    if (status != 200) {
        disp.syncExec(new Runnable() {
            public void run() {
                MessageDialog.openError(null, "Error Sending File", resp);
            }
        });
        return false;

    }
    MonitorPreferences.setLastSendDate(d);
    return true;

}

From source file:net.morphbank.webclient.RemoteImageProcessing.java

public void sendImage(String strURL, String id, String originalFileName, String imageFileName)
        throws Exception {
    File input = new File(imageFileName);
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);

    Part[] parts = { new StringPart("id", id), new StringPart("fileName", originalFileName),
            new FilePart("image", originalFileName, input) };
    RequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
    post.setRequestEntity(entity);//  w  w  w  . ja  va2  s .c  om
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {
        System.out.println("Trying post");
        int postStatus = httpclient.executeMethod(post);
        // Display status code
        System.out.println("Response status code: " + postStatus);
        // Display response
        System.out.print("Response body: ");
        InputStream response = post.getResponseBodyAsStream();
        for (int i = response.read(); i != -1; i = response.read()) {
            System.out.write(i);
        }
        System.out.flush();
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
}

From source file:net.morphbank.webclient.PostXML.java

public void post(String strURL, String strXMLFilename) throws Exception {
    File input = new File(strXMLFilename);
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);
    // Request content will be retrieved directly
    // from the input stream Part[] parts = {
    Part[] parts = { new FilePart("uploadFile", strXMLFilename, input) };
    RequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
    // RequestEntity entity = new FileRequestEntity(input,
    // "text/xml;charset=utf-8");
    post.setRequestEntity(entity);//from   w  ww  .ja va 2  s.co m
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {
        System.out.println("Trying post");
        int result = httpclient.executeMethod(post);
        // Display status code
        System.out.println("Response status code: " + result);
        // Display response
        System.out.println("Response body: ");
        InputStream response = post.getResponseBodyAsStream();
        //int j = response.read(); System.out.write(j);
        for (int i = response.read(); i != -1; i = response.read()) {
            System.out.write(i);
        }
        //System.out.flush();
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
}

From source file:edu.tsinghua.lumaqq.test.CustomHeadUploader.java

/**
 * /*from   w  ww .  j  a v a2 s . c  o m*/
 * 
 * @param filename
 */
public void upload(String filename, QQUser user) {
    HttpClient client = new HttpClient();
    HostConfiguration conf = new HostConfiguration();
    conf.setHost(QQ.QQ_SERVER_UPLOAD_CUSTOM_HEAD);
    client.setHostConfiguration(conf);
    PostMethod method = new PostMethod("/cgi-bin/cface/upload");
    method.addRequestHeader("Accept", "*/*");
    method.addRequestHeader("Pragma", "no-cache");

    StringPart uid = new StringPart("clientuin", String.valueOf(user.getQQ()));
    uid.setContentType(null);
    uid.setTransferEncoding(null);

    //StringPart clientkey = new StringPart("clientkey", "0D649E66B0C1DBBDB522CE9C846754EF6AFA10BBF1A48A532DF6369BBCEF6EE7");
    //StringPart clientkey = new StringPart("clientkey", "3285284145CC19EC0FFB3B25E4F6817FF3818B0E72F1C4E017D9238053BA2040");
    StringPart clientkey = new StringPart("clientkey",
            "2FEEBE858DAEDFE6352870E32E5297ABBFC8C87125F198A5232FA7ADA9EADE67");
    //StringPart clientkey = new StringPart("clientkey", "8FD643A7913C785AB612F126C6CD68A253F459B90EBCFD9375053C159418AF16");
    //      StringPart clientkey = new StringPart("clientkey", Util.convertByteToHexStringWithoutSpace(user.getClientKey()));
    clientkey.setContentType(null);
    clientkey.setTransferEncoding(null);

    //StringPart sign = new StringPart("sign", "2D139466226299A73F8BCDA7EE9AB157E8D9DA0BB38B6F4942A1658A00BD4C1FEE415838810E5AEF40B90E2AA384A875");
    //StringPart sign = new StringPart("sign", "50F479417088F26EFC75B9BCCF945F35346188BB9ADD3BDF82098C9881DA086E3B28D56726D6CB2331909B62459E1E62");
    //StringPart sign = new StringPart("sign", "31A69198C19A7C4BFB60DCE352FE2CC92C9D27E7C7FEADE1CBAAFD988906981ECC0DD1782CBAE88A2B716F84F9E285AA");
    StringPart sign = new StringPart("sign",
            "68FFB636DE63D164D4072D7581213C77EC7B425DDFEB155428768E1E409935AA688AC88910A74C5D2D94D5EF2A3D1764");
    sign.setContentType(null);
    sign.setTransferEncoding(null);

    FilePart file;
    try {
        file = new FilePart("customfacefile", filename, new File(filename));
    } catch (FileNotFoundException e) {
        return;
    }

    Part[] parts = new Part[] { uid, clientkey, sign, file };
    MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams());

    method.setRequestEntity(entity);
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            Header header = method.getResponseHeader("CFace-Msg");
            System.out.println(header.getValue());
            header = method.getResponseHeader("CFace-RetCode");
            System.out.println(header.getValue());
        }
    } catch (HttpException e) {
        return;
    } catch (IOException e) {
        return;
    } finally {
        method.releaseConnection();
    }
}

From source file:net.morphbank.webclient.ProcessFiles.java

public InputStream post(String strURL, String strXMLFilename, PrintWriter out) throws Exception {
    InputStream response = null;/*from ww w . j a va  2 s .  co m*/
    File input = new File(strXMLFilename);
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);
    // Request content will be retrieved directly
    // from the input stream Part[] parts = {
    Part[] parts = { new FilePart("uploadFile", strXMLFilename, input) };
    RequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
    // RequestEntity entity = new FileRequestEntity(input,
    // "text/xml;charset=utf-8");
    post.setRequestEntity(entity);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {
        int result = httpclient.executeMethod(post);
        // Display status code
        System.out.println("Response status code: " + result);
        // Display response
        response = post.getResponseBodyAsStream();
        for (int i = response.read(); i != -1; i = response.read()) {
            out.write(i);
        }
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
    return response;
}

From source file:com.dtolabs.client.utils.WebserviceHttpClientChannel.java

/**
 * Returns the RequestEntity for the Post method request.  If a file upload is included, it will return a
 * MultipartRequestEntity with the file as one part.  otherwise, null is returned.
 *///from   w w  w. j a  va 2  s . c  o  m
protected RequestEntity getRequestEntity(final PostMethod method) {
    if (uploadFile != null) {
        logger.debug("attempting to upload file with colony request");
        try {
            final Part[] parts = new Part[] { new FilePart(
                    null != getFileparam() ? getFileparam() : "uploadFile", uploadFile.getName(), uploadFile) };
            return new MultipartRequestEntity(parts, method.getParams());
        } catch (FileNotFoundException e) {
            throw new CoreException(
                    "Could not upload file in request to server: " + uploadFile.getAbsolutePath(), e);
        }
    } else {
        return null;
    }
}

From source file:games.strategy.triplea.pbem.AxisAndAlliesForumPoster.java

public boolean postTurnSummary(final String message, final String subject) {
    try {//from w  w w. j a  va2  s  . co m
        login();

        // Now we load the post page, and find the hidden fields needed to post
        final GetMethod get = new GetMethod(
                "http://www.axisandallies.org/forums/index.php?action=post;topic=" + m_topicId + ".0");
        int status = m_client.executeMethod(m_hostConfiguration, get, m_httpState);
        String body = get.getResponseBodyAsString();
        if (status == 200) {
            String numReplies;
            String seqNum;
            String sc;
            Matcher m = NUM_REPLIES_PATTERN.matcher(body);
            if (m.matches()) {
                numReplies = m.group(1);
            } else {
                throw new Exception("Hidden field 'num_replies' not found on page");
            }

            m = SEQ_NUM_PATTERN.matcher(body);
            if (m.matches()) {
                seqNum = m.group(1);
            } else {
                throw new Exception("Hidden field 'seqnum' not found on page");
            }

            m = SC_PATTERN.matcher(body);
            if (m.matches()) {
                sc = m.group(1);
            } else {
                throw new Exception("Hidden field 'sc' not found on page");
            }

            // now we have the required hidden fields to reply to
            final PostMethod post = new PostMethod(
                    "http://www.axisandallies.org/forums/index.php?action=post2;start=0;board=40");

            try {
                // Construct the multi part post
                final List<Part> parts = new ArrayList<Part>();

                parts.add(createStringPart("topic", m_topicId));
                parts.add(createStringPart("subject", subject));
                parts.add(createStringPart("icon", "xx"));
                parts.add(createStringPart("message", message));

                // If the user has chosen to receive notifications, ensure this setting is passed on
                parts.add(createStringPart("notify", NOTIFY_PATTERN.matcher(body).matches() ? "1" : "0"));

                if (m_includeSaveGame && m_saveGameFile != null) {
                    final FilePart part = new FilePart("attachment[]", m_saveGameFileName, m_saveGameFile);
                    part.setContentType("application/octet-stream");
                    part.setTransferEncoding(null);
                    part.setCharSet(null);
                    parts.add(part);
                }

                parts.add(createStringPart("post", "Post"));
                parts.add(createStringPart("num_replies", numReplies));
                parts.add(createStringPart("additional_options", "1"));
                parts.add(createStringPart("sc", sc));
                parts.add(createStringPart("seqnum", seqNum));

                final MultipartRequestEntity entity = new MultipartRequestEntity(
                        parts.toArray(new Part[parts.size()]), new HttpMethodParams());
                post.setRequestEntity(entity);

                // add headers
                post.addRequestHeader("Referer",
                        "http://www.axisandallies.org/forums/index.php?action=post;topic=" + m_topicId
                                + ".0;num_replies=" + numReplies);
                post.addRequestHeader("Accept", "*/*");

                try {
                    // the site has spam prevention which means you can't post until 15 seconds after login
                    Thread.sleep(15 * 1000);
                } catch (final InterruptedException ie) {
                    ie.printStackTrace(); // this should never happen
                }

                post.setFollowRedirects(false);
                status = m_client.executeMethod(m_hostConfiguration, post, m_httpState);
                body = post.getResponseBodyAsString();
                if (status == 302) {
                    // site responds with a 302 redirect back to the forum index (board=40)

                    // The syntax for post is ".....topic=xx.yy" where xx is the thread id, and yy is the post number in the given thread
                    // since the site is lenient we can just give a high post_number to go to the last post in the thread
                    m_turnSummaryRef = "http://www.axisandallies.org/forums/index.php?topic=" + m_topicId
                            + ".10000";
                } else {
                    // these two patterns find general errors, where the first pattern checks if the error text appears,
                    // the second pattern extracts the error message. This could be the "The last posting from your IP was less than 15 seconds ago.Please try again later"

                    // this patter finds errors that are marked in red (for instance "You are not allowed to post URLs", or
                    // "Some one else has posted while you vere reading"

                    Matcher matcher = ERROR_LIST_PATTERN.matcher(body);
                    if (matcher.matches()) {
                        throw new Exception("The site gave an error: '" + matcher.group(1) + "'");
                    }

                    matcher = AN_ERROR_OCCURRED_PATTERN.matcher(body);
                    if (matcher.matches()) {
                        matcher = ERROR_TEXT_PATTERN.matcher(body);
                        if (matcher.matches()) {
                            throw new Exception("The site gave an error: '" + matcher.group(1) + "'");
                        }
                    }

                    final Header refreshHeader = post.getResponseHeader("Refresh");
                    if (refreshHeader != null) {
                        // sometimes the message will be flagged as spam, and a refresh url is given
                        final String value = refreshHeader.getValue(); // refresh: 0; URL=http://...topic=26114.new%3bspam=true#new
                        final Pattern p = Pattern.compile("[^;]*;\\s*url=.*spam=true.*",
                                Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
                        m = p.matcher(value);
                        if (m.matches()) {
                            throw new Exception("The summary was posted but was flagged as spam");
                        }
                    }
                    throw new Exception(
                            "Unknown error, please contact the forum owner and also post a bug to the tripleA development team");
                }
            } finally {
                post.releaseConnection();
                // Commented out log out call since it was causing all of a user's sessions to be logged out and doesn't appear to be needed
                // final GetMethod logout = new GetMethod("http://www.axisandallies.org/forums/index.php?action=logout;sesc=" + sc);
                // try
                // {
                // status = m_client.executeMethod(m_hostConfiguration, logout, m_httpState);
                // // site responds with a 200 + Refresh header to redirect to index.php
                // if (status != 200)
                // {
                // // nothing we can do if this fails
                // }
                // } finally
                // {
                // logout.releaseConnection();
                // }
            }
        } else {
            throw new Exception("Unable to load forum post " + m_topicId);
        }

    } catch (final Exception e) {
        m_turnSummaryRef = e.getMessage();
        return false;
    }

    return true;
}

From source file:ca.uvic.cs.tagsea.statistics.svn.jobs.SVNCommentScanningJob.java

/**
 * @param files//from  www  .  jav  a 2 s .  com
 */
private IStatus sendFile(File file) {
    String uploadScript = "http://stgild.cs.uvic.ca/cgi-bin/tagSEAUpload.cgi";
    int id = TagSEAPlugin.getDefault().getUserID();
    if (id < 0) {
        id = askForID();
        if (id == 0) {
            //just do nothing.
            return Status.OK_STATUS;
        }
    }
    HttpClient client = new HttpClient();
    IStatus s = Status.OK_STATUS;
    String message = "";

    try {
        PostMethod post = new PostMethod(uploadScript);
        Part[] parts = { new StringPart("KIND", "subversion"),
                new FilePart("MYLAR" + id, file.getName(), file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        int status = client.executeMethod(post);
        String resp = getData(post.getResponseBodyAsStream());
        if (status != 200) {
            message += resp + ";";
            s = new Status(IStatus.ERROR, SVNStatistics.PLUGIN_ID, status, message, null);
        }
    } catch (IOException e) {
        message += file.getAbsolutePath() + " could not be sent;";
        s = new Status(IStatus.ERROR, SVNStatistics.PLUGIN_ID, 0, message, e);
    }

    return s;
}