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]);
/* Open the POI filesystem. */
NPOIFSFileSystem poifs = new NPOIFSFileSystem(summaryFile, false);
try (NPOIFSFileSystem poifs = new NPOIFSFileSystem(summaryFile, false)) {
/* Read the summary information. */
DirectoryEntry dir = poifs.getRoot();
SummaryInformation si;
try
{
si = (SummaryInformation)PropertySetFactory.create(
dir, SummaryInformation.DEFAULT_STREAM_NAME);
/* Read the summary information. */
DirectoryEntry dir = poifs.getRoot();
SummaryInformation si;
try {
si = (SummaryInformation) PropertySetFactory.create(
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.
*
*
* @author Andrew C. Oliver
* @author Jason Height
*/
public class SViewerPanel extends JPanel {
/** 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*/
public static void main(String[] args) {
if(args.length < 1) {
public static void main(String[] args) throws IOException {
if (args.length < 1) {
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);
JFrame frame;
frame = new JFrame() {
@ -283,6 +277,7 @@ public void paint(Graphics g) {
System.exit(0);
}
}
@Override
public synchronized void setTitle(String title) {
super.setTitle(title);
@ -291,13 +286,10 @@ public void paint(Graphics g) {
};
frame.setTitle("Viewer Frame");
frame.getContentPane().add(p, BorderLayout.CENTER);
frame.setSize(800,640);
frame.setSize(800, 640);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
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. */
int displayedFiles = 0;
for (final String filename : args) {
try {
FileInputStream fis = new FileInputStream(filename);
try (FileInputStream fis = new FileInputStream(filename)) {
POIFSReader r = new POIFSReader();
r.registerListener(new TreeReaderListener(filename, rootNode));
r.read(fis);
fis.close();
displayedFiles++;
} catch (IOException ex) {
System.err.println(filename + ": " + ex);

View File

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

View File

@ -45,68 +45,60 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class DrawingBorders {
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")) {
wb = new HSSFWorkbook();
} else {
wb = new XSSFWorkbook();
// 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" + (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
// and xml based workbooks. The choice of which one to create is
// made by checking the file extension.
Workbook workbook;
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);
try (Workbook workbook = workbookName.endsWith(".xlsx") ? new XSSFWorkbook() : new HSSFWorkbook()) {
// Build the first data validation to occupy cell A1. Note
// that it retrieves it's data from the named area or region called
// CHOICES. Further information about this can be found in the
// static buildDataSheet() method below.
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
DataValidationConstraint dvConstraint = dvHelper.createFormulaListConstraint("CHOICES");
DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
sheet.addValidationData(validation);
// Now, build the linked or dependent drop down list that will
// occupy cell B1. The key to the whole process is the use of the
// INDIRECT() function. In the buildDataSheet(0 method, a series of
// named regions are created and the names of three of them mirror
// the options available to the user in the first drop down list
// (in cell A1). Using the INDIRECT() function makes it possible
// to convert the selection the user makes in that first drop down
// into the addresses of a named region of cells and then to use
// those cells to populate the second drop down list.
addressList = new CellRangeAddressList(0, 0, 1, 1);
dvConstraint = dvHelper.createFormulaListConstraint(
"INDIRECT(UPPER($A$1))");
validation = dvHelper.createValidation(dvConstraint, addressList);
sheet.addValidationData(validation);
FileOutputStream fos = new FileOutputStream(workbookName);
workbook.write(fos);
fos.close();
workbook.close();
// 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
// that it retrieves it's data from the named area or region called
// CHOICES. Further information about this can be found in the
// static buildDataSheet() method below.
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
DataValidationConstraint dvConstraint = dvHelper.createFormulaListConstraint("CHOICES");
DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
sheet.addValidationData(validation);
// Now, build the linked or dependent drop down list that will
// occupy cell B1. The key to the whole process is the use of the
// INDIRECT() function. In the buildDataSheet(0 method, a series of
// named regions are created and the names of three of them mirror
// the options available to the user in the first drop down list
// (in cell A1). Using the INDIRECT() function makes it possible
// to convert the selection the user makes in that first drop down
// into the addresses of a named region of cells and then to use
// those cells to populate the second drop down list.
addressList = new CellRangeAddressList(0, 0, 1, 1);
dvConstraint = dvHelper.createFormulaListConstraint(
"INDIRECT(UPPER($A$1))");
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)
throws FileNotFoundException, IOException {
FileWriter fw;
BufferedWriter bw = null;
ArrayList<String> line;
StringBuffer buffer;
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() + "]");
// 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
// all of the data recovered from the Excel workbooks' sheets, rows
// 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 {
try (XMLSlideShow ppt = new XMLSlideShow()) {
for (String arg : args) {
FileInputStream is = new FileInputStream(arg);
XMLSlideShow src = new XMLSlideShow(is);
is.close();
for (XSLFSlide srcSlide : src.getSlides()) {
ppt.createSlide().importContent(srcSlide);
try (FileInputStream is = new FileInputStream(arg);
XMLSlideShow src = new XMLSlideShow(is)) {
for (XSLFSlide srcSlide : src.getSlides()) {
ppt.createSlide().importContent(srcSlide);
}
}
src.close();
}
try (FileOutputStream out = new FileOutputStream("merged.pptx")) {

View File

@ -17,6 +17,8 @@
package org.apache.poi;
import static org.apache.poi.hpsf.PropertySetFactory.newDocumentSummaryInformation;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
@ -141,7 +143,7 @@ public abstract class POIDocument implements Closeable {
sInf = PropertySetFactory.newSummaryInformation();
}
if (dsInf == null) {
dsInf = PropertySetFactory.newDocumentSummaryInformation();
dsInf = newDocumentSummaryInformation();
}
}
@ -277,47 +279,47 @@ public abstract class POIDocument implements Closeable {
* {@link NPOIFSFileSystem} occurs
*/
protected void writeProperties(NPOIFSFileSystem outFS, List<String> writtenEntries) throws IOException {
EncryptionInfo ei = getEncryptionInfo();
final EncryptionInfo ei = getEncryptionInfo();
final boolean encryptProps = (ei != null && ei.isDocPropsEncrypted());
NPOIFSFileSystem fs = (encryptProps) ? new NPOIFSFileSystem() : 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);
}
}
try (NPOIFSFileSystem tmpFS = new NPOIFSFileSystem()) {
final NPOIFSFileSystem fs = (encryptProps) ? tmpFS : outFS;
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;
}
// create empty document summary
dsi = PropertySetFactory.newDocumentSummaryInformation();
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();
writePropertySet(name, ps, outFS);
if (writtenEntries != null) {
writtenEntries.add(name);
}
}

View File

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

View File

@ -247,16 +247,7 @@ public class SignatureInfo implements SignatureConfigurable {
"system properties.");
}
try {
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;
}
try (final DigestOutputStream dos = getDigestStream(algo, key)) {
dos.init();
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.
* the parts can be validated independently.

View File

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

View File

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

View File

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