Example usage for java.io ByteArrayOutputStream size

List of usage examples for java.io ByteArrayOutputStream size

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream size.

Prototype

public synchronized int size() 

Source Link

Document

Returns the current size of the buffer.

Usage

From source file:org.kuali.kfs.module.purap.document.web.struts.PrintAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    //get parameters
    String poDocNumber = request.getParameter("poDocNumber");
    Integer vendorQuoteId = new Integer(request.getParameter("vendorQuoteId"));
    if (StringUtils.isEmpty(poDocNumber) || StringUtils.isEmpty(poDocNumber)) {
        throw new RuntimeException();
    }/* w w w .  j  a v  a  2 s.com*/

    // doc service - get this doc
    PurchaseOrderDocument po = (PurchaseOrderDocument) SpringContext.getBean(DocumentService.class)
            .getByDocumentHeaderId(poDocNumber);
    DocumentAuthorizer documentAuthorizer = SpringContext.getBean(DocumentHelperService.class)
            .getDocumentAuthorizer(po);

    if (!(documentAuthorizer.canInitiate(KFSConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER,
            GlobalVariables.getUserSession().getPerson())
            || documentAuthorizer.canInitiate(
                    KFSConstants.FinancialDocumentTypeCodes.CONTRACT_MANAGER_ASSIGNMENT,
                    GlobalVariables.getUserSession().getPerson()))) {
        throw new DocumentInitiationException(KFSKeyConstants.AUTHORIZATION_ERROR_DOCUMENT, new String[] {
                GlobalVariables.getUserSession().getPerson().getPrincipalName(), "print", "Purchase Order" });
    }

    // get the vendor quote
    PurchaseOrderVendorQuote poVendorQuote = null;
    for (PurchaseOrderVendorQuote vendorQuote : po.getPurchaseOrderVendorQuotes()) {
        if (vendorQuote.getPurchaseOrderVendorQuoteIdentifier().equals(vendorQuoteId)) {
            poVendorQuote = vendorQuote;
            break;
        }
    }

    if (poVendorQuote == null) {
        throw new RuntimeException();
    }

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    poVendorQuote.setTransmitPrintDisplayed(false);
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_QUOTE_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        // call the print service
        boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po,
                poVendorQuote, baosPDF);

        if (!success) {
            poVendorQuote.setTransmitPrintDisplayed(true);
            if (baosPDF != null) {
                baosPDF.reset();
            }
            return mapping.findForward(KFSConstants.MAPPING_BASIC);
        }
        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        // sbContentDispValue.append("inline");
        sbContentDispValue.append("attachment");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:ch.admin.hermes.etl.load.cmis.AlfrescoCMISClient.java

/**
 * Laedt eine Datei von http://www.hermes.admin.ch in Alfresco hoch.
 * @param parentId Parent Id/* ww  w  .ja  v  a2 s  .  co m*/
 * @param name Name
 * @param properties Eigenschaften
 * @param localname Lokaler Name wenn Datei oder URL wenn von http://www.hermes.admin.ch
 * @return neu erstelles Dokument
 * @throws Exception Allgemeiner I/O Fehler
 */
private Document postFile(String parentId, String name, HashMap<String, Object> properties, URL url)
        throws IOException, URISyntaxException {
    Folder parent = (Folder) session.getObject(parentId, session.getDefaultContext());

    // Dokument von http://www.hermes.admin.ch holen
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (url != null) {
        HttpGet req = new HttpGet(url.toURI());
        req.addHeader("Accept", "application/json;odata=verbose;charset=utf-8");
        req.addHeader("Content-Type", "application/octet-stream");

        HttpResponse resp = client.execute(req);
        checkError(resp, url.toString());

        byte buf[] = new byte[128 * 32768];
        InputStream inp = resp.getEntity().getContent();
        for (int length; (length = inp.read(buf, 0, buf.length)) > 0;)
            out.write(buf, 0, length);
        out.close();

        EntityUtils.consume(resp.getEntity());
    }
    String mimeType = mimeTypesMap.getContentType(url.getFile());
    if (properties == null)
        properties = new HashMap<String, Object>();

    properties.put("cmis:name", name);
    // This works because we are using the OpenCMIS extension for Alfresco
    properties.put("cmis:objectTypeId", "cmis:document,P:cm:titled");

    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    ContentStream contentStream = new ContentStreamImpl(name, BigInteger.valueOf(out.size()), mimeType, in);
    properties.put(PropertyIds.CONTENT_STREAM_FILE_NAME, name);
    properties.put(PropertyIds.CONTENT_STREAM_LENGTH, out.size());
    properties.put(PropertyIds.CONTENT_STREAM_MIME_TYPE, mimeType);

    Document doc = parent.createDocument(properties, contentStream, VersioningState.MAJOR);
    in.close();
    return (doc);
}

From source file:org.commoncrawl.util.CompressedURLFPListV2.java

public static void validateURLFPSerializationSingleSubDomain() {

    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    Builder firstBuilder = new Builder(FLAG_ARCHIVE_SEGMENT_ID);

    TreeMultimap<Long, URLFPV2> sourceMap = TreeMultimap.create();
    TreeMultimap<Long, URLFPV2> destMap = TreeMultimap.create();
    ;//from  w  ww .j  a v a  2 s.c  o  m

    // single top level domain with one sub domain an two urls
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "0", 1);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_2 + "1", 1);

    // single top level domain with one sub domain an two urls
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "2", 1);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_2 + "3", 1);

    // single top level domain with one sub domain an two urls
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "4", 1);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_2 + "5", 1);

    // single top level domain with one sub domain an two urls
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "6", 1);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_2 + "7", 1);

    // single top level domain with one sub domain an two urls
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "8", 1);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_2 + "9", 1);

    addMapToBuilder(firstBuilder, sourceMap);

    try {
        // flush to byte stream ...
        firstBuilder.flush(byteStream);
        // now set up to read the stream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(byteStream.toByteArray(), 0,
                byteStream.size());
        Reader reader = new Reader(inputStream);

        while (reader.hasNext()) {
            URLFPV2 fp = reader.next();
            destMap.put(fp.getRootDomainHash(), fp);
        }
        reader.close();

        // dump both lists
        for (long rootDomain : sourceMap.keySet()) {
            for (URLFPV2 URLFPV2 : sourceMap.get(rootDomain)) {
                System.out.println("SourceFP Root:" + URLFPV2.getRootDomainHash() + " Domain:"
                        + URLFPV2.getDomainHash() + " URL:" + URLFPV2.getUrlHash());
            }
        }
        for (long rootDomain : destMap.keySet()) {
            for (URLFPV2 URLFPV2 : destMap.get(rootDomain)) {
                System.out.println("DestFP Root:" + URLFPV2.getRootDomainHash() + " Domain:"
                        + URLFPV2.getDomainHash() + " URL:" + URLFPV2.getUrlHash());
            }
        }

        Assert.assertTrue(sourceMap.equals(destMap));

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.emc.esu.api.rest.AbstractEsuRestApi.java

protected byte[] readStream(InputStream in, int contentLength) throws IOException {
    try {// ww w . j  av  a 2  s.  co  m
        byte[] output;
        // If we know the content length, read it directly into a buffer.
        if (contentLength != -1) {
            output = new byte[contentLength];

            int c = 0;
            while (c < contentLength) {
                int read = in.read(output, c, contentLength - c);
                if (read == -1) {
                    // EOF!
                    throw new EOFException(
                            "EOF reading response at position " + c + " size " + (contentLength - c));
                }
                c += read;
            }

            return output;
        } else {
            l4j.debug("Content length is unknown.  Buffering output.");
            // Else, use a ByteArrayOutputStream to collect the response.
            byte[] buffer = new byte[4096];

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int c = 0;
            while ((c = in.read(buffer)) != -1) {
                baos.write(buffer, 0, c);
            }
            baos.close();

            l4j.debug("Buffered " + baos.size() + " response bytes");

            return baos.toByteArray();
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }

}

From source file:org.kuali.kfs.module.purap.document.web.struts.BulkReceivingAction.java

public ActionForward printReceivingTicket(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String blkDocId = request.getParameter("docId");
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();

    try {// w w w  .j av  a  2  s. c o  m
        // will throw validation exception if errors occur
        SpringContext.getBean(BulkReceivingService.class).performPrintReceivingTicketPDF(blkDocId, baosPDF);

        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        String useJavascript = request.getParameter("useJavascript");
        if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
            sbContentDispValue.append("attachment");
        } else {
            sbContentDispValue.append("inline");
        }
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_RECEIVING_TICKET_");
        sbFilename.append(blkDocId);
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos = response.getOutputStream();
        baosPDF.writeTo(sos);
        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:org.alder.fotobuchconvert.ifolor.Decryptor.java

private byte[] loadCompressedBinaryData(InputStream is) throws IOException, UnsupportedEncodingException {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buffer = new byte[4096];

    int bytesRead;
    // load md5 sum
    MessageDigest md;/*from   w  w w .ja v  a  2s . c  om*/
    try {
        md = MessageDigest.getInstance(DIGEST_MD52);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    byte[] md5 = new byte[md.getDigestLength()];
    bytesRead = is.read(md5, 0, md5.length);
    if (bytesRead != md.getDigestLength())
        throw new IOException(UNEXPECTED_END_OF_FILE);

    // load size
    bytesRead = is.read(buffer, 0, 4);
    if (bytesRead != 4)
        throw new IOException(UNEXPECTED_END_OF_FILE);
    int dataSize = (((int) buffer[3] & 0xFF) << 24) | (((int) buffer[2] & 0xFF) << 16)
            | (((int) buffer[1] & 0xFF) << 8) | ((int) buffer[0] & 0xFF);
    log.debug("uncompressed file size: " + dataSize);

    GZIPInputStream gzipIs = new GZIPInputStream(is);
    while ((bytesRead = gzipIs.read(buffer)) != -1) {
        md.update(buffer, 0, bytesRead);
        output.write(buffer, 0, bytesRead);
        if (dumpData)
            System.out.print(new String(buffer, 0, bytesRead, CHARSET_cp1252));
    }
    if (dumpData)
        System.out.println();

    buffer = md.digest();
    for (int i = 0; i < buffer.length; i++)
        if (buffer[i] != md5[i])
            throw new IOException("MD5 mismatch");

    if (output.size() != dataSize)
        throw new IOException(String.format("File size mismatch: %d instead of %d", output.size(), dataSize));

    log.debug("MD5 ok");

    return output.toByteArray();
}

From source file:org.dbgl.gui.AddGameWizardDialog.java

protected void doReloadTemplate(int templateIndex) {
    try {// w  w w .  j a  va2  s  . c o m
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bos);

        Conf templateConf = new Conf(templatesList.get(templateIndex), profile.getConf().getDbversion(), ps);
        profile.getConf().reloadTemplate(templateConf);

        selectSettingsByConfiguration(profile.getConf());
        profile.setNativeCommandsList(
                dbase.readNativeCommandsList(-1, templatesList.get(templateIndex).getId()));

        if (bos.size() > 0) {
            GeneralPurposeDialogs.warningMessage(getParent(), bos.toString());
            bos.reset();
        }
    } catch (IOException | SQLException e) {
        GeneralPurposeDialogs.warningMessage(getParent(), e);
    }
}

From source file:org.openlmis.report.exporter.JasperReportExporter.java

/**
 *
 * @param jasperPrint//  w  ww  .ja  va 2 s  .co m
 * @param response
 * @param byteArrayOutputStream
 * @return
 */
public HttpServletResponse exportXls(JasperPrint jasperPrint, String outputFileName,
        HttpServletResponse response, ByteArrayOutputStream byteArrayOutputStream) {

    JRXlsExporter exporter = new JRXlsExporter();

    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, byteArrayOutputStream);

    exporter.setParameter(JRXlsAbstractExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
    exporter.setParameter(JRXlsAbstractExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
    exporter.setParameter(JRXlsAbstractExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS, Boolean.TRUE);
    exporter.setParameter(JRXlsAbstractExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
    exporter.setParameter(JRXlsExporterParameter.IS_IGNORE_GRAPHICS, Boolean.FALSE);
    exporter.setParameter(JRXlsAbstractExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);

    try {
        exporter.exportReport();

    } catch (JRException e) {
        throw new RuntimeException(e);
    }

    String fileName = outputFileName.isEmpty() ? "openlmisReport.xls" : outputFileName + ".xls";
    response.setHeader(CONTENT_DISPOSITION, INLINE_FILENAME + fileName);

    response.setContentType(Constants.MEDIA_TYPE_EXCEL);
    response.setContentLength(byteArrayOutputStream.size());

    return response;
}

From source file:org.jets3t.service.impl.soap.axis.SoapS3Service.java

protected S3Object putObjectImpl(String bucketName, S3Object object) throws S3ServiceException {
    if (log.isDebugEnabled()) {
        log.debug("Creating Object with key " + object.getKey() + " in bucket " + bucketName);
    }//from   ww  w  .  ja  v a2s.  c o m

    Grant[] grants = null;
    if (object.getAcl() != null) {
        grants = convertACLtoGrants(object.getAcl());
    }
    MetadataEntry[] metadata = convertMetadata(object.getMetadataMap());

    try {
        AmazonS3SoapBindingStub s3SoapBinding = getSoapBinding();
        long contentLength = object.getContentLength();
        String contentType = object.getContentType();
        if (contentType == null) {
            // Set default content type.
            contentType = Mimetypes.MIMETYPE_OCTET_STREAM;
        }

        if (object.getDataInputStream() != null) {
            if (log.isDebugEnabled()) {
                log.debug("Uploading data input stream for S3Object: " + object.getKey());
            }

            if (contentLength == 0 && object.getDataInputStream().available() > 0) {

                if (log.isWarnEnabled()) {
                    log.warn("S3Object " + object.getKey()
                            + " - Content-Length was set to 0 despite having a non-empty data"
                            + " input stream. The Content-length will be determined in memory.");
                }

                // Read all data into memory to determine it's length.
                BufferedInputStream bis = new BufferedInputStream(object.getDataInputStream());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedOutputStream bos = new BufferedOutputStream(baos);
                try {
                    byte[] buffer = new byte[8192];
                    int read = -1;
                    while ((read = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, read);
                    }
                } finally {
                    if (bis != null) {
                        bis.close();
                    }
                    if (bos != null) {
                        bos.close();
                    }
                }

                contentLength = baos.size();
                object.setDataInputStream(new ByteArrayInputStream(baos.toByteArray()));

                if (log.isDebugEnabled()) {
                    log.debug("Content-Length value has been reset to " + contentLength);
                }
            }

            DataHandler dataHandler = new DataHandler(
                    new SourceDataSource(null, contentType, new StreamSource(object.getDataInputStream())));
            s3SoapBinding.addAttachment(dataHandler);
        } else {
            DataHandler dataHandler = new DataHandler(
                    new SourceDataSource(null, contentType, new StreamSource()));
            s3SoapBinding.addAttachment(dataHandler);
        }

        Calendar timestamp = getTimeStamp(System.currentTimeMillis());
        String signature = ServiceUtils.signWithHmacSha1(getAWSSecretKey(),
                Constants.SOAP_SERVICE_NAME + "PutObject" + convertDateToString(timestamp));
        PutObjectResult result = s3SoapBinding.putObject(bucketName, object.getKey(), metadata, contentLength,
                grants, null, getAWSAccessKey(), timestamp, signature, null);

        // Ensure no data was corrupted, if we have the MD5 hash available to check.
        String eTag = result.getETag().substring(1, result.getETag().length() - 1);
        String eTagAsBase64 = ServiceUtils.toBase64(ServiceUtils.fromHex(eTag));
        String md5HashAsBase64 = object.getMd5HashAsBase64();
        if (md5HashAsBase64 != null && !eTagAsBase64.equals(md5HashAsBase64)) {
            throw new S3ServiceException(
                    "Object created but ETag returned by S3 does not match MD5 hash value of object");
        }

        object.setETag(result.getETag());
        object.setContentLength(contentLength);
        object.setContentType(contentType);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new S3ServiceException("Unable to Create Object: " + object.getKey(), e);
    }
    return object;
}

From source file:com.eucalyptus.blockstorage.S3SnapshotTransfer.java

/**
 * Compresses the snapshot and uploads it to a bucket in objectstorage gateway as a single or multipart upload based on the configuration in
 * {@link StorageInfo}. Bucket name should be configured before invoking this method. It can be looked up and initialized by {@link #prepareForUpload()} or
 * explicitly set using {@link #setBucketName(String)}
 * // w w  w  .  j  a va 2  s .co m
 * @param sourceFileName
 *            absolute path to the snapshot on the file system
 */
@Override
public void upload(String sourceFileName) throws SnapshotTransferException {
    validateInput(); // Validate input
    loadTransferConfig(); // Load the transfer configuration parameters from database
    SnapshotProgressCallback progressCallback = new SnapshotProgressCallback(snapshotId); // Setup the progress callback

    Boolean error = Boolean.FALSE;
    ArrayBlockingQueue<SnapshotPart> partQueue = null;
    SnapshotPart part = null;
    SnapshotUploadInfo snapUploadInfo = null;
    Future<List<PartETag>> uploadPartsFuture = null;
    Future<String> completeUploadFuture = null;

    byte[] buffer = new byte[READ_BUFFER_SIZE];
    Long readOffset = 0L;
    Long bytesRead = 0L;
    Long bytesWritten = 0L;
    int len;
    int partNumber = 1;

    try {
        // Get the uncompressed file size for uploading as metadata
        Long uncompressedSize = getFileSize(sourceFileName);

        // Setup the snapshot and part entities.
        snapUploadInfo = SnapshotUploadInfo.create(snapshotId, bucketName, keyName);
        Path zipFilePath = Files.createTempFile(keyName + '-', '-' + String.valueOf(partNumber));
        part = SnapshotPart.createPart(snapUploadInfo, zipFilePath.toString(), partNumber, readOffset);

        FileInputStream inputStream = new FileInputStream(sourceFileName);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gzipStream = new GZIPOutputStream(baos);
        FileOutputStream outputStream = new FileOutputStream(zipFilePath.toString());

        try {
            LOG.debug("Reading snapshot " + snapshotId + " and compressing it to disk in chunks of size "
                    + partSize + " bytes or greater");
            while ((len = inputStream.read(buffer)) > 0) {
                bytesRead += len;
                gzipStream.write(buffer, 0, len);

                if ((bytesWritten + baos.size()) < partSize) {
                    baos.writeTo(outputStream);
                    bytesWritten += baos.size();
                    baos.reset();
                } else {
                    gzipStream.close();
                    baos.writeTo(outputStream); // Order is important. Closing the gzip stream flushes stuff
                    bytesWritten += baos.size();
                    baos.reset();
                    outputStream.close();

                    if (partNumber > 1) {// Update the part status
                        part = part.updateStateCreated(bytesWritten, bytesRead, Boolean.FALSE);
                    } else {// Initialize multipart upload only once after the first part is created
                        LOG.info("Uploading snapshot " + snapshotId
                                + " to objectstorage using multipart upload");
                        progressCallback.setUploadSize(uncompressedSize);
                        uploadId = initiateMulitpartUpload(uncompressedSize);
                        snapUploadInfo = snapUploadInfo.updateUploadId(uploadId);
                        part = part.updateStateCreated(uploadId, bytesWritten, bytesRead, Boolean.FALSE);
                        partQueue = new ArrayBlockingQueue<SnapshotPart>(queueSize);
                        uploadPartsFuture = Threads.enqueue(serviceConfig, UploadPartTask.class, poolSize,
                                new UploadPartTask(partQueue, progressCallback));
                    }

                    // Check for the future task before adding part to the queue.
                    if (uploadPartsFuture != null && uploadPartsFuture.isDone()) {
                        // This task shouldn't be done until the last part is added. If it is done at this point, then something might have gone wrong
                        throw new SnapshotUploadPartException(
                                "Error uploading parts, aborting part creation process. Check previous log messages for the exact error");
                    }

                    // Add part to the queue
                    partQueue.put(part);

                    // Prep the metadata for the next part
                    readOffset += bytesRead;
                    bytesRead = 0L;
                    bytesWritten = 0L;

                    // Setup the part entity for next part
                    zipFilePath = Files.createTempFile(keyName + '-', '-' + String.valueOf((++partNumber)));
                    part = SnapshotPart.createPart(snapUploadInfo, zipFilePath.toString(), partNumber,
                            readOffset);

                    gzipStream = new GZIPOutputStream(baos);
                    outputStream = new FileOutputStream(zipFilePath.toString());
                }
            }

            gzipStream.close();
            baos.writeTo(outputStream);
            bytesWritten += baos.size();
            baos.reset();
            outputStream.close();
            inputStream.close();

            // Update the part status
            part = part.updateStateCreated(bytesWritten, bytesRead, Boolean.TRUE);

            // Update the snapshot upload info status
            snapUploadInfo = snapUploadInfo.updateStateCreatedParts(partNumber);
        } catch (Exception e) {
            LOG.error("Failed to upload " + snapshotId + " due to: ", e);
            error = Boolean.TRUE;
            throw new SnapshotTransferException("Failed to upload " + snapshotId + " due to: ", e);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (gzipStream != null) {
                gzipStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            baos.reset();
        }

        if (partNumber > 1) {
            // Check for the future task before adding the last part to the queue.
            if (uploadPartsFuture != null && uploadPartsFuture.isDone()) {
                // This task shouldn't be done until the last part is added. If it is done at this point, then something might have gone wrong
                throw new SnapshotUploadPartException(
                        "Error uploading parts, aborting part upload process. Check previous log messages for the exact error");
            }
            // Add the last part to the queue
            partQueue.put(part);
            // Kick off the completion task
            completeUploadFuture = Threads.enqueue(serviceConfig, CompleteMpuTask.class, poolSize,
                    new CompleteMpuTask(uploadPartsFuture, snapUploadInfo, partNumber));
        } else {
            try {
                LOG.info("Uploading snapshot " + snapshotId
                        + " to objectstorage as a single object. Compressed size of snapshot (" + bytesWritten
                        + " bytes) is less than minimum part size (" + partSize
                        + " bytes) for multipart upload");
                PutObjectResult putResult = uploadSnapshotAsSingleObject(zipFilePath.toString(), bytesWritten,
                        uncompressedSize, progressCallback);
                markSnapshotAvailable();
                try {
                    part = part.updateStateUploaded(putResult.getETag());
                    snapUploadInfo = snapUploadInfo.updateStateUploaded(putResult.getETag());
                } catch (Exception e) {
                    LOG.debug("Failed to update status in DB for " + snapUploadInfo);
                }
                LOG.info("Uploaded snapshot " + snapshotId + " to objectstorage");
            } catch (Exception e) {
                error = Boolean.TRUE;
                LOG.error("Failed to upload snapshot " + snapshotId + " due to: ", e);
                throw new SnapshotTransferException("Failed to upload snapshot " + snapshotId + " due to: ", e);
            } finally {
                deleteFile(zipFilePath);
            }
        }
    } catch (SnapshotTransferException e) {
        error = Boolean.TRUE;
        throw e;
    } catch (Exception e) {
        error = Boolean.TRUE;
        LOG.error("Failed to upload snapshot " + snapshotId + " due to: ", e);
        throw new SnapshotTransferException("Failed to upload snapshot " + snapshotId + " due to: ", e);
    } finally {
        if (error) {
            abortUpload(snapUploadInfo);
            if (uploadPartsFuture != null && !uploadPartsFuture.isDone()) {
                uploadPartsFuture.cancel(true);
            }
            if (completeUploadFuture != null && !completeUploadFuture.isDone()) {
                completeUploadFuture.cancel(true);
            }
        }
    }
}