Sonar fixes - use try-with-resources

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1870653 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2019-11-30 23:00:08 +00:00
parent 4f8aeb705e
commit b4b661acc1
24 changed files with 605 additions and 638 deletions

View File

@ -62,30 +62,30 @@ public class OOXMLPasswordsTry implements Closeable {
}
public String tryAll(File wordfile) throws IOException, GeneralSecurityException {
// Load
BufferedReader r = new BufferedReader(new FileReader(wordfile));
long start = System.currentTimeMillis();
int count = 0;
// Try each password in turn, reporting progress
String valid = null;
String password;
while ((password = r.readLine()) != null) {
if (isValid(password)) {
valid = password;
break;
}
count++;
if (count % 1000 == 0) {
int secs = (int)((System.currentTimeMillis() - start) / 1000);
System.out.println("Done " + count + " passwords, " +
secs + " seconds, last password " + password);
// Load
try (BufferedReader r = new BufferedReader(new FileReader(wordfile))) {
long start = System.currentTimeMillis();
int count = 0;
// Try each password in turn, reporting progress
String password;
while ((password = r.readLine()) != null) {
if (isValid(password)) {
valid = password;
break;
}
count++;
if (count % 1000 == 0) {
int secs = (int) ((System.currentTimeMillis() - start) / 1000);
System.out.println("Done " + count + " passwords, " +
secs + " seconds, last password " + password);
}
}
}
// Tidy and return (null if no match)
r.close();
return valid;
}
public boolean isValid(String password) throws GeneralSecurityException {
@ -103,10 +103,11 @@ public class OOXMLPasswordsTry implements Closeable {
System.out.println("Trying passwords from " + words + " against " + ooxml);
System.out.println();
OOXMLPasswordsTry pt = new OOXMLPasswordsTry(ooxml);
String password = pt.tryAll(words);
pt.close();
String password;
try (OOXMLPasswordsTry pt = new OOXMLPasswordsTry(ooxml)) {
password = pt.tryAll(words);
}
System.out.println();
if (password == null) {

View File

@ -46,78 +46,76 @@ public final class DataExtraction {
return;
}
FileInputStream is = new FileInputStream(args[0]);
HSLFSlideShow ppt = new HSLFSlideShow(is);
is.close();
try (FileInputStream is = new FileInputStream(args[0]);
HSLFSlideShow ppt = new HSLFSlideShow(is)) {
//extract all sound files embedded in this presentation
HSLFSoundData[] sound = ppt.getSoundData();
for (HSLFSoundData aSound : sound) {
String type = aSound.getSoundType(); //*.wav
String name = aSound.getSoundName(); //typically file name
byte[] data = aSound.getData(); //raw bytes
//extract all sound files embedded in this presentation
HSLFSoundData[] sound = ppt.getSoundData();
for (HSLFSoundData aSound : sound) {
String type = aSound.getSoundType(); //*.wav
String name = aSound.getSoundName(); //typically file name
byte[] data = aSound.getData(); //raw bytes
//save the sound on disk
FileOutputStream out = new FileOutputStream(name + type);
out.write(data);
out.close();
}
int oleIdx=-1, picIdx=-1;
for (HSLFSlide slide : ppt.getSlides()) {
//extract embedded OLE documents
for (HSLFShape shape : slide.getShapes()) {
if (shape instanceof HSLFObjectShape) {
oleIdx++;
HSLFObjectShape ole = (HSLFObjectShape) shape;
HSLFObjectData data = ole.getObjectData();
String name = ole.getInstanceName();
if ("Worksheet".equals(name)) {
//read xls
@SuppressWarnings({ "unused", "resource" })
HSSFWorkbook wb = new HSSFWorkbook(data.getInputStream());
} else if ("Document".equals(name)) {
HWPFDocument doc = new HWPFDocument(data.getInputStream());
//read the word document
Range r = doc.getRange();
for(int k = 0; k < r.numParagraphs(); k++) {
Paragraph p = r.getParagraph(k);
System.out.println(p.text());
}
//save on disk
FileOutputStream out = new FileOutputStream(name + "-("+(oleIdx)+").doc");
doc.write(out);
out.close();
doc.close();
} else {
FileOutputStream out = new FileOutputStream(ole.getProgId() + "-"+(oleIdx+1)+".dat");
InputStream dis = data.getInputStream();
byte[] chunk = new byte[2048];
int count;
while ((count = dis.read(chunk)) >= 0) {
out.write(chunk,0,count);
}
is.close();
out.close();
}
//save the sound on disk
try (FileOutputStream out = new FileOutputStream(name + type)) {
out.write(data);
}
//Pictures
else if (shape instanceof HSLFPictureShape) {
picIdx++;
HSLFPictureShape p = (HSLFPictureShape) shape;
HSLFPictureData data = p.getPictureData();
String ext = data.getType().extension;
FileOutputStream out = new FileOutputStream("pict-" + picIdx + ext);
out.write(data.getData());
out.close();
}
int oleIdx = -1, picIdx = -1;
for (HSLFSlide slide : ppt.getSlides()) {
//extract embedded OLE documents
for (HSLFShape shape : slide.getShapes()) {
if (shape instanceof HSLFObjectShape) {
oleIdx++;
HSLFObjectShape ole = (HSLFObjectShape) shape;
HSLFObjectData data = ole.getObjectData();
String name = ole.getInstanceName();
if ("Worksheet".equals(name)) {
//read xls
@SuppressWarnings({"unused", "resource"})
HSSFWorkbook wb = new HSSFWorkbook(data.getInputStream());
} else if ("Document".equals(name)) {
try (HWPFDocument doc = new HWPFDocument(data.getInputStream())) {
//read the word document
Range r = doc.getRange();
for (int k = 0; k < r.numParagraphs(); k++) {
Paragraph p = r.getParagraph(k);
System.out.println(p.text());
}
//save on disk
try (FileOutputStream out = new FileOutputStream(name + "-(" + (oleIdx) + ").doc")) {
doc.write(out);
}
}
} else {
try (FileOutputStream out = new FileOutputStream(ole.getProgId() + "-" + (oleIdx + 1) + ".dat");
InputStream dis = data.getInputStream()) {
byte[] chunk = new byte[2048];
int count;
while ((count = dis.read(chunk)) >= 0) {
out.write(chunk, 0, count);
}
}
}
}
//Pictures
else if (shape instanceof HSLFPictureShape) {
picIdx++;
HSLFPictureShape p = (HSLFPictureShape) shape;
HSLFPictureData data = p.getPictureData();
String ext = data.getType().extension;
try (FileOutputStream out = new FileOutputStream("pict-" + picIdx + ext)) {
out.write(data.getData());
}
}
}
}
}
ppt.close();
}
private static void usage(){

View File

@ -31,47 +31,44 @@ import org.apache.poi.hslf.usermodel.HSLFTextRun;
/**
* Demonstrates how to read hyperlinks from a presentation
*
* @author Yegor Kozlov
*/
public final class Hyperlinks {
public static void main(String[] args) throws Exception {
for (String arg : args) {
FileInputStream is = new FileInputStream(arg);
HSLFSlideShow ppt = new HSLFSlideShow(is);
is.close();
try (FileInputStream is = new FileInputStream(arg);
HSLFSlideShow ppt = new HSLFSlideShow(is)) {
for (HSLFSlide slide : ppt.getSlides()) {
System.out.println("\nslide " + slide.getSlideNumber());
for (HSLFSlide slide : ppt.getSlides()) {
System.out.println("\nslide " + slide.getSlideNumber());
// read hyperlinks from the slide's text runs
System.out.println("- reading hyperlinks from the text runs");
for (List<HSLFTextParagraph> paras : slide.getTextParagraphs()) {
for (HSLFTextParagraph para : paras) {
for (HSLFTextRun run : para) {
HSLFHyperlink link = run.getHyperlink();
// read hyperlinks from the slide's text runs
System.out.println("- reading hyperlinks from the text runs");
for (List<HSLFTextParagraph> paras : slide.getTextParagraphs()) {
for (HSLFTextParagraph para : paras) {
for (HSLFTextRun run : para) {
HSLFHyperlink link = run.getHyperlink();
if (link != null) {
System.out.println(toStr(link, run.getRawText()));
}
}
}
}
// in PowerPoint you can assign a hyperlink to a shape without text,
// for example to a Line object. The code below demonstrates how to
// read such hyperlinks
System.out.println("- reading hyperlinks from the slide's shapes");
for (HSLFShape sh : slide.getShapes()) {
if (sh instanceof HSLFSimpleShape) {
HSLFHyperlink link = ((HSLFSimpleShape) sh).getHyperlink();
if (link != null) {
System.out.println(toStr(link, run.getRawText()));
System.out.println(toStr(link, null));
}
}
}
}
// in PowerPoint you can assign a hyperlink to a shape without text,
// for example to a Line object. The code below demonstrates how to
// read such hyperlinks
System.out.println("- reading hyperlinks from the slide's shapes");
for (HSLFShape sh : slide.getShapes()) {
if (sh instanceof HSLFSimpleShape) {
HSLFHyperlink link = ((HSLFSimpleShape) sh).getHyperlink();
if (link != null) {
System.out.println(toStr(link, null));
}
}
}
}
ppt.close();
}
}

View File

@ -15,16 +15,25 @@
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.hssf.view;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.JApplet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@ -39,141 +48,149 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook;
* @author Jason Height
*/
public class SViewer extends JApplet {
private SViewerPanel panel;
boolean isStandalone;
String filename;
private SViewerPanel panel;
boolean isStandalone;
String filename;
/**Get a parameter value*/
public String getParameter(String key, String def) {
return isStandalone ? System.getProperty(key, def) :
(getParameter(key) != null ? getParameter(key) : def);
}
/**Construct the applet*/
public SViewer() {
}
/**Initialize the applet*/
@Override
public void init() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
/**Component initialization*/
private void jbInit() throws Exception {
InputStream i = null;
boolean isurl = false;
if (filename == null) filename = getParameter("filename");
if (filename == null || filename.substring(0,7).equals("http://")) {
isurl = true;
if (filename == null) filename = getParameter("url");
i = getXLSFromURL(filename);
/**
* Get a parameter value
*/
public String getParameter(String key, String def) {
return isStandalone ? System.getProperty(key, def) :
(getParameter(key) != null ? getParameter(key) : def);
}
HSSFWorkbook wb = null;
if (isurl) {
wb = constructWorkbook(i);
} else {
wb = constructWorkbook(filename);
}
panel = new SViewerPanel(wb, false);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(panel, BorderLayout.CENTER);
}
private HSSFWorkbook constructWorkbook(String filename) throws FileNotFoundException, IOException {
HSSFWorkbook wb = null;
FileInputStream in = new FileInputStream(filename);
wb = new HSSFWorkbook(in);
in.close();
return wb;
}
private HSSFWorkbook constructWorkbook(InputStream in) throws IOException {
HSSFWorkbook wb = null;
wb = new HSSFWorkbook(in);
in.close();
return wb;
}
/**Start the applet*/
@Override
public void start() {
}
/**Stop the applet*/
@Override
public void stop() {
}
/**Destroy the applet*/
@Override
public void destroy() {
}
/**Get Applet information*/
@Override
public String getAppletInfo() {
return "Applet Information";
}
/**Get parameter info*/
@Override
public String[][] getParameterInfo() {
return null;
}
/**
* opens a url and returns an inputstream
*
*/
private InputStream getXLSFromURL(String urlstring) throws MalformedURLException, IOException {
URL url = new URL(urlstring);
URLConnection uc = url.openConnection();
String field = uc.getHeaderField(0);
for (int i=0;field != null; i++) {
System.out.println(field);
field = uc.getHeaderField(i);
}
return new BufferedInputStream(uc.getInputStream());
}
/**Main method*/
public static void main(String[] args) {
if(args.length < 1) {
throw new IllegalArgumentException("A filename to view must be supplied as the first argument, but none was given");
/**
* Construct the applet
*/
public SViewer() {
}
SViewer applet = new SViewer();
applet.isStandalone = true;
applet.filename = args[0];
Frame frame;
frame = new Frame() {
@Override
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.exit(0);
/**
* Initialize the applet
*/
@Override
public void init() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
@Override
public synchronized void setTitle(String title) {
super.setTitle(title);
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
}
};
frame.setTitle("Applet Frame");
frame.add(applet, BorderLayout.CENTER);
applet.init();
applet.start();
frame.setSize(400,320);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
frame.setVisible(true);
}
}
/**
* Component initialization
*/
private void jbInit() throws Exception {
boolean isurl = false;
if (filename == null) {
filename = getParameter("filename");
}
if (filename == null || filename.contains("://")) {
isurl = true;
if (filename == null) {
filename = getParameter("url");
}
}
final HSSFWorkbook wb;
try (InputStream is = isurl ? getXLSFromURL(filename) : new FileInputStream(filename)) {
wb = new HSSFWorkbook(is);
}
panel = new SViewerPanel(wb, false);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(panel, BorderLayout.CENTER);
}
/**
* Start the applet
*/
@Override
public void start() {
}
/**
* Stop the applet
*/
@Override
public void stop() {
}
/**
* Destroy the applet
*/
@Override
public void destroy() {
}
/**
* Get Applet information
*/
@Override
public String getAppletInfo() {
return "Applet Information";
}
/**
* Get parameter info
*/
@Override
public String[][] getParameterInfo() {
return null;
}
/**
* opens a url and returns an inputstream
*/
private InputStream getXLSFromURL(String urlstring) throws MalformedURLException, IOException {
URL url = new URL(urlstring);
URLConnection uc = url.openConnection();
String field = uc.getHeaderField(0);
for (int i = 0; field != null; i++) {
System.out.println(field);
field = uc.getHeaderField(i);
}
return new BufferedInputStream(uc.getInputStream());
}
/**
* Main method
*/
public static void main(String[] args) {
if (args.length < 1) {
throw new IllegalArgumentException("A filename to view must be supplied as the first argument, but none was given");
}
SViewer applet = new SViewer();
applet.isStandalone = true;
applet.filename = args[0];
Frame frame;
frame = new Frame() {
@Override
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.exit(0);
}
}
@Override
public synchronized void setTitle(String title) {
super.setTitle(title);
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
}
};
frame.setTitle("Applet Frame");
frame.add(applet, BorderLayout.CENTER);
applet.init();
applet.start();
frame.setSize(400, 320);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
frame.setVisible(true);
}
}

View File

@ -65,41 +65,36 @@ public class ConditionalFormats {
* @param args pass "-xls" to generate an HSSF workbook, default is XSSF
*/
public static void main(String[] args) throws IOException {
Workbook wb;
final boolean isHSSF = args.length > 0 && args[0].equals("-xls");
try (Workbook wb = isHSSF ? new HSSFWorkbook() : new XSSFWorkbook()) {
if(args.length > 0 && args[0].equals("-xls")) {
wb = new HSSFWorkbook();
} else {
wb = new XSSFWorkbook();
sameCell(wb.createSheet("Same Cell"));
multiCell(wb.createSheet("MultiCell"));
overlapping(wb.createSheet("Overlapping"));
errors(wb.createSheet("Errors"));
hideDupplicates(wb.createSheet("Hide Dups"));
formatDuplicates(wb.createSheet("Duplicates"));
inList(wb.createSheet("In List"));
expiry(wb.createSheet("Expiry"));
shadeAlt(wb.createSheet("Shade Alt"));
shadeBands(wb.createSheet("Shade Bands"));
iconSets(wb.createSheet("Icon Sets"));
colourScales(wb.createSheet("Colour Scales"));
dataBars(wb.createSheet("Data Bars"));
// print overlapping rule results
evaluateRules(wb, "Overlapping");
// Write the output to a file
String file = "cf-poi.xls";
if (wb instanceof XSSFWorkbook) {
file += "x";
}
try (FileOutputStream out = new FileOutputStream(file)) {
wb.write(out);
}
System.out.println("Generated: " + file);
}
sameCell(wb.createSheet("Same Cell"));
multiCell(wb.createSheet("MultiCell"));
overlapping(wb.createSheet("Overlapping"));
errors(wb.createSheet("Errors"));
hideDupplicates(wb.createSheet("Hide Dups"));
formatDuplicates(wb.createSheet("Duplicates"));
inList(wb.createSheet("In List"));
expiry(wb.createSheet("Expiry"));
shadeAlt(wb.createSheet("Shade Alt"));
shadeBands(wb.createSheet("Shade Bands"));
iconSets(wb.createSheet("Icon Sets"));
colourScales(wb.createSheet("Colour Scales"));
dataBars(wb.createSheet("Data Bars"));
// print overlapping rule results
evaluateRules(wb, "Overlapping");
// Write the output to a file
String file = "cf-poi.xls";
if(wb instanceof XSSFWorkbook) {
file += "x";
}
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.close();
System.out.println("Generated: " + file);
wb.close();
}
/**

View File

@ -83,9 +83,7 @@ public class ChartFromScratch {
Double[] values1 = listCountries.toArray(new Double[0]);
Double[] values2 = listSpeakers.toArray(new Double[0]);
try {
XMLSlideShow ppt = new XMLSlideShow();
try (XMLSlideShow ppt = new XMLSlideShow()) {
XSLFSlide slide = ppt.createSlide();
XSLFChart chart = ppt.createChart();
Rectangle2D rect2D = new java.awt.Rectangle(XDDFChart.DEFAULT_X, XDDFChart.DEFAULT_Y,
@ -97,10 +95,6 @@ public class ChartFromScratch {
ppt.write(out);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println("Done");
}

View File

@ -123,42 +123,40 @@ public class BiffDrawingToXml {
return;
}
String input = getInputFileName(params);
FileInputStream inp = new FileInputStream(input);
String output = getOutputFileName(input);
FileOutputStream outputStream = new FileOutputStream(output);
writeToFile(outputStream, inp, isExcludeWorkbookRecords(params), params);
inp.close();
outputStream.close();
try (FileInputStream inp = new FileInputStream(input);
FileOutputStream outputStream = new FileOutputStream(output)) {
writeToFile(outputStream, inp, isExcludeWorkbookRecords(params), params);
}
}
public static void writeToFile(OutputStream fos, InputStream xlsWorkbook, boolean excludeWorkbookRecords, String[] params) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook(xlsWorkbook);
InternalWorkbook internalWorkbook = workbook.getInternalWorkbook();
DrawingGroupRecord r = (DrawingGroupRecord) internalWorkbook.findFirstRecordBySid(DrawingGroupRecord.sid);
try (HSSFWorkbook workbook = new HSSFWorkbook(xlsWorkbook)) {
InternalWorkbook internalWorkbook = workbook.getInternalWorkbook();
DrawingGroupRecord r = (DrawingGroupRecord) internalWorkbook.findFirstRecordBySid(DrawingGroupRecord.sid);
StringBuilder builder = new StringBuilder();
builder.append("<workbook>\n");
String tab = "\t";
if (!excludeWorkbookRecords && r != null) {
r.decode();
List<EscherRecord> escherRecords = r.getEscherRecords();
for (EscherRecord record : escherRecords) {
builder.append(record.toXml(tab));
StringBuilder builder = new StringBuilder();
builder.append("<workbook>\n");
String tab = "\t";
if (!excludeWorkbookRecords && r != null) {
r.decode();
List<EscherRecord> escherRecords = r.getEscherRecords();
for (EscherRecord record : escherRecords) {
builder.append(record.toXml(tab));
}
}
}
List<Integer> sheets = getSheetsIndexes(params, workbook);
for (Integer i : sheets) {
HSSFPatriarch p = workbook.getSheetAt(i).getDrawingPatriarch();
if(p != null ) {
builder.append(tab).append("<sheet").append(i).append(">\n");
builder.append(p.getBoundAggregate().toXml(tab + "\t"));
builder.append(tab).append("</sheet").append(i).append(">\n");
List<Integer> sheets = getSheetsIndexes(params, workbook);
for (Integer i : sheets) {
HSSFPatriarch p = workbook.getSheetAt(i).getDrawingPatriarch();
if (p != null) {
builder.append(tab).append("<sheet").append(i).append(">\n");
builder.append(p.getBoundAggregate().toXml(tab + "\t"));
builder.append(tab).append("</sheet").append(i).append(">\n");
}
}
builder.append("</workbook>\n");
fos.write(builder.toString().getBytes(StringUtil.UTF8));
}
builder.append("</workbook>\n");
fos.write(builder.toString().getBytes(StringUtil.UTF8));
fos.close();
workbook.close();
}
}

View File

@ -223,24 +223,17 @@ public class ExcelExtractor extends POIOLE2TextExtractor implements org.apache.p
return;
}
InputStream is;
if(cmdArgs.getInputFile() == null) {
is = System.in;
} else {
is = new FileInputStream(cmdArgs.getInputFile());
try (InputStream is = cmdArgs.getInputFile() == null ? System.in : new FileInputStream(cmdArgs.getInputFile());
HSSFWorkbook wb = new HSSFWorkbook(is);
ExcelExtractor extractor = new ExcelExtractor(wb);
) {
extractor.setIncludeSheetNames(cmdArgs.shouldShowSheetNames());
extractor.setFormulasNotResults(!cmdArgs.shouldEvaluateFormulas());
extractor.setIncludeCellComments(cmdArgs.shouldShowCellComments());
extractor.setIncludeBlankCells(cmdArgs.shouldShowBlankCells());
extractor.setIncludeHeadersFooters(cmdArgs.shouldIncludeHeadersFooters());
System.out.println(extractor.getText());
}
HSSFWorkbook wb = new HSSFWorkbook(is);
is.close();
ExcelExtractor extractor = new ExcelExtractor(wb);
extractor.setIncludeSheetNames(cmdArgs.shouldShowSheetNames());
extractor.setFormulasNotResults(!cmdArgs.shouldEvaluateFormulas());
extractor.setIncludeCellComments(cmdArgs.shouldShowCellComments());
extractor.setIncludeBlankCells(cmdArgs.shouldShowBlankCells());
extractor.setIncludeHeadersFooters(cmdArgs.shouldIncludeHeadersFooters());
System.out.println(extractor.getText());
extractor.close();
wb.close();
}
@Override

View File

@ -121,7 +121,7 @@ public class StandardDecryptor extends Decryptor implements Cloneable {
}
@Override
@SuppressWarnings("resource")
@SuppressWarnings({"resource", "squid:S2095"})
public InputStream getDataStream(DirectoryNode dir) throws IOException {
DocumentInputStream dis = dir.createDocumentInputStream(DEFAULT_POIFS_ENTRY);

View File

@ -127,7 +127,7 @@ public class StandardEncryptor extends Encryptor implements Cloneable {
protected final File fileOut;
protected final DirectoryNode dir;
@SuppressWarnings("resource")
@SuppressWarnings({"resource", "squid:S2095"})
private StandardCipherOutputStream(DirectoryNode dir, File fileOut) throws IOException {
// although not documented, we need the same padding as with agile encryption
// and instead of calculating the missing bytes for the block size ourselves

View File

@ -62,16 +62,15 @@ public class POIFSLister {
}
public static void viewFile(final String filename, boolean withSizes) throws IOException {
POIFSFileSystem fs = new POIFSFileSystem(new File(filename));
displayDirectory(fs.getRoot(), "", withSizes);
fs.close();
try (POIFSFileSystem fs = new POIFSFileSystem(new File(filename))) {
displayDirectory(fs.getRoot(), "", withSizes);
}
}
public static void viewFileOld(final String filename, boolean withSizes) throws IOException {
try (FileInputStream fis = new FileInputStream(filename)) {
POIFSFileSystem fs = new POIFSFileSystem(fis);
try (FileInputStream fis = new FileInputStream(filename);
POIFSFileSystem fs = new POIFSFileSystem(fis)) {
displayDirectory(fs.getRoot(), "", withSizes);
fs.close();
}
}

View File

@ -107,13 +107,11 @@ public class Ole10Native {
* @throws Ole10NativeException on invalid or unexcepted data format
*/
public static Ole10Native createFromEmbeddedOleObject(DirectoryNode directory) throws IOException, Ole10NativeException {
DocumentEntry nativeEntry =
(DocumentEntry)directory.getEntry(OLE10_NATIVE);
byte[] data = IOUtils.safelyAllocate(nativeEntry.getSize(), MAX_RECORD_LENGTH);
int readBytes = directory.createDocumentInputStream(nativeEntry).read(data);
assert(readBytes == data.length);
return new Ole10Native(data, 0);
DocumentEntry nativeEntry = (DocumentEntry)directory.getEntry(OLE10_NATIVE);
try (DocumentInputStream dis = directory.createDocumentInputStream(nativeEntry)) {
byte[] data = IOUtils.toByteArray(dis, nativeEntry.getSize(), MAX_RECORD_LENGTH);
return new Ole10Native(data, 0);
}
}
/**

View File

@ -78,10 +78,11 @@ public class VBAMacroExtractor {
} else {
System.err.println("STDOUT");
}
VBAMacroReader reader = new VBAMacroReader(input);
Map<String,String> macros = reader.readMacros();
reader.close();
final Map<String,String> macros;
try (VBAMacroReader reader = new VBAMacroReader(input)) {
macros = reader.readMacros();
}
final String divider = "---------------------------------------";
for (Entry<String, String> entry : macros.entrySet()) {
@ -94,11 +95,10 @@ public class VBAMacroExtractor {
System.out.println(moduleCode);
} else {
File out = new File(outputDir, moduleName + extension);
FileOutputStream fout = new FileOutputStream(out);
OutputStreamWriter fwriter = new OutputStreamWriter(fout, StringUtil.UTF8);
fwriter.write(moduleCode);
fwriter.close();
fout.close();
try (FileOutputStream fout = new FileOutputStream(out);
OutputStreamWriter fwriter = new OutputStreamWriter(fout, StringUtil.UTF8)) {
fwriter.write(moduleCode);
}
System.out.println("Extracted " + out);
}
}

View File

@ -17,16 +17,26 @@
package org.apache.poi.ooxml.util;
import org.apache.poi.openxml4j.opc.*;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ooxml.POIXMLException;
import org.apache.poi.util.IOUtils;
import java.io.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import org.apache.poi.ooxml.POIXMLException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackageProperties;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.util.IOUtils;
/**
* Provides handy methods to work with OOXML packages
*/
@ -51,27 +61,27 @@ public final class PackageHelper {
String path = file.getAbsolutePath();
OPCPackage dest = OPCPackage.create(path);
PackageRelationshipCollection rels = pkg.getRelationships();
for (PackageRelationship rel : rels) {
PackagePart part = pkg.getPart(rel);
PackagePart part_tgt;
if (rel.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) {
copyProperties(pkg.getPackageProperties(), dest.getPackageProperties());
continue;
}
dest.addRelationship(part.getPartName(), rel.getTargetMode(), rel.getRelationshipType());
part_tgt = dest.createPart(part.getPartName(), part.getContentType());
try (OPCPackage dest = OPCPackage.create(path)) {
PackageRelationshipCollection rels = pkg.getRelationships();
for (PackageRelationship rel : rels) {
PackagePart part = pkg.getPart(rel);
PackagePart part_tgt;
if (rel.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) {
copyProperties(pkg.getPackageProperties(), dest.getPackageProperties());
continue;
}
dest.addRelationship(part.getPartName(), rel.getTargetMode(), rel.getRelationshipType());
part_tgt = dest.createPart(part.getPartName(), part.getContentType());
OutputStream out = part_tgt.getOutputStream();
IOUtils.copy(part.getInputStream(), out);
out.close();
OutputStream out = part_tgt.getOutputStream();
IOUtils.copy(part.getInputStream(), out);
out.close();
if(part.hasRelationships()) {
copy(pkg, part, dest, part_tgt);
if (part.hasRelationships()) {
copy(pkg, part, dest, part_tgt);
}
}
}
dest.close();
//the temp file will be deleted when JVM terminates
new File(path).deleteOnExit();

View File

@ -120,34 +120,33 @@ public final class AesZipFileZipEntrySource implements ZipEntrySource {
SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, CipherAlgorithm.aes128.jceId);
Cipher ciEnc = CryptoFunctions.getCipher(skeySpec, CipherAlgorithm.aes128, ChainingMode.cbc, ivBytes, Cipher.ENCRYPT_MODE, PADDING);
ZipArchiveInputStream zis = new ZipArchiveInputStream(is);
FileOutputStream fos = new FileOutputStream(tmpFile);
ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos);
ZipArchiveEntry ze;
while ((ze = zis.getNextZipEntry()) != null) {
// the cipher output stream pads the data, therefore we can't reuse the ZipEntry with set sizes
// as those will be validated upon close()
ZipArchiveEntry zeNew = new ZipArchiveEntry(ze.getName());
zeNew.setComment(ze.getComment());
zeNew.setExtra(ze.getExtra());
zeNew.setTime(ze.getTime());
// zeNew.setMethod(ze.getMethod());
zos.putArchiveEntry(zeNew);
FilterOutputStream fos2 = new FilterOutputStream(zos) {
// don't close underlying ZipOutputStream
@Override
public void close() {}
};
CipherOutputStream cos = new CipherOutputStream(fos2, ciEnc);
IOUtils.copy(zis, cos);
cos.close();
fos2.close();
zos.closeArchiveEntry();
try (ZipArchiveInputStream zis = new ZipArchiveInputStream(is);
FileOutputStream fos = new FileOutputStream(tmpFile);
ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos)) {
ZipArchiveEntry ze;
while ((ze = zis.getNextZipEntry()) != null) {
// the cipher output stream pads the data, therefore we can't reuse the ZipEntry with set sizes
// as those will be validated upon close()
ZipArchiveEntry zeNew = new ZipArchiveEntry(ze.getName());
zeNew.setComment(ze.getComment());
zeNew.setExtra(ze.getExtra());
zeNew.setTime(ze.getTime());
// zeNew.setMethod(ze.getMethod());
zos.putArchiveEntry(zeNew);
FilterOutputStream fos2 = new FilterOutputStream(zos) {
// don't close underlying ZipOutputStream
@Override
public void close() {
}
};
CipherOutputStream cos = new CipherOutputStream(fos2, ciEnc);
IOUtils.copy(zis, cos);
cos.close();
fos2.close();
zos.closeArchiveEntry();
}
}
zos.close();
fos.close();
zis.close();
}
private static AesZipFileZipEntrySource fileToSource(File tmpFile, byte[] keyBytes, byte[] ivBytes) throws IOException {

View File

@ -337,6 +337,7 @@ public final class PPTX2PNG {
}
}
@SuppressWarnings({"resource", "squid:S2095"})
private MFProxy initProxy(File file) throws IOException {
MFProxy proxy;
final String fileName = file.getName().toLowerCase(Locale.ROOT);

View File

@ -51,16 +51,12 @@ public final class VSDDumper {
System.exit(1);
}
POIFSFileSystem poifs = new POIFSFileSystem(new File(args[0]));
try {
HDGFDiagram hdgf = new HDGFDiagram(poifs);
try (POIFSFileSystem poifs = new POIFSFileSystem(new File(args[0]));
HDGFDiagram hdgf = new HDGFDiagram(poifs)) {
PrintStream ps = System.out;
ps.println("Opened " + args[0]);
VSDDumper vd = new VSDDumper(ps, hdgf);
vd.dumpFile();
} finally {
poifs.close();
}
}

View File

@ -51,108 +51,108 @@ public final class SlideIdListing {
// Create the slideshow object, for normal working with
HSLFSlideShowImpl hss = new HSLFSlideShowImpl(args[0]);
HSLFSlideShow ss = new HSLFSlideShow(hss);
try (HSLFSlideShowImpl hss = new HSLFSlideShowImpl(args[0]);
HSLFSlideShow ss = new HSLFSlideShow(hss)) {
// Grab the base contents
fileContents = hss.getUnderlyingBytes();
Record[] records = hss.getRecords();
Record[] latestRecords = ss.getMostRecentCoreRecords();
// Grab the base contents
fileContents = hss.getUnderlyingBytes();
Record[] records = hss.getRecords();
Record[] latestRecords = ss.getMostRecentCoreRecords();
// Grab any records that interest us
Document document = null;
for (Record latestRecord : latestRecords) {
if (latestRecord instanceof Document) {
document = (Document) latestRecord;
}
}
System.out.println();
// Look for SlidePersistAtoms, and report what they have to
// say about possible slide IDs
SlideListWithText[] slwts = document.getSlideListWithTexts();
for (SlideListWithText slwt : slwts) {
Record[] cr = slwt.getChildRecords();
for (Record record : cr) {
if (record instanceof SlidePersistAtom) {
SlidePersistAtom spa = (SlidePersistAtom) record;
System.out.println("SlidePersistAtom knows about slide:");
System.out.println("\t" + spa.getRefID());
System.out.println("\t" + spa.getSlideIdentifier());
// Grab any records that interest us
Document document = null;
for (Record latestRecord : latestRecords) {
if (latestRecord instanceof Document) {
document = (Document) latestRecord;
}
}
}
System.out.println();
System.out.println();
// Look for latest core records that are slides or notes
for (int i=0; i<latestRecords.length; i++) {
if (latestRecords[i] instanceof Slide) {
Slide s = (Slide)latestRecords[i];
SlideAtom sa = s.getSlideAtom();
System.out.println("Found the latest version of a slide record:");
System.out.println("\tCore ID is " + s.getSheetId());
System.out.println("\t(Core Records count is " + i + ")");
System.out.println("\tDisk Position is " + s.getLastOnDiskOffset());
System.out.println("\tMaster ID is " + sa.getMasterID());
System.out.println("\tNotes ID is " + sa.getNotesID());
}
}
System.out.println();
for (int i=0; i<latestRecords.length; i++) {
if (latestRecords[i] instanceof Notes) {
Notes n = (Notes)latestRecords[i];
NotesAtom na = n.getNotesAtom();
System.out.println("Found the latest version of a notes record:");
System.out.println("\tCore ID is " + n.getSheetId());
System.out.println("\t(Core Records count is " + i + ")");
System.out.println("\tDisk Position is " + n.getLastOnDiskOffset());
System.out.println("\tMatching slide is " + na.getSlideID());
}
}
System.out.println();
// Find any persist ones first
int pos = 0;
for (Record r : records) {
if (r.getRecordType() == 6001L) {
// PersistPtrFullBlock
System.out.println("Found PersistPtrFullBlock at " + pos + " (" + Integer.toHexString(pos) + ")");
}
if (r.getRecordType() == 6002L) {
// PersistPtrIncrementalBlock
System.out.println("Found PersistPtrIncrementalBlock at " + pos + " (" + Integer.toHexString(pos) + ")");
PersistPtrHolder pph = (PersistPtrHolder) r;
// Check the sheet offsets
int[] sheetIDs = pph.getKnownSlideIDs();
Map<Integer, Integer> sheetOffsets = pph.getSlideLocationsLookup();
for (Integer id : sheetIDs) {
Integer offset = sheetOffsets.get(id);
System.out.println(" Knows about sheet " + id);
System.out.println(" That sheet lives at " + offset);
Record atPos = findRecordAtPos(offset.intValue());
System.out.println(" The record at that pos is of type " + atPos.getRecordType());
System.out.println(" The record at that pos has class " + atPos.getClass().getName());
if (!(atPos instanceof PositionDependentRecord)) {
System.out.println(" ** The record class isn't position aware! **");
// Look for SlidePersistAtoms, and report what they have to
// say about possible slide IDs
SlideListWithText[] slwts = document.getSlideListWithTexts();
for (SlideListWithText slwt : slwts) {
Record[] cr = slwt.getChildRecords();
for (Record record : cr) {
if (record instanceof SlidePersistAtom) {
SlidePersistAtom spa = (SlidePersistAtom) record;
System.out.println("SlidePersistAtom knows about slide:");
System.out.println("\t" + spa.getRefID());
System.out.println("\t" + spa.getSlideIdentifier());
}
}
}
// Increase the position by the on disk size
ByteArrayOutputStream baos = new ByteArrayOutputStream();
r.writeOut(baos);
pos += baos.size();
}
System.out.println();
ss.close();
// Look for latest core records that are slides or notes
for (int i = 0; i < latestRecords.length; i++) {
if (latestRecords[i] instanceof Slide) {
Slide s = (Slide) latestRecords[i];
SlideAtom sa = s.getSlideAtom();
System.out.println("Found the latest version of a slide record:");
System.out.println("\tCore ID is " + s.getSheetId());
System.out.println("\t(Core Records count is " + i + ")");
System.out.println("\tDisk Position is " + s.getLastOnDiskOffset());
System.out.println("\tMaster ID is " + sa.getMasterID());
System.out.println("\tNotes ID is " + sa.getNotesID());
}
}
System.out.println();
for (int i = 0; i < latestRecords.length; i++) {
if (latestRecords[i] instanceof Notes) {
Notes n = (Notes) latestRecords[i];
NotesAtom na = n.getNotesAtom();
System.out.println("Found the latest version of a notes record:");
System.out.println("\tCore ID is " + n.getSheetId());
System.out.println("\t(Core Records count is " + i + ")");
System.out.println("\tDisk Position is " + n.getLastOnDiskOffset());
System.out.println("\tMatching slide is " + na.getSlideID());
}
}
System.out.println();
// Find any persist ones first
int pos = 0;
for (Record r : records) {
if (r.getRecordType() == 6001L) {
// PersistPtrFullBlock
System.out.println("Found PersistPtrFullBlock at " + pos + " (" + Integer.toHexString(pos) + ")");
}
if (r.getRecordType() == 6002L) {
// PersistPtrIncrementalBlock
System.out.println("Found PersistPtrIncrementalBlock at " + pos + " (" + Integer.toHexString(pos) + ")");
PersistPtrHolder pph = (PersistPtrHolder) r;
// Check the sheet offsets
int[] sheetIDs = pph.getKnownSlideIDs();
Map<Integer, Integer> sheetOffsets = pph.getSlideLocationsLookup();
for (Integer id : sheetIDs) {
Integer offset = sheetOffsets.get(id);
System.out.println(" Knows about sheet " + id);
System.out.println(" That sheet lives at " + offset);
Record atPos = findRecordAtPos(offset.intValue());
System.out.println(" The record at that pos is of type " + atPos.getRecordType());
System.out.println(" The record at that pos has class " + atPos.getClass().getName());
if (!(atPos instanceof PositionDependentRecord)) {
System.out.println(" ** The record class isn't position aware! **");
}
}
}
// Increase the position by the on disk size
ByteArrayOutputStream baos = new ByteArrayOutputStream();
r.writeOut(baos);
pos += baos.size();
}
}
System.out.println();
}

View File

@ -35,20 +35,20 @@ public final class ImageExtractor {
System.err.println("\tImageExtractor <file>");
return;
}
HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl(args[0]));
try (HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl(args[0]))) {
//extract all pictures contained in the presentation
int i = 0;
for (HSLFPictureData pict : ppt.getPictureData()) {
// picture data
byte[] data = pict.getData();
//extract all pictures contained in the presentation
int i = 0;
for (HSLFPictureData pict : ppt.getPictureData()) {
// picture data
byte[] data = pict.getData();
PictureType type = pict.getType();
try (FileOutputStream out = new FileOutputStream("pict_" + i++ + type.extension)) {
out.write(data);
}
}
PictureType type = pict.getType();
FileOutputStream out = new FileOutputStream("pict_" + i++ + type.extension);
out.write(data);
out.close();
}
ppt.close();
}
}

View File

@ -79,9 +79,9 @@ public final class PowerPointExtractor extends POIOLE2TextExtractor {
file = args[0];
}
PowerPointExtractor ppe = new PowerPointExtractor(file);
System.out.println(ppe.getText(true, notes, comments, master));
ppe.close();
try (PowerPointExtractor ppe = new PowerPointExtractor(file)) {
System.out.println(ppe.getText(true, notes, comments, master));
}
}
public PowerPointExtractor(final HSLFSlideShow slideShow) {

View File

@ -131,16 +131,9 @@ public class CurrentUserAtom
}
// Grab the contents
int len = docProps.getSize();
_contents = IOUtils.safelyAllocate(len, MAX_RECORD_LENGTH);
InputStream in = dir.createDocumentInputStream("Current User");
int readLen = in.read(_contents);
in.close();
if (len != readLen) {
throw new IOException("Current User input stream ended prematurely - expected "+len+" bytes - received "+readLen+" bytes");
}
try (InputStream in = dir.createDocumentInputStream("Current User")) {
_contents = IOUtils.toByteArray(in, docProps.getSize(), MAX_RECORD_LENGTH);
}
// See how long it is. If it's under 28 bytes long, we can't
// read it

View File

@ -511,33 +511,31 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
persistIds.put(oldToNewPositions.get(entry.getValue()), entry.getKey());
}
HSLFSlideShowEncrypted encData = new HSLFSlideShowEncrypted(getDocumentEncryptionAtom());
try (HSLFSlideShowEncrypted encData = new HSLFSlideShowEncrypted(getDocumentEncryptionAtom())) {
for (Record record : _records) {
assert (record instanceof PositionDependentRecord);
// We've already figured out their new location, and
// told them that
// Tell them of the positions of the other records though
PositionDependentRecord pdr = (PositionDependentRecord) record;
Integer persistId = persistIds.get(pdr.getLastOnDiskOffset());
if (persistId == null) {
persistId = 0;
}
for (Record record : _records) {
assert (record instanceof PositionDependentRecord);
// We've already figured out their new location, and
// told them that
// Tell them of the positions of the other records though
PositionDependentRecord pdr = (PositionDependentRecord) record;
Integer persistId = persistIds.get(pdr.getLastOnDiskOffset());
if (persistId == null) {
persistId = 0;
}
// For now, we're only handling PositionDependentRecord's that
// happen at the top level.
// In future, we'll need the handle them everywhere, but that's
// a bit trickier
pdr.updateOtherRecordReferences(oldToNewPositions);
// For now, we're only handling PositionDependentRecord's that
// happen at the top level.
// In future, we'll need the handle them everywhere, but that's
// a bit trickier
pdr.updateOtherRecordReferences(oldToNewPositions);
// Whatever happens, write out that record tree
if (os != null) {
record.writeOut(encData.encryptRecord(os, persistId, record));
// Whatever happens, write out that record tree
if (os != null) {
record.writeOut(encData.encryptRecord(os, persistId, record));
}
}
}
encData.close();
// Update and write out the Current User atom
int oldLastUserEditAtomPos = (int) currentUser.getCurrentEditOffset();
Integer newLastUserEditAtomPos = oldToNewPositions.get(oldLastUserEditAtomPos);
@ -657,53 +655,52 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
}
getDocumentSummaryInformation();
// set new encryption settings
HSLFSlideShowEncrypted encryptedSS = new HSLFSlideShowEncrypted(getDocumentEncryptionAtom());
_records = encryptedSS.updateEncryptionRecord(_records);
// The list of entries we've written out
List<String> writtenEntries = new ArrayList<>(1);
final List<String> writtenEntries = new ArrayList<>(1);
// Write out the Property Streams
writeProperties(outFS, writtenEntries);
// set new encryption settings
try (HSLFSlideShowEncrypted encryptedSS = new HSLFSlideShowEncrypted(getDocumentEncryptionAtom())) {
_records = encryptedSS.updateEncryptionRecord(_records);
BufAccessBAOS baos = new BufAccessBAOS();
// Write out the Property Streams
writeProperties(outFS, writtenEntries);
// For position dependent records, hold where they were and now are
// As we go along, update, and hand over, to any Position Dependent
// records we happen across
updateAndWriteDependantRecords(baos, null);
BufAccessBAOS baos = new BufAccessBAOS();
// Update our cached copy of the bytes that make up the PPT stream
_docstream = new byte[baos.size()];
System.arraycopy(baos.getBuf(), 0, _docstream, 0, baos.size());
baos.close();
// For position dependent records, hold where they were and now are
// As we go along, update, and hand over, to any Position Dependent
// records we happen across
updateAndWriteDependantRecords(baos, null);
// Write the PPT stream into the POIFS layer
ByteArrayInputStream bais = new ByteArrayInputStream(_docstream);
outFS.createOrUpdateDocument(bais, POWERPOINT_DOCUMENT);
writtenEntries.add(POWERPOINT_DOCUMENT);
// Update our cached copy of the bytes that make up the PPT stream
_docstream = new byte[baos.size()];
System.arraycopy(baos.getBuf(), 0, _docstream, 0, baos.size());
baos.close();
currentUser.setEncrypted(encryptedSS.getDocumentEncryptionAtom() != null);
currentUser.writeToFS(outFS);
writtenEntries.add("Current User");
// Write the PPT stream into the POIFS layer
ByteArrayInputStream bais = new ByteArrayInputStream(_docstream);
outFS.createOrUpdateDocument(bais, POWERPOINT_DOCUMENT);
writtenEntries.add(POWERPOINT_DOCUMENT);
currentUser.setEncrypted(encryptedSS.getDocumentEncryptionAtom() != null);
currentUser.writeToFS(outFS);
writtenEntries.add("Current User");
if (_pictures.size() > 0) {
BufAccessBAOS pict = new BufAccessBAOS();
for (HSLFPictureData p : _pictures) {
int offset = pict.size();
p.write(pict);
encryptedSS.encryptPicture(pict.getBuf(), offset);
}
outFS.createOrUpdateDocument(
if (_pictures.size() > 0) {
BufAccessBAOS pict = new BufAccessBAOS();
for (HSLFPictureData p : _pictures) {
int offset = pict.size();
p.write(pict);
encryptedSS.encryptPicture(pict.getBuf(), offset);
}
outFS.createOrUpdateDocument(
new ByteArrayInputStream(pict.getBuf(), 0, pict.size()), "Pictures"
);
writtenEntries.add("Pictures");
pict.close();
}
);
writtenEntries.add("Pictures");
pict.close();
}
encryptedSS.close();
}
// If requested, copy over any other streams we spot, eg Macros
if (copyAllOtherNodes) {

View File

@ -17,9 +17,10 @@
package org.apache.poi.hwpf;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.security.GeneralSecurityException;
import org.apache.poi.EncryptedDocumentException;
@ -48,7 +49,6 @@ import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.BoundedInputStream;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Internal;
import org.apache.poi.util.LittleEndianByteArrayInputStream;
@ -320,40 +320,29 @@ public abstract class HWPFDocumentCore extends POIDocument {
* @return the read bytes
* @throws IOException if the stream can't be found
*/
protected byte[] getDocumentEntryBytes(String name, int encryptionOffset, int len) throws IOException {
protected byte[] getDocumentEntryBytes(String name, int encryptionOffset, final int len) throws IOException {
DirectoryNode dir = getDirectory();
DocumentEntry documentProps = (DocumentEntry)dir.getEntry(name);
DocumentInputStream dis = dir.createDocumentInputStream(documentProps);
EncryptionInfo ei = (encryptionOffset > -1) ? getEncryptionInfo() : null;
int streamSize = documentProps.getSize();
ByteArrayOutputStream bos = new ByteArrayOutputStream(Math.min(streamSize,len));
boolean isEncrypted = (encryptionOffset > -1 && getEncryptionInfo() != null);
InputStream is = dis;
try {
if (ei != null) {
try {
Decryptor dec = ei.getDecryptor();
is = dec.getDataStream(dis, streamSize, 0);
if (encryptionOffset > 0) {
ChunkedCipherInputStream cis = (ChunkedCipherInputStream)is;
byte[] plain = IOUtils.safelyAllocate(encryptionOffset, MAX_RECORD_LENGTH);
cis.readPlain(plain, 0, encryptionOffset);
bos.write(plain);
}
} catch (GeneralSecurityException e) {
throw new IOException(e.getMessage(), e);
}
}
// This simplifies a few combinations, so we actually always try to copy len bytes
// regardless if encryptionOffset is greater than 0
if (len < Integer.MAX_VALUE) {
is = new BoundedInputStream(is, len);
}
IOUtils.copy(is, bos);
return bos.toByteArray();
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(dis);
try (DocumentInputStream dis = dir.createDocumentInputStream(documentProps);
InputStream is = isEncrypted ? getDecryptedStream(dis, streamSize, encryptionOffset) : dis) {
return IOUtils.toByteArray(is, Math.min(streamSize, len));
} catch (GeneralSecurityException e) {
throw new IOException("Unable to decrypt data for entry: "+name, e);
}
}
private InputStream getDecryptedStream(DocumentInputStream dis, int streamSize, int encryptionOffset)
throws IOException, GeneralSecurityException {
Decryptor dec = getEncryptionInfo().getDecryptor();
ChunkedCipherInputStream cis = (ChunkedCipherInputStream)dec.getDataStream(dis, streamSize, 0);
byte[] plain = {};
if (encryptionOffset > 0) {
plain = IOUtils.safelyAllocate(encryptionOffset, MAX_RECORD_LENGTH);
cis.readPlain(plain, 0, encryptionOffset);
}
return new SequenceInputStream(new ByteArrayInputStream(plain), cis);
}
}

View File

@ -19,7 +19,6 @@ package org.apache.poi.hssf.dev;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintStream;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.OldExcelFormatException;
@ -50,15 +49,8 @@ public class TestBiffDrawingToXml extends BaseXLSIteratingTest {
@Override
void runOneFile(File pFile) throws Exception {
PrintStream save = System.out;
try {
//System.setOut(new PrintStream(TestBiffViewer.NULL_OUTPUT_STREAM));
// use a NullOutputStream to not write the bytes anywhere for best runtime
try (InputStream wb = new FileInputStream(pFile)) {
BiffDrawingToXml.writeToFile(NULL_OUTPUT_STREAM, wb, false, new String[]{});
}
} finally {
System.setOut(save);
}
try (InputStream wb = new FileInputStream(pFile)) {
BiffDrawingToXml.writeToFile(NULL_OUTPUT_STREAM, wb, false, new String[0]);
}
}
}