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,18 +79,15 @@ 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(
try {
si = (SummaryInformation) PropertySetFactory.create(
dir, SummaryInformation.DEFAULT_STREAM_NAME);
}
catch (FileNotFoundException ex)
{
} catch (FileNotFoundException ex) {
// There is no summary information yet. We have to create a new one
si = PropertySetFactory.newSummaryInformation();
}
@ -107,13 +104,10 @@ public class ModifyDocumentSummaryInformation {
/* Read the document summary information. */
DocumentSummaryInformation dsi;
try
{
dsi = (DocumentSummaryInformation)PropertySetFactory.create(
try {
dsi = (DocumentSummaryInformation) PropertySetFactory.create(
dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);
}
catch (FileNotFoundException ex)
{
} catch (FileNotFoundException ex) {
/* There is no document summary information yet. We have to create a
* new one. */
dsi = PropertySetFactory.newDocumentSummaryInformation();
@ -155,6 +149,6 @@ public class ModifyDocumentSummaryInformation {
* 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];
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);
fos = new FileOutputStream(outputFile);
workbook.write(fos);
fos.close();
workbook.close();
}
}
/**

View File

@ -45,14 +45,8 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class DrawingBorders {
public static void main(String[] args) throws IOException {
Workbook wb;
if (args.length > 0 && args[0].equals("-xls")) {
wb = new HSSFWorkbook();
} else {
wb = new XSSFWorkbook();
}
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);
@ -99,14 +93,12 @@ public class DrawingBorders {
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);
String file = "db-poi.xls" + (wb instanceof XSSFWorkbook ? "x" : "");
try (FileOutputStream out = new FileOutputStream(file)) {
wb.write(out);
out.close();
wb.close();
}
System.out.println("Generated: " + file);
}
}
}

View File

@ -69,12 +69,7 @@ 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();
}
try (Workbook workbook = workbookName.endsWith(".xlsx") ? new XSSFWorkbook() : 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
@ -107,10 +102,10 @@ public class LinkedDropDownLists {
validation = dvHelper.createValidation(dvConstraint, addressList);
sheet.addValidationData(validation);
FileOutputStream fos = new FileOutputStream(workbookName);
try (FileOutputStream fos = new FileOutputStream(workbookName)) {
workbook.write(fos);
fos.close();
workbook.close();
}
}
}
/**

View File

@ -451,18 +451,14 @@ public class ToCSV {
*/
private void saveCSVFile(File file)
throws FileNotFoundException, IOException {
FileWriter fw;
BufferedWriter bw = null;
ArrayList<String> line;
StringBuffer buffer;
String csvLineElement;
try {
System.out.println("Saving the CSV file [" + file.getName() + "]");
// Open a writer onto the CSV file.
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
System.out.println("Saving the CSV file [" + file.getName() + "]");
// Step through the elements of the ArrayList that was used to hold
// all of the data recovered from the Excel workbooks' sheets, rows
@ -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();
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;
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);
}
}
writePropertySet(SummaryInformation.DEFAULT_STREAM_NAME, getSummaryInformation(), fs, writtenEntries);
writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, getDocumentSummaryInformation(), fs, writtenEntries);
if (!encryptProps) {
return;
}
// create empty document summary
dsi = PropertySetFactory.newDocumentSummaryInformation();
writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, dsi, outFS);
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!");
throw new EncryptedDocumentException(
"Using " + ei.getEncryptionMode() + " encryption. Only CryptoAPI encryption supports encrypted property sets!");
}
CryptoAPIEncryptor enc = (CryptoAPIEncryptor)encGen;
CryptoAPIEncryptor enc = (CryptoAPIEncryptor) encGen;
try {
enc.setSummaryEntries(outFS.getRoot(), getEncryptedPropertyStreamName(), fs);
} catch (GeneralSecurityException e) {
throw new IOException(e);
} finally {
fs.close();
}
}
}
private void writePropertySet(String name, PropertySet ps, NPOIFSFileSystem outFS, List<String> writtenEntries)
throws IOException {
if (ps == null) {
return;
}
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;

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,13 +96,13 @@ 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 );
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,13 +164,13 @@ 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 );
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
protected void afterProcess()

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 );