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:com.utest.domain.service.util.FileUploadUtil.java

public static void uploadFile(final File targetFile, final String targetURL, final String targerFormFieldName_)
        throws Exception {
    final PostMethod filePost = new PostMethod(targetURL);
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    filePost.addRequestHeader("X-Atlassian-Token", "no-check");
    try {/*from  ww w  .j  a  v a2  s .c  o m*/
        final FilePart fp = new FilePart(targerFormFieldName_, targetFile);
        fp.setTransferEncoding(null);
        final Part[] parts = { fp };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        final HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        final int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            Logger.getLogger(FileUploadUtil.class)
                    .info("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            Logger.getLogger(FileUploadUtil.class)
                    .info("Upload failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (final Exception ex) {
        Logger.getLogger(FileUploadUtil.class)
                .error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage(), ex);
        throw ex;
    } finally {
        Logger.getLogger(FileUploadUtil.class).debug(new String(filePost.getResponseBody()));
        filePost.releaseConnection();
    }

}

From source file:com.infosupport.service.LPRServiceCaller.java

public static void postData(String urlString, File file) {
    try {//  www  .jav  a2  s. c  o m
        PostMethod postMessage = new PostMethod(urlString);
        Part[] parts = { new FilePart("lpimage", file), new StringPart("country", "eu"),
                new StringPart("nonce", "123456789") };
        postMessage.setRequestEntity(new MultipartRequestEntity(parts, postMessage.getParams()));
        HttpClient client = new HttpClient();
        client.executeMethod(postMessage);
    } catch (IOException e) {
        Log.w(TAG, "IOException, waarschijnlijk geen internet connectie aanwezig...");
    }
}

From source file:com.mycompany.semconsolewebapp.FileUpload.java

public static void uploadFileAndMetaDataToServer(String imagePath, String operators, String channel, int kv,
        int mag, int wd) throws FileNotFoundException {
    File f = new File(imagePath);
    Part[] parts = { new StringPart("working_depth", Integer.toString(wd)),
            new StringPart("magnification", Integer.toString(mag)),
            new StringPart("voltage", Integer.toString(kv * 1000)), new StringPart("operators", operators),
            new StringPart("sensor", channel), new StringPart("update_metadata", "1"), new FilePart("img", f) };
    try {//from  ww w .jav a  2s .co  m
        uploadFileToServer(parts);
    } catch (IOException e) {
    }
}

From source file:de.laeubisoft.tools.ant.validation.Tools.java

/**
 * Creates a {@link RequestEntity} that can be used for submitting a file
 * //  w  ww .j av  a 2 s .co  m
 * @param params
 *            the params to use
 * @param methodParams
 *            the {@link HttpMethodParams} of the requesting method
 * @return {@link RequestEntity} that can be used for submitting the given
 *         file via Multipart
 * @throws IOException
 *             if something is wrong with the file...
 */
public static RequestEntity createFileUpload(File file, String filePartName, String charset,
        List<NameValuePair> params, HttpMethodParams methodParams) throws IOException {
    if (file == null) {
        throw new FileNotFoundException("file not present!");
    }
    List<Part> parts = nvToParts(params);
    FilePart fp = new FilePart(filePartName, file);
    fp.setContentType(URLConnection.guessContentTypeFromName(file.getName()));
    if (charset != null) {
        fp.setCharSet(charset);
    }
    parts.add(fp);
    return new MultipartRequestEntity(parts.toArray(new Part[0]), methodParams);
}

From source file:jp.co.cyberagent.jenkins.plugins.DeployStrategyAndroid.java

@Override
public List<Part> getParts() throws FileNotFoundException {
    List<Part> parts = super.getParts();
    parts.add(new FilePart("apk", new FilePathPartSource(mApkFile)));
    return parts;
}

From source file:com.mycompany.semconsolewebapp.FileUpload.java

public static void uploadFileToServer(String imagePath) {
    String stem = DEPOLYED_PATH;//from  w w w  . j  a  v  a  2  s  . c o  m
    if (IS_LOCAL) {
        stem = LOCAL_PATH;
    }

    try {
        String uploadURL = getUploadURL(stem + "geturl");
        Part[] p = { new FilePart("img", new File(imagePath)) };
        uploadImage(uploadURL, p);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.unc.lib.dl.cdr.sword.server.test.DepositClientsByHand.java

@Test
public void testUpload() throws Exception {
    String user = "";
    String password = "";
    String pid = "uuid:c9aba0a2-12e9-4767-822e-b285a37b07d7";
    String payloadMimeType = "text/xml";
    String payloadPath = "src/test/resources/dcDocument.xml";
    String metadataPath = "src/test/resources/atompubMODS.xml";
    String depositPath = "https://localhost:444/services/sword/collection/";
    String testSlug = "ingesttestslug";

    HttpClient client = HttpClientUtil.getAuthenticatedClient(depositPath + pid, user, password);
    client.getParams().setAuthenticationPreemptive(true);

    PostMethod post = new PostMethod(depositPath + pid);

    File payload = new File(payloadPath);
    File atom = new File(metadataPath);
    FilePart payloadPart = new FilePart("payload", payload);
    payloadPart.setContentType(payloadMimeType);
    payloadPart.setTransferEncoding("binary");

    Part[] parts = { payloadPart, new FilePart("atom", atom, "application/atom+xml", "utf-8") };
    MultipartRequestEntity mpEntity = new MultipartRequestEntity(parts, post.getParams());
    String boundary = mpEntity.getContentType();
    boundary = boundary.substring(boundary.indexOf("boundary=") + 9);

    Header header = new Header("Content-type",
            "multipart/related; type=application/atom+xml; boundary=" + boundary);
    post.addRequestHeader(header);/*from w  ww . ja v a2  s .  c  om*/

    Header slug = new Header("Slug", testSlug);
    post.addRequestHeader(slug);

    post.setRequestEntity(mpEntity);

    LOG.debug("" + client.executeMethod(post));
}

From source file:com.linkedin.pinot.server.realtime.ServerSegmentCompletionProtocolHandler.java

public SegmentCompletionProtocol.Response segmentCommit(long offset, final String segmentName,
        final File segmentTarFile) throws FileNotFoundException {
    SegmentCompletionProtocol.SegmentCommitRequest request = new SegmentCompletionProtocol.SegmentCommitRequest(
            segmentName, offset, _instance);
    final InputStream inputStream = new FileInputStream(segmentTarFile);
    Part[] parts = { new FilePart(segmentName, new PartSource() {
        @Override/*from   w w  w . j a v  a 2  s  . co m*/
        public long getLength() {
            return segmentTarFile.length();
        }

        @Override
        public String getFileName() {
            return "fileName";
        }

        @Override
        public InputStream createInputStream() throws IOException {
            return new BufferedInputStream(inputStream);
        }
    }) };
    return doHttp(request, parts);
}

From source file:com.nokia.carbide.internal.bugreport.model.Communication.java

/**
 * Sends given fields as a bug_report to the server provided by product.
 * @param fields values which are sent to the server
 * @param product product provides e.g. server URL
 * @return bug_id of the added bug_entry
 * @throws RuntimeException if an error occurred. Error can be either some communication error 
 * or error message provided by the server (e.g. invalid password)
 *//*from  www. j  a v a 2 s.c om*/
public static String sendBugReport(Hashtable<String, String> fields, IProduct product) throws RuntimeException {

    // Nothing to send
    if (fields == null || fields.size() < 1) {
        throw new RuntimeException(Messages.getString("Communication.NothingToSend")); //$NON-NLS-1$
    }

    String bugNumber = ""; //$NON-NLS-1$
    String url = product.getUrl();
    if (url.startsWith("https")) { //$NON-NLS-1$
        // we'll support HTTPS with trusted (i.e. signed) certificates
        //         Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    PostMethod filePost = new PostMethod(url);
    Part[] parts = new Part[fields.size()];
    int i = 0;
    Iterator<Map.Entry<String, String>> it = fields.entrySet().iterator();

    // create parts
    while (it.hasNext()) {
        Map.Entry<String, String> productField = it.next();

        // attachment field
        if (productField.getKey() == FieldsHandler.FIELD_ATTACHMENT) {
            File f = new File(productField.getValue());
            try {
                parts[i] = new FilePart(FieldsHandler.FIELD_DATA, f);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                parts[i] = new StringPart(FieldsHandler.FIELD_DATA,
                        Messages.getString("Communication.NotFound")); //$NON-NLS-1$
            }
            // string field
        } else {
            parts[i] = new StringPart(productField.getKey(), productField.getValue());
        }
        i++;
    }

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

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    setProxyData(client, filePost);
    int status = 0;
    String receivedData = ""; //$NON-NLS-1$
    try {
        status = client.executeMethod(filePost);
        receivedData = filePost.getResponseBodyAsString(1024 * 1024);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        filePost.releaseConnection();
    }

    // HTTP status codes: 2xx = Success
    if (status >= 200 && status < 300) {
        // some error occurred in the server side (e.g. invalid password)
        if (receivedData.contains(FieldsHandler.TAG_RESPONSE_ERROR)
                && receivedData.contains(FieldsHandler.TAG_RESPONSE_ERROR_CLOSE)) {
            int beginIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_ERROR)
                    + FieldsHandler.TAG_RESPONSE_ERROR.length();
            int endIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_ERROR_CLOSE);
            String error = receivedData.substring(beginIndex, endIndex);
            error = error.trim();
            throw new RuntimeException(error);
            // bug_entry was added successfully to database, read the bug_number
        } else if (receivedData.contains(FieldsHandler.TAG_RESPONSE_BUG_ID)
                && receivedData.contains(FieldsHandler.TAG_RESPONSE_BUG_ID_CLOSE)) {
            int beginIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_BUG_ID)
                    + FieldsHandler.TAG_RESPONSE_BUG_ID.length();
            int endIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_BUG_ID_CLOSE);
            bugNumber = receivedData.substring(beginIndex, endIndex);
            bugNumber = bugNumber.trim();
            // some unknown error
        } else {
            throw new RuntimeException(Messages.getString("Communication.UnknownError")); //$NON-NLS-1$
        }
        // some HTTP error (status code other than 2xx)
    } else {
        String error = Messages.getString("Communication.HttpError") + status; //$NON-NLS-1$
        throw new RuntimeException(error);
    }

    return bugNumber;
}

From source file:jp.co.cyberagent.jenkins.plugins.DeployStrategyIOs.java

@Override
public List<Part> getParts() throws FileNotFoundException {
    List<Part> parts = super.getParts();
    parts.add(new FilePart("ipa", new FilePathPartSource(mIpaFile)));
    return parts;
}