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:my.swingconnect.SwingConnectUI.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    {//from ww  w  .ja va  2s. c  o  m

        int i = 0;
        while (i < results.size()) {
            String path = results.get(i);
            System.out.println("Printing path" + path);
            targetFile1 = new File(path);

            //                    String targetURL = jTextField3.getSelectedItem().toString();
            //                String targetURL = jTextField3.getSelectedText();
            String targetURL = "http://photo-drop.com/uploader.php";

            //                    if (!targetURL
            //
            //                            .equals(
            //
            //                            cmbURLModel.getElementAt(
            //
            //                            cmbURL.getSelectedIndex()))) {
            //
            //                        cmbURLModel.addElement(targetURL);
            //
            //                    }

            System.out.println(targetURL);
            //From the apache package: the class that implements POST method

            PostMethod filePost = new PostMethod(targetURL);

            filePost.getParams().setBooleanParameter(

                    HttpMethodParams.USE_EXPECT_CONTINUE,

                    jCheckBox1.isSelected());
            try {

                System.out.println("Uploading " + targetFile1.getName() + " to " + targetURL);
                jTextArea2.append("Uploading " + targetFile1.getName() + " to " + targetURL);
                filename = targetFile1.toString();
                System.out.println(filename);
                javapostmethod f = new javapostmethod();
                f.sendPost(filename);

                Part[] parts = {

                        new FilePart(targetFile1.getName(), targetFile1)

                };

                filePost.setRequestEntity(

                        new MultipartRequestEntity(parts,

                                filePost.getParams())

                );

                HttpClient client = new HttpClient();

                client.getHttpConnectionManager().

                        getParams().setConnectionTimeout(5000);

                int status = client.executeMethod(filePost);
                if (status == HttpStatus.SC_OK) {
                    jTextArea2.append("Upload complete, response=" + filePost.getResponseBodyAsString());
                    jTextArea2.append("Uploaded from:" + filename);
                } else {
                    jTextArea2.append("Upload failed, response=" + HttpStatus.getStatusText(status));
                }
            } catch (Exception ex) {
                jTextArea2.append("Error: " + ex.getMessage());
                ex.printStackTrace();
            } finally {
                filePost.releaseConnection();
            }

            i++;

        }

        //

    }

}

From source file:com.apatar.ui.Actions.java

private void publishToApatar() throws HttpException, IOException {
    JPublishToApatarDialog dlg = new JPublishToApatarDialog(ApatarUiMain.MAIN_FRAME);
    dlg.setVisible(true);/*from w w w  .j av  a  2s .  c  om*/

    if (dlg.getOption() == JPublishToApatarDialog.CANCEL_OPTION) {
        return;
    }

    PostMethod method = new PostMethod(PUBLISH_TO_APATAR_URL);

    File file;
    if (dlg.isSelectFromFile()) {
        file = new File(dlg.getFilePath());
    } else {
        String tempFolderName = "tempdatamap/";
        File tempFolder = new File(tempFolderName);
        if (!tempFolder.exists()) {
            tempFolder.mkdir();
        }
        String fileName = "tempdatamap/" + dlg.getDataMapName().replaceAll("[|/\\:*?\"<> ]", "_") + ".aptr";
        ReadWriteXMLDataUi rwXMLdata = new ReadWriteXMLDataUi();
        file = rwXMLdata.writeXMLData(fileName.toString(), ApplicationData.getProject(), true);
    }

    Part[] parts = new Part[14];
    parts[0] = new StringPart("option", "com_remository");
    parts[1] = new StringPart("task", "");
    parts[1] = new StringPart("func", "savefile");
    parts[2] = new StringPart("element", "component");
    parts[3] = new StringPart("client", "");
    parts[4] = new StringPart("oldid", "0");
    parts[5] = new FilePart("userfile", file);
    parts[6] = new StringPart("containerid", "" + dlg.getDataMapLocation().getId());
    parts[7] = new StringPart("filetitle", dlg.getDataMapName());
    parts[8] = new StringPart("description", dlg.getDataMapDescription());
    parts[9] = new StringPart("smalldesc", dlg.getShortDescription());
    parts[10] = new StringPart("filetags", dlg.getTags());
    parts[11] = new StringPart("pubExternal", "true");
    parts[12] = new StringPart("username", dlg.getUserName());
    parts[13] = new StringPart("password", CoreUtils.getMD5(dlg.getPassword()));

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

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME,
                "Upload failed, response=" + HttpStatus.getStatusText(status));
    } else {
        StringBuffer buff = new StringBuffer(method.getResponseBodyAsString());

        try {
            Matcher matcher = ApatarRegExp.getMatcher("<meta name=\"apatarResponse\" content=\"[a-zA-Z_0-9]+\"",
                    buff.toString());
            boolean patternFound = false;
            while (matcher.find()) {
                patternFound = true;
                String result = matcher.group();
                result = result.replaceFirst("<meta name=\"apatarResponse\" content=\"", "");
                result = result.replace("\"", "");
                if (result.equalsIgnoreCase("done")) {
                    JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "File has been published");
                } else if (result.equalsIgnoreCase("error_xml")) {
                    JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "File is not valid");
                } else if (result.equalsIgnoreCase("error_login")) {
                    JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Name or Password is not valid");
                }
            }
            if (!patternFound) {
                JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME,
                        "Wrong response from server. Please check your connection.");
            }
        } catch (ApatarException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.sun.faban.harness.webclient.ResultAction.java

/**
 * This method is responsible for uploading the runs to repository.
 * @param uploadSet/*from w  w  w .  j  a va  2 s.  c  om*/
 * @param replaceSet
 * @return HashSet
 * @throws java.io.IOException
 */
public static HashSet<String> uploadRuns(String[] runIds, HashSet<File> uploadSet, HashSet<String> replaceSet)
        throws IOException {
    // 3. Upload the run
    HashSet<String> duplicates = new HashSet<String>();

    // Prepare run id set for cross checking.
    HashSet<String> runIdSet = new HashSet<String>(runIds.length);
    for (String runId : runIds) {
        runIdSet.add(runId);
    }

    // Prepare the parts for the request.
    ArrayList<Part> params = new ArrayList<Part>();
    params.add(new StringPart("host", Config.FABAN_HOST));
    for (String replaceId : replaceSet) {
        params.add(new StringPart("replace", replaceId));
    }
    for (File jarFile : uploadSet) {
        params.add(new FilePart("jarfile", jarFile));
    }
    Part[] parts = new Part[params.size()];
    parts = params.toArray(parts);

    // Send the request for each reposotory.
    for (URL repository : Config.repositoryURLs) {
        URL repos = new URL(repository, "/controller/uploader/upload_runs");
        PostMethod post = new PostMethod(repos.toString());
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_FORBIDDEN)
            logger.warning("Server denied permission to upload run !");
        else if (status == HttpStatus.SC_NOT_ACCEPTABLE)
            logger.warning("Run origin error!");
        else if (status != HttpStatus.SC_CREATED)
            logger.warning(
                    "Server responded with status code " + status + ". Status code 201 (SC_CREATED) expected.");
        for (File jarFile : uploadSet) {
            jarFile.delete();
        }

        String response = post.getResponseBodyAsString();

        if (status == HttpStatus.SC_CREATED) {

            StringTokenizer t = new StringTokenizer(response.trim(), "\n");
            while (t.hasMoreTokens()) {
                String duplicateRun = t.nextToken().trim();
                if (duplicateRun.length() > 0)
                    duplicates.add(duplicateRun.trim());
            }

            for (Iterator<String> iter = duplicates.iterator(); iter.hasNext();) {
                String runId = iter.next();
                if (!runIdSet.contains(runId)) {
                    logger.warning("Unexpected archive response from " + repos + ": " + runId);
                    iter.remove();
                }
            }
        } else {
            logger.warning("Message from repository: " + response);
        }
    }
    return duplicates;
}

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}
 * //from   w w w .  j av a  2  s .c o  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: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()));
    }//w ww.  j av a  2 s  .  c o m

    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:edu.umd.cs.buildServer.BuildServerDaemon.java

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

    dumpOutcomes(projectSubmission);/*ww  w.  jav  a2s. co  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.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);
            }/*  ww w . j a  va  2  s .com*/
        } 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:edu.stanford.epad.plugins.qifpwrapper.QIFPHandler.java

public static String sendRequest(String url, String epadSessionID, File dicomsZip, File dsosZip,
        String statusURL) throws Exception {
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    if (epadSessionID != null)
        postMethod.setRequestHeader("Cookie", "JSESSIONID=" + epadSessionID);
    try {/* w w  w .  j a v  a 2s  .  c om*/
        Part[] parts = { new FilePart("dicoms", dicomsZip), new FilePart("dsos", dsosZip),
                new StringPart("statusUrl", statusURL) };

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

        int response = client.executeMethod(postMethod);
        String responseStr = postMethod.getResponseBodyAsString();
        JSONObject responseJson = new JSONObject(responseStr);

        String instanceId = (String) responseJson.get("workflowInstanceID");

        if (response == HttpServletResponse.SC_OK)
            ;
        return instanceId;

    } catch (Exception e) {
        log.warning("Exception calling ePAD", e);
        return null;
    } finally {
        postMethod.releaseConnection();
    }

}

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();/* w w  w  .j av a  2  s .  co  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:edu.unc.lib.dl.fedora.ManagementClient.java

public String upload(File file, boolean retry) {
    String result = null;//from w w w  .ja v a  2s  .c o m
    String uploadURL = this.getFedoraContextUrl() + "/upload";
    PostMethod post = new PostMethod(uploadURL);
    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    log.debug("Uploading file with forwarded groups: " + GroupsThreadStore.getGroupString());
    post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());
    try {
        log.debug("Uploading to " + uploadURL);
        Part[] parts = { new FilePart("file", file) };
        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);
            }
        }

        switch (status) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_CREATED:
        case HttpStatus.SC_ACCEPTED:
            result = sw.toString().trim();
            log.info("Upload complete, response=" + result);
            break;
        case HttpStatus.SC_FORBIDDEN:
            log.warn("Authorization to Fedora failed, attempting to reestablish connection.");
            try {
                this.initializeConnections();
                return upload(file, false);
            } catch (Exception e) {
                log.error("Failed to reestablish connection to Fedora", e);
            }
            break;
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
            throw new FedoraTimeoutException("Fedora service unavailable, upload failed");
        default:
            log.warn("Upload failed, response=" + HttpStatus.getStatusText(status));
            log.debug(sw.toString().trim());
            break;
        }
    } catch (ServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ServiceException(ex);
    } finally {
        post.releaseConnection();
    }
    return result;
}