From 2841f3cd0e71a366f7e1fd91a61fbedcbd67cf5d Mon Sep 17 00:00:00 2001 From: Andreas Beeker Date: Sat, 18 Apr 2020 21:31:18 +0000 Subject: [PATCH] Sonar fixes - Ignore System.out-calls and args checks in examples Remove superfluous internal methods git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1876704 13f79535-47bb-0310-9956-ffa450edef68 --- .../poi/crypt/examples/EncryptionUtils.java | 46 --- .../poi/crypt/examples/OOXMLPasswordsTry.java | 104 ++---- .../poi/examples/util/TempFileUtils.java | 8 +- .../apache/poi/hpsf/examples/CopyCompare.java | 53 +-- .../ModifyDocumentSummaryInformation.java | 7 +- .../hpsf/examples/ReadCustomPropertySets.java | 105 +++--- .../apache/poi/hpsf/examples/ReadTitle.java | 41 +-- .../hpsf/examples/WriteAuthorAndTitle.java | 344 ++++-------------- .../apache/poi/hpsf/examples/WriteTitle.java | 33 +- .../poi/hslf/examples/ApacheconEU08.java | 6 +- .../poi/hslf/examples/CreateHyperlink.java | 6 +- .../poi/hslf/examples/DataExtraction.java | 109 +++--- .../poi/hslf/examples/Graphics2DDemo.java | 17 +- .../poi/hslf/examples/HeadersFootersDemo.java | 4 +- .../apache/poi/hslf/examples/Hyperlinks.java | 43 +-- .../apache/poi/hslf/examples/SoundFinder.java | 7 +- .../LoadPasswordProtectedXlsxStreaming.java | 25 +- .../examples/LoadPasswordProtectedXlsx.java | 32 +- .../org/apache/poi/hpsf/ClipboardData.java | 17 +- .../apache/poi/hpsf/PropertySetFactory.java | 27 +- .../org/apache/poi/hssf/dev/BiffViewer.java | 36 +- .../poifs/filesystem/POIFSDocumentPath.java | 256 ++++--------- src/java/org/apache/poi/util/HexDump.java | 143 +------- .../poi/hssf/model/TestDrawingAggregate.java | 3 +- .../org/apache/poi/util/TestHexDump.java | 93 +---- 25 files changed, 465 insertions(+), 1100 deletions(-) delete mode 100644 src/examples/src/org/apache/poi/crypt/examples/EncryptionUtils.java diff --git a/src/examples/src/org/apache/poi/crypt/examples/EncryptionUtils.java b/src/examples/src/org/apache/poi/crypt/examples/EncryptionUtils.java deleted file mode 100644 index c2b795cb5e..0000000000 --- a/src/examples/src/org/apache/poi/crypt/examples/EncryptionUtils.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.crypt.examples; - -import java.io.InputStream; - -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; - -public class EncryptionUtils { - private EncryptionUtils() { - } - - public static InputStream decrypt(final InputStream inputStream, final String pwd) throws Exception { - try { - POIFSFileSystem fs = new POIFSFileSystem(inputStream); - EncryptionInfo info = new EncryptionInfo(fs); - Decryptor d = Decryptor.getInstance(info); - if (!d.verifyPassword(pwd)) { - throw new RuntimeException("incorrect password"); - } - return d.getDataStream(fs); - } finally { - IOUtils.closeQuietly(inputStream); - } - } -} diff --git a/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java b/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java index 033a4cdda8..15a91cef16 100644 --- a/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java +++ b/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java @@ -19,13 +19,12 @@ package org.apache.poi.crypt.examples; -import java.io.BufferedReader; -import java.io.Closeable; import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Paths; import java.security.GeneralSecurityException; +import java.util.Optional; +import java.util.function.Predicate; import org.apache.poi.poifs.crypt.Decryptor; import org.apache.poi.poifs.crypt.EncryptionInfo; @@ -33,88 +32,55 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem; /** * Tries a list of possible passwords for an OOXML protected file - * + * * Note that this isn't very fast, and is aimed at when you have * just a few passwords to check. * For serious processing, you'd be best off grabbing the hash * out with POI or office2john.py, then running that against * "John The Ripper" or GPU enabled version of "hashcat" */ -public class OOXMLPasswordsTry implements Closeable { - private POIFSFileSystem fs; - private EncryptionInfo info; - private Decryptor d; - - private OOXMLPasswordsTry(POIFSFileSystem fs) throws IOException { - info = new EncryptionInfo(fs); - d = Decryptor.getInstance(info); - this.fs = fs; - } - private OOXMLPasswordsTry(File file) throws IOException { - this(new POIFSFileSystem(file, true)); - } - private OOXMLPasswordsTry(InputStream is) throws IOException { - this(new POIFSFileSystem(is)); - } - - public void close() throws IOException { - fs.close(); - } - - public String tryAll(File wordfile) throws IOException, GeneralSecurityException { - String valid = null; - // Load - try (BufferedReader r = new BufferedReader(new FileReader(wordfile))) { - long start = System.currentTimeMillis(); - int count = 0; +public final class OOXMLPasswordsTry { - // Try each password in turn, reporting progress - String password; - while ((password = r.readLine()) != null) { - if (isValid(password)) { - valid = password; - break; - } - count++; + private OOXMLPasswordsTry() {} - 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) - return valid; - } - public boolean isValid(String password) throws GeneralSecurityException { - return d.verifyPassword(password); - } - + @SuppressWarnings({"java:S106","java:S4823"}) public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Use:"); System.err.println(" OOXMLPasswordsTry "); System.exit(1); } - File ooxml = new File(args[0]); - File words = new File(args[1]); - + String ooxml = args[0], words = args[1]; + System.out.println("Trying passwords from " + words + " against " + ooxml); System.out.println(); - String password; - try (OOXMLPasswordsTry pt = new OOXMLPasswordsTry(ooxml)) { - password = pt.tryAll(words); + try (POIFSFileSystem fs = new POIFSFileSystem(new File(ooxml), true)) { + EncryptionInfo info = new EncryptionInfo(fs); + Decryptor d = Decryptor.getInstance(info); + + final long start = System.currentTimeMillis(); + final int[] count = { 0 }; + Predicate counter = (s) -> { + if (++count[0] % 1000 == 0) { + int secs = (int) ((System.currentTimeMillis() - start) / 1000); + System.out.println("Done " + count[0] + " passwords, " + secs + " seconds, last password " + s); + } + return true; + }; + + // Try each password in turn, reporting progress + Optional found = Files.lines(Paths.get(words)).filter(counter).filter(w -> isValid(d, w)).findFirst(); + + System.out.println(found.map(s -> "Password found: " + s).orElse("Error - No password matched")); } - - System.out.println(); - if (password == null) { - System.out.println("Error - No password matched"); - } else { - System.out.println("Password found!"); - System.out.println(password); + } + + private static boolean isValid(Decryptor dec, String password) { + try { + return dec.verifyPassword(password); + } catch (GeneralSecurityException e) { + return false; } } } diff --git a/src/examples/src/org/apache/poi/examples/util/TempFileUtils.java b/src/examples/src/org/apache/poi/examples/util/TempFileUtils.java index 5d4f7ab531..b5ad6ea9f1 100644 --- a/src/examples/src/org/apache/poi/examples/util/TempFileUtils.java +++ b/src/examples/src/org/apache/poi/examples/util/TempFileUtils.java @@ -20,15 +20,15 @@ package org.apache.poi.examples.util; import java.io.File; -import java.io.IOException; import org.apache.poi.util.TempFile; -public class TempFileUtils { +public final class TempFileUtils { private TempFileUtils() { } - - public static void checkTempFiles() throws IOException { + + @SuppressWarnings("java:S106") + public static void checkTempFiles() { String tmpDir = System.getProperty(TempFile.JAVA_IO_TMPDIR) + "/poifiles"; File tempDir = new File(tmpDir); if(tempDir.exists()) { diff --git a/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java b/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java index d494e256fb..cf85fe7260 100644 --- a/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java +++ b/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java @@ -18,11 +18,9 @@ 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.io.UnsupportedEncodingException; import java.util.HashMap; @@ -45,6 +43,7 @@ import org.apache.poi.poifs.filesystem.DocumentInputStream; import org.apache.poi.poifs.filesystem.EntryUtils; import org.apache.poi.poifs.filesystem.POIFSDocumentPath; import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.util.IOUtils; import org.apache.poi.util.TempFile; /** @@ -66,6 +65,7 @@ import org.apache.poi.util.TempFile; * with the same attributes, and the sections must contain the same properties. * Details like the ordering of the properties do not matter.

*/ +@SuppressWarnings({"java:S106","java:S4823"}) public final class CopyCompare { private CopyCompare() {} @@ -85,8 +85,7 @@ public final class CopyCompare { * @throws UnsupportedEncodingException if a character encoding is not * supported. */ - public static void main(final String[] args) - throws UnsupportedEncodingException, IOException { + public static void main(final String[] args) throws IOException { String originalFileName = null; String copyFileName = null; @@ -137,9 +136,8 @@ public final class CopyCompare { * PropertySet#PropertySet(PropertySet)} constructor.

*/ static class CopyFile implements POIFSReaderListener { - private String dstName; - private OutputStream out; - private POIFSFileSystem poiFs; + private final String dstName; + private final POIFSFileSystem poiFs; /** @@ -166,23 +164,16 @@ public final class CopyCompare { * "event" object. */ final POIFSDocumentPath path = event.getPath(); final String name = event.getName(); - final DocumentInputStream stream = event.getStream(); Throwable t = null; - try { + try (final DocumentInputStream stream = event.getStream()) { /* Find out whether the current document is a property set * stream or not. */ if (stream != null && PropertySet.isPropertySetStream(stream)) { /* Yes, the current document is a property set stream. * Let's create a PropertySet instance from it. */ - PropertySet ps = null; - try { - ps = PropertySetFactory.create(stream); - } catch (NoPropertySetStreamException ex) { - /* This exception will not be thrown because we already - * checked above. */ - } + PropertySet ps = PropertySetFactory.create(stream); /* Copy the property set to the destination POI file * system. */ @@ -192,7 +183,7 @@ public final class CopyCompare { * copy it unmodified to the destination POIFS. */ copy(poiFs, path, name, stream); } - } catch (MarkUnsupportedException | WritingNotSupportedException | IOException ex) { + } catch (MarkUnsupportedException | WritingNotSupportedException | IOException | NoPropertySetStreamException ex) { t = ex; } @@ -254,20 +245,10 @@ public final class CopyCompare { // create the directories to the document final DirectoryEntry de = getPath(poiFs, path); // check the parameters after the directories have been created - if (stream == null || name == null) { - // Empty directory - return; + if (stream != null && name != null) { + byte[] data = IOUtils.toByteArray(stream); + de.createDocument(name, new ByteArrayInputStream(data)); } - 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); } @@ -275,9 +256,9 @@ public final class CopyCompare { * Writes the POI file system to a disk file. */ public void close() throws IOException { - out = new FileOutputStream(dstName); - poiFs.writeFilesystem(out); - out.close(); + try (OutputStream fos = new FileOutputStream(dstName)) { + poiFs.writeFilesystem(fos); + } } @@ -318,9 +299,10 @@ public final class CopyCompare { /* Check whether this directory has already been created. */ final String s = path.toString(); DirectoryEntry de = paths.get(s); - if (de != null) + if (de != null) { /* Yes: return the corresponding DirectoryEntry. */ return de; + } /* No: We have to create the directory - or return the root's * DirectoryEntry. */ @@ -334,8 +316,7 @@ public final class CopyCompare { * ensure that the parent directory exists: */ de = getPath(poiFs, path.getParent()); /* Now create the target directory: */ - de = de.createDirectory(path.getComponent - (path.length() - 1)); + de = de.createDirectory(path.getComponent(path.length() - 1)); } paths.put(s, de); return de; diff --git a/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java b/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java index bc3429f324..41711061fa 100644 --- a/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java +++ b/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java @@ -65,7 +65,10 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem; * * */ -public class ModifyDocumentSummaryInformation { +@SuppressWarnings({"java:S106","java:S4823"}) +public final class ModifyDocumentSummaryInformation { + + private ModifyDocumentSummaryInformation() {} /** *

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: */ - List
sections = ps.getSections(); - int nr = 0; - for (Section sec : sections) { - /* Print a single section: */ - out(" Section " + nr++ + ":"); - String s = hex(sec.getFormatID().getBytes()); - s = s.substring(0, s.length() - 1); - out(" Format ID: " + s); + /* Print the list of sections: */ + List
sections = ps.getSections(); + int nr = 0; + for (Section sec : sections) { + /* Print a single section: */ + out(" Section " + nr++ + ":"); + String s = sec.getFormatID().toString(); + s = s.substring(0, s.length() - 1); + out(" Format ID: " + s); - /* Print the number of properties in this section. */ - int propertyCount = sec.getPropertyCount(); - out(" No. of properties: " + propertyCount); + /* Print the number of properties in this section. */ + int propertyCount = sec.getPropertyCount(); + out(" No. of properties: " + propertyCount); - /* Print the properties: */ - Property[] properties = sec.getProperties(); - for (Property p : properties) { - /* Print a single property: */ - long id = p.getID(); - long type = p.getType(); - Object value = p.getValue(); - out(" Property ID: " + id + ", type: " + type + - ", value: " + value); - } + /* Print the properties: */ + Property[] properties = sec.getProperties(); + for (Property p : properties) { + /* Print a single property: */ + long id = p.getID(); + long type = p.getType(); + Object value = p.getValue(); + out(" Property ID: " + id + ", type: " + type + + ", value: " + value); } } } - private static void out(final String msg) - { + private static void out(final String msg) { System.out.println(msg); } - - private static String hex(final byte[] bytes) - { - return HexDump.dump(bytes, 0L, 0); - } - } diff --git a/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java b/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java index 38313a14c5..1072064998 100644 --- a/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java +++ b/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java @@ -24,7 +24,6 @@ import org.apache.poi.hpsf.PropertySetFactory; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.poifs.eventfilesystem.POIFSReader; import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; /** *

Sample 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 Map paths = new HashMap<>(); - - - - /** - *

Ensures 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; iThis class is a simple sample application showing how to create a property * set and write it to disk.

*/ -public class WriteTitle -{ +@SuppressWarnings({"java:S106","java:S4823"}) +public final class WriteTitle { + + private WriteTitle() {} + /** *

Runs 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 (List 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())); - } - } - } - } + slide.getTextParagraphs().stream(). + flatMap(List::stream). + map(HSLFTextParagraph::getTextRuns). + flatMap(List::stream). + forEach(run -> out(run.getHyperlink(), run)); // 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)); - } - } - } + slide.getShapes().stream(). + filter(sh -> sh instanceof HSLFSimpleShape). + forEach(sh -> out(((HSLFSimpleShape) sh).getHyperlink(), null)); } } } - } + } - static String toStr(HSLFHyperlink link, String rawText) { + private static void out(HSLFHyperlink link, HSLFTextRun run) { + if (link == null) { + return; + } + String rawText = run == null ? null : run.getRawText(); //in ppt end index is inclusive String formatStr = "title: %1$s, address: %2$s" + (rawText == null ? "" : ", start: %3$s, end: %4$s, substring: %5$s"); - return String.format(Locale.ROOT, formatStr, link.getLabel(), link.getAddress(), link.getStartIndex(), link.getEndIndex(), rawText); + String line = String.format(Locale.ROOT, formatStr, link.getLabel(), link.getAddress(), link.getStartIndex(), link.getEndIndex(), rawText); + System.out.println(line); } } diff --git a/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java b/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java index 112500d97f..49ca94be9b 100644 --- a/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java +++ b/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java @@ -28,7 +28,10 @@ import org.apache.poi.hslf.usermodel.HSLFSoundData; /** * For each slide iterate over shapes and found associated sound data. */ -public class SoundFinder { +@SuppressWarnings({"java:S106", "java:S4823"}) +public final class SoundFinder { + private SoundFinder() {} + public static void main(String[] args) throws IOException { try (FileInputStream fis = new FileInputStream(args[0])) { try (HSLFSlideShow ppt = new HSLFSlideShow(fis)) { @@ -54,7 +57,7 @@ public class SoundFinder { * @return 0-based reference to a sound in the sound collection * or -1 if the shape is not associated with a sound */ - protected static int getSoundReference(HSLFShape shape){ + private static int getSoundReference(HSLFShape shape){ int soundRef = -1; //dive into the shape container and search for InteractiveInfoAtom InteractiveInfoAtom info = shape.getClientDataRecord(RecordTypes.InteractiveInfo.typeID); diff --git a/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/LoadPasswordProtectedXlsxStreaming.java b/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/LoadPasswordProtectedXlsxStreaming.java index f02ec50191..2e7df6c441 100644 --- a/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/LoadPasswordProtectedXlsxStreaming.java +++ b/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/LoadPasswordProtectedXlsxStreaming.java @@ -19,15 +19,13 @@ package org.apache.poi.xssf.eventusermodel.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.temp.AesZipFileZipEntrySource; import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.eventusermodel.XSSFReader.SheetIterator; +import org.apache.poi.xssf.usermodel.examples.LoadPasswordProtectedXlsx; /** * An example that loads a password protected workbook and counts the sheets. @@ -37,23 +35,16 @@ import org.apache.poi.xssf.eventusermodel.XSSFReader.SheetIterator; *
  • AesZipFileZipEntrySource 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 p = (path != null) ? Objects::isNull : (s) -> (s == null || s.isEmpty()); + if (Stream.of(s2).anyMatch(p)) { + throw new IllegalArgumentException("components cannot contain null or empty strings"); } + + this.components = Stream.concat(Stream.of(s1),Stream.of(s2)).toArray(String[]::new); } /** - * equality. Two POIFSDocumentPath instances are equal if they - * have the same number of component Strings, and if each - * component String is equal to its coresponding component String + * Two POIFSDocumentPath instances are equal if they have the same number of component Strings, + * and if each component String is equal to its corresponding component String * * @param o the object we're checking equality for * * @return true if the object is equal to this object */ - public boolean equals(final Object o) - { - boolean rval = false; - - if ((o != null) && (o.getClass() == this.getClass())) - { - if (this == o) - { - rval = true; - } - else - { - POIFSDocumentPath path = ( POIFSDocumentPath ) o; - - if (path.components.length == this.components.length) - { - rval = true; - for (int j = 0; j < this.components.length; j++) - { - if (!path.components[ j ] - .equals(this.components[ j ])) - { - rval = false; - break; - } - } - } - } + public boolean equals(final Object o) { + if (this == o) { + return true; } - return rval; + + if ((o != null) && (o.getClass() == this.getClass())) { + POIFSDocumentPath path = ( POIFSDocumentPath ) o; + return Arrays.equals(this.components, path.components); + } + return false; } /** @@ -192,30 +115,14 @@ public class POIFSDocumentPath * @return hashcode */ - public int hashCode() - { - if (hashcode == 0) - { - hashcode = computeHashCode(); - } - return hashcode; - } - - private int computeHashCode() { - int code = 0; - for (int j = 0; j < components.length; j++) - { - code += components[ j ].hashCode(); - } - return code; + public int hashCode() { + return (hashcode == 0) ? (hashcode = Arrays.hashCode(components)) : hashcode; } /** * @return the number of components */ - - public int length() - { + public int length() { return components.length; } @@ -228,10 +135,7 @@ public class POIFSDocumentPath * * @exception ArrayIndexOutOfBoundsException if n < 0 or n >= length() */ - - public String getComponent(int n) - throws ArrayIndexOutOfBoundsException - { + public String getComponent(int n) throws ArrayIndexOutOfBoundsException { return components[ n ]; } @@ -242,21 +146,10 @@ public class POIFSDocumentPath * @since 2002-01-24 * @return path of parent, or null if this path is the root path */ - - public POIFSDocumentPath getParent() - { - final int length = components.length - 1; - - if (length < 0) - { - return null; - } - String[] parentComponents = new String[ length ]; - System.arraycopy(components, 0, parentComponents, 0, length); - - return new POIFSDocumentPath(parentComponents); + public POIFSDocumentPath getParent() { + return (components.length == 0) ? null : new POIFSDocumentPath(Arrays.copyOf(components, components.length - 1)); } - + /** *

    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.

    @@ -264,13 +157,8 @@ public class POIFSDocumentPath * @since 2016-04-09 * @return The last name in the document path's name sequence, or empty string if this is the root path */ - - public String getName() - { - if (components.length == 0) { - return ""; - } - return components[components.length - 1]; + public String getName() { + return components.length == 0 ? "" : components[components.length - 1]; } /** @@ -281,22 +169,8 @@ public class POIFSDocumentPath * * @since 2002-01-24 */ - - public String toString() - { - final StringBuilder b = new StringBuilder(); - final int l = length(); - - b.append(File.separatorChar); - for (int i = 0; i < l; i++) - { - b.append(getComponent(i)); - if (i < l - 1) - { - b.append(File.separatorChar); - } - } - return b.toString(); + public String toString() { + return File.separatorChar + String.join(String.valueOf(File.separatorChar), components); } -} // end public class POIFSDocumentPath +} diff --git a/src/java/org/apache/poi/util/HexDump.java b/src/java/org/apache/poi/util/HexDump.java index 5afd1dbe18..184c48bd1e 100644 --- a/src/java/org/apache/poi/util/HexDump.java +++ b/src/java/org/apache/poi/util/HexDump.java @@ -17,13 +17,9 @@ package org.apache.poi.util; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; -import java.io.PrintStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -31,7 +27,7 @@ import java.nio.charset.StandardCharsets; * dump data in hexadecimal format */ @Internal -public class HexDump { +public final class HexDump { public static final String EOL = System.getProperty("line.separator"); public static final Charset UTF8 = StandardCharsets.UTF_8; @@ -105,8 +101,8 @@ public class HexDump { public static String dump(final byte [] data, final long offset, final int index) { return dump(data, offset, index, Integer.MAX_VALUE); - } - + } + /** * dump an array of bytes to a String * @@ -128,23 +124,23 @@ public class HexDump { int data_length = (length == Integer.MAX_VALUE || length < 0 || index+length < 0) ? data.length : Math.min(data.length,index+length); - - + + if ((index < 0) || (index >= data.length)) { String err = "illegal index: "+index+" into array of length "+data.length; throw new ArrayIndexOutOfBoundsException(err); } - + long display_offset = offset + index; StringBuilder buffer = new StringBuilder(74); - + for (int j = index; j < data_length; j += 16) { int chars_read = data_length - j; if (chars_read > 16) { chars_read = 16; } - + writeHex(buffer, display_offset, 8, ""); for (int k = 0; k < 16; k++) { if (k < chars_read) { @@ -168,7 +164,7 @@ public class HexDump { if (Character.isISOControl(charB)) { return '.'; } - + switch (charB) { // printable, but not compilable with current compiler encoding case 0xFF: @@ -180,7 +176,7 @@ public class HexDump { } return charB; } - + /** * Converts the parameter to a hex value. * @@ -205,58 +201,6 @@ public class HexDump { return retVal.toString(); } - /** - * Converts the parameter to a hex value. - * - * @param value The value to convert - * @return A String representing the array of shorts - */ - public static String toHex(final short[] value) - { - StringBuilder retVal = new StringBuilder(); - retVal.append('['); - for(int x = 0; x < value.length; x++) - { - if (x>0) { - retVal.append(", "); - } - retVal.append(toHex(value[x])); - } - retVal.append(']'); - return retVal.toString(); - } - - /** - *

    Converts the parameter to a hex value breaking the results into - * lines.

    - * - * @param value The value to convert - * @param bytesPerLine The maximum number of bytes per line. The next byte - * will be written to a new line - * @return A String representing the array of bytes - */ - public static String toHex(final byte[] value, final int bytesPerLine) { - if (value.length == 0) { - return ": 0"; - } - final int digits = (int) Math.round(Math.log(value.length) / Math.log(10) + 0.5); - StringBuilder retVal = new StringBuilder(); - writeHex(retVal, 0, digits, ""); - retVal.append(": "); - for(int x=0, i=-1; x < value.length; x++) { - if (++i == bytesPerLine) { - retVal.append('\n'); - writeHex(retVal, x, digits, ""); - retVal.append(": "); - i = 0; - } else if (x>0) { - retVal.append(", "); - } - retVal.append(toHex(value[x])); - } - return retVal.toString(); - } - /** * Converts the parameter to a hex value. * @@ -305,57 +249,6 @@ public class HexDump { return sb.toString(); } - /** - * Converts the string to a string of hex values by - * using String.getBytes(LocaleUtil.CHARSET_1252) to - * convert the string to a byte-array. - * - * @param value The value to convert - * @return The resulted hex string - */ - public static String toHex(String value) { - return (value == null || value.length() == 0) - ? "[]" - : toHex(value.getBytes(LocaleUtil.CHARSET_1252)); - } - - /** - * Dumps 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; } }