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

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

Introduction

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

Prototype

public ByteArrayPartSource(String paramString, byte[] paramArrayOfByte) 

Source Link

Usage

From source file:JiraWebClient.java

public void attachFile(final JiraIssue issue, final String comment, final String filename,
        final byte[] contents, final String contentType, IProgressMonitor monitor) throws JiraException {
    attachFile(issue, comment, new FilePart("filename.1", new ByteArrayPartSource(filename, contents)), //$NON-NLS-1$
            contentType, monitor);/*ww  w.  jav  a2  s  .  c om*/
}

From source file:io.fabric8.gateway.servlet.ProxyServlet.java

/**
 * Sets up the given {@link EntityEnclosingMethod} to send the same multipart
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are
 *                               configuring to send a multipart request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the mutlipart data to be sent via the {@link EntityEnclosingMethod}
 *//*from  w w  w  .  j av  a 2  s  . c o m*/
private void handleMultipartPost(EntityEnclosingMethod entityEnclosingMethod,
        HttpServletRequest httpServletRequest) throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), entityEnclosingMethod.getParams());
        entityEnclosingMethod.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        entityEnclosingMethod.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:com.intuit.tank.httpclient3.TankHttpClient3.java

private List<Part> buildParts(BaseRequest request) {
    List<Part> parts = new ArrayList<Part>();
    for (PartHolder h : TankHttpUtil.getPartsFromBody(request)) {
        if (h.getFileName() == null) {
            StringPart stringPart = new StringPart(h.getPartName(), new String(h.getBodyAsString()));
            if (h.isContentTypeSet()) {
                stringPart.setContentType(h.getContentType());
            }/*from w ww.  ja v a2 s  .c  o  m*/
            parts.add(stringPart);
        } else {
            PartSource partSource = new ByteArrayPartSource(h.getFileName(), h.getBody());
            FilePart p = new FilePart(h.getPartName(), partSource);
            if (h.isContentTypeSet()) {
                p.setContentType(h.getContentType());
            }
            parts.add(p);
        }
    }
    return parts;
}

From source file:edu.umd.cs.eclipse.courseProjectManager.TurninProjectAction.java

public void run(IAction action) {
    // TODO Refactor: Should the places where we raise a dialog and return
    // could throw an exception instead?
    String timeOfSubmission = "t" + System.currentTimeMillis();

    // Make sure we can get the workbench...
    IWorkbench workbench = PlatformUI.getWorkbench();
    if (workbench == null) {
        Dialogs.errorDialog(null, "Warning: project submission failed", "Could not submit project",
                "Internal error: Can't get workbench", IStatus.ERROR);
        return;//from w  w w  . java 2s .  c o  m
    }
    // ...and the workbenchWindow
    IWorkbenchWindow wwin = workbench.getActiveWorkbenchWindow();
    if (wwin == null) {
        Dialogs.errorDialog(null, "Error submitting project", "Could not submit project",
                "Internal error: Can't get workbench window", IStatus.ERROR);
        return;
    }

    // Shell to use as parent of dialogs.
    Shell parent = wwin.getShell();
    // Sanity check.
    if (!(selection instanceof IStructuredSelection)) {
        Dialogs.errorDialog(parent, "Warning: Selection is Invalid",
                "Invalid turnin action: You have selected an object that is not a Project. Please select a Project and try again.",
                "Object selected is not a Project", IStatus.WARNING);
        return;
    }
    IStructuredSelection structured = (IStructuredSelection) selection;
    Object obj = structured.getFirstElement();
    Debug.print("Selection object is a " + obj.getClass().getName() + " @" + System.identityHashCode(obj));
    IProject project;
    if (obj instanceof IProject) {
        project = (IProject) obj;
    } else if (obj instanceof IProjectNature) {
        project = ((IProjectNature) obj).getProject();
    } else {
        Dialogs.errorDialog(null, "Warning: Selection is Invalid",
                "Invalid turnin action: You have selected an object that is not a Project. Please select a Project and try again.",
                "Object selected is not a Project", IStatus.WARNING);
        return;
    }
    Debug.print("Got the IProject for the turnin action @" + System.identityHashCode(project));

    // ================================= save dirty editors
    // ========================================
    // save dirty editors
    try {
        if (!saveDirtyEditors(project, workbench)) {
            Dialogs.errorDialog(parent, "Submit not performed",
                    "Projects cannot be submitted unless all open files are saved",
                    "Unsaved files prevent submission", IStatus.WARNING);
            return;
        }
    } catch (CoreException e) {
        Dialogs.errorDialog(parent, "Submit not performed",
                "Could not turn on cvs management for all project files", e);
        return;
    }

    // ========================= Add all non-ignored files in the project
    // =========================
    IResource[] files;
    try {
        Set<IResource> resourceSet = getProjectResources(project);
        ArrayList<IFile> addedFiles = new ArrayList<IFile>();
        for (Iterator<IResource> iter = resourceSet.iterator(); iter.hasNext();) {
            IResource resource = iter.next();
            if (resource instanceof IFile) {
                IFile file = (IFile) resource;
                if (!AutoCVSPlugin.isCVSIgnored(file) && !AutoCVSPlugin.isCVSManaged(file)) {
                    addedFiles.add(file);
                }
            }
        }
        files = (IResource[]) addedFiles.toArray(new IResource[addedFiles.size()]);
    } catch (CoreException e) {
        Dialogs.errorDialog(parent, "Submit not performed",
                "Could not perform submit; unable to find non-ignored resources", e);
        return;
        // TODO what to do here?
    }

    // ================================= perform CVS commit
    // ========================================
    // TODO Somehow move this into the previous try block
    // This forces add/commit operations when AutoSync was shut off
    // Would it just be easier to enable autoSync and then trigger
    // a resource changed delta, since this method appears to enable
    // autoSync anyway?
    //
    String cvsStatus = "Not performed";
    try {
        cvsStatus = forceCommit(project, files);
    } catch (Exception e) {
        Dialogs.errorDialog(parent,
                "CVS commit not performed as part of submission due to unexpected exception",
                e.getClass().getName() + " " + e.getMessage(), e);
    }

    // ================================= perform CVS tag
    // ========================================
    try {
        CVSOperations.tagProject(project, timeOfSubmission, CVSOperations.SYNC);
    } catch (Exception e) {
        AutoCVSPlugin.getPlugin().getEventLog()
                .logError("Error tagging submission; submission via the web unlikely to work", e);
    }

    // ================================= find properties
    // ========================================
    // find the .submitProject file
    IResource submitProjectFile = project.findMember(AutoCVSPlugin.SUBMITPROJECT);
    if (submitProjectFile == null) {
        Dialogs.errorDialog(parent, "Warning: Project submission not enabled", "Submission is not enabled",
                "There is no " + AutoCVSPlugin.SUBMITPROJECT + " file for the project", IStatus.ERROR);
        return;
    }
    // Get the properties from the .submit file, and the .submitUser file,
    // if it exists
    // or can be fetched from the server
    Properties allSubmissionProps = null;
    try {
        allSubmissionProps = getAllProperties(timeOfSubmission, parent, project, submitProjectFile);
    } catch (IOException e) {
        String message = "IOException finding " + AutoCVSPlugin.SUBMITPROJECT + " and "
                + AutoCVSPlugin.SUBMITUSER + " files; " + cvsStatus;
        AutoCVSPlugin.getPlugin().getEventLog().logError(message, e);
        Dialogs.errorDialog(parent, "Submission failed", message, e.getMessage(), IStatus.ERROR);
        Debug.print("IOException: " + e);
        return;
    } catch (CoreException e) {
        String message = "IOException finding " + AutoCVSPlugin.SUBMITPROJECT + " and "
                + AutoCVSPlugin.SUBMITUSER + " files; " + cvsStatus;
        AutoCVSPlugin.getPlugin().getEventLog().logError(message, e);
        Dialogs.errorDialog(parent, "Submission failed", message, e.getMessage(), IStatus.ERROR);
        Debug.print("CoreException: " + e);
        return;
    }

    //
    // THE ACTUAL SUBMIT HAPPENS HERE
    //
    try {
        // ============================== find files to submit
        // ====================================
        Collection<IFile> cvsFiles = findFilesForSubmission(project);

        // ========================== assemble zip file in byte array
        // ==============================

        ByteArrayOutputStream bytes = new ByteArrayOutputStream(4096);
        ZipOutputStream zipfile = new ZipOutputStream(bytes);
        zipfile.setComment("zipfile for submission created by CourseProjectManager version "
                + AutoCVSPlugin.getPlugin().getVersion());

        try {
            byte[] buf = new byte[4096];
            for (IFile file : cvsFiles) {
                if (!file.exists()) {
                    Debug.print("Resource " + file.getName() + " being ignored because it doesn't exist");
                    continue;
                }

                ZipEntry entry = new ZipEntry(file.getProjectRelativePath().toString());
                entry.setTime(file.getModificationStamp());

                zipfile.putNextEntry(entry);
                // Copy file data to zip file
                InputStream in = file.getContents();

                try {
                    while (true) {
                        int n = in.read(buf);
                        if (n < 0)
                            break;
                        zipfile.write(buf, 0, n);
                    }
                } finally {
                    in.close();
                }
                zipfile.closeEntry();
            }
        } catch (IOException e1) {
            Dialogs.errorDialog(parent, "Warning: Project submission failed",
                    "Unable to zip files for submission\n" + cvsStatus, e1);
            return;
        } finally {
            if (zipfile != null)
                zipfile.close();
        }

        // ============================== Post to submit server
        // ====================================
        String version = System.getProperties().getProperty("java.runtime.version");
        boolean useEasyHttps = version.startsWith("1.3") || version.startsWith("1.2")
                || version.startsWith("1.4.0") || version.startsWith("1.4.1")
                || version.startsWith("1.4.2_0") && version.charAt(7) < '5';
        if (useEasyHttps) {
            String submitURL = allSubmissionProps.getProperty("submitURL");
            if (submitURL.startsWith("https"))
                submitURL = "easy" + submitURL;
            allSubmissionProps.setProperty("submitURL", submitURL);
        }
        // prepare multipart post method
        MultipartPostMethod filePost = new MultipartPostMethod(allSubmissionProps.getProperty("submitURL"));

        // add properties
        addAllPropertiesButSubmitURL(allSubmissionProps, filePost);

        // add filepart
        byte[] allInput = bytes.toByteArray();
        filePost.addPart(new FilePart("submittedFiles", new ByteArrayPartSource("submit.zip", allInput)));

        // prepare httpclient
        HttpClient client = new HttpClient();
        client.setConnectionTimeout(5000);
        int status = client.executeMethod(filePost);

        // Piggy-back uploading the launch events onto submitting.
        EclipseLaunchEventLog.postEventLogToServer(project);

        if (status == HttpStatus.SC_OK) {
            Dialogs.okDialog(parent, "Project submission successful",
                    "Project " + allSubmissionProps.getProperty("projectNumber")
                            + " was submitted successfully\n" + filePost.getResponseBodyAsString());

        } else {
            Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submission failed",
                    filePost.getStatusText() + "\n " + cvsStatus, IStatus.CANCEL);
            AutoCVSPlugin.getPlugin().getEventLog().logMessage(filePost.getResponseBodyAsString());
        }

    } catch (CoreException e) {
        Dialogs.errorDialog(parent, "Warning: Project submission failed",
                "Project submissions via https failed\n" + cvsStatus, e);
    } catch (HttpConnection.ConnectionTimeoutException e) {
        Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submissions failed",
                "Connection timeout while trying to connect to submit server\n " + cvsStatus, IStatus.ERROR);
    } catch (IOException e) {
        Dialogs.errorDialog(parent, "Warning: Project submission failed",
                "Project submissions failed\n " + cvsStatus, e);
    }
}

From source file:it.geosolutions.httpproxy.HTTPProxy.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST data as was sent in the given {@link HttpServletRequest}
 * //  www  .  ja va 2 s.co  m
 * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a multipart POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains the mutlipart POST data to be sent via the {@link PostMethod}
 */
private void handleMultipart(EntityEnclosingMethod methodProxyRequest, HttpServletRequest httpServletRequest)
        throws ServletException {

    // ////////////////////////////////////////////
    // Create a factory for disk-based file items
    // ////////////////////////////////////////////

    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

    // /////////////////////////////
    // Set factory constraints
    // /////////////////////////////

    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(Utils.DEFAULT_FILE_UPLOAD_TEMP_DIRECTORY);

    // //////////////////////////////////
    // Create a new file upload handler
    // //////////////////////////////////

    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

    // //////////////////////////
    // Parse the request
    // //////////////////////////

    try {

        // /////////////////////////////////////
        // Get the multipart items as a list
        // /////////////////////////////////////

        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);

        // /////////////////////////////////////////
        // Create a list to hold all of the parts
        // /////////////////////////////////////////

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

        // /////////////////////////////////////////
        // Iterate the multipart items list
        // /////////////////////////////////////////

        for (FileItem fileItemCurrent : listFileItems) {

            // //////////////////////////////////////
            // If the current item is a form field,
            // then create a string part
            // //////////////////////////////////////

            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(
                        // The field name
                        fileItemCurrent.getFieldName(),
                        // The field value
                        fileItemCurrent.getString());

                // ////////////////////////////
                // Add the part to the list
                // ////////////////////////////

                listParts.add(stringPart);

            } else {

                // /////////////////////////////////////////////////////
                // The item is a file upload, so we create a FilePart
                // /////////////////////////////////////////////////////

                FilePart filePart = new FilePart(

                        // /////////////////////
                        // The field name
                        // /////////////////////

                        fileItemCurrent.getFieldName(),

                        new ByteArrayPartSource(
                                // The uploaded file name
                                fileItemCurrent.getName(),
                                // The uploaded file contents
                                fileItemCurrent.get()));

                // /////////////////////////////
                // Add the part to the list
                // /////////////////////////////

                listParts.add(filePart);
            }
        }

        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), methodProxyRequest.getParams());

        methodProxyRequest.setRequestEntity(multipartRequestEntity);

        // ////////////////////////////////////////////////////////////////////////
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        // ////////////////////////////////////////////////////////////////////////

        methodProxyRequest.setRequestHeader(Utils.CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());

    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:edu.umd.cs.buildServer.BuildServerDaemon.java

@Override
protected void reportTestResults(ProjectSubmission<?> projectSubmission)
        throws MissingConfigurationPropertyException {

    dumpOutcomes(projectSubmission);/*w ww  . j a  v  a  2 s.  c  o  m*/

    getLog().info("Test outcome collection for " + projectSubmission.getSubmissionPK() + " for test setup "
            + projectSubmission.getTestSetupPK() + " contains "
            + projectSubmission.getTestOutcomeCollection().size() + " entries");

    // Format the test outcome collection as bytes in memory
    ByteArrayOutputStream sink = new ByteArrayOutputStream();
    ObjectOutputStream out = null;
    try {
        out = new ObjectOutputStream(sink);
    } catch (IOException ignore) {
        getLog().error("IOException creating ObjectOutputStream");
    }

    TestOutcomeCollection c = projectSubmission.getTestOutcomeCollection();

    // Print some info about the size of the collection
    getLog().info("Got TestOutcomeCollection; size: " + c.size());
    for (TestOutcome to : c.getAllOutcomes()) {
        // Truncate to avoid OutOfMemories
        to.truncateLongTestResult();
        // Most important size to print is the longResult len - it
        // can be really long
        int length = to.getLongTestResult().length();
        getLog().info("  Outcome " + to.getTestNumber() + ": " + to.getTestName() + " = " + to.getOutcome()
                + (length > 0 ? ", longResult len: " + length : ""));

    }

    try {
        c.write(out);
    } catch (IOException ignore) {
        getLog().error("IOException writing to ObjectOutputStream", ignore);
    } catch (Error e) {
        // Can happen if the long test output is really long; we
        // truncate down to 64K (also the limit imposed by the
        // MySQL 'text' type) in order to avoid this, but we should
        // note it.
        getLog().error("While writing, caught Error", e);
        getLog().error("Rethrowing...");
        throw (e);
    }

    try {
        out.close();
    } catch (IOException ignore) {
        getLog().error("IOException closing ObjectOutputStream");
    }

    byte[] testOutcomeData = sink.toByteArray();
    String subPK = projectSubmission.getSubmissionPK();
    String jarfilePK = projectSubmission.getTestSetupPK();
    int outcomes = projectSubmission.getTestOutcomeCollection().size();
    getLog().info("Test data for submission " + subPK + " for test setup " + jarfilePK + " contains "
            + testOutcomeData.length + " bytes from " + outcomes + " test outcomes");

    String hostname = getBuildServerConfiguration().getHostname();

    MultipartPostMethod method = new MultipartPostMethod(getReportTestResultsURL());

    method.addParameter("submissionPK", projectSubmission.getSubmissionPK());
    method.addParameter("testSetupPK", projectSubmission.getTestSetupPK());
    method.addParameter("projectJarfilePK", projectSubmission.getTestSetupPK());
    method.addParameter("newTestSetup", projectSubmission.getIsNewTestSetup());

    method.addParameter("newProjectJarfile", projectSubmission.getIsNewTestSetup());
    method.addParameter("isBackgroundRetest", projectSubmission.getIsBackgroundRetest());
    method.addParameter("testMachine", hostname);
    method.addParameter("testDurationsMillis", Long.toString(projectSubmission.getTestDurationMillis()));

    addCommonParameters(method);

    method.addParameter("kind", projectSubmission.getKind());

    // CodeMetrics
    if (projectSubmission.getCodeMetrics() != null) {
        getLog().debug("Code Metrics: " + projectSubmission.getCodeMetrics());
        projectSubmission.getCodeMetrics().mapIntoHttpHeader(method);
    }
    method.addPart(new FilePart("testResults", new ByteArrayPartSource("testresults.out", testOutcomeData)));
    printURI(method);

    try {
        getLog().debug("Submitting test results for " + projectSubmission.getSubmissionPK() + "...");

        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK)
            getLog().debug("Done submitting test results for submissionPK "
                    + projectSubmission.getSubmissionPK() + "; statusCode=" + statusCode);
        else {

            getLog().error("Error submitting test results for submissionPK "
                    + projectSubmission.getSubmissionPK() + ": " + statusCode + ": " + method.getStatusText());
            getLog().error(method.getResponseBodyAsString());
            // TODO: Should we do anything else in case of an error?
        }
    } catch (HttpException e) {
        getLog().error("Internal error: HttpException submitting test results", e);
        return;
    } catch (IOException e) {
        getLog().error("Internal error: IOException submitting test results", e);
        return;
    } finally {
        getLog().trace("Releasing connection...");
        method.releaseConnection();
        getLog().trace("Done releasing connection");
    }
}

From source file:com.ning.http.client.providers.NettyAsyncHttpProvider.java

/**
 * This is quite ugly has the code is coming from the HTTPClient.
 *
 * @param params/*from   w w w.  ja va  2s .  c  om*/
 * @param methodParams
 * @return
 * @throws java.io.FileNotFoundException
 */
private MultipartRequestEntity createMultipartRequestEntity(List<Part> params, HttpMethodParams methodParams)
        throws FileNotFoundException {
    org.apache.commons.httpclient.methods.multipart.Part[] parts = new org.apache.commons.httpclient.methods.multipart.Part[params
            .size()];
    int i = 0;

    for (Part part : params) {
        if (part instanceof StringPart) {
            parts[i] = new org.apache.commons.httpclient.methods.multipart.StringPart(part.getName(),
                    ((StringPart) part).getValue(), "UTF-8");
        } else if (part instanceof FilePart) {
            parts[i] = new org.apache.commons.httpclient.methods.multipart.FilePart(part.getName(),
                    ((FilePart) part).getFile(), ((FilePart) part).getMimeType(),
                    ((FilePart) part).getCharSet());

        } else if (part instanceof ByteArrayPart) {
            PartSource source = new ByteArrayPartSource(((ByteArrayPart) part).getFileName(),
                    ((ByteArrayPart) part).getData());
            parts[i] = new org.apache.commons.httpclient.methods.multipart.FilePart(part.getName(), source,
                    ((ByteArrayPart) part).getMimeType(), ((ByteArrayPart) part).getCharSet());

        } else if (part == null) {
            throw new NullPointerException("Part cannot be null");
        } else {
            throw new IllegalArgumentException(
                    String.format("Unsupported part type for multipart parameter %s", part.getName()));
        }
        ++i;
    }
    return new MultipartRequestEntity(parts, methodParams);
}

From source file:com.liferay.portal.util.HttpImpl.java

protected org.apache.commons.httpclient.methods.multipart.FilePart toCommonsFilePart(Http.FilePart filePart) {

    return new org.apache.commons.httpclient.methods.multipart.FilePart(filePart.getName(),
            new ByteArrayPartSource(filePart.getFileName(), filePart.getValue()), filePart.getContentType(),
            filePart.getCharSet());/*from w  ww.  j av a  2 s . c o  m*/
}

From source file:edu.unc.lib.dl.fedora.ManagementClient.java

public String upload(byte[] bytes, String fileName) {
    String result = null;// www.j  a v a  2  s . c o  m
    // construct a post request to Fedora upload service
    String uploadURL = this.getFedoraContextUrl() + "/upload";
    PostMethod post = new PostMethod(uploadURL);
    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    log.debug("Uploading XML with forwarded groups: " + GroupsThreadStore.getGroupString());
    post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());
    try {
        log.debug("Uploading to " + uploadURL);
        Part[] parts = { new FilePart("file", new ByteArrayPartSource(fileName, bytes)) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        int status = httpClient.executeMethod(post);

        StringWriter sw = new StringWriter();
        try (InputStream in = post.getResponseBodyAsStream(); PrintWriter pw = new PrintWriter(sw)) {
            int b;
            while ((b = in.read()) != -1) {
                pw.write(b);
            }
        }
        if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_ACCEPTED) {
            result = sw.toString().trim();
            log.debug("Upload complete, response=" + result);
        } else {
            log.warn("Upload failed, response=" + HttpStatus.getStatusText(status));
            log.debug(sw.toString().trim());
        }
    } catch (Exception ex) {
        log.error("Upload failed due to error", ex);
        throw new ServiceException(ex);
    } finally {
        post.releaseConnection();
    }
    return result;
}

From source file:com.ning.http.client.providers.apache.ApacheAsyncHttpProvider.java

private MultipartRequestEntity createMultipartRequestEntity(String charset, List<Part> params,
        HttpMethodParams methodParams) throws FileNotFoundException {
    org.apache.commons.httpclient.methods.multipart.Part[] parts = new org.apache.commons.httpclient.methods.multipart.Part[params
            .size()];//  w w  w.  java  2s .co m
    int i = 0;

    for (Part part : params) {
        if (part instanceof StringPart) {
            parts[i] = new org.apache.commons.httpclient.methods.multipart.StringPart(part.getName(),
                    ((StringPart) part).getValue(), charset);
        } else if (part instanceof FilePart) {
            parts[i] = new org.apache.commons.httpclient.methods.multipart.FilePart(part.getName(),
                    ((FilePart) part).getFile(), ((FilePart) part).getMimeType(),
                    ((FilePart) part).getCharSet());

        } else if (part instanceof ByteArrayPart) {
            PartSource source = new ByteArrayPartSource(((ByteArrayPart) part).getFileName(),
                    ((ByteArrayPart) part).getData());
            parts[i] = new org.apache.commons.httpclient.methods.multipart.FilePart(part.getName(), source,
                    ((ByteArrayPart) part).getMimeType(), ((ByteArrayPart) part).getCharSet());

        } else if (part == null) {
            throw new NullPointerException("Part cannot be null");
        } else {
            throw new IllegalArgumentException(
                    String.format("Unsupported part type for multipart parameter %s", part.getName()));
        }
        ++i;
    }
    return new MultipartRequestEntity(parts, methodParams);
}