sonar fixes and

disable closing of outputstream in ZipPackage.saveImpl() - see https://stackoverflow.com/questions/50646538/stream-close-exception-occures

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1832746 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2018-06-02 20:29:35 +00:00
parent 87f7eac9c5
commit 9eb3789509
14 changed files with 256 additions and 303 deletions

View File

@ -79,82 +79,76 @@ public class ModifyDocumentSummaryInformation {
File summaryFile = new File(args[0]); File summaryFile = new File(args[0]);
/* Open the POI filesystem. */ /* Open the POI filesystem. */
NPOIFSFileSystem poifs = new NPOIFSFileSystem(summaryFile, false); try (NPOIFSFileSystem poifs = new NPOIFSFileSystem(summaryFile, false)) {
/* Read the summary information. */ /* Read the summary information. */
DirectoryEntry dir = poifs.getRoot(); DirectoryEntry dir = poifs.getRoot();
SummaryInformation si; SummaryInformation si;
try try {
{ si = (SummaryInformation) PropertySetFactory.create(
si = (SummaryInformation)PropertySetFactory.create( dir, SummaryInformation.DEFAULT_STREAM_NAME);
dir, SummaryInformation.DEFAULT_STREAM_NAME); } catch (FileNotFoundException ex) {
// There is no summary information yet. We have to create a new one
si = PropertySetFactory.newSummaryInformation();
}
/* Change the author to "Rainer Klute". Any former author value will
* be lost. If there has been no author yet, it will be created. */
si.setAuthor("Rainer Klute");
System.out.println("Author changed to " + si.getAuthor() + ".");
/* Handling the document summary information is analogous to handling
* the summary information. An additional feature, however, are the
* custom properties. */
/* Read the document summary information. */
DocumentSummaryInformation dsi;
try {
dsi = (DocumentSummaryInformation) PropertySetFactory.create(
dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);
} catch (FileNotFoundException ex) {
/* There is no document summary information yet. We have to create a
* new one. */
dsi = PropertySetFactory.newDocumentSummaryInformation();
}
/* Change the category to "POI example". Any former category value will
* be lost. If there has been no category yet, it will be created. */
dsi.setCategory("POI example");
System.out.println("Category changed to " + dsi.getCategory() + ".");
/* Read the custom properties. If there are no custom properties yet,
* the application has to create a new CustomProperties object. It will
* serve as a container for custom properties. */
CustomProperties customProperties = dsi.getCustomProperties();
if (customProperties == null)
customProperties = new CustomProperties();
/* Insert some custom properties into the container. */
customProperties.put("Key 1", "Value 1");
customProperties.put("Schl\u00fcssel 2", "Wert 2");
customProperties.put("Sample Number", new Integer(12345));
customProperties.put("Sample Boolean", Boolean.TRUE);
customProperties.put("Sample Date", new Date());
/* Read a custom property. */
Object value = customProperties.get("Sample Number");
System.out.println("Custom Sample Number is now " + value);
/* Write the custom properties back to the document summary
* information. */
dsi.setCustomProperties(customProperties);
/* Write the summary information and the document summary information
* to the POI filesystem. */
si.write(dir, SummaryInformation.DEFAULT_STREAM_NAME);
dsi.write(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);
/* Write the POI filesystem back to the original file. Please note that
* in production code you should take care when write directly to the
* origin, to make sure you don't loose things on error */
poifs.writeFilesystem();
} }
catch (FileNotFoundException ex)
{
// There is no summary information yet. We have to create a new one
si = PropertySetFactory.newSummaryInformation();
}
/* Change the author to "Rainer Klute". Any former author value will
* be lost. If there has been no author yet, it will be created. */
si.setAuthor("Rainer Klute");
System.out.println("Author changed to " + si.getAuthor() + ".");
/* Handling the document summary information is analogous to handling
* the summary information. An additional feature, however, are the
* custom properties. */
/* Read the document summary information. */
DocumentSummaryInformation dsi;
try
{
dsi = (DocumentSummaryInformation)PropertySetFactory.create(
dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);
}
catch (FileNotFoundException ex)
{
/* There is no document summary information yet. We have to create a
* new one. */
dsi = PropertySetFactory.newDocumentSummaryInformation();
}
/* Change the category to "POI example". Any former category value will
* be lost. If there has been no category yet, it will be created. */
dsi.setCategory("POI example");
System.out.println("Category changed to " + dsi.getCategory() + ".");
/* Read the custom properties. If there are no custom properties yet,
* the application has to create a new CustomProperties object. It will
* serve as a container for custom properties. */
CustomProperties customProperties = dsi.getCustomProperties();
if (customProperties == null)
customProperties = new CustomProperties();
/* Insert some custom properties into the container. */
customProperties.put("Key 1", "Value 1");
customProperties.put("Schl\u00fcssel 2", "Wert 2");
customProperties.put("Sample Number", new Integer(12345));
customProperties.put("Sample Boolean", Boolean.TRUE);
customProperties.put("Sample Date", new Date());
/* Read a custom property. */
Object value = customProperties.get("Sample Number");
System.out.println("Custom Sample Number is now " + value);
/* Write the custom properties back to the document summary
* information. */
dsi.setCustomProperties(customProperties);
/* Write the summary information and the document summary information
* to the POI filesystem. */
si.write(dir, SummaryInformation.DEFAULT_STREAM_NAME);
dsi.write(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);
/* Write the POI filesystem back to the original file. Please note that
* in production code you should take care when write directly to the
* origin, to make sure you don't loose things on error */
poifs.writeFilesystem();
poifs.close();
} }
} }

View File

@ -27,10 +27,6 @@ import org.apache.poi.hssf.usermodel.*;
/** /**
* This class presents the sheets to the user. * This class presents the sheets to the user.
*
*
* @author Andrew C. Oliver
* @author Jason Height
*/ */
public class SViewerPanel extends JPanel { public class SViewerPanel extends JPanel {
/** This field is the magic number to convert from a Character width to a /** This field is the magic number to convert from a Character width to a
@ -264,15 +260,13 @@ public void paint(Graphics g) {
} }
/**Main method*/ /**Main method*/
public static void main(String[] args) { public static void main(String[] args) throws IOException {
if(args.length < 1) { if (args.length < 1) {
throw new IllegalArgumentException("A filename to view must be supplied as the first argument, but none was given"); throw new IllegalArgumentException("A filename to view must be supplied as the first argument, but none was given");
} }
try {
FileInputStream in = new FileInputStream(args[0]);
HSSFWorkbook wb = new HSSFWorkbook(in);
in.close();
try (FileInputStream in = new FileInputStream(args[0]);
HSSFWorkbook wb = new HSSFWorkbook(in)) {
SViewerPanel p = new SViewerPanel(wb, true); SViewerPanel p = new SViewerPanel(wb, true);
JFrame frame; JFrame frame;
frame = new JFrame() { frame = new JFrame() {
@ -283,6 +277,7 @@ public void paint(Graphics g) {
System.exit(0); System.exit(0);
} }
} }
@Override @Override
public synchronized void setTitle(String title) { public synchronized void setTitle(String title) {
super.setTitle(title); super.setTitle(title);
@ -291,13 +286,10 @@ public void paint(Graphics g) {
}; };
frame.setTitle("Viewer Frame"); frame.setTitle("Viewer Frame");
frame.getContentPane().add(p, BorderLayout.CENTER); frame.getContentPane().add(p, BorderLayout.CENTER);
frame.setSize(800,640); frame.setSize(800, 640);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2); frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
frame.setVisible(true); frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
System.exit(1);
} }
} }
} }

View File

@ -85,12 +85,10 @@ public class POIBrowser extends JFrame
/* Add the POI filesystems to the tree. */ /* Add the POI filesystems to the tree. */
int displayedFiles = 0; int displayedFiles = 0;
for (final String filename : args) { for (final String filename : args) {
try { try (FileInputStream fis = new FileInputStream(filename)) {
FileInputStream fis = new FileInputStream(filename);
POIFSReader r = new POIFSReader(); POIFSReader r = new POIFSReader();
r.registerListener(new TreeReaderListener(filename, rootNode)); r.registerListener(new TreeReaderListener(filename, rootNode));
r.read(fis); r.read(fis);
fis.close();
displayedFiles++; displayedFiles++;
} catch (IOException ex) { } catch (IOException ex) {
System.err.println(filename + ": " + ex); System.err.println(filename + ": " + ex);

View File

@ -817,27 +817,22 @@ public class AddDimensionedImage {
* @param args the command line arguments * @param args the command line arguments
*/ */
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
String imageFile;
String outputFile;
FileOutputStream fos;
Workbook workbook;
Sheet sheet;
if(args.length < 2){ if(args.length < 2){
System.err.println("Usage: AddDimensionedImage imageFile outputFile"); System.err.println("Usage: AddDimensionedImage imageFile outputFile");
return; return;
} }
workbook = new HSSFWorkbook(); // OR XSSFWorkbook
sheet = workbook.createSheet("Picture Test"); final String imageFile = args[0];
imageFile = args[0]; final String outputFile = args[1];
outputFile = args[1];
new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(), try (final Workbook workbook = new HSSFWorkbook();
new File(imageFile).toURI().toURL(), 100, 40, final FileOutputStream fos = new FileOutputStream(outputFile)) { // OR XSSFWorkbook
AddDimensionedImage.EXPAND_ROW_AND_COLUMN); Sheet sheet = workbook.createSheet("Picture Test");
fos = new FileOutputStream(outputFile); new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(),
workbook.write(fos); new File(imageFile).toURI().toURL(), 100, 40,
fos.close(); AddDimensionedImage.EXPAND_ROW_AND_COLUMN);
workbook.close(); workbook.write(fos);
}
} }
/** /**

View File

@ -45,68 +45,60 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class DrawingBorders { public class DrawingBorders {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
Workbook wb; try (Workbook wb = (args.length > 0 && args[0].equals("-xls"))
? new HSSFWorkbook() : new XSSFWorkbook()) {
// add a sheet, and put some values into it
Sheet sh1 = wb.createSheet("Sheet1");
Row r = sh1.createRow(0);
Cell c = r.createCell(1);
c.setCellValue("All Borders Medium Width");
r = sh1.createRow(4);
c = r.createCell(1);
c.setCellValue("Medium Outside / Thin Inside Borders");
r = sh1.createRow(8);
c = r.createCell(1);
c.setCellValue("Colored Borders");
if (args.length > 0 && args[0].equals("-xls")) { // draw borders (three 3x3 grids)
wb = new HSSFWorkbook(); PropertyTemplate pt = new PropertyTemplate();
} else { // #1) these borders will all be medium in default color
wb = new XSSFWorkbook(); pt.drawBorders(new CellRangeAddress(1, 3, 1, 3),
BorderStyle.MEDIUM, BorderExtent.ALL);
// #2) these cells will have medium outside borders and thin inside borders
pt.drawBorders(new CellRangeAddress(5, 7, 1, 3),
BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(5, 7, 1, 3), BorderStyle.THIN,
BorderExtent.INSIDE);
// #3) these cells will all be medium weight with different colors for the
// outside, inside horizontal, and inside vertical borders. The center
// cell will have no borders.
pt.drawBorders(new CellRangeAddress(9, 11, 1, 3),
BorderStyle.MEDIUM, IndexedColors.RED.getIndex(),
BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(9, 11, 1, 3),
BorderStyle.MEDIUM, IndexedColors.BLUE.getIndex(),
BorderExtent.INSIDE_VERTICAL);
pt.drawBorders(new CellRangeAddress(9, 11, 1, 3),
BorderStyle.MEDIUM, IndexedColors.GREEN.getIndex(),
BorderExtent.INSIDE_HORIZONTAL);
pt.drawBorders(new CellRangeAddress(10, 10, 2, 2),
BorderStyle.NONE,
BorderExtent.ALL);
// apply borders to sheet
pt.applyBorders(sh1);
// add another sheet and apply the borders to it
Sheet sh2 = wb.createSheet("Sheet2");
pt.applyBorders(sh2);
// Write the output to a file
String file = "db-poi.xls" + (wb instanceof XSSFWorkbook ? "x" : "");
try (FileOutputStream out = new FileOutputStream(file)) {
wb.write(out);
}
System.out.println("Generated: " + file);
} }
// add a sheet, and put some values into it
Sheet sh1 = wb.createSheet("Sheet1");
Row r = sh1.createRow(0);
Cell c = r.createCell(1);
c.setCellValue("All Borders Medium Width");
r = sh1.createRow(4);
c = r.createCell(1);
c.setCellValue("Medium Outside / Thin Inside Borders");
r = sh1.createRow(8);
c = r.createCell(1);
c.setCellValue("Colored Borders");
// draw borders (three 3x3 grids)
PropertyTemplate pt = new PropertyTemplate();
// #1) these borders will all be medium in default color
pt.drawBorders(new CellRangeAddress(1, 3, 1, 3),
BorderStyle.MEDIUM, BorderExtent.ALL);
// #2) these cells will have medium outside borders and thin inside borders
pt.drawBorders(new CellRangeAddress(5, 7, 1, 3),
BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(5, 7, 1, 3), BorderStyle.THIN,
BorderExtent.INSIDE);
// #3) these cells will all be medium weight with different colors for the
// outside, inside horizontal, and inside vertical borders. The center
// cell will have no borders.
pt.drawBorders(new CellRangeAddress(9, 11, 1, 3),
BorderStyle.MEDIUM, IndexedColors.RED.getIndex(),
BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(9, 11, 1, 3),
BorderStyle.MEDIUM, IndexedColors.BLUE.getIndex(),
BorderExtent.INSIDE_VERTICAL);
pt.drawBorders(new CellRangeAddress(9, 11, 1, 3),
BorderStyle.MEDIUM, IndexedColors.GREEN.getIndex(),
BorderExtent.INSIDE_HORIZONTAL);
pt.drawBorders(new CellRangeAddress(10, 10, 2, 2),
BorderStyle.NONE,
BorderExtent.ALL);
// apply borders to sheet
pt.applyBorders(sh1);
// add another sheet and apply the borders to it
Sheet sh2 = wb.createSheet("Sheet2");
pt.applyBorders(sh2);
// Write the output to a file
String file = "db-poi.xls";
if (wb instanceof XSSFWorkbook)
file += "x";
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.close();
wb.close();
System.out.println("Generated: " + file);
} }
} }

View File

@ -69,48 +69,43 @@ public class LinkedDropDownLists {
// Using the ss.usermodel allows this class to support both binary // Using the ss.usermodel allows this class to support both binary
// and xml based workbooks. The choice of which one to create is // and xml based workbooks. The choice of which one to create is
// made by checking the file extension. // made by checking the file extension.
Workbook workbook; try (Workbook workbook = workbookName.endsWith(".xlsx") ? new XSSFWorkbook() : new HSSFWorkbook()) {
if (workbookName.endsWith(".xlsx")) {
workbook = new XSSFWorkbook();
} else {
workbook = new HSSFWorkbook();
}
// Build the sheet that will hold the data for the validations. This
// must be done first as it will create names that are referenced
// later.
Sheet sheet = workbook.createSheet("Linked Validations");
LinkedDropDownLists.buildDataSheet(sheet);
// Build the first data validation to occupy cell A1. Note // Build the sheet that will hold the data for the validations. This
// that it retrieves it's data from the named area or region called // must be done first as it will create names that are referenced
// CHOICES. Further information about this can be found in the // later.
// static buildDataSheet() method below. Sheet sheet = workbook.createSheet("Linked Validations");
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); LinkedDropDownLists.buildDataSheet(sheet);
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
DataValidationConstraint dvConstraint = dvHelper.createFormulaListConstraint("CHOICES"); // Build the first data validation to occupy cell A1. Note
DataValidation validation = dvHelper.createValidation(dvConstraint, addressList); // that it retrieves it's data from the named area or region called
sheet.addValidationData(validation); // CHOICES. Further information about this can be found in the
// static buildDataSheet() method below.
// Now, build the linked or dependent drop down list that will CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
// occupy cell B1. The key to the whole process is the use of the DataValidationHelper dvHelper = sheet.getDataValidationHelper();
// INDIRECT() function. In the buildDataSheet(0 method, a series of DataValidationConstraint dvConstraint = dvHelper.createFormulaListConstraint("CHOICES");
// named regions are created and the names of three of them mirror DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
// the options available to the user in the first drop down list sheet.addValidationData(validation);
// (in cell A1). Using the INDIRECT() function makes it possible
// to convert the selection the user makes in that first drop down // Now, build the linked or dependent drop down list that will
// into the addresses of a named region of cells and then to use // occupy cell B1. The key to the whole process is the use of the
// those cells to populate the second drop down list. // INDIRECT() function. In the buildDataSheet(0 method, a series of
addressList = new CellRangeAddressList(0, 0, 1, 1); // named regions are created and the names of three of them mirror
dvConstraint = dvHelper.createFormulaListConstraint( // the options available to the user in the first drop down list
"INDIRECT(UPPER($A$1))"); // (in cell A1). Using the INDIRECT() function makes it possible
validation = dvHelper.createValidation(dvConstraint, addressList); // to convert the selection the user makes in that first drop down
sheet.addValidationData(validation); // into the addresses of a named region of cells and then to use
// those cells to populate the second drop down list.
FileOutputStream fos = new FileOutputStream(workbookName); addressList = new CellRangeAddressList(0, 0, 1, 1);
workbook.write(fos); dvConstraint = dvHelper.createFormulaListConstraint(
fos.close(); "INDIRECT(UPPER($A$1))");
workbook.close(); validation = dvHelper.createValidation(dvConstraint, addressList);
sheet.addValidationData(validation);
try (FileOutputStream fos = new FileOutputStream(workbookName)) {
workbook.write(fos);
}
}
} }
/** /**

View File

@ -451,19 +451,15 @@ public class ToCSV {
*/ */
private void saveCSVFile(File file) private void saveCSVFile(File file)
throws FileNotFoundException, IOException { throws FileNotFoundException, IOException {
FileWriter fw;
BufferedWriter bw = null;
ArrayList<String> line; ArrayList<String> line;
StringBuffer buffer; StringBuffer buffer;
String csvLineElement; String csvLineElement;
try {
// Open a writer onto the CSV file.
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
System.out.println("Saving the CSV file [" + file.getName() + "]"); System.out.println("Saving the CSV file [" + file.getName() + "]");
// Open a writer onto the CSV file.
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
// Step through the elements of the ArrayList that was used to hold // Step through the elements of the ArrayList that was used to hold
// all of the data recovered from the Excel workbooks' sheets, rows // all of the data recovered from the Excel workbooks' sheets, rows
// and cells. // and cells.
@ -507,12 +503,6 @@ public class ToCSV {
} }
} }
} }
finally {
if(bw != null) {
bw.flush();
bw.close();
}
}
} }
/** /**

View File

@ -30,15 +30,12 @@ public final class MergePresentations {
public static void main(String args[]) throws Exception { public static void main(String args[]) throws Exception {
try (XMLSlideShow ppt = new XMLSlideShow()) { try (XMLSlideShow ppt = new XMLSlideShow()) {
for (String arg : args) { for (String arg : args) {
FileInputStream is = new FileInputStream(arg); try (FileInputStream is = new FileInputStream(arg);
XMLSlideShow src = new XMLSlideShow(is); XMLSlideShow src = new XMLSlideShow(is)) {
is.close(); for (XSLFSlide srcSlide : src.getSlides()) {
ppt.createSlide().importContent(srcSlide);
for (XSLFSlide srcSlide : src.getSlides()) { }
ppt.createSlide().importContent(srcSlide);
} }
src.close();
} }
try (FileOutputStream out = new FileOutputStream("merged.pptx")) { try (FileOutputStream out = new FileOutputStream("merged.pptx")) {

View File

@ -17,6 +17,8 @@
package org.apache.poi; package org.apache.poi;
import static org.apache.poi.hpsf.PropertySetFactory.newDocumentSummaryInformation;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.Closeable; import java.io.Closeable;
@ -141,7 +143,7 @@ public abstract class POIDocument implements Closeable {
sInf = PropertySetFactory.newSummaryInformation(); sInf = PropertySetFactory.newSummaryInformation();
} }
if (dsInf == null) { if (dsInf == null) {
dsInf = PropertySetFactory.newDocumentSummaryInformation(); dsInf = newDocumentSummaryInformation();
} }
} }
@ -277,47 +279,47 @@ public abstract class POIDocument implements Closeable {
* {@link NPOIFSFileSystem} occurs * {@link NPOIFSFileSystem} occurs
*/ */
protected void writeProperties(NPOIFSFileSystem outFS, List<String> writtenEntries) throws IOException { protected void writeProperties(NPOIFSFileSystem outFS, List<String> writtenEntries) throws IOException {
EncryptionInfo ei = getEncryptionInfo(); final EncryptionInfo ei = getEncryptionInfo();
final boolean encryptProps = (ei != null && ei.isDocPropsEncrypted()); final boolean encryptProps = (ei != null && ei.isDocPropsEncrypted());
NPOIFSFileSystem fs = (encryptProps) ? new NPOIFSFileSystem() : outFS; try (NPOIFSFileSystem tmpFS = new NPOIFSFileSystem()) {
final NPOIFSFileSystem fs = (encryptProps) ? tmpFS : outFS;
SummaryInformation si = getSummaryInformation();
if (si != null) {
writePropertySet(SummaryInformation.DEFAULT_STREAM_NAME, si, fs);
if(writtenEntries != null) {
writtenEntries.add(SummaryInformation.DEFAULT_STREAM_NAME);
}
}
DocumentSummaryInformation dsi = getDocumentSummaryInformation();
if (dsi != null) {
writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, dsi, fs);
if(writtenEntries != null) {
writtenEntries.add(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
}
}
if (!encryptProps) { writePropertySet(SummaryInformation.DEFAULT_STREAM_NAME, getSummaryInformation(), fs, writtenEntries);
writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, getDocumentSummaryInformation(), fs, writtenEntries);
if (!encryptProps) {
return;
}
// create empty document summary
writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, newDocumentSummaryInformation(), outFS);
// remove summary, if previously available
if (outFS.getRoot().hasEntry(SummaryInformation.DEFAULT_STREAM_NAME)) {
outFS.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME).delete();
}
Encryptor encGen = ei.getEncryptor();
if (!(encGen instanceof CryptoAPIEncryptor)) {
throw new EncryptedDocumentException(
"Using " + ei.getEncryptionMode() + " encryption. Only CryptoAPI encryption supports encrypted property sets!");
}
CryptoAPIEncryptor enc = (CryptoAPIEncryptor) encGen;
try {
enc.setSummaryEntries(outFS.getRoot(), getEncryptedPropertyStreamName(), fs);
} catch (GeneralSecurityException e) {
throw new IOException(e);
}
}
}
private void writePropertySet(String name, PropertySet ps, NPOIFSFileSystem outFS, List<String> writtenEntries)
throws IOException {
if (ps == null) {
return; return;
} }
writePropertySet(name, ps, outFS);
// create empty document summary if (writtenEntries != null) {
dsi = PropertySetFactory.newDocumentSummaryInformation(); writtenEntries.add(name);
writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, dsi, outFS);
// remove summary, if previously available
if (outFS.getRoot().hasEntry(SummaryInformation.DEFAULT_STREAM_NAME)) {
outFS.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME).delete();
}
Encryptor encGen = ei.getEncryptor();
if (!(encGen instanceof CryptoAPIEncryptor)) {
throw new EncryptedDocumentException("Using "+ei.getEncryptionMode()+" encryption. Only CryptoAPI encryption supports encrypted property sets!");
}
CryptoAPIEncryptor enc = (CryptoAPIEncryptor)encGen;
try {
enc.setSummaryEntries(outFS.getRoot(), getEncryptedPropertyStreamName(), fs);
} catch (GeneralSecurityException e) {
throw new IOException(e);
} finally {
fs.close();
} }
} }

View File

@ -483,9 +483,10 @@ public final class ZipPackage extends OPCPackage {
// Check that the document was open in write mode // Check that the document was open in write mode
throwExceptionIfReadOnly(); throwExceptionIfReadOnly();
try (final ZipOutputStream zos = (outputStream instanceof ZipOutputStream) final ZipOutputStream zos = (outputStream instanceof ZipOutputStream)
? (ZipOutputStream) outputStream : new ZipOutputStream(outputStream)) { ? (ZipOutputStream) outputStream : new ZipOutputStream(outputStream);
try {
// If the core properties part does not exist in the part list, // If the core properties part does not exist in the part list,
// we save it as well // we save it as well
if (this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size() == 0 && if (this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size() == 0 &&
@ -537,6 +538,8 @@ public final class ZipPackage extends OPCPackage {
throw new OpenXML4JException(errMsg + pm); throw new OpenXML4JException(errMsg + pm);
} }
} }
zos.finish();
} catch (OpenXML4JRuntimeException e) { } catch (OpenXML4JRuntimeException e) {
// no need to wrap this type of Exception // no need to wrap this type of Exception
throw e; throw e;
@ -544,7 +547,7 @@ public final class ZipPackage extends OPCPackage {
throw new OpenXML4JRuntimeException( throw new OpenXML4JRuntimeException(
"Fail to save: an error occurs while saving the package : " "Fail to save: an error occurs while saving the package : "
+ e.getMessage(), e); + e.getMessage(), e);
} }
} }
/** /**

View File

@ -247,16 +247,7 @@ public class SignatureInfo implements SignatureConfigurable {
"system properties."); "system properties.");
} }
try { try (final DigestOutputStream dos = getDigestStream(algo, key)) {
final DigestOutputStream dos;
switch (algo) {
case md2: case md5: case sha1: case sha256: case sha384: case sha512:
dos = new SignatureOutputStream(algo, key);
break;
default:
dos = new DigestOutputStream(algo, key);
break;
}
dos.init(); dos.init();
final Document document = (Document)xmlSignContext.getParent(); final Document document = (Document)xmlSignContext.getParent();
@ -270,6 +261,15 @@ public class SignatureInfo implements SignatureConfigurable {
} }
} }
private static DigestOutputStream getDigestStream(final HashAlgorithm algo, final PrivateKey key) {
switch (algo) {
case md2: case md5: case sha1: case sha256: case sha384: case sha512:
return new SignatureOutputStream(algo, key);
default:
return new DigestOutputStream(algo, key);
}
}
/** /**
* @return a signature part for each signature document. * @return a signature part for each signature document.
* the parts can be validated independently. * the parts can be validated independently.

View File

@ -23,6 +23,7 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.OutputKeys; import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactory;
@ -95,12 +96,12 @@ public class WordToFoConverter extends AbstractWordConverter
static Document process( File docFile ) throws Exception static Document process( File docFile ) throws Exception
{ {
final HWPFDocumentCore hwpfDocument = WordToFoUtils.loadDoc( docFile ); final DocumentBuilder docBuild = XMLHelper.getDocumentBuilderFactory().newDocumentBuilder();
WordToFoConverter wordToFoConverter = new WordToFoConverter( try (final HWPFDocumentCore hwpfDocument = WordToFoUtils.loadDoc( docFile )) {
XMLHelper.getDocumentBuilderFactory().newDocumentBuilder() WordToFoConverter wordToFoConverter = new WordToFoConverter(docBuild.newDocument());
.newDocument() ); wordToFoConverter.processDocument(hwpfDocument);
wordToFoConverter.processDocument( hwpfDocument ); return wordToFoConverter.getDocument();
return wordToFoConverter.getDocument(); }
} }
private List<Element> endnotes = new ArrayList<>(0); private List<Element> endnotes = new ArrayList<>(0);

View File

@ -24,6 +24,7 @@ import java.util.Deque;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys; import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
@ -163,12 +164,12 @@ public class WordToHtmlConverter extends AbstractWordConverter
static Document process( File docFile ) throws IOException, ParserConfigurationException static Document process( File docFile ) throws IOException, ParserConfigurationException
{ {
final HWPFDocumentCore wordDocument = AbstractWordUtils.loadDoc( docFile ); final DocumentBuilder docBuild = XMLHelper.getDocumentBuilderFactory().newDocumentBuilder();
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter( try (final HWPFDocumentCore wordDocument = AbstractWordUtils.loadDoc( docFile )) {
XMLHelper.getDocumentBuilderFactory().newDocumentBuilder() WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(docBuild.newDocument());
.newDocument() ); wordToHtmlConverter.processDocument(wordDocument);
wordToHtmlConverter.processDocument( wordDocument ); return wordToHtmlConverter.getDocument();
return wordToHtmlConverter.getDocument(); }
} }
@Override @Override

View File

@ -79,22 +79,15 @@ public final class HWPFLister
{ {
private static HWPFDocumentCore loadDoc( File docFile ) throws IOException private static HWPFDocumentCore loadDoc( File docFile ) throws IOException
{ {
final FileInputStream istream = new FileInputStream( docFile ); try (final FileInputStream istream = new FileInputStream( docFile )) {
try
{
return loadDoc( istream ); return loadDoc( istream );
} }
finally
{
IOUtils.closeQuietly( istream );
}
} }
private static HWPFDocumentCore loadDoc( InputStream inputStream ) private static HWPFDocumentCore loadDoc( InputStream inputStream )
throws IOException throws IOException
{ {
final POIFSFileSystem poifsFileSystem = HWPFDocumentCore final POIFSFileSystem poifsFileSystem = HWPFDocumentCore.verifyAndBuildPOIFS( inputStream );
.verifyAndBuildPOIFS( inputStream );
try try
{ {
return new HWPFDocument( poifsFileSystem ); return new HWPFDocument( poifsFileSystem );