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:com.zimbra.client.ZMailbox.java

/**
 * Uploads HTTP post parts to <tt>FileUploadServlet</tt>.
 * @return the attachment id/*from   ww  w . j  av  a 2s .  co  m*/
 */
public String uploadAttachments(Part[] parts, int msTimeout) throws ServiceException {
    String aid = null;

    URI uri = getUploadURI();
    HttpClient client = getHttpClient(uri);

    // make the post
    PostMethod post = new PostMethod(uri.toString());
    post.getParams().setSoTimeout(msTimeout);

    int statusCode;
    try {
        if (mCsrfToken != null) {
            post.setRequestHeader(Constants.CSRF_TOKEN, mCsrfToken);
        }
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        statusCode = HttpClientUtil.executeMethod(client, post);

        // parse the response
        if (statusCode == HttpServletResponse.SC_OK) {
            String response = post.getResponseBodyAsString();
            aid = getAttachmentId(response);
        } else if (statusCode == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE) {
            throw ZClientException.UPLOAD_SIZE_LIMIT_EXCEEDED("upload size limit exceeded", null);
        } else {
            throw ZClientException.UPLOAD_FAILED("Attachment post failed, status=" + statusCode, null);
        }
    } catch (IOException e) {
        throw ZClientException.IO_ERROR(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
    return aid;
}

From source file:net.sourceforge.tagsea.instrumentation.network.NetworkSendJob.java

@Override
public IStatus run(IProgressMonitor monitor) {
    //      Date lastSend = InstrumentationPreferences.getLastSendDate();
    //      if (!TagSEAInstrumentationPlugin.getDefault().today().after(lastSend)) {
    //         InstrumentationPreferences.tagSendDate();
    //         return Status.OK_STATUS;
    //      }/*from   w  w w .  ja  va 2 s .com*/

    monitor.beginTask("Sending TagSEA log info", 10);
    monitor.subTask("Saving log state");
    //force a save.
    try {
        TagSEAInstrumentationPlugin.getDefault().saving(new ISaveContext() {
            public IPath[] getFiles() {
                return new IPath[0];
            }

            public int getKind() {
                return ISaveContext.FULL_SAVE;
            }

            public int getPreviousSaveNumber() {
                return 0;
            }

            public IProject getProject() {
                return null;
            }

            public int getSaveNumber() {
                return 0;
            }

            public IPath lookup(IPath file) {
                return null;
            }

            public void map(IPath file, IPath location) {
            }

            public void needDelta() {
            }

            public void needSaveNumber() {
            }
        });
    } catch (Exception e) {
        String message = "Error sending TagSEA logs" + ((e.getMessage() != null) ? ": " + e.getMessage() : "");
        InstrumentationPreferences.tagSendDate();
        return new Status(Status.ERROR, TagSEAInstrumentationPlugin.PLUGIN_ID, Status.ERROR, message, e);
    }
    monitor.worked(1);
    final File[] files = gatherFiles();
    if (files.length == 0) {
        InstrumentationPreferences.tagSendDate();
        return Status.OK_STATUS;
    }
    final Object[] result = new Object[1];
    Display.getDefault().syncExec(new Runnable() {
        public void run() {
            UploadWizard wizard = new UploadWizard(files);
            wizard.setWindowTitle("TagSEA Logs Upload");
            WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), wizard);
            dialog.open();
            result[0] = wizard.getResult();
        }
    });
    File[] compressFiles = (File[]) result[0];
    if (compressFiles == null || compressFiles.length == 0) {
        InstrumentationPreferences.tagSendDate();
        return Status.OK_STATUS;
    }

    Exception caught = null;
    //package the files.
    File file = null;
    try {
        monitor.subTask("Packaging files");
        file = compressLogs(compressFiles);
        monitor.worked(4);
        if (file != null) {
            monitor.subTask("Sending files");
            PostMethod post = new PostMethod(NetworkUtilities.UPLOAD_SCRIPT);
            int id = InstrumentationPreferences.getUID();
            Part[] parts = { new FilePart("TAGSEA" + id, file.getName(), file) };
            post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
            HttpClient client = new HttpClient();
            int status = client.executeMethod(post);
            String resp = NetworkUtilities.readInputAsString(post.getResponseBodyAsStream());
            if (status != 200) {
                IOException ex = new IOException(resp);
                throw (ex);
            }
        } else {
            monitor.done();
        }
    } catch (FileNotFoundException e) {
        caught = e;
    } catch (HttpException e) {
        caught = e;
    } catch (IOException e) {
        caught = e;
    } finally {
        InstrumentationPreferences.tagSendDate();
        monitor.done();
        if (file != null && file.exists())
            file.delete();
    }
    if (caught != null) {
        String message = "Error sending TagSEA logs";
        return new Status(Status.ERROR, TagSEAInstrumentationPlugin.PLUGIN_ID, Status.ERROR, message, caught);
    }
    return Status.OK_STATUS;
}

From source file:net.xmind.signin.internal.XMindNetRequest.java

private RequestEntity generateRequestEntity() {
    if (multipart) {
        List<Part> parts = new ArrayList<Part>(params.size());
        for (Parameter param : params) {
            if (param.value instanceof File) {
                try {
                    parts.add(new FilePart(param.name, (File) param.value));
                } catch (FileNotFoundException e) {
                }// w  w w .j a  va  2  s .c  om
            } else {
                parts.add(new StringPart(param.name, param.getValue(), "utf-8")); //$NON-NLS-1$
            }
        }
        return new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), method.getParams());
    } else {
        String query = generateQueryString();
        try {
            return new ByteArrayRequestEntity(query.getBytes("utf-8"), DEFAULT_CONTENT_TYPE); //$NON-NLS-1$
        } catch (UnsupportedEncodingException e) {
            //should not happen
        }
    }
    return null;
}

From source file:nl.nn.adapterframework.http.HttpSender.java

protected void addMultiPartToPostMethod(PostMethod hmethod, String message, ParameterValueList parameters,
        ParameterResolutionContext prc) throws SenderException {
    List<Part> partList = new ArrayList<Part>();
    if (StringUtils.isNotEmpty(getInputMessageParam())) {
        StringPart stringPart = new StringPart(getInputMessageParam(), message);
        partList.add(stringPart);//from  w  w  w  . jav  a 2  s  . c om
        if (log.isDebugEnabled())
            log.debug(getLogPrefix() + "appended stringpart [" + getInputMessageParam() + "] with value ["
                    + message + "]");
    }
    if (parameters != null) {
        for (int i = 0; i < parameters.size(); i++) {
            ParameterValue pv = parameters.getParameterValue(i);
            String paramType = pv.getDefinition().getType();
            String name = pv.getDefinition().getName();
            if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) {
                Object value = pv.getValue();
                if (value instanceof FileInputStream) {
                    FileInputStream fis = (FileInputStream) value;
                    String fileName = null;
                    String sessionKey = pv.getDefinition().getSessionKey();
                    if (sessionKey != null) {
                        fileName = (String) prc.getSession().get(sessionKey + "Name");
                    }
                    FileStreamPartSource fsps = new FileStreamPartSource(fis, fileName);
                    FilePart filePart = new FilePart(name, fsps);
                    partList.add(filePart);
                    if (log.isDebugEnabled())
                        log.debug(getLogPrefix() + "appended filepart [" + name + "] with value [" + value
                                + "] and name [" + fileName + "]");
                } else {
                    throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass()
                            + "] for parameter [" + name + "]");
                }
            } else {
                String value = pv.asStringValue("");
                StringPart stringPart = new StringPart(name, value);
                partList.add(stringPart);
                if (log.isDebugEnabled())
                    log.debug(getLogPrefix() + "appended stringpart [" + name + "] with value [" + value + "]");
            }
        }
    }
    if (StringUtils.isNotEmpty(getMultipartXmlSessionKey())) {
        String multipartXml = (String) prc.getSession().get(getMultipartXmlSessionKey());
        if (StringUtils.isEmpty(multipartXml)) {
            log.warn(getLogPrefix() + "sessionKey [" + getMultipartXmlSessionKey() + "] is empty");
        } else {
            Element partsElement;
            try {
                partsElement = XmlUtils.buildElement(multipartXml);
            } catch (DomBuilderException e) {
                throw new SenderException(getLogPrefix() + "error building multipart xml", e);
            }
            Collection parts = XmlUtils.getChildTags(partsElement, "part");
            if (parts == null || parts.size() == 0) {
                log.warn(getLogPrefix() + "no part(s) in multipart xml [" + multipartXml + "]");
            } else {
                int c = 0;
                Iterator iter = parts.iterator();
                while (iter.hasNext()) {
                    c++;
                    Element partElement = (Element) iter.next();
                    //String partType = partElement.getAttribute("type");
                    String partName = partElement.getAttribute("name");
                    String partSessionKey = partElement.getAttribute("sessionKey");
                    Object partObject = prc.getSession().get(partSessionKey);
                    if (partObject instanceof FileInputStream) {
                        FileInputStream fis = (FileInputStream) partObject;
                        FileStreamPartSource fsps = new FileStreamPartSource(fis, partName);
                        FilePart filePart = new FilePart(partSessionKey, fsps);
                        partList.add(filePart);
                        if (log.isDebugEnabled())
                            log.debug(getLogPrefix() + "appended filepart [" + partSessionKey
                                    + "]  with value [" + partObject + "] and name [" + partName + "]");
                    } else {
                        String partValue = (String) prc.getSession().get(partSessionKey);
                        StringPart stringPart = new StringPart(partSessionKey, partValue);
                        partList.add(stringPart);
                        if (log.isDebugEnabled())
                            log.debug(getLogPrefix() + "appended stringpart [" + partSessionKey
                                    + "]  with value [" + partValue + "]");
                    }
                }
            }
        }
    }
    Part[] parts = new Part[partList.size()];
    partList.toArray(parts);
    MultipartRequestEntity request = new MultipartRequestEntity(parts, hmethod.getParams());
    hmethod.setRequestEntity(request);
}

From source file:no.sws.client.SwsClient.java

private PostMethod createPostMethod(final NameValuePair[] httpParams, final String swsXml) {

    final PostMethod result = new PostMethod(this.BUTLER_PATH);

    // set the given http params on PostMethod
    result.setQueryString(httpParams);//from   ww  w.  j  a  va2 s.  c o  m

    // legger til en "fil" Dette er egentlig bare en String som ligger lagret i minne.
    ByteArrayPartSource xml;
    try {
        xml = new ByteArrayPartSource("sws.xml", swsXml.getBytes("UTF-8"));
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    final Part[] parts = { new FilePart("xml", xml, "text/xml", "UTF-8") };

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

    return result;
}

From source file:ome.formats.importer.util.FileUploader.java

/**
 * Upload files from error container to url
 *
 * @param url - url to send to/*www  .j av a2s.  c  o m*/
 * @param timeout - timeout
 * @param upload - error container with files in it
 */
public void uploadFiles(String url, int timeout, ErrorContainer upload) {
    if (client == null)
        client = new HttpClient();

    this.files = upload.getFiles();
    setSessionId(upload.getToken());

    int fileCount = 0;

    for (String f : files) {
        if (cancelUpload) {
            System.err.println(cancelUpload);
            continue;
        }

        fileCount++;
        final int count = fileCount;
        final File file = new File(f);

        try {
            HttpClientParams params = new HttpClientParams();
            params.setConnectionManagerTimeout(timeout);
            client.setParams(params);

            method = new PostMethod(url);

            String format = "";

            if (upload.getFileFormat() != null)
                format = upload.getFileFormat();
            else
                format = "unknown";

            final ErrorFilePart errorFilePart = new ErrorFilePart("Filedata", file);

            Part[] parts = { new StringPart("token", upload.getToken()), new StringPart("file_format", format),
                    errorFilePart };

            final long fileLength = file.length();

            MultipartRequestEntity mpre = new MultipartRequestEntity(parts, method.getParams());

            ProgressListener listener = new ProgressListener() {

                private long partsTotal = -1;

                /* (non-Javadoc)
                 * @see ome.formats.importer.util.FileUploadCounter.ProgressListener#update(long)
                 */
                public void update(long bytesRead) {

                    if (cancelUpload)
                        errorFilePart.cancel = true;

                    long partsDone = 0;
                    long parts = (long) Math.ceil(fileLength / 10.0f);
                    if (fileLength != 0)
                        partsDone = bytesRead / parts;

                    if (partsTotal == partsDone) {
                        return;
                    }
                    partsTotal = partsDone;

                    notifyObservers(new ImportEvent.FILE_UPLOAD_STARTED(file.getName(), count, files.length,
                            null, null, null));

                    long uploadedBytes = bytesRead / 2;
                    if (fileLength == -1) {

                        notifyObservers(new ImportEvent.FILE_UPLOAD_BYTES(file.getName(), count, files.length,
                                uploadedBytes, null, null));

                    } else {

                        notifyObservers(new ImportEvent.FILE_UPLOAD_BYTES(file.getName(), count, files.length,
                                uploadedBytes, fileLength, null));

                    }
                }
            };

            FileUploadCounter hfre = new FileUploadCounter(mpre, listener);

            method.setRequestEntity(hfre);

            int status = client.executeMethod(method);

            if (status == HttpStatus.SC_OK) {

                notifyObservers(new ImportEvent.FILE_UPLOAD_COMPLETE(file.getName(), count, files.length, null,
                        null, null));
                log.info("Uploaded file '" + file.getName() + "' to QA system");
                upload.setStatus(1);

            } else {
                notifyObservers(new ImportEvent.FILE_UPLOAD_COMPLETE(file.getName(), count, files.length, null,
                        null, null));
            }
        } catch (Exception ex) {
            notifyObservers(
                    new ImportEvent.FILE_UPLOAD_ERROR(file.getName(), count, files.length, null, null, ex));
        }
    }

    notifyObservers(new ImportEvent.FILE_UPLOAD_FINISHED(null, 0, 0, null, null, null));

}

From source file:ome.formats.importer.util.HtmlMessenger.java

/**
 * Instantiate html messenger/*from   w  ww .  j  a  v  a2  s.  com*/
 *
 * @param url
 * @param postList - variables list in post
 * @throws HtmlMessengerException
 */
public HtmlMessenger(String url, List<Part> postList) throws HtmlMessengerException {
    try {
        HostConfiguration cfg = new HostConfiguration();
        cfg.setHost(url);
        String proxyHost = System.getProperty(PROXY_HOST);
        String proxyPort = System.getProperty(PROXY_PORT);
        if (proxyHost != null && proxyPort != null) {
            int port = Integer.parseInt(proxyPort);
            cfg.setProxy(proxyHost, port);
        }

        client = new HttpClient();
        client.setHostConfiguration(cfg);
        HttpClientParams params = new HttpClientParams();
        params.setConnectionManagerTimeout(CONN_TIMEOUT);
        params.setSoTimeout(CONN_TIMEOUT);
        client.setParams(params);

        method = new PostMethod(url);

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

        int i = 0;
        for (Part part : postList) {
            parts[i] = part;
            i++;
        }

        MultipartRequestEntity mpre = new MultipartRequestEntity(parts, method.getParams());

        ProgressListener listener = new ProgressListener() {
            /* (non-Javadoc)
             * @see ome.formats.importer.util.FileUploadCounter.ProgressListener#update(long)
             */
            public void update(long bytesRead) {
            }
        };

        FileUploadCounter hfre = new FileUploadCounter(mpre, listener);

        method.setRequestEntity(hfre);

    } catch (Exception e) {
        e.printStackTrace();
        throw new HtmlMessengerException("Error creating post parameters", e);
    }

}

From source file:ome.formats.importer.util.HtmlMessenger.java

/**
 * Login to website//from   ww  w . j  av  a 2 s  .  c  o  m
 *
* @param url
* @param username
* @param password
* @return
* @throws HtmlMessengerException
*/
public String login(String url, String username, String password) throws HtmlMessengerException {
    String serverReply = "";
    Reader reader = null;

    try {
        // Execute the POST method
        PostMethod loginMethod = new PostMethod(url);

        Part[] parts = { new StringPart("username", username), new StringPart("password", password) };

        MultipartRequestEntity mpre = new MultipartRequestEntity(parts, loginMethod.getParams());

        ProgressListener listener = new ProgressListener() {
            /* (non-Javadoc)
            * @see ome.formats.importer.util.FileUploadCounter.ProgressListener#update(long)
            */
            public void update(long bytesRead) {
            }
        };

        FileUploadCounter hfre = new FileUploadCounter(mpre, listener);

        loginMethod.setRequestEntity(hfre);

        int statusCode = client.executeMethod(loginMethod);
        if (statusCode != -1) {
            reader = new InputStreamReader(loginMethod.getResponseBodyAsStream(),
                    loginMethod.getRequestCharSet());
            char[] buf = new char[32678];
            StringBuilder str = new StringBuilder();
            for (int n; (n = reader.read(buf)) != -1;)
                str.append(buf, 0, n);
            loginMethod.releaseConnection();
            serverReply = str.toString();
        }
        return serverReply;
    } catch (Exception e) {
        throw new HtmlMessengerException("Cannot Connect", e);
    } finally {
        Utils.closeQuietly(reader);
    }
}

From source file:org.activiti.rest.HttpMultipartRepresentation.java

public void processStreamAndSetMediaType(final String fileName, InputStream fileStream,
        Map<String, String> additionalFormFields) throws IOException {
    // Copy the stream in a bytearray to get the length
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    IOUtils.copy(fileStream, output);/*from  w  ww.j a  v a 2 s. c om*/

    final int length = output.toByteArray().length;
    final InputStream stream = new ByteArrayInputStream(output.toByteArray());

    List<Part> parts = new ArrayList<Part>();

    // Filepart is based on in-memory stream an file-name rather than an actual file
    FilePart filePart = new FilePart(fileName, new PartSource() {
        @Override
        public long getLength() {
            return length;
        }

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

        @Override
        public InputStream createInputStream() throws IOException {
            return stream;
        }
    });
    parts.add(filePart);

    if (additionalFormFields != null && !additionalFormFields.isEmpty()) {
        for (Entry<String, String> field : additionalFormFields.entrySet()) {
            parts.add(new StringPart(field.getKey(), field.getValue()));
        }
    }

    MultipartRequestEntity entity = new MultipartRequestEntity(parts.toArray(new Part[] {}),
            new HttpMethodParams());

    // Let the entity write the raw multipart to a bytearray, which is used as a source
    // for the input-stream returned by this Representation
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    entity.writeRequest(os);
    setMediaType(new MediaType(entity.getContentType()));
    setStream(new ByteArrayInputStream(os.toByteArray()));
}

From source file:org.alfresco.repo.publishing.slideshare.SlideShareConnectorImpl.java

public InputStream sendMultiPartMessage(String url, Map<String, String> parameters, Map<String, File> files)
        throws IOException, SlideShareErrorException {
    PostMethod method = new PostMethod(url);
    List<Part> partList = new ArrayList<Part>();
    partList.add(createStringPart("api_key", this.apiKey));
    Date now = new Date();
    String ts = Long.toString(now.getTime() / 1000);
    String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase();
    partList.add(createStringPart("ts", ts));
    partList.add(createStringPart("hash", hash));
    Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator();
    while (entryIt.hasNext()) {
        Map.Entry<String, String> entry = entryIt.next();
        partList.add(createStringPart(entry.getKey(), entry.getValue()));
    }/*www  . ja  v a2 s  . co  m*/
    Iterator<Map.Entry<String, File>> entryFileIt = files.entrySet().iterator();
    while (entryFileIt.hasNext()) {
        Map.Entry<String, File> entry = entryFileIt.next();
        partList.add(createFilePart(entry.getKey(), entry.getValue()));
    }
    MultipartRequestEntity requestEntity = new MultipartRequestEntity(
            partList.toArray(new Part[partList.size()]), method.getParams());
    method.setRequestEntity(requestEntity);
    logger.debug("Sending multipart POST message to " + method.getURI().getURI() + " with parts " + partList);
    int statusCode = httpClient.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        logger.debug("Server replied with a " + statusCode + " HTTP status code ("
                + HttpStatus.getStatusText(statusCode) + ")");
        throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode));
    }
    if (logger.isDebugEnabled()) {
        logger.debug(method.getResponseBodyAsString());
    }
    InputStream result = new ByteArrayInputStream(method.getResponseBody());
    method.releaseConnection();
    return result;
}