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

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

Introduction

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

Prototype

PartSource

Source Link

Usage

From source file:com.foglyn.fogbugz.AttachmentData.java

PartSource getPartSource() {
    return new PartSource() {
        public InputStream createInputStream() throws IOException {
            return AttachmentData.this.createInputStream();
        }/* w  ww  . j ava  2  s. com*/

        public String getFileName() {
            return AttachmentData.this.getFilename();
        }

        public long getLength() {
            return AttachmentData.this.getLength();
        }
    };
}

From source file:at.gv.egiz.bku.binding.multipart.SLResultPart.java

public SLResultPart(SLResult slResult, String encoding) {
    super((slResult.getResultType() == SLResultType.XML) ? DataUrlConnection.FORMPARAM_XMLRESPONSE
            : DataUrlConnection.FORMPARAM_BINARYRESPONSE, new PartSource() {

                @Override/*  www  .  j a va2 s . c  om*/
                public long getLength() {
                    // may return null, as sendData() is overridden
                    return 0;
                }

                @Override
                public String getFileName() {
                    // return null, to prevent content-disposition header 
                    return null;
                }

                @Override
                public InputStream createInputStream() throws IOException {
                    // may return null, as sendData() is overridden below 
                    return null;
                }
            });
    this.slResult = slResult;
    this.encoding = encoding;
}

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/*  w ww.  j a  va 2s  .c o  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.linkedin.pinot.common.utils.FileUploadUtils.java

public static int sendFile(final String host, final String port, final String path, final String fileName,
        final InputStream inputStream, final long lengthInBytes, SendFileMethod httpMethod) {
    EntityEnclosingMethod method = null;
    try {/*from   w ww .  j  a v a 2 s .c o m*/
        method = httpMethod.forUri("http://" + host + ":" + port + "/" + path);
        Part[] parts = { new FilePart(fileName, new PartSource() {
            @Override
            public long getLength() {
                return lengthInBytes;
            }

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

            @Override
            public InputStream createInputStream() throws IOException {
                return new BufferedInputStream(inputStream);
            }
        }) };
        method.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams()));
        FILE_UPLOAD_HTTP_CLIENT.executeMethod(method);
        if (method.getStatusCode() >= 400) {
            String errorString = "POST Status Code: " + method.getStatusCode() + "\n";
            if (method.getResponseHeader("Error") != null) {
                errorString += "ServletException: " + method.getResponseHeader("Error").getValue();
            }
            throw new HttpException(errorString);
        }
        return method.getStatusCode();
    } catch (Exception e) {
        LOGGER.error("Caught exception while sending file: {}", fileName, e);
        Utils.rethrowException(e);
        throw new AssertionError("Should not reach this");
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:edu.wisc.ssec.mcidasv.supportform.Submitter.java

/** 
 * Creates a file attachment that's based upon a real file.
 * /*from  ww w .ja v a2  s .c  om*/
 * @param id The parameter ID. Usually something like 
 * {@literal "form_data[att_two]"}.
 * @param file Path to the file that's going to be attached.
 * 
 * @return {@code POST}-able file attachment using the name and contents of
 * {@code file}.
 */
private static FilePart buildRealFilePart(final String id, final String file) {
    return new FilePart(id, new PartSource() {
        public InputStream createInputStream() {
            try {
                return IOUtil.getInputStream(file);
            } catch (Exception e) {
                throw new WrapperException("Reading file: " + file, e);
            }
        }

        public String getFileName() {
            return new File(file).getName();
        }

        public long getLength() {
            return new File(file).length();
        }
    });
}

From source file:edu.wisc.ssec.mcidasv.supportform.Submitter.java

/**
 * Creates a file attachment that isn't based upon an actual file. Useful 
 * for something like the {@literal "extra"} attachment where you collect
 * a bunch of data but don't want to deal with creating a temporary file.
 * //  w ww  .  j a va 2  s .c  o  m
 * @param id Parameter ID. Typically something like 
 * {@literal "form_data[att_extra]"}.
 * @param file Fake name of the file. Can be whatever you like.
 * @param data The actual data to place inside the attachment.
 * 
 * @return {@code POST}-able file attachment using a spoofed filename!
 */
private static FilePart buildFakeFilePart(final String id, final String file, final byte[] data) {
    return new FilePart(id, new PartSource() {
        public InputStream createInputStream() {
            return new ByteArrayInputStream(data);
        }

        public String getFileName() {
            return file;
        }

        public long getLength() {
            return data.length;
        }
    });
}

From source file:com.kaltura.client.KalturaClientBase.java

private PostMethod getPostMultiPartWithFiles(PostMethod method, KalturaParams kparams, KalturaFiles kfiles) {

    String boundary = "---------------------------" + System.currentTimeMillis();
    List<Part> parts = new ArrayList<Part>();
    parts.add(new StringPart(HttpMethodParams.MULTIPART_BOUNDARY, boundary));

    for (Entry<String, String> itr : kparams.entrySet()) {
        parts.add(new StringPart(itr.getKey(), itr.getValue()));
    }/*from w  w  w .jav  a2 s .  c om*/

    for (String key : kfiles.keySet()) {
        final KalturaFile kFile = kfiles.get(key);
        parts.add(new StringPart(key, "filename=" + kFile.getName()));
        if (kFile.getFile() != null) {
            // use the file
            File file = kFile.getFile();
            try {
                parts.add(new FilePart(key, file));
            } catch (FileNotFoundException e) {
                // TODO this sort of leaves the submission in a weird state... -AZ
                if (logger.isEnabled())
                    logger.error("Exception while iterating over kfiles", e);
            }
        } else {
            // use the input stream
            PartSource fisPS = new PartSource() {
                public long getLength() {
                    return kFile.getSize();
                }

                public String getFileName() {
                    return kFile.getName();
                }

                public InputStream createInputStream() throws IOException {
                    return kFile.getInputStream();
                }
            };
            parts.add(new FilePart(key, fisPS));
        }
    }

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

    method.setRequestEntity(new MultipartRequestEntity(allParts, method.getParams()));

    return method;
}

From source file:com.borhan.client.BorhanClientBase.java

private PostMethod getPostMultiPartWithFiles(PostMethod method, BorhanParams kparams, BorhanFiles kfiles) {

    String boundary = "---------------------------" + System.currentTimeMillis();
    List<Part> parts = new ArrayList<Part>();
    parts.add(new StringPart(HttpMethodParams.MULTIPART_BOUNDARY, boundary));

    parts.add(new StringPart("json", kparams.toString()));

    for (String key : kfiles.keySet()) {
        final BorhanFile kFile = kfiles.get(key);
        parts.add(new StringPart(key, "filename=" + kFile.getName()));
        if (kFile.getFile() != null) {
            // use the file
            File file = kFile.getFile();
            try {
                parts.add(new FilePart(key, file));
            } catch (FileNotFoundException e) {
                // TODO this sort of leaves the submission in a weird
                // state... -AZ
                if (logger.isEnabled())
                    logger.error("Exception while iterating over kfiles", e);
            }/*from  w  w w . j  ava2s .c  o m*/
        } else {
            // use the input stream
            PartSource fisPS = new PartSource() {
                public long getLength() {
                    return kFile.getSize();
                }

                public String getFileName() {
                    return kFile.getName();
                }

                public InputStream createInputStream() throws IOException {
                    return kFile.getInputStream();
                }
            };
            parts.add(new FilePart(key, fisPS));
        }
    }

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

    method.setRequestEntity(new MultipartRequestEntity(allParts, method.getParams()));

    return method;
}

From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java

private PostMethod postInternal(String formUrl, Map<String, String> changed, final ITaskAttachment attach)
        throws FogBugzClientException, HttpException, IOException, MarshalException, ValidationException {

    WebClientUtil.setupHttpClient(httpClient, proxy, formUrl, null, null);
    if (!authenticated && hasAuthenticationCredentials()) {
        authenticate();/*from w  ww.j a  va2  s  .c  o m*/
    }

    String requestUrl = WebClientUtil.getRequestPath(formUrl + "&token=" + token);

    ArrayList<Part> parts = new ArrayList<Part>();
    if (attach != null) {
        requestUrl += "&nFileCount=1";
        FilePart part = new FilePart("File1", new PartSource() {

            public InputStream createInputStream() throws IOException {
                return attach.createInputStream();
            }

            public String getFileName() {
                return attach.getFilename();
            }

            public long getLength() {
                return attach.getLength();
            }

        });
        part.setTransferEncoding(null);
        parts.add(part);
        parts.add(new StringPart("Content-Type", attach.getContentType()));
    }
    PostMethod postMethod = new PostMethod(requestUrl);
    // postMethod.setRequestHeader("Content-Type",
    // "application/x-www-form-urlencoded; charset="
    // + characterEncoding);

    // postMethod.setRequestBody(formData);
    postMethod.setDoAuthentication(true);

    for (String key : changed.keySet()) {
        StringPart p = new StringPart(key, changed.get(key));
        p.setTransferEncoding(null);
        p.setContentType(null);
        parts.add(p);
    }
    postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), postMethod.getParams()));

    int status = httpClient.executeMethod(postMethod);
    if (status == HttpStatus.SC_OK) {
        return postMethod;
    } else {
        postMethod.getResponseBody();
        postMethod.releaseConnection();
        throw new IOException(
                "Communication error occurred during upload. \n\n" + HttpStatus.getStatusText(status));
    }
}

From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java

private PostMethod postInternal(String formUrl, Map<String, String> changed, final ITaskAttachment attach,
        IProgressMonitor monitor)//  w  w  w .  j  ava2s. c  om
        throws FogBugzClientException, HttpException, IOException, MarshalException, ValidationException {

    WebClientUtil.setupHttpClient(httpClient, proxy, formUrl, null, null);
    if (!authenticated && hasAuthenticationCredentials()) {
        monitor.subTask("Authenticating request");
        authenticate();
        if (checkMonitor(monitor))
            return null;
    }

    String requestUrl = WebClientUtil.getRequestPath(formUrl + "&token=" + token);

    ArrayList<Part> parts = new ArrayList<Part>();
    if (attach != null) {
        requestUrl += "&nFileCount=1";
        FilePart part = new FilePart("File1", new PartSource() {

            public InputStream createInputStream() throws IOException {
                return attach.createInputStream();
            }

            public String getFileName() {
                return attach.getFilename();
            }

            public long getLength() {
                return attach.getLength();
            }

        });
        part.setTransferEncoding(null);
        parts.add(part);
        parts.add(new StringPart("Content-Type", attach.getContentType()));
    }
    PostMethod postMethod = new PostMethod(requestUrl);
    // postMethod.setRequestHeader("Content-Type",
    // "application/x-www-form-urlencoded; charset="
    // + characterEncoding);

    // postMethod.setRequestBody(formData);
    postMethod.setDoAuthentication(true);

    for (String key : changed.keySet()) {
        StringPart p = new StringPart(key, changed.get(key));
        p.setTransferEncoding(null);
        p.setContentType(null);
        parts.add(p);
    }
    postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), postMethod.getParams()));

    monitor.subTask("Sending request");
    int status = httpClient.executeMethod(postMethod);
    if (status == HttpStatus.SC_OK) {
        return postMethod;
    } else {
        postMethod.getResponseBody();
        postMethod.releaseConnection();
        throw new IOException(
                "Communication error occurred during upload. \n\n" + HttpStatus.getStatusText(status));
    }
}