From 2841f3cd0e71a366f7e1fd91a61fbedcbd67cf5d Mon Sep 17 00:00:00 2001
From: Andreas Beeker
Main method - see class description.
@@ -91,6 +94,7 @@ public class ModifyDocumentSummaryInformation { // There is no summary information yet. We have to create a new one si = PropertySetFactory.newSummaryInformation(); } + assert(si != null); /* Change the author to "Rainer Klute". Any former author value will * be lost. If there has been no author yet, it will be created. */ @@ -112,6 +116,7 @@ public class ModifyDocumentSummaryInformation { * new one. */ dsi = PropertySetFactory.newDocumentSummaryInformation(); } + assert(dsi != null); /* Change the category to "POI example". Any former category value will * be lost. If there has been no category yet, it will be created. */ diff --git a/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java b/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java index 9282b7cd32..f2b47e6de5 100644 --- a/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java +++ b/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java @@ -28,8 +28,6 @@ import org.apache.poi.hpsf.PropertySetFactory; import org.apache.poi.hpsf.Section; import org.apache.poi.poifs.eventfilesystem.POIFSReader; import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.util.HexDump; /** *Sample application showing how to read a document's custom property set. @@ -37,6 +35,7 @@ import org.apache.poi.util.HexDump; * *
Explanations can be found in the HPSF HOW-TO.
*/ +@SuppressWarnings({"java:S106","java:S4823"}) public final class ReadCustomPropertySets { private ReadCustomPropertySets() {} @@ -47,85 +46,63 @@ public final class ReadCustomPropertySets { * @param args Command-line arguments (unused). * @throws IOException if any I/O exception occurs. */ - public static void main(final String[] args) - throws IOException - { + public static void main(final String[] args) throws IOException { final String filename = args[0]; POIFSReader r = new POIFSReader(); /* Register a listener for *all* documents. */ - r.registerListener(new MyPOIFSReaderListener()); + r.registerListener(ReadCustomPropertySets::processPOIFSReaderEvent); r.read(new File(filename)); } - static class MyPOIFSReaderListener implements POIFSReaderListener - { - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - PropertySet ps; - try - { - ps = PropertySetFactory.create(event.getStream()); - } - catch (NoPropertySetStreamException ex) - { - out("No property set stream: \"" + event.getPath() + - event.getName() + "\""); - return; - } - catch (Exception ex) - { - throw new RuntimeException - ("Property set stream \"" + - event.getPath() + event.getName() + "\": " + ex); - } + public static void processPOIFSReaderEvent(final POIFSReaderEvent event) { + final String streamName = event.getPath() + event.getName(); + PropertySet ps; + try { + ps = PropertySetFactory.create(event.getStream()); + } catch (NoPropertySetStreamException ex) { + out("No property set stream: \"" + streamName + "\""); + return; + } catch (Exception ex) { + throw new RuntimeException("Property set stream \"" + streamName + "\": " + ex); + } - /* Print the name of the property set stream: */ - out("Property set stream \"" + event.getPath() + - event.getName() + "\":"); + /* Print the name of the property set stream: */ + out("Property set stream \"" + streamName + "\":"); - /* Print the number of sections: */ - final long sectionCount = ps.getSectionCount(); - out(" No. of sections: " + sectionCount); + /* Print the number of sections: */ + final long sectionCount = ps.getSectionCount(); + out(" No. of sections: " + sectionCount); - /* Print the list of sections: */ - ListSample application showing how to read a OLE 2 document's @@ -33,8 +32,8 @@ import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; * *
Explanations can be found in the HPSF HOW-TO.
*/ -public final class ReadTitle -{ +@SuppressWarnings({"java:S106","java:S4823"}) +public final class ReadTitle { private ReadTitle() {} /** @@ -44,38 +43,22 @@ public final class ReadTitle * be the name of a POI filesystem to read. * @throws IOException if any I/O exception occurs. */ - public static void main(final String[] args) throws IOException - { + public static void main(final String[] args) throws IOException { final String filename = args[0]; POIFSReader r = new POIFSReader(); - r.registerListener(new MyPOIFSReaderListener(), SummaryInformation.DEFAULT_STREAM_NAME); + r.registerListener(ReadTitle::processPOIFSReaderEvent, SummaryInformation.DEFAULT_STREAM_NAME); r.read(new File(filename)); } - static class MyPOIFSReaderListener implements POIFSReaderListener - { - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - SummaryInformation si; - try - { - si = (SummaryInformation) - PropertySetFactory.create(event.getStream()); - } - catch (Exception ex) - { - throw new RuntimeException - ("Property set stream \"" + - event.getPath() + event.getName() + "\": " + ex); - } - final String title = si.getTitle(); - if (title != null) - System.out.println("Title: \"" + title + "\""); - else - System.out.println("Document has no title."); + private static void processPOIFSReaderEvent(final POIFSReaderEvent event) { + SummaryInformation si; + try { + si = (SummaryInformation) PropertySetFactory.create(event.getStream()); + } catch (Exception ex) { + throw new RuntimeException("Property set stream \"" + event.getPath() + event.getName() + "\": " + ex); } + final String title = si.getTitle(); + System.out.println(title != null ? "Title: \"" + title + "\"" : "Document has no title."); } - } diff --git a/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java b/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java index 36c6f8287a..5a03de0edb 100644 --- a/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java +++ b/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java @@ -17,15 +17,11 @@ package org.apache.poi.hpsf.examples; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.util.HashMap; -import java.util.Map; import org.apache.poi.hpsf.HPSFRuntimeException; import org.apache.poi.hpsf.MarkUnsupportedException; @@ -39,7 +35,6 @@ import org.apache.poi.hpsf.WritingNotSupportedException; import org.apache.poi.hpsf.wellknown.PropertyIDMap; import org.apache.poi.poifs.eventfilesystem.POIFSReader; import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; import org.apache.poi.poifs.filesystem.DirectoryEntry; import org.apache.poi.poifs.filesystem.DocumentInputStream; import org.apache.poi.poifs.filesystem.POIFSDocumentPath; @@ -49,15 +44,15 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem; *This class is a sample application which shows how to write or modify the * author and title property of an OLE 2 document. This could be done in two * different ways:
- * + * *The first approach is to open the OLE 2 file as a POI filesystem * (see class {@link POIFSFileSystem}), read the summary information property * set (see classes {@link SummaryInformation} and {@link PropertySet}), write * the author and title properties into it and write the property set back into * the POI filesystem.
The second approach does not modify the original POI filesystem, but * instead creates a new one. All documents from the original POIFS are copied * to the destination POIFS, except for the summary information stream. The @@ -65,9 +60,9 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem; * it to the destination POIFS. It there are several summary information streams * in the original POIFS - e.g. in subordinate directories - they are modified * just the same.
This sample application takes the second approach. It expects the name of * the existing POI filesystem's name as its first command-line parameter and * the name of the output POIFS as the second command-line argument. The @@ -76,9 +71,10 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem; * encounters a summary information stream it reads its properties. Then it sets * the "author" and "title" properties to new values and writes the modified * summary information stream into the output file.
- * + * *Further explanations can be found in the HPSF HOW-TO.
*/ +@SuppressWarnings({"java:S106","java:S4823"}) public final class WriteAuthorAndTitle { private WriteAuthorAndTitle() {} @@ -89,301 +85,89 @@ public final class WriteAuthorAndTitle { * be the name of a POI filesystem to read. * @throws IOException if any I/O exception occurs. */ - public static void main(final String[] args) throws IOException - { + public static void main(final String[] args) throws IOException { /* Check whether we have exactly two command-line arguments. */ - if (args.length != 2) - { - System.err.println("Usage: " + WriteAuthorAndTitle.class.getName() + - " originPOIFS destinationPOIFS"); + if (args.length != 2) { + System.err.println("Usage: WriteAuthorAndTitle originPOIFS destinationPOIFS"); System.exit(1); } - + /* Read the names of the origin and destination POI filesystems. */ - final String srcName = args[0]; - final String dstName = args[1]; + final String srcName = args[0], dstName = args[1]; /* Read the origin POIFS using the eventing API. The real work is done * in the class ModifySICopyTheRest which is registered here as a * POIFSReader. */ - final POIFSReader r = new POIFSReader(); - final ModifySICopyTheRest msrl = new ModifySICopyTheRest(dstName); - r.registerListener(msrl); - r.read(new File(srcName)); + try (POIFSFileSystem poifs = new POIFSFileSystem(); + OutputStream out = new FileOutputStream(dstName)) { + final POIFSReader r = new POIFSReader(); + r.registerListener((e) -> handleEvent(poifs, e)); + r.read(new File(srcName)); - /* Write the new POIFS to disk. */ - msrl.close(); + /* Write the new POIFS to disk. */ + poifs.writeFilesystem(out); + } } - + private interface InputStreamSupplier { + InputStream get() throws IOException, WritingNotSupportedException; + } /** - *This class does all the work. As its name implies it modifies a - * summary information property set and copies everything else unmodified - * to the destination POI filesystem. Since an instance of it is registered - * as a {@link POIFSReader} its method {@link - * #processPOIFSReaderEvent(POIFSReaderEvent)} is called for each document - * in the origin POIFS.
+ * The method is called by POI's eventing API for each file in the origin POIFS. */ - static class ModifySICopyTheRest implements POIFSReaderListener - { - private String dstName; - private OutputStream out; - private POIFSFileSystem poiFs; + private static void handleEvent(final POIFSFileSystem poiFs, final POIFSReaderEvent event) { + // The following declarations are shortcuts for accessing the "event" object. + final DocumentInputStream stream = event.getStream(); + try { + final InputStreamSupplier isSup; - /** - * The constructor of a {@link ModifySICopyTheRest} instance creates - * the target POIFS. It also stores the name of the file the POIFS will - * be written to once it is complete. - * - * @param dstName The name of the disk file the destination POIFS is to - * be written to. - */ - ModifySICopyTheRest(final String dstName) - { - this.dstName = dstName; - poiFs = new POIFSFileSystem(); - } + // Find out whether the current document is a property set stream or not. + if (PropertySet.isPropertySetStream(stream)) { + // Yes, the current document is a property set stream. Let's create a PropertySet instance from it. + PropertySet ps = PropertySetFactory.create(stream); + // Now we know that we really have a property set. + // The next step is to find out whether it is a summary information or not. + if (ps.isSummaryInformation()) { + // Create a mutable property set as a copy of the original read-only property set. + ps = new PropertySet(ps); - /** - * The method is called by POI's eventing API for each file in the - * origin POIFS. - */ - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - /* The following declarations are shortcuts for accessing the - * "event" object. */ - final POIFSDocumentPath path = event.getPath(); - final String name = event.getName(); - final DocumentInputStream stream = event.getStream(); + // Retrieve the section containing the properties to modify. + // A summary information property set contains exactly one section. + final Section s = ps.getSections().get(0); - Throwable t = null; - - try { - /* Find out whether the current document is a property set - * stream or not. */ - if (PropertySet.isPropertySetStream(stream)) { - try { - /* Yes, the current document is a property set stream. - * Let's create a PropertySet instance from it. */ - PropertySet ps = PropertySetFactory.create(stream); - - /* Now we know that we really have a property set. The next - * step is to find out whether it is a summary information - * or not. */ - if (ps.isSummaryInformation()) { - /* Yes, it is a summary information. We will modify it - * and write the result to the destination POIFS. */ - editSI(poiFs, path, name, ps); - } else { - /* No, it is not a summary information. We don't care - * about its internals and copy it unmodified to the - * destination POIFS. */ - copy(poiFs, path, name, ps); - } - } catch (NoPropertySetStreamException ex) { - /* This exception will not be thrown because we already - * checked above. */ - } - } else { - /* No, the current document is not a property set stream. We - * copy it unmodified to the destination POIFS. */ - copy(poiFs, event.getPath(), event.getName(), stream); + // Set the properties. + s.setProperty(PropertyIDMap.PID_AUTHOR, Variant.VT_LPSTR, "Rainer Klute"); + s.setProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPWSTR, "Test"); } - } catch (MarkUnsupportedException | WritingNotSupportedException | IOException ex) { - t = ex; + + isSup = ps::toInputStream; + } else { + // No, the current document is not a property set stream. We copy it unmodified to the destination POIFS. + isSup = event::getStream; } - /* According to the definition of the processPOIFSReaderEvent method - * we cannot pass checked exceptions to the caller. The following - * lines check whether a checked exception occurred and throws an - * unchecked exception. The message of that exception is that of - * the underlying checked exception. */ - if (t != null) { - throw new HPSFRuntimeException("Could not read file \"" + path + "/" + name, t); - } - } + try (InputStream is = isSup.get()) { + final POIFSDocumentPath path = event.getPath(); + // Ensures that the directory hierarchy for a document in a POI fileystem is in place. + // Get the root directory. It does not have to be created since it always exists in a POIFS. + DirectoryEntry de = poiFs.getRoot(); - /** - *Receives a summary information property set modifies (or creates) - * its "author" and "title" properties and writes the result under the - * same path and name as the origin to a destination POI filesystem.
- * - * @param poiFs The POI filesystem to write to. - * @param path The original (and destination) stream's path. - * @param name The original (and destination) stream's name. - * @param si The property set. It should be a summary information - * property set. - */ - void editSI(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final PropertySet si) - throws WritingNotSupportedException, IOException - - { - /* Get the directory entry for the target stream. */ - final DirectoryEntry de = getPath(poiFs, path); - - /* Create a mutable property set as a copy of the original read-only - * property set. */ - final PropertySet mps = new PropertySet(si); - - /* Retrieve the section containing the properties to modify. A - * summary information property set contains exactly one section. */ - final Section s = mps.getSections().get(0); - - /* Set the properties. */ - s.setProperty(PropertyIDMap.PID_AUTHOR, Variant.VT_LPSTR, - "Rainer Klute"); - s.setProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPWSTR, - "Test"); - - /* Create an input stream containing the bytes the property set - * stream consists of. */ - final InputStream pss = mps.toInputStream(); - - /* Write the property set stream to the POIFS. */ - de.createDocument(name, pss); - } - - - /** - *Writes a {@link PropertySet} to a POI filesystem. This method is - * simpler than {@link #editSI} because the origin property set has just - * to be copied.
- * - * @param poiFs The POI filesystem to write to. - * @param path The file's path in the POI filesystem. - * @param name The file's name in the POI filesystem. - * @param ps The property set to write. - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final PropertySet ps) - throws WritingNotSupportedException, IOException - { - final DirectoryEntry de = getPath(poiFs, path); - final PropertySet mps = new PropertySet(ps); - de.createDocument(name, mps.toInputStream()); - } - - - - /** - *Copies the bytes from a {@link DocumentInputStream} to a new - * stream in a POI filesystem.
- * - * @param poiFs The POI filesystem to write to. - * @param path The source document's path. - * @param name The source document's name. - * @param stream The stream containing the source document. - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final DocumentInputStream stream) throws IOException - { - final DirectoryEntry de = getPath(poiFs, path); - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - int c; - while ((c = stream.read()) != -1) - out.write(c); - stream.close(); - out.close(); - final InputStream in = - new ByteArrayInputStream(out.toByteArray()); - de.createDocument(name, in); - } - - - /** - * Writes the POI file system to a disk file. - */ - public void close() throws IOException - { - out = new FileOutputStream(dstName); - poiFs.writeFilesystem(out); - out.close(); - } - - - - /** Contains the directory paths that have already been created in the - * output POI filesystem and maps them to their corresponding - * {@link org.apache.poi.poifs.filesystem.DirectoryNode}s. */ - private final MapEnsures that the directory hierarchy for a document in a POI - * fileystem is in place. When a document is to be created somewhere in - * a POI filesystem its directory must be created first. This method - * creates all directories between the POI filesystem root and the - * directory the document should belong to which do not yet exist.
- * - *Unfortunately POI does not offer a simple method to interrogate - * the POIFS whether a certain child node (file or directory) exists in - * a directory. However, since we always start with an empty POIFS which - * contains the root directory only and since each directory in the - * POIFS is created by this method we can maintain the POIFS's directory - * hierarchy ourselves: The {@link DirectoryEntry} of each directory - * created is stored in a {@link Map}. The directories' path names map - * to the corresponding {@link DirectoryEntry} instances.
- * - * @param poiFs The POI filesystem the directory hierarchy is created - * in, if needed. - * @param path The document's path. This method creates those directory - * components of this hierarchy which do not yet exist. - * @return The directory entry of the document path's parent. The caller - * should use this {@link DirectoryEntry} to create documents in it. - */ - public DirectoryEntry getPath(final POIFSFileSystem poiFs, - final POIFSDocumentPath path) - { - try - { - /* Check whether this directory has already been created. */ - final String s = path.toString(); - DirectoryEntry de = paths.get(s); - if (de != null) - /* Yes: return the corresponding DirectoryEntry. */ - return de; - - /* No: We have to create the directory - or return the root's - * DirectoryEntry. */ - int l = path.length(); - if (l == 0) - /* Get the root directory. It does not have to be created - * since it always exists in a POIFS. */ - de = poiFs.getRoot(); - else - { - /* Create a subordinate directory. The first step is to - * ensure that the parent directory exists: */ - de = getPath(poiFs, path.getParent()); - /* Now create the target directory: */ - de = de.createDirectory(path.getComponent - (path.length() - 1)); + for (int i=0; iRuns the example program.
* - * @param args Command-line arguments. The first and only command-line + * @param args Command-line arguments. The first and only command-line * argument is the name of the POI file system to create. * @throws IOException if any I/O exception occurs. - * @throws WritingNotSupportedException if HPSF does not (yet) support + * @throws WritingNotSupportedException if HPSF does not (yet) support * writing a certain property type. */ public static void main(final String[] args) @@ -51,8 +54,7 @@ public class WriteTitle /* Check whether we have exactly one command-line argument. */ if (args.length != 1) { - System.err.println("Usage: " + WriteTitle.class.getName() + - "destinationPOIFS"); + System.err.println("Usage: " + WriteTitle.class.getName() + "destinationPOIFS"); System.exit(1); } @@ -70,7 +72,7 @@ public class WriteTitle * SectionIDMap.SUMMARY_INFORMATION_ID. */ ms.setFormatID(SummaryInformation.FORMAT_ID); - /* Create an empty property. */ + /* Create an empty property. */ final Property p = new Property(); /* Fill the property with appropriate settings so that it specifies the @@ -82,12 +84,13 @@ public class WriteTitle /* Place the property into the section. */ ms.setProperty(p); - /* Create the POI file system the property set is to be written to. */ - try (final POIFSFileSystem poiFs = new POIFSFileSystem()) { - /* For writing the property set into a POI file system it has to be - * handed over to the POIFS.createDocument() method as an input stream - * which produces the bytes making out the property set stream. */ - final InputStream is = mps.toInputStream(); + /* Create the POI file system the property set is to be written to. + * For writing the property set into a POI file system it has to be + * handed over to the POIFS.createDocument() method as an input stream + * which produces the bytes making out the property set stream. */ + try (final POIFSFileSystem poiFs = new POIFSFileSystem(); + final InputStream is = mps.toInputStream(); + final FileOutputStream fos = new FileOutputStream(fileName)) { /* Create the summary information property set in the POI file * system. It is given the default name most (if not all) summary @@ -95,9 +98,7 @@ public class WriteTitle poiFs.createDocument(is, SummaryInformation.DEFAULT_STREAM_NAME); /* Write the whole POI file system to a disk file. */ - try (FileOutputStream fos = new FileOutputStream(fileName)) { - poiFs.writeFilesystem(fos); - } + poiFs.writeFilesystem(fos); } } } diff --git a/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java b/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java index 517e99b044..87877e4ef1 100644 --- a/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java +++ b/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java @@ -51,9 +51,11 @@ import org.apache.poi.sl.usermodel.VerticalAlignment; @SuppressWarnings("java:S1192") public final class ApacheconEU08 { + private ApacheconEU08() {} + public static void main(String[] args) throws IOException { + // use HSLFSlideShow or XMLSlideShow try (SlideShow,?> ppt = new HSLFSlideShow()) { - // SlideShow,?> ppt = new XMLSlideShow(); ppt.setPageSize(new Dimension(720, 540)); slide1(ppt); @@ -394,7 +396,7 @@ public final class ApacheconEU08 { graphics.setFont(new Font("Arial", Font.BOLD, 10)); for (int i = 0, idx = 1; i < def.length; i+=2, idx++) { graphics.setColor(Color.black); - int width = ((Integer)def[i+1]).intValue(); + int width = (Integer) def[i + 1]; graphics.drawString("Q" + idx, x-20, y+20); graphics.drawString(width + "%", x + width + 10, y + 20); graphics.setColor((Color)def[i]); diff --git a/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java b/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java index 9227e79e52..65fb0b9876 100644 --- a/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java +++ b/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java @@ -29,8 +29,10 @@ import org.apache.poi.hslf.usermodel.HSLFTextBox; /** * Demonstrates how to create hyperlinks in PowerPoint presentations */ -public abstract class CreateHyperlink { - +public final class CreateHyperlink { + + private CreateHyperlink() {} + public static void main(String[] args) throws IOException { try (HSLFSlideShow ppt = new HSLFSlideShow()) { HSLFSlide slideA = ppt.createSlide(); diff --git a/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java b/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java index 818580a955..2c7aac83a2 100644 --- a/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java +++ b/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java @@ -19,6 +19,7 @@ package org.apache.poi.hslf.examples; import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.IOException; import java.io.InputStream; import org.apache.poi.hslf.usermodel.HSLFObjectData; @@ -33,12 +34,16 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.Paragraph; import org.apache.poi.hwpf.usermodel.Range; +import org.apache.poi.util.IOUtils; /** * Demonstrates how you can extract misc embedded data from a ppt file */ +@SuppressWarnings({"java:S106","java:S4823"}) public final class DataExtraction { + private DataExtraction() {} + public static void main(String[] args) throws Exception { if (args.length == 0) { @@ -46,20 +51,13 @@ public final class DataExtraction { return; } - try (FileInputStream is = new FileInputStream(args[0]); - HSLFSlideShow ppt = new HSLFSlideShow(is)) { + try (FileInputStream fis = new FileInputStream(args[0]); + HSLFSlideShow ppt = new HSLFSlideShow(fis)) { //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 - try (FileOutputStream out = new FileOutputStream(name + type)) { - out.write(data); - } + handleSound(aSound); } int oleIdx = -1, picIdx = -1; @@ -71,35 +69,18 @@ public final class DataExtraction { 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())) { + switch (name == null ? "" : name) { + case "Worksheet": + //read xls + handleWorkbook(data, name, oleIdx); + break; + case "Document": //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); - } - } + handleDocument(data, name, oleIdx); + break; + default: + handleUnknown(data, ole.getProgId(), oleIdx); + break; } } @@ -108,16 +89,60 @@ public final class DataExtraction { 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()); - } + handlePicture(data, picIdx); } } } } } + private static void handleWorkbook(HSLFObjectData data, String name, int oleIdx) throws IOException { + try (InputStream is = data.getInputStream(); + HSSFWorkbook wb = new HSSFWorkbook(is); + FileOutputStream out = new FileOutputStream(name + "-(" + (oleIdx) + ").xls")) { + wb.write(out); + } + } + + private static void handleDocument(HSLFObjectData data, String name, int oleIdx) throws IOException { + try (InputStream is = data.getInputStream(); + HWPFDocument doc = new HWPFDocument(is); + FileOutputStream out = new FileOutputStream(name + "-(" + (oleIdx) + ").doc")) { + 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 + doc.write(out); + } + } + + private static void handleUnknown(HSLFObjectData data, String name, int oleIdx) throws IOException { + try (InputStream is = data.getInputStream(); + FileOutputStream out = new FileOutputStream(name + "-" + (oleIdx + 1) + ".dat")) { + IOUtils.copy(is, out); + } + } + + private static void handlePicture(HSLFPictureData data, int picIdx) throws IOException { + String ext = data.getType().extension; + try (FileOutputStream out = new FileOutputStream("pict-" + picIdx + ext)) { + out.write(data.getData()); + } + } + + private static void handleSound(HSLFSoundData aSound) throws IOException { + String type = aSound.getSoundType(); //*.wav + String name = aSound.getSoundName(); //typically file name + + //save the sound on disk + try (FileOutputStream out = new FileOutputStream(name + type)) { + out.write(aSound.getData()); + } + } + private static void usage(){ System.out.println("Usage: DataExtraction ppt"); } diff --git a/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java b/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java index b8d84efc36..963033ad12 100644 --- a/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java +++ b/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java @@ -23,23 +23,24 @@ import java.awt.Graphics2D; import java.awt.Rectangle; import java.io.FileOutputStream; -import org.apache.poi.hslf.model.PPGraphics2D; import org.apache.poi.hslf.usermodel.HSLFGroupShape; import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlideShow; +import org.apache.poi.sl.draw.SLGraphics; /** * Demonstrates how to draw into a slide using the HSLF Graphics2D driver. - * - * @author Yegor Kozlov */ public final class Graphics2DDemo { + private Graphics2DDemo() {} + /** * A simple bar chart demo */ public static void main(String[] args) throws Exception { - try (HSLFSlideShow ppt = new HSLFSlideShow()) { + try (HSLFSlideShow ppt = new HSLFSlideShow(); + FileOutputStream out = new FileOutputStream("hslf-graphics.ppt")) { //bar chart data. The first value is the bar color, the second is the width Object[] def = new Object[]{ Color.yellow, 40, @@ -56,14 +57,14 @@ public final class Graphics2DDemo { group.setAnchor(bounds); group.setInteriorAnchor(new Rectangle(0, 0, 100, 100)); slide.addShape(group); - Graphics2D graphics = new PPGraphics2D(group); + Graphics2D graphics = new SLGraphics(group); //draw a simple bar graph int x = 10, y = 10; graphics.setFont(new Font("Arial", Font.BOLD, 10)); for (int i = 0, idx = 1; i < def.length; i += 2, idx++) { graphics.setColor(Color.black); - int width = ((Integer) def[i + 1]).intValue(); + int width = (Integer) def[i + 1]; graphics.drawString("Q" + idx, x - 5, y + 10); graphics.drawString(width + "%", x + width + 3, y + 10); graphics.setColor((Color) def[i]); @@ -75,9 +76,7 @@ public final class Graphics2DDemo { graphics.draw(group.getInteriorAnchor()); graphics.drawString("Performance", x + 30, y + 10); - try (FileOutputStream out = new FileOutputStream("hslf-graphics.ppt")) { - ppt.write(out); - } + ppt.write(out); } } } diff --git a/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java b/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java index 8c9a743c6f..28fc8b1343 100644 --- a/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java +++ b/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java @@ -25,7 +25,9 @@ import org.apache.poi.hslf.usermodel.HSLFSlideShow; /** * Demonstrates how to set headers / footers */ -public abstract class HeadersFootersDemo { +public final class HeadersFootersDemo { + private HeadersFootersDemo() {} + public static void main(String[] args) throws IOException { try (HSLFSlideShow ppt = new HSLFSlideShow()) { HeadersFooters slideHeaders = ppt.getSlideHeadersFooters(); diff --git a/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java b/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java index a3010bf132..f63afb44d2 100644 --- a/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java +++ b/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java @@ -22,7 +22,6 @@ import java.util.List; import java.util.Locale; import org.apache.poi.hslf.usermodel.HSLFHyperlink; -import org.apache.poi.hslf.usermodel.HSLFShape; import org.apache.poi.hslf.usermodel.HSLFSimpleShape; import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlideShow; @@ -32,49 +31,47 @@ import org.apache.poi.hslf.usermodel.HSLFTextRun; /** * Demonstrates how to read hyperlinks from a presentation */ +@SuppressWarnings({"java:S106", "java:S4823"}) public final class Hyperlinks { + private Hyperlinks() {} + public static void main(String[] args) throws Exception { for (String arg : args) { try (FileInputStream is = new FileInputStream(arg); - HSLFSlideShow ppt = new HSLFSlideShow(is)) { + HSLFSlideShow ppt = new HSLFSlideShow(is)) { 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 (ListAesZipFileZipEntrySource
is used to ensure that temp files are encrypted.
* */ -public class LoadPasswordProtectedXlsxStreaming { +public final class LoadPasswordProtectedXlsxStreaming { - public static void main(String[] args) throws Exception { - if(args.length != 2) { - throw new IllegalArgumentException("Expected 2 params: filename and password"); - } - TempFileUtils.checkTempFiles(); - String filename = args[0]; - String password = args[1]; - try (FileInputStream fis = new FileInputStream(filename); - InputStream unencryptedStream = EncryptionUtils.decrypt(fis, password)) { - printSheetCount(unencryptedStream); - } - TempFileUtils.checkTempFiles(); + private LoadPasswordProtectedXlsxStreaming() { } - public static void printSheetCount(final InputStream inputStream) throws Exception { + public static void main(String[] args) throws Exception { + LoadPasswordProtectedXlsx.execute(args, LoadPasswordProtectedXlsxStreaming::printSheetCount); + } + + private static void printSheetCount(final InputStream inputStream) throws Exception { try (AesZipFileZipEntrySource source = AesZipFileZipEntrySource.createZipEntrySource(inputStream); OPCPackage pkg = OPCPackage.open(source)) { XSSFReader reader = new XSSFReader(pkg); diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/LoadPasswordProtectedXlsx.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/LoadPasswordProtectedXlsx.java index 6365e7fa64..50149bdae7 100644 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/LoadPasswordProtectedXlsx.java +++ b/src/examples/src/org/apache/poi/xssf/usermodel/examples/LoadPasswordProtectedXlsx.java @@ -22,10 +22,12 @@ package org.apache.poi.xssf.usermodel.examples; import java.io.FileInputStream; import java.io.InputStream; -import org.apache.poi.crypt.examples.EncryptionUtils; import org.apache.poi.examples.util.TempFileUtils; import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.poifs.crypt.Decryptor; +import org.apache.poi.poifs.crypt.EncryptionInfo; import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** @@ -35,9 +37,17 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook; *
AesZipFileZipEntrySource
is used to ensure that temp files are encrypted.
* */ -public class LoadPasswordProtectedXlsx { - +public final class LoadPasswordProtectedXlsx { + + public interface EncryptionHandler { + void handle(final InputStream inputStream) throws Exception; + } + public static void main(String[] args) throws Exception { + execute(args, LoadPasswordProtectedXlsx::printSheetCount); + } + + public static void execute(String[] args, EncryptionHandler handler) throws Exception { if(args.length != 2) { throw new IllegalArgumentException("Expected 2 params: filename and password"); } @@ -45,13 +55,21 @@ public class LoadPasswordProtectedXlsx { String filename = args[0]; String password = args[1]; try (FileInputStream fis = new FileInputStream(filename); - InputStream unencryptedStream = EncryptionUtils.decrypt(fis, password)) { - printSheetCount(unencryptedStream); + POIFSFileSystem fs = new POIFSFileSystem(fis)) { + EncryptionInfo info = new EncryptionInfo(fs); + Decryptor d = Decryptor.getInstance(info); + if (!d.verifyPassword(password)) { + throw new RuntimeException("incorrect password"); + } + try (InputStream unencryptedStream = d.getDataStream(fs)) { + handler.handle(unencryptedStream); + } } TempFileUtils.checkTempFiles(); } - - public static void printSheetCount(final InputStream inputStream) throws Exception { + + + private static void printSheetCount(final InputStream inputStream) throws Exception { try (AesZipFileZipEntrySource source = AesZipFileZipEntrySource.createZipEntrySource(inputStream); OPCPackage pkg = OPCPackage.open(source); XSSFWorkbook workbook = new XSSFWorkbook(pkg)) { diff --git a/src/java/org/apache/poi/hpsf/ClipboardData.java b/src/java/org/apache/poi/hpsf/ClipboardData.java index 4c1869fcac..f002bdbdf1 100644 --- a/src/java/org/apache/poi/hpsf/ClipboardData.java +++ b/src/java/org/apache/poi/hpsf/ClipboardData.java @@ -18,8 +18,8 @@ package org.apache.poi.hpsf; import org.apache.poi.util.IOUtils; import org.apache.poi.util.Internal; +import org.apache.poi.util.LittleEndian; import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.apache.poi.util.LittleEndianByteArrayOutputStream; import org.apache.poi.util.LittleEndianConsts; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; @@ -39,7 +39,7 @@ public class ClipboardData { int size = lei.readInt(); if ( size < 4 ) { - String msg = + String msg = "ClipboardData at offset "+offset+" size less than 4 bytes "+ "(doesn't even have format field!). Setting to format == 0 and hope for the best"; LOG.log( POILogger.WARN, msg); @@ -59,15 +59,10 @@ public class ClipboardData { public byte[] toByteArray() { byte[] result = new byte[LittleEndianConsts.INT_SIZE*2+_value.length]; - LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(result,0); - try { - bos.writeInt(LittleEndianConsts.INT_SIZE + _value.length); - bos.writeInt(_format); - bos.write(_value); - return result; - } finally { - IOUtils.closeQuietly(bos); - } + LittleEndian.putInt(result, 0, LittleEndianConsts.INT_SIZE + _value.length); + LittleEndian.putInt(result, 4, _format); + System.arraycopy(_value, 0, result, 8, _value.length); + return result; } public void setValue( byte[] value ) { diff --git a/src/java/org/apache/poi/hpsf/PropertySetFactory.java b/src/java/org/apache/poi/hpsf/PropertySetFactory.java index 06029ab137..d5e0c5c0c2 100644 --- a/src/java/org/apache/poi/hpsf/PropertySetFactory.java +++ b/src/java/org/apache/poi/hpsf/PropertySetFactory.java @@ -23,7 +23,7 @@ import java.io.InputStream; import java.io.UnsupportedEncodingException; import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DocumentEntry; +import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.DocumentInputStream; import org.apache.poi.util.LittleEndianInputStream; @@ -36,7 +36,7 @@ public class PropertySetFactory { * Creates the most specific {@link PropertySet} from an entry * in the specified POIFS Directory. This is preferrably a {@link * DocumentSummaryInformation} or a {@link SummaryInformation}. If - * the specified entry does not contain a property set stream, an + * the specified entry does not contain a property set stream, an * exception is thrown. If no entry is found with the given name, * an exception is thrown. * @@ -52,19 +52,10 @@ public class PropertySetFactory { */ public static PropertySet create(final DirectoryEntry dir, final String name) throws FileNotFoundException, NoPropertySetStreamException, IOException, UnsupportedEncodingException { - InputStream inp = null; - try { - DocumentEntry entry = (DocumentEntry)dir.getEntry(name); - inp = new DocumentInputStream(entry); - try { - return create(inp); - } catch (MarkUnsupportedException e) { - return null; - } - } finally { - if (inp != null) { - inp.close(); - } + try (DocumentInputStream inp = ((DirectoryNode)dir).createDocumentInputStream(name)) { + return create(inp); + } catch (MarkUnsupportedException e) { + return null; } } @@ -96,18 +87,18 @@ public class PropertySetFactory { byte[] clsIdBuf = new byte[ClassID.LENGTH]; leis.readFully(clsIdBuf); int sectionCount = (int)leis.readUInt(); - + if (byteOrder != PropertySet.BYTE_ORDER_ASSERTION || format != PropertySet.FORMAT_ASSERTION || sectionCount < 0) { throw new NoPropertySetStreamException(); } - + if (sectionCount > 0) { leis.readFully(clsIdBuf); } stream.reset(); - + ClassID clsId = new ClassID(clsIdBuf, 0); if (sectionCount > 0 && PropertySet.matchesSummary(clsId, SummaryInformation.FORMAT_ID)) { return new SummaryInformation(stream); diff --git a/src/java/org/apache/poi/hssf/dev/BiffViewer.java b/src/java/org/apache/poi/hssf/dev/BiffViewer.java index 8e380855b8..d7a6f45a15 100644 --- a/src/java/org/apache/poi/hssf/dev/BiffViewer.java +++ b/src/java/org/apache/poi/hssf/dev/BiffViewer.java @@ -19,6 +19,7 @@ package org.apache.poi.hssf.dev; import java.io.DataInputStream; import java.io.File; +import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -393,21 +394,10 @@ public final class BiffViewer { // args = new String[] { "--out", "", }; CommandArgs cmdArgs = CommandArgs.parse(args); - PrintWriter pw; - if (cmdArgs.shouldOutputToFile()) { - OutputStream os = new FileOutputStream(cmdArgs.getFile().getAbsolutePath() + ".out"); - pw = new PrintWriter(new OutputStreamWriter(os, StringUtil.UTF8)); - } else { - // Use the system default encoding when sending to System Out - pw = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset())); - } - - POIFSFileSystem fs = null; - InputStream is = null; - try { - fs = new POIFSFileSystem(cmdArgs.getFile(), true); - is = getPOIFSInputStream(fs); - + try (POIFSFileSystem fs = new POIFSFileSystem(cmdArgs.getFile(), true); + InputStream is = getPOIFSInputStream(fs); + PrintWriter pw = getOutputStream(cmdArgs.shouldOutputToFile() ? cmdArgs.getFile().getAbsolutePath() : null) + ) { if (cmdArgs.shouldOutputRawHexOnly()) { byte[] data = IOUtils.toByteArray(is); HexDump.dump(data, 0, System.out, 0); @@ -417,13 +407,21 @@ public final class BiffViewer { runBiffViewer(pw, is, dumpInterpretedRecords, dumpHex, dumpInterpretedRecords, cmdArgs.suppressHeader()); } - } finally { - IOUtils.closeQuietly(is); - IOUtils.closeQuietly(fs); - IOUtils.closeQuietly(pw); } } + static PrintWriter getOutputStream(String outputPath) throws FileNotFoundException { + // Use the system default encoding when sending to System Out + OutputStream os = System.out; + Charset cs = Charset.defaultCharset(); + if (outputPath != null) { + cs = StringUtil.UTF8; + os = new FileOutputStream(outputPath + ".out"); + } + return new PrintWriter(new OutputStreamWriter(os, cs)); + } + + static InputStream getPOIFSInputStream(POIFSFileSystem fs) throws IOException { String workbookName = HSSFWorkbook.getWorkbookDirEntryName(fs.getRoot()); return fs.createDocumentInputStream(workbookName); diff --git a/src/java/org/apache/poi/poifs/filesystem/POIFSDocumentPath.java b/src/java/org/apache/poi/poifs/filesystem/POIFSDocumentPath.java index d32214e024..c613bdcd3f 100644 --- a/src/java/org/apache/poi/poifs/filesystem/POIFSDocumentPath.java +++ b/src/java/org/apache/poi/poifs/filesystem/POIFSDocumentPath.java @@ -15,175 +15,98 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - + package org.apache.poi.poifs.filesystem; import java.io.File; +import java.util.Arrays; +import java.util.Objects; +import java.util.function.Predicate; +import java.util.stream.Stream; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; /** * Class POIFSDocumentPath - * - * @author Marc Johnson (mjohnson at apache dot org) - * @version %I%, %G% */ -public class POIFSDocumentPath -{ +public class POIFSDocumentPath { + private static final POILogger log = POILogFactory.getLogger(POIFSDocumentPath.class); - + private final String[] components; private int hashcode; //lazy-compute hashCode /** - * constructor for the path of a document that is not in the root - * of the POIFSFileSystem - * - * @param components the Strings making up the path to a document. - * The Strings must be ordered as they appear in - * the directory hierarchy of the the document - * -- the first string must be the name of a - * directory in the root of the POIFSFileSystem, - * and every Nth (for N > 1) string thereafter - * must be the name of a directory in the - * directory identified by the (N-1)th string. - *
- * If the components parameter is null or has - * zero length, the POIFSDocumentPath is - * appropriate for a document that is in the - * root of a POIFSFileSystem - * - * @exception IllegalArgumentException if any of the elements in - * the components parameter - * are null or have zero - * length - */ - - public POIFSDocumentPath(final String [] components) - throws IllegalArgumentException - { - if (components == null) - { - this.components = new String[ 0 ]; - } - else - { - this.components = new String[ components.length ]; - for (int j = 0; j < components.length; j++) - { - if ((components[ j ] == null) - || (components[ j ].length() == 0)) - { - throw new IllegalArgumentException( - "components cannot contain null or empty strings"); - } - this.components[ j ] = components[ j ]; - } - } - } - - /** - * simple constructor for the path of a document that is in the - * root of the POIFSFileSystem. The constructor that takes an - * array of Strings can also be used to create such a + * simple constructor for the path of a document that is in the root of the POIFSFileSystem. + * The constructor that takes an array of Strings can also be used to create such a * POIFSDocumentPath by passing it a null or empty String array */ - - public POIFSDocumentPath() - { - this.components = new String[ 0 ]; + public POIFSDocumentPath() { + components = new String[0]; } /** - * constructor that adds additional subdirectories to an existing - * path + * constructor for the path of a document that is not in the root of the POIFSFileSystem + * + * @param components the Strings making up the path to a document. + * The Strings must be ordered as they appear in the directory hierarchy of the the document. + * The first string must be the name of a directory in the root of the POIFSFileSystem, and + * every Nth (for N > 1) string thereafter must be the name of a directory in the directory + * identified by the (N-1)th string.
If the components parameter is null or has zero length,
+ * the POIFSDocumentPath is appropriate for a document that is in the root of a POIFSFileSystem
+ *
+ * @exception IllegalArgumentException
+ * if any of the elements in the components parameter are null or have zero length
+ */
+ public POIFSDocumentPath(final String [] components) throws IllegalArgumentException {
+ this(null, components);
+ }
+
+ /**
+ * constructor that adds additional subdirectories to an existing path
*
* @param path the existing path
* @param components the additional subdirectory names to be added
*
- * @exception IllegalArgumentException if any of the Strings in
- * components is null or zero
- * length
+ * @exception IllegalArgumentException
+ * if any of the Strings in components is null or zero length
*/
+ public POIFSDocumentPath(final POIFSDocumentPath path, final String[] components) throws IllegalArgumentException {
+ String[] s1 = (path == null) ? new String[0] : path.components;
+ String[] s2 = (components == null) ? new String[0] : components;
- public POIFSDocumentPath(final POIFSDocumentPath path,
- final String [] components)
- throws IllegalArgumentException
- {
- if (components == null)
- {
- this.components = new String[ path.components.length ];
- }
- else
- {
- this.components =
- new String[ path.components.length + components.length ];
- }
- System.arraycopy(path.components, 0, this.components, 0, path.components.length);
- if (components != null)
- {
- for (int j = 0; j < components.length; j++)
- {
- if (components[ j ] == null)
- {
- throw new IllegalArgumentException(
- "components cannot contain null");
- }
- if (components[ j ].length() == 0)
- {
- log.log(POILogger.WARN, "Directory under " + path + " has an empty name, " +
- "not all OLE2 readers will handle this file correctly!");
- }
-
- this.components[ j + path.components.length ] =
- components[ j ];
- }
+ // TODO: Although the Javadoc says empty strings are forbidden, the adapted legacy
+ // implementation allowed it in case a path was specified...
+ Predicate Returns the last name in the document path's name sequence.
* If the document path's name sequence is empty, then the empty string is returned. Converts the parameter to a hex value breaking the results into
- * lines.bytesToDump
bytes to an output stream.
- *
- * @param in The stream to read from
- * @param out The output stream
- * @param start The index to use as the starting position for the left hand side label
- * @param bytesToDump The number of bytes to output. Use -1 to read until the end of file.
- */
- public static void dump( InputStream in, PrintStream out, int start, int bytesToDump ) throws IOException
- {
- ByteArrayOutputStream buf = new ByteArrayOutputStream();
- if (bytesToDump == -1)
- {
- int c = in.read();
- while (c != -1)
- {
- buf.write(c);
- c = in.read();
- }
- }
- else
- {
- int bytesRemaining = bytesToDump;
- while (bytesRemaining-- > 0)
- {
- int c = in.read();
- if (c == -1) {
- break;
- }
- buf.write(c);
- }
- }
-
- byte[] data = buf.toByteArray();
- dump(data, 0, out, start, data.length);
- }
-
/**
* @return string of 16 (zero padded) uppercase hex chars and prefixed with '0x'
*/
@@ -364,7 +257,7 @@ public class HexDump {
writeHex(sb, value, 16, "0x");
return sb.toString();
}
-
+
/**
* @return string of 8 (zero padded) uppercase hex chars and prefixed with '0x'
*/
@@ -373,7 +266,7 @@ public class HexDump {
writeHex(sb, value & 0xFFFFFFFFL, 8, "0x");
return sb.toString();
}
-
+
/**
* @return string of 4 (zero padded) uppercase hex chars and prefixed with '0x'
*/
@@ -382,7 +275,7 @@ public class HexDump {
writeHex(sb, value & 0xFFFFL, 4, "0x");
return sb.toString();
}
-
+
/**
* @return string of 2 (zero padded) uppercase hex chars and prefixed with '0x'
*/
@@ -391,7 +284,7 @@ public class HexDump {
writeHex(sb, value & 0xFFL, 2, "0x");
return sb.toString();
}
-
+
/**
* @see Integer#toHexString(int)
* @see Long#toHexString(long)
@@ -406,13 +299,5 @@ public class HexDump {
acc >>>= 4;
}
sb.append(buf);
- }
-
-
- public static void main(String[] args) throws IOException {
- InputStream in = new FileInputStream(args[0]);
- byte[] b = IOUtils.toByteArray(in);
- in.close();
- System.out.println(HexDump.dump(b, 0, 0));
}
}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java b/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java
index 22a138f1bd..47918cfb0e 100644
--- a/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java
+++ b/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java
@@ -55,7 +55,6 @@ import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFTestHelper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.util.HexDump;
import org.junit.Test;
public class TestDrawingAggregate {
@@ -231,7 +230,7 @@ public class TestDrawingAggregate {
for(EscherRecord r : records) {
out.write(r.serialize());
}
- assertEquals(HexDump.toHex(dgBytes, 10), HexDump.toHex(out.toByteArray(), 10));
+ assertArrayEquals(dgBytes, out.toByteArray());
}
/**
diff --git a/src/testcases/org/apache/poi/util/TestHexDump.java b/src/testcases/org/apache/poi/util/TestHexDump.java
index 198b8bc7a2..cf575c770b 100644
--- a/src/testcases/org/apache/poi/util/TestHexDump.java
+++ b/src/testcases/org/apache/poi/util/TestHexDump.java
@@ -22,7 +22,11 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import java.io.*;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.io.UnsupportedEncodingException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@@ -35,12 +39,7 @@ public class TestHexDump {
@BeforeClass
public static void setUp() throws UnsupportedEncodingException {
SYSTEM_OUT = System.out;
- System.setOut(new PrintStream(new OutputStream() {
- @Override
- public void write(int b) throws IOException {
-
- }
- }, false, "UTF-8"));
+ System.setOut(new PrintStream(new OutputStream() {public void write(int b) {}}, false, "UTF-8"));
}
@AfterClass
@@ -153,10 +152,6 @@ public class TestHexDump {
public void testToHex() {
assertEquals("000A", HexDump.toHex((short)0xA));
- assertEquals("[]", HexDump.toHex(new short[] { }));
- assertEquals("[000A]", HexDump.toHex(new short[] { 0xA }));
- assertEquals("[000A, 000B]", HexDump.toHex(new short[] { 0xA, 0xB }));
-
assertEquals("0A", HexDump.toHex((byte)0xA));
assertEquals("0000000A", HexDump.toHex(0xA));
@@ -164,12 +159,6 @@ public class TestHexDump {
assertEquals("[0A]", HexDump.toHex(new byte[] { 0xA }));
assertEquals("[0A, 0B]", HexDump.toHex(new byte[] { 0xA, 0xB }));
- assertEquals(": 0", HexDump.toHex(new byte[] { }, 10));
- assertEquals("0: 0A", HexDump.toHex(new byte[] { 0xA }, 10));
- assertEquals("0: 0A, 0B", HexDump.toHex(new byte[] { 0xA, 0xB }, 10));
- assertEquals("0: 0A, 0B\n2: 0C, 0D", HexDump.toHex(new byte[] { 0xA, 0xB, 0xC, 0xD }, 2));
- assertEquals("0: 0A, 0B\n2: 0C, 0D\n4: 0E, 0F", HexDump.toHex(new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0xF }, 2));
-
assertEquals("FFFF", HexDump.toHex((short)0xFFFF));
assertEquals("00000000000004D2", HexDump.toHex(1234L));
@@ -185,7 +174,7 @@ public class TestHexDump {
}
@Test
- public void testDumpToString() throws Exception {
+ public void testDumpToString() {
byte[] testArray = testArray();
String dump = HexDump.dump(testArray, 0, 0);
//System.out.println("Hex: \n" + dump);
@@ -199,93 +188,37 @@ public class TestHexDump {
}
@Test(expected=ArrayIndexOutOfBoundsException.class)
- public void testDumpToStringOutOfIndex1() throws Exception {
+ public void testDumpToStringOutOfIndex1() {
HexDump.dump(new byte[1], 0, -1);
}
@Test(expected=ArrayIndexOutOfBoundsException.class)
- public void testDumpToStringOutOfIndex2() throws Exception {
+ public void testDumpToStringOutOfIndex2() {
HexDump.dump(new byte[1], 0, 2);
}
@Test(expected=ArrayIndexOutOfBoundsException.class)
- public void testDumpToStringOutOfIndex3() throws Exception {
+ public void testDumpToStringOutOfIndex3() {
HexDump.dump(new byte[1], 0, 1);
}
@Test
- public void testDumpToStringNoDataEOL1() throws Exception {
+ public void testDumpToStringNoDataEOL1() {
HexDump.dump(new byte[0], 0, 1);
}
@Test
- public void testDumpToStringNoDataEOL2() throws Exception {
+ public void testDumpToStringNoDataEOL2() {
HexDump.dump(new byte[0], 0, 0);
}
- @Test
- public void testDumpToPrintStream() throws IOException {
- byte[] testArray = testArray();
- ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
- PrintStream out = new PrintStream(byteOut,true,LocaleUtil.CHARSET_1252.name());
- ByteArrayInputStream byteIn = new ByteArrayInputStream(testArray);
- byteIn.mark(256);
- String str;
-
- byteIn.reset();
- byteOut.reset();
- HexDump.dump(byteIn, out, 0, 256);
- str = new String(byteOut.toByteArray(), LocaleUtil.CHARSET_1252);
- assertTrue("Had: \n" + str, str.contains("0123456789:;<=>?"));
-
- // test with more than we have
- byteIn.reset();
- byteOut.reset();
- HexDump.dump(byteIn, out, 0, 1000);
- str = new String(byteOut.toByteArray(), LocaleUtil.CHARSET_1252);
- assertTrue("Had: \n" + str, str.contains("0123456789:;<=>?"));
-
- // test with -1
- byteIn.reset();
- byteOut.reset();
- HexDump.dump(byteIn, out, 0, -1);
- str = new String(byteOut.toByteArray(), LocaleUtil.CHARSET_1252);
- assertTrue("Had: \n" + str, str.contains("0123456789:;<=>?"));
-
- byteIn.reset();
- byteOut.reset();
- HexDump.dump(byteIn, out, 1, 235);
- str = new String(byteOut.toByteArray(), LocaleUtil.CHARSET_1252);
- assertTrue("Line contents should be moved by one now, but Had: \n" + str,
- str.contains("123456789:;<=>?@"));
-
- byteIn.close();
- byteOut.close();
- }
-
- @Test
- public void testMain() throws Exception {
- File file = TempFile.createTempFile("HexDump", ".dat");
- try {
- try (FileOutputStream out = new FileOutputStream(file)) {
- IOUtils.copy(new ByteArrayInputStream("teststring".getBytes(LocaleUtil.CHARSET_1252)), out);
- }
- assertTrue(file.exists());
- assertTrue(file.length() > 0);
-
- HexDump.main(new String[] { file.getAbsolutePath() });
- } finally {
- assertTrue(file.exists() && file.delete());
- }
- }
-
private static byte[] testArray() {
byte[] testArray = new byte[ 256 ];
for (int j = 0; j < 256; j++) {
testArray[ j ] = ( byte ) j;
}
-
+
return testArray;
}
}