Example usage for org.apache.poi.poifs.crypt EncryptionMode agile

List of usage examples for org.apache.poi.poifs.crypt EncryptionMode agile

Introduction

In this page you can find the example usage for org.apache.poi.poifs.crypt EncryptionMode agile.

Prototype

EncryptionMode agile

To view the source code for org.apache.poi.poifs.crypt EncryptionMode agile.

Click Source Link

Usage

From source file:uk.ac.ucl.cs.cmic.giftcloud.uploader.ExcelWriter.java

License:Open Source License

@Override
protected void saveFile(final File file) throws IOException {
    if (spreadsheetPassword.isPresent() && StringUtils.isNotBlank(new String(spreadsheetPassword.get()))) {
        try {//  w w  w  .  jav a2 s .  co  m
            // Write the unencrypted spreadsheet to an in-memory stream
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workbook.write(baos);
            baos.close();

            // Create objects for encryption
            POIFSFileSystem fs = new POIFSFileSystem();
            EncryptionInfo info = new EncryptionInfo(fs, EncryptionMode.agile);
            Encryptor enc = info.getEncryptor();

            // Set the password
            enc.confirmPassword(new String(spreadsheetPassword.get()));

            // Open the in-memory spreadsheet
            InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
            OPCPackage opc = OPCPackage.open(inputStream);
            OutputStream os = enc.getDataStream(fs);
            opc.save(os);
            opc.close();
            inputStream.close();

            // Write the encrypted Excel spreadsheet
            FileOutputStream fos = new FileOutputStream(file);
            fs.writeFilesystem(fos);
            fos.close();
        } catch (InvalidFormatException e) {
            throw new IOException(
                    "Unable to save the patient list file due to the following InvalidFormatException when reading the excel file:"
                            + e.getLocalizedMessage(),
                    e);
        } catch (GeneralSecurityException e) {
            throw new IOException(
                    "Unable to save the patient list file due to the following GeneralSecurityException when reading the excel file:"
                            + e.getLocalizedMessage(),
                    e);
        }
    } else {
        // Write the unencrypted spreadsheet to an in-memory stream
        final FileOutputStream fos = new FileOutputStream(file);
        workbook.write(fos);
        fos.close();
    }
}