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
This commit is contained in:
Andreas Beeker 2020-04-18 21:31:18 +00:00
parent 7b2674f5af
commit 2841f3cd0e
25 changed files with 465 additions and 1100 deletions

View File

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

View File

@ -19,13 +19,12 @@
package org.apache.poi.crypt.examples; package org.apache.poi.crypt.examples;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.nio.file.Files;
import java.io.IOException; import java.nio.file.Paths;
import java.io.InputStream;
import java.security.GeneralSecurityException; 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.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo; 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 * 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 * Note that this isn't very fast, and is aimed at when you have
* just a few passwords to check. * just a few passwords to check.
* For serious processing, you'd be best off grabbing the hash * For serious processing, you'd be best off grabbing the hash
* out with POI or office2john.py, then running that against * out with POI or office2john.py, then running that against
* "John The Ripper" or GPU enabled version of "hashcat" * "John The Ripper" or GPU enabled version of "hashcat"
*/ */
public class OOXMLPasswordsTry implements Closeable { public final class OOXMLPasswordsTry {
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;
// Try each password in turn, reporting progress private OOXMLPasswordsTry() {}
String password;
while ((password = r.readLine()) != null) {
if (isValid(password)) {
valid = password;
break;
}
count++;
if (count % 1000 == 0) { @SuppressWarnings({"java:S106","java:S4823"})
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);
}
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
if (args.length < 2) { if (args.length < 2) {
System.err.println("Use:"); System.err.println("Use:");
System.err.println(" OOXMLPasswordsTry <file.ooxml> <wordlist>"); System.err.println(" OOXMLPasswordsTry <file.ooxml> <wordlist>");
System.exit(1); System.exit(1);
} }
File ooxml = new File(args[0]); String ooxml = args[0], words = args[1];
File words = new File(args[1]);
System.out.println("Trying passwords from " + words + " against " + ooxml); System.out.println("Trying passwords from " + words + " against " + ooxml);
System.out.println(); System.out.println();
String password; try (POIFSFileSystem fs = new POIFSFileSystem(new File(ooxml), true)) {
try (OOXMLPasswordsTry pt = new OOXMLPasswordsTry(ooxml)) { EncryptionInfo info = new EncryptionInfo(fs);
password = pt.tryAll(words); Decryptor d = Decryptor.getInstance(info);
final long start = System.currentTimeMillis();
final int[] count = { 0 };
Predicate<String> 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<String> 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) { private static boolean isValid(Decryptor dec, String password) {
System.out.println("Error - No password matched"); try {
} else { return dec.verifyPassword(password);
System.out.println("Password found!"); } catch (GeneralSecurityException e) {
System.out.println(password); return false;
} }
} }
} }

View File

@ -20,15 +20,15 @@
package org.apache.poi.examples.util; package org.apache.poi.examples.util;
import java.io.File; import java.io.File;
import java.io.IOException;
import org.apache.poi.util.TempFile; import org.apache.poi.util.TempFile;
public class TempFileUtils { public final class TempFileUtils {
private 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"; String tmpDir = System.getProperty(TempFile.JAVA_IO_TMPDIR) + "/poifiles";
File tempDir = new File(tmpDir); File tempDir = new File(tmpDir);
if(tempDir.exists()) { if(tempDir.exists()) {

View File

@ -18,11 +18,9 @@
package org.apache.poi.hpsf.examples; package org.apache.poi.hpsf.examples;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.HashMap; 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.EntryUtils;
import org.apache.poi.poifs.filesystem.POIFSDocumentPath; import org.apache.poi.poifs.filesystem.POIFSDocumentPath;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.TempFile; 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. * with the same attributes, and the sections must contain the same properties.
* Details like the ordering of the properties do not matter.</p> * Details like the ordering of the properties do not matter.</p>
*/ */
@SuppressWarnings({"java:S106","java:S4823"})
public final class CopyCompare { public final class CopyCompare {
private CopyCompare() {} private CopyCompare() {}
@ -85,8 +85,7 @@ public final class CopyCompare {
* @throws UnsupportedEncodingException if a character encoding is not * @throws UnsupportedEncodingException if a character encoding is not
* supported. * supported.
*/ */
public static void main(final String[] args) public static void main(final String[] args) throws IOException {
throws UnsupportedEncodingException, IOException {
String originalFileName = null; String originalFileName = null;
String copyFileName = null; String copyFileName = null;
@ -137,9 +136,8 @@ public final class CopyCompare {
* PropertySet#PropertySet(PropertySet)} constructor.</p> * PropertySet#PropertySet(PropertySet)} constructor.</p>
*/ */
static class CopyFile implements POIFSReaderListener { static class CopyFile implements POIFSReaderListener {
private String dstName; private final String dstName;
private OutputStream out; private final POIFSFileSystem poiFs;
private POIFSFileSystem poiFs;
/** /**
@ -166,23 +164,16 @@ public final class CopyCompare {
* "event" object. */ * "event" object. */
final POIFSDocumentPath path = event.getPath(); final POIFSDocumentPath path = event.getPath();
final String name = event.getName(); final String name = event.getName();
final DocumentInputStream stream = event.getStream();
Throwable t = null; Throwable t = null;
try { try (final DocumentInputStream stream = event.getStream()) {
/* Find out whether the current document is a property set /* Find out whether the current document is a property set
* stream or not. */ * stream or not. */
if (stream != null && PropertySet.isPropertySetStream(stream)) { if (stream != null && PropertySet.isPropertySetStream(stream)) {
/* Yes, the current document is a property set stream. /* Yes, the current document is a property set stream.
* Let's create a PropertySet instance from it. */ * Let's create a PropertySet instance from it. */
PropertySet ps = null; PropertySet ps = PropertySetFactory.create(stream);
try {
ps = PropertySetFactory.create(stream);
} catch (NoPropertySetStreamException ex) {
/* This exception will not be thrown because we already
* checked above. */
}
/* Copy the property set to the destination POI file /* Copy the property set to the destination POI file
* system. */ * system. */
@ -192,7 +183,7 @@ public final class CopyCompare {
* copy it unmodified to the destination POIFS. */ * copy it unmodified to the destination POIFS. */
copy(poiFs, path, name, stream); copy(poiFs, path, name, stream);
} }
} catch (MarkUnsupportedException | WritingNotSupportedException | IOException ex) { } catch (MarkUnsupportedException | WritingNotSupportedException | IOException | NoPropertySetStreamException ex) {
t = ex; t = ex;
} }
@ -254,20 +245,10 @@ public final class CopyCompare {
// create the directories to the document // create the directories to the document
final DirectoryEntry de = getPath(poiFs, path); final DirectoryEntry de = getPath(poiFs, path);
// check the parameters after the directories have been created // check the parameters after the directories have been created
if (stream == null || name == null) { if (stream != null && name != null) {
// Empty directory byte[] data = IOUtils.toByteArray(stream);
return; 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. * Writes the POI file system to a disk file.
*/ */
public void close() throws IOException { public void close() throws IOException {
out = new FileOutputStream(dstName); try (OutputStream fos = new FileOutputStream(dstName)) {
poiFs.writeFilesystem(out); poiFs.writeFilesystem(fos);
out.close(); }
} }
@ -318,9 +299,10 @@ public final class CopyCompare {
/* Check whether this directory has already been created. */ /* Check whether this directory has already been created. */
final String s = path.toString(); final String s = path.toString();
DirectoryEntry de = paths.get(s); DirectoryEntry de = paths.get(s);
if (de != null) if (de != null) {
/* Yes: return the corresponding DirectoryEntry. */ /* Yes: return the corresponding DirectoryEntry. */
return de; return de;
}
/* No: We have to create the directory - or return the root's /* No: We have to create the directory - or return the root's
* DirectoryEntry. */ * DirectoryEntry. */
@ -334,8 +316,7 @@ public final class CopyCompare {
* ensure that the parent directory exists: */ * ensure that the parent directory exists: */
de = getPath(poiFs, path.getParent()); de = getPath(poiFs, path.getParent());
/* Now create the target directory: */ /* Now create the target directory: */
de = de.createDirectory(path.getComponent de = de.createDirectory(path.getComponent(path.length() - 1));
(path.length() - 1));
} }
paths.put(s, de); paths.put(s, de);
return de; return de;

View File

@ -65,7 +65,10 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
* *
* </ol> * </ol>
*/ */
public class ModifyDocumentSummaryInformation { @SuppressWarnings({"java:S106","java:S4823"})
public final class ModifyDocumentSummaryInformation {
private ModifyDocumentSummaryInformation() {}
/** /**
* <p>Main method - see class description.</p> * <p>Main method - see class description.</p>
@ -91,6 +94,7 @@ public class ModifyDocumentSummaryInformation {
// There is no summary information yet. We have to create a new one // There is no summary information yet. We have to create a new one
si = PropertySetFactory.newSummaryInformation(); si = PropertySetFactory.newSummaryInformation();
} }
assert(si != null);
/* Change the author to "Rainer Klute". Any former author value will /* Change the author to "Rainer Klute". Any former author value will
* be lost. If there has been no author yet, it will be created. */ * be lost. If there has been no author yet, it will be created. */
@ -112,6 +116,7 @@ public class ModifyDocumentSummaryInformation {
* new one. */ * new one. */
dsi = PropertySetFactory.newDocumentSummaryInformation(); dsi = PropertySetFactory.newDocumentSummaryInformation();
} }
assert(dsi != null);
/* Change the category to "POI example". Any former category value will /* Change the category to "POI example". Any former category value will
* be lost. If there has been no category yet, it will be created. */ * be lost. If there has been no category yet, it will be created. */

View File

@ -28,8 +28,6 @@ import org.apache.poi.hpsf.PropertySetFactory;
import org.apache.poi.hpsf.Section; import org.apache.poi.hpsf.Section;
import org.apache.poi.poifs.eventfilesystem.POIFSReader; import org.apache.poi.poifs.eventfilesystem.POIFSReader;
import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;
import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
import org.apache.poi.util.HexDump;
/** /**
* <p>Sample application showing how to read a document's custom property set. * <p>Sample application showing how to read a document's custom property set.
@ -37,6 +35,7 @@ import org.apache.poi.util.HexDump;
* *
* <p>Explanations can be found in the HPSF HOW-TO.</p> * <p>Explanations can be found in the HPSF HOW-TO.</p>
*/ */
@SuppressWarnings({"java:S106","java:S4823"})
public final class ReadCustomPropertySets { public final class ReadCustomPropertySets {
private ReadCustomPropertySets() {} private ReadCustomPropertySets() {}
@ -47,85 +46,63 @@ public final class ReadCustomPropertySets {
* @param args Command-line arguments (unused). * @param args Command-line arguments (unused).
* @throws IOException if any I/O exception occurs. * @throws IOException if any I/O exception occurs.
*/ */
public static void main(final String[] args) public static void main(final String[] args) throws IOException {
throws IOException
{
final String filename = args[0]; final String filename = args[0];
POIFSReader r = new POIFSReader(); POIFSReader r = new POIFSReader();
/* Register a listener for *all* documents. */ /* Register a listener for *all* documents. */
r.registerListener(new MyPOIFSReaderListener()); r.registerListener(ReadCustomPropertySets::processPOIFSReaderEvent);
r.read(new File(filename)); r.read(new File(filename));
} }
static class MyPOIFSReaderListener implements POIFSReaderListener public static void processPOIFSReaderEvent(final POIFSReaderEvent event) {
{ final String streamName = event.getPath() + event.getName();
@Override PropertySet ps;
public void processPOIFSReaderEvent(final POIFSReaderEvent event) try {
{ ps = PropertySetFactory.create(event.getStream());
PropertySet ps; } catch (NoPropertySetStreamException ex) {
try out("No property set stream: \"" + streamName + "\"");
{ return;
ps = PropertySetFactory.create(event.getStream()); } catch (Exception ex) {
} throw new RuntimeException("Property set stream \"" + streamName + "\": " + ex);
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);
}
/* Print the name of the property set stream: */ /* Print the name of the property set stream: */
out("Property set stream \"" + event.getPath() + out("Property set stream \"" + streamName + "\":");
event.getName() + "\":");
/* Print the number of sections: */ /* Print the number of sections: */
final long sectionCount = ps.getSectionCount(); final long sectionCount = ps.getSectionCount();
out(" No. of sections: " + sectionCount); out(" No. of sections: " + sectionCount);
/* Print the list of sections: */ /* Print the list of sections: */
List<Section> sections = ps.getSections(); List<Section> sections = ps.getSections();
int nr = 0; int nr = 0;
for (Section sec : sections) { for (Section sec : sections) {
/* Print a single section: */ /* Print a single section: */
out(" Section " + nr++ + ":"); out(" Section " + nr++ + ":");
String s = hex(sec.getFormatID().getBytes()); String s = sec.getFormatID().toString();
s = s.substring(0, s.length() - 1); s = s.substring(0, s.length() - 1);
out(" Format ID: " + s); out(" Format ID: " + s);
/* Print the number of properties in this section. */ /* Print the number of properties in this section. */
int propertyCount = sec.getPropertyCount(); int propertyCount = sec.getPropertyCount();
out(" No. of properties: " + propertyCount); out(" No. of properties: " + propertyCount);
/* Print the properties: */ /* Print the properties: */
Property[] properties = sec.getProperties(); Property[] properties = sec.getProperties();
for (Property p : properties) { for (Property p : properties) {
/* Print a single property: */ /* Print a single property: */
long id = p.getID(); long id = p.getID();
long type = p.getType(); long type = p.getType();
Object value = p.getValue(); Object value = p.getValue();
out(" Property ID: " + id + ", type: " + type + out(" Property ID: " + id + ", type: " + type +
", value: " + value); ", value: " + value);
}
} }
} }
} }
private static void out(final String msg) private static void out(final String msg) {
{
System.out.println(msg); System.out.println(msg);
} }
private static String hex(final byte[] bytes)
{
return HexDump.dump(bytes, 0L, 0);
}
} }

View File

@ -24,7 +24,6 @@ import org.apache.poi.hpsf.PropertySetFactory;
import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.eventfilesystem.POIFSReader; import org.apache.poi.poifs.eventfilesystem.POIFSReader;
import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;
import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
/** /**
* <p>Sample application showing how to read a OLE 2 document's * <p>Sample application showing how to read a OLE 2 document's
@ -33,8 +32,8 @@ import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
* *
* <p>Explanations can be found in the HPSF HOW-TO.</p> * <p>Explanations can be found in the HPSF HOW-TO.</p>
*/ */
public final class ReadTitle @SuppressWarnings({"java:S106","java:S4823"})
{ public final class ReadTitle {
private ReadTitle() {} private ReadTitle() {}
/** /**
@ -44,38 +43,22 @@ public final class ReadTitle
* be the name of a POI filesystem to read. * be the name of a POI filesystem to read.
* @throws IOException if any I/O exception occurs. * @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]; final String filename = args[0];
POIFSReader r = new POIFSReader(); 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)); r.read(new File(filename));
} }
static class MyPOIFSReaderListener implements POIFSReaderListener private static void processPOIFSReaderEvent(final POIFSReaderEvent event) {
{ SummaryInformation si;
@Override try {
public void processPOIFSReaderEvent(final POIFSReaderEvent event) si = (SummaryInformation) PropertySetFactory.create(event.getStream());
{ } catch (Exception ex) {
SummaryInformation si; throw new RuntimeException("Property set stream \"" + event.getPath() + event.getName() + "\": " + ex);
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.");
} }
final String title = si.getTitle();
System.out.println(title != null ? "Title: \"" + title + "\"" : "Document has no title.");
} }
} }

View File

@ -17,15 +17,11 @@
package org.apache.poi.hpsf.examples; package org.apache.poi.hpsf.examples;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.hpsf.HPSFRuntimeException; import org.apache.poi.hpsf.HPSFRuntimeException;
import org.apache.poi.hpsf.MarkUnsupportedException; 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.hpsf.wellknown.PropertyIDMap;
import org.apache.poi.poifs.eventfilesystem.POIFSReader; import org.apache.poi.poifs.eventfilesystem.POIFSReader;
import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; 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.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream; import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.POIFSDocumentPath; import org.apache.poi.poifs.filesystem.POIFSDocumentPath;
@ -49,15 +44,15 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
* <p>This class is a sample application which shows how to write or modify the * <p>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 * author and title property of an OLE 2 document. This could be done in two
* different ways:</p> * different ways:</p>
* *
* <ul> * <ul>
* *
* <li><p>The first approach is to open the OLE 2 file as a POI filesystem * <li><p>The first approach is to open the OLE 2 file as a POI filesystem
* (see class {@link POIFSFileSystem}), read the summary information property * (see class {@link POIFSFileSystem}), read the summary information property
* set (see classes {@link SummaryInformation} and {@link PropertySet}), write * set (see classes {@link SummaryInformation} and {@link PropertySet}), write
* the author and title properties into it and write the property set back into * the author and title properties into it and write the property set back into
* the POI filesystem.</p></li> * the POI filesystem.</p></li>
* *
* <li><p>The second approach does not modify the original POI filesystem, but * <li><p>The second approach does not modify the original POI filesystem, but
* instead creates a new one. All documents from the original POIFS are copied * instead creates a new one. All documents from the original POIFS are copied
* to the destination POIFS, except for the summary information stream. The * 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 * it to the destination POIFS. It there are several summary information streams
* in the original POIFS - e.g. in subordinate directories - they are modified * in the original POIFS - e.g. in subordinate directories - they are modified
* just the same.</p></li> * just the same.</p></li>
* *
* </ul> * </ul>
* *
* <p>This sample application takes the second approach. It expects the name of * <p>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 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 * 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 * encounters a summary information stream it reads its properties. Then it sets
* the "author" and "title" properties to new values and writes the modified * the "author" and "title" properties to new values and writes the modified
* summary information stream into the output file.</p> * summary information stream into the output file.</p>
* *
* <p>Further explanations can be found in the HPSF HOW-TO.</p> * <p>Further explanations can be found in the HPSF HOW-TO.</p>
*/ */
@SuppressWarnings({"java:S106","java:S4823"})
public final class WriteAuthorAndTitle { public final class WriteAuthorAndTitle {
private WriteAuthorAndTitle() {} private WriteAuthorAndTitle() {}
@ -89,301 +85,89 @@ public final class WriteAuthorAndTitle {
* be the name of a POI filesystem to read. * be the name of a POI filesystem to read.
* @throws IOException if any I/O exception occurs. * @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. */ /* Check whether we have exactly two command-line arguments. */
if (args.length != 2) if (args.length != 2) {
{ System.err.println("Usage: WriteAuthorAndTitle originPOIFS destinationPOIFS");
System.err.println("Usage: " + WriteAuthorAndTitle.class.getName() +
" originPOIFS destinationPOIFS");
System.exit(1); System.exit(1);
} }
/* Read the names of the origin and destination POI filesystems. */ /* Read the names of the origin and destination POI filesystems. */
final String srcName = args[0]; final String srcName = args[0], dstName = args[1];
final String dstName = args[1];
/* Read the origin POIFS using the eventing API. The real work is done /* Read the origin POIFS using the eventing API. The real work is done
* in the class ModifySICopyTheRest which is registered here as a * in the class ModifySICopyTheRest which is registered here as a
* POIFSReader. */ * POIFSReader. */
final POIFSReader r = new POIFSReader(); try (POIFSFileSystem poifs = new POIFSFileSystem();
final ModifySICopyTheRest msrl = new ModifySICopyTheRest(dstName); OutputStream out = new FileOutputStream(dstName)) {
r.registerListener(msrl); final POIFSReader r = new POIFSReader();
r.read(new File(srcName)); r.registerListener((e) -> handleEvent(poifs, e));
r.read(new File(srcName));
/* Write the new POIFS to disk. */ /* Write the new POIFS to disk. */
msrl.close(); poifs.writeFilesystem(out);
}
} }
private interface InputStreamSupplier {
InputStream get() throws IOException, WritingNotSupportedException;
}
/** /**
* <p>This class does all the work. As its name implies it modifies a * The method is called by POI's eventing API for each file in the origin POIFS.
* 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.</p>
*/ */
static class ModifySICopyTheRest implements POIFSReaderListener private static void handleEvent(final POIFSFileSystem poiFs, final POIFSReaderEvent event) {
{ // The following declarations are shortcuts for accessing the "event" object.
private String dstName; final DocumentInputStream stream = event.getStream();
private OutputStream out;
private POIFSFileSystem poiFs;
try {
final InputStreamSupplier isSup;
/** // Find out whether the current document is a property set stream or not.
* The constructor of a {@link ModifySICopyTheRest} instance creates if (PropertySet.isPropertySetStream(stream)) {
* the target POIFS. It also stores the name of the file the POIFS will // Yes, the current document is a property set stream. Let's create a PropertySet instance from it.
* be written to once it is complete. PropertySet ps = PropertySetFactory.create(stream);
*
* @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();
}
// 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);
/** // Retrieve the section containing the properties to modify.
* The method is called by POI's eventing API for each file in the // A summary information property set contains exactly one section.
* origin POIFS. final Section s = ps.getSections().get(0);
*/
@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();
Throwable t = null; // Set the properties.
s.setProperty(PropertyIDMap.PID_AUTHOR, Variant.VT_LPSTR, "Rainer Klute");
try { s.setProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPWSTR, "Test");
/* 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);
} }
} 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 try (InputStream is = isSup.get()) {
* we cannot pass checked exceptions to the caller. The following final POIFSDocumentPath path = event.getPath();
* 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);
}
}
// 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();
/** for (int i=0; i<path.length(); i++) {
* <p>Receives a summary information property set modifies (or creates) String subDir = path.getComponent(i);
* its "author" and "title" properties and writes the result under the de = (de.hasEntry(subDir)) ? (DirectoryEntry)de.getEntry(subDir) : de.createDirectory(subDir);
* same path and name as the origin to a destination POI filesystem.</p>
*
* @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);
}
/**
* <p>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.</p>
*
* @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());
}
/**
* <p>Copies the bytes from a {@link DocumentInputStream} to a new
* stream in a POI filesystem.</p>
*
* @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<String, DirectoryEntry> paths = new HashMap<>();
/**
* <p>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.</p>
*
* <p>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.</p>
*
* @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));
} }
paths.put(s, de);
return de; de.createDocument(event.getName(), is);
}
catch (IOException ex)
{
/* This exception will be thrown if the directory already
* exists. However, since we have full control about directory
* creation we can ensure that this will never happen. */
ex.printStackTrace(System.err);
throw new RuntimeException(ex);
} }
} catch (MarkUnsupportedException | WritingNotSupportedException | IOException | NoPropertySetStreamException ex) {
// According to the definition of the processPOIFSReaderEvent method we cannot pass checked
// exceptions to the caller.
throw new HPSFRuntimeException("Could not read file " + event.getPath() + "/" + event.getName(), ex);
} }
} }
} }

View File

@ -34,15 +34,18 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
* <p>This class is a simple sample application showing how to create a property * <p>This class is a simple sample application showing how to create a property
* set and write it to disk.</p> * set and write it to disk.</p>
*/ */
public class WriteTitle @SuppressWarnings({"java:S106","java:S4823"})
{ public final class WriteTitle {
private WriteTitle() {}
/** /**
* <p>Runs the example program.</p> * <p>Runs the example program.</p>
* *
* @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. * argument is the name of the POI file system to create.
* @throws IOException if any I/O exception occurs. * @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. * writing a certain property type.
*/ */
public static void main(final String[] args) public static void main(final String[] args)
@ -51,8 +54,7 @@ public class WriteTitle
/* Check whether we have exactly one command-line argument. */ /* Check whether we have exactly one command-line argument. */
if (args.length != 1) if (args.length != 1)
{ {
System.err.println("Usage: " + WriteTitle.class.getName() + System.err.println("Usage: " + WriteTitle.class.getName() + "destinationPOIFS");
"destinationPOIFS");
System.exit(1); System.exit(1);
} }
@ -70,7 +72,7 @@ public class WriteTitle
* SectionIDMap.SUMMARY_INFORMATION_ID. */ * SectionIDMap.SUMMARY_INFORMATION_ID. */
ms.setFormatID(SummaryInformation.FORMAT_ID); ms.setFormatID(SummaryInformation.FORMAT_ID);
/* Create an empty property. */ /* Create an empty property. */
final Property p = new Property(); final Property p = new Property();
/* Fill the property with appropriate settings so that it specifies the /* Fill the property with appropriate settings so that it specifies the
@ -82,12 +84,13 @@ public class WriteTitle
/* Place the property into the section. */ /* Place the property into the section. */
ms.setProperty(p); ms.setProperty(p);
/* Create the POI file system the property set is to be written to. */ /* 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
/* 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
* handed over to the POIFS.createDocument() method as an input stream * which produces the bytes making out the property set stream. */
* which produces the bytes making out the property set stream. */ try (final POIFSFileSystem poiFs = new POIFSFileSystem();
final InputStream is = mps.toInputStream(); final InputStream is = mps.toInputStream();
final FileOutputStream fos = new FileOutputStream(fileName)) {
/* Create the summary information property set in the POI file /* Create the summary information property set in the POI file
* system. It is given the default name most (if not all) summary * 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); poiFs.createDocument(is, SummaryInformation.DEFAULT_STREAM_NAME);
/* Write the whole POI file system to a disk file. */ /* Write the whole POI file system to a disk file. */
try (FileOutputStream fos = new FileOutputStream(fileName)) { poiFs.writeFilesystem(fos);
poiFs.writeFilesystem(fos);
}
} }
} }
} }

View File

@ -51,9 +51,11 @@ import org.apache.poi.sl.usermodel.VerticalAlignment;
@SuppressWarnings("java:S1192") @SuppressWarnings("java:S1192")
public final class ApacheconEU08 { public final class ApacheconEU08 {
private ApacheconEU08() {}
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
// use HSLFSlideShow or XMLSlideShow
try (SlideShow<?,?> ppt = new HSLFSlideShow()) { try (SlideShow<?,?> ppt = new HSLFSlideShow()) {
// SlideShow<?,?> ppt = new XMLSlideShow();
ppt.setPageSize(new Dimension(720, 540)); ppt.setPageSize(new Dimension(720, 540));
slide1(ppt); slide1(ppt);
@ -394,7 +396,7 @@ public final class ApacheconEU08 {
graphics.setFont(new Font("Arial", Font.BOLD, 10)); graphics.setFont(new Font("Arial", Font.BOLD, 10));
for (int i = 0, idx = 1; i < def.length; i+=2, idx++) { for (int i = 0, idx = 1; i < def.length; i+=2, idx++) {
graphics.setColor(Color.black); 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("Q" + idx, x-20, y+20);
graphics.drawString(width + "%", x + width + 10, y + 20); graphics.drawString(width + "%", x + width + 10, y + 20);
graphics.setColor((Color)def[i]); graphics.setColor((Color)def[i]);

View File

@ -29,8 +29,10 @@ import org.apache.poi.hslf.usermodel.HSLFTextBox;
/** /**
* Demonstrates how to create hyperlinks in PowerPoint presentations * 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 { public static void main(String[] args) throws IOException {
try (HSLFSlideShow ppt = new HSLFSlideShow()) { try (HSLFSlideShow ppt = new HSLFSlideShow()) {
HSLFSlide slideA = ppt.createSlide(); HSLFSlide slideA = ppt.createSlide();

View File

@ -19,6 +19,7 @@ package org.apache.poi.hslf.examples;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.apache.poi.hslf.usermodel.HSLFObjectData; 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.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph; import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range; 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 * Demonstrates how you can extract misc embedded data from a ppt file
*/ */
@SuppressWarnings({"java:S106","java:S4823"})
public final class DataExtraction { public final class DataExtraction {
private DataExtraction() {}
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
if (args.length == 0) { if (args.length == 0) {
@ -46,20 +51,13 @@ public final class DataExtraction {
return; return;
} }
try (FileInputStream is = new FileInputStream(args[0]); try (FileInputStream fis = new FileInputStream(args[0]);
HSLFSlideShow ppt = new HSLFSlideShow(is)) { HSLFSlideShow ppt = new HSLFSlideShow(fis)) {
//extract all sound files embedded in this presentation //extract all sound files embedded in this presentation
HSLFSoundData[] sound = ppt.getSoundData(); HSLFSoundData[] sound = ppt.getSoundData();
for (HSLFSoundData aSound : sound) { for (HSLFSoundData aSound : sound) {
String type = aSound.getSoundType(); //*.wav handleSound(aSound);
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);
}
} }
int oleIdx = -1, picIdx = -1; int oleIdx = -1, picIdx = -1;
@ -71,35 +69,18 @@ public final class DataExtraction {
HSLFObjectShape ole = (HSLFObjectShape) shape; HSLFObjectShape ole = (HSLFObjectShape) shape;
HSLFObjectData data = ole.getObjectData(); HSLFObjectData data = ole.getObjectData();
String name = ole.getInstanceName(); String name = ole.getInstanceName();
if ("Worksheet".equals(name)) { switch (name == null ? "" : name) {
case "Worksheet":
//read xls //read xls
@SuppressWarnings({"unused", "resource"}) handleWorkbook(data, name, oleIdx);
HSSFWorkbook wb = new HSSFWorkbook(data.getInputStream()); break;
case "Document":
} else if ("Document".equals(name)) {
try (HWPFDocument doc = new HWPFDocument(data.getInputStream())) {
//read the word document //read the word document
Range r = doc.getRange(); handleDocument(data, name, oleIdx);
for (int k = 0; k < r.numParagraphs(); k++) { break;
Paragraph p = r.getParagraph(k); default:
System.out.println(p.text()); handleUnknown(data, ole.getProgId(), oleIdx);
} break;
//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);
}
}
} }
} }
@ -108,16 +89,60 @@ public final class DataExtraction {
picIdx++; picIdx++;
HSLFPictureShape p = (HSLFPictureShape) shape; HSLFPictureShape p = (HSLFPictureShape) shape;
HSLFPictureData data = p.getPictureData(); HSLFPictureData data = p.getPictureData();
String ext = data.getType().extension; handlePicture(data, picIdx);
try (FileOutputStream out = new FileOutputStream("pict-" + picIdx + ext)) {
out.write(data.getData());
}
} }
} }
} }
} }
} }
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(){ private static void usage(){
System.out.println("Usage: DataExtraction ppt"); System.out.println("Usage: DataExtraction ppt");
} }

View File

@ -23,23 +23,24 @@ import java.awt.Graphics2D;
import java.awt.Rectangle; import java.awt.Rectangle;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import org.apache.poi.hslf.model.PPGraphics2D;
import org.apache.poi.hslf.usermodel.HSLFGroupShape; import org.apache.poi.hslf.usermodel.HSLFGroupShape;
import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow; 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. * Demonstrates how to draw into a slide using the HSLF Graphics2D driver.
*
* @author Yegor Kozlov
*/ */
public final class Graphics2DDemo { public final class Graphics2DDemo {
private Graphics2DDemo() {}
/** /**
* A simple bar chart demo * A simple bar chart demo
*/ */
public static void main(String[] args) throws Exception { 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 //bar chart data. The first value is the bar color, the second is the width
Object[] def = new Object[]{ Object[] def = new Object[]{
Color.yellow, 40, Color.yellow, 40,
@ -56,14 +57,14 @@ public final class Graphics2DDemo {
group.setAnchor(bounds); group.setAnchor(bounds);
group.setInteriorAnchor(new Rectangle(0, 0, 100, 100)); group.setInteriorAnchor(new Rectangle(0, 0, 100, 100));
slide.addShape(group); slide.addShape(group);
Graphics2D graphics = new PPGraphics2D(group); Graphics2D graphics = new SLGraphics(group);
//draw a simple bar graph //draw a simple bar graph
int x = 10, y = 10; int x = 10, y = 10;
graphics.setFont(new Font("Arial", Font.BOLD, 10)); graphics.setFont(new Font("Arial", Font.BOLD, 10));
for (int i = 0, idx = 1; i < def.length; i += 2, idx++) { for (int i = 0, idx = 1; i < def.length; i += 2, idx++) {
graphics.setColor(Color.black); 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("Q" + idx, x - 5, y + 10);
graphics.drawString(width + "%", x + width + 3, y + 10); graphics.drawString(width + "%", x + width + 3, y + 10);
graphics.setColor((Color) def[i]); graphics.setColor((Color) def[i]);
@ -75,9 +76,7 @@ public final class Graphics2DDemo {
graphics.draw(group.getInteriorAnchor()); graphics.draw(group.getInteriorAnchor());
graphics.drawString("Performance", x + 30, y + 10); graphics.drawString("Performance", x + 30, y + 10);
try (FileOutputStream out = new FileOutputStream("hslf-graphics.ppt")) { ppt.write(out);
ppt.write(out);
}
} }
} }
} }

View File

@ -25,7 +25,9 @@ import org.apache.poi.hslf.usermodel.HSLFSlideShow;
/** /**
* Demonstrates how to set headers / footers * Demonstrates how to set headers / footers
*/ */
public abstract class HeadersFootersDemo { public final class HeadersFootersDemo {
private HeadersFootersDemo() {}
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
try (HSLFSlideShow ppt = new HSLFSlideShow()) { try (HSLFSlideShow ppt = new HSLFSlideShow()) {
HeadersFooters slideHeaders = ppt.getSlideHeadersFooters(); HeadersFooters slideHeaders = ppt.getSlideHeadersFooters();

View File

@ -22,7 +22,6 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import org.apache.poi.hslf.usermodel.HSLFHyperlink; 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.HSLFSimpleShape;
import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow; 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 * Demonstrates how to read hyperlinks from a presentation
*/ */
@SuppressWarnings({"java:S106", "java:S4823"})
public final class Hyperlinks { public final class Hyperlinks {
private Hyperlinks() {}
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
for (String arg : args) { for (String arg : args) {
try (FileInputStream is = new FileInputStream(arg); try (FileInputStream is = new FileInputStream(arg);
HSLFSlideShow ppt = new HSLFSlideShow(is)) { HSLFSlideShow ppt = new HSLFSlideShow(is)) {
for (HSLFSlide slide : ppt.getSlides()) { for (HSLFSlide slide : ppt.getSlides()) {
System.out.println("\nslide " + slide.getSlideNumber()); System.out.println("\nslide " + slide.getSlideNumber());
// read hyperlinks from the slide's text runs // read hyperlinks from the slide's text runs
System.out.println("- reading hyperlinks from the text runs"); System.out.println("- reading hyperlinks from the text runs");
for (List<HSLFTextParagraph> paras : slide.getTextParagraphs()) { slide.getTextParagraphs().stream().
for (HSLFTextParagraph para : paras) { flatMap(List::stream).
for (HSLFTextRun run : para) { map(HSLFTextParagraph::getTextRuns).
HSLFHyperlink link = run.getHyperlink(); flatMap(List::stream).
if (link != null) { forEach(run -> out(run.getHyperlink(), run));
System.out.println(toStr(link, run.getRawText()));
}
}
}
}
// in PowerPoint you can assign a hyperlink to a shape without text, // in PowerPoint you can assign a hyperlink to a shape without text,
// for example to a Line object. The code below demonstrates how to // for example to a Line object. The code below demonstrates how to
// read such hyperlinks // read such hyperlinks
System.out.println("- reading hyperlinks from the slide's shapes"); System.out.println("- reading hyperlinks from the slide's shapes");
for (HSLFShape sh : slide.getShapes()) { slide.getShapes().stream().
if (sh instanceof HSLFSimpleShape) { filter(sh -> sh instanceof HSLFSimpleShape).
HSLFHyperlink link = ((HSLFSimpleShape) sh).getHyperlink(); forEach(sh -> out(((HSLFSimpleShape) sh).getHyperlink(), null));
if (link != null) {
System.out.println(toStr(link, 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 //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"); 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);
} }
} }

View File

@ -28,7 +28,10 @@ import org.apache.poi.hslf.usermodel.HSLFSoundData;
/** /**
* For each slide iterate over shapes and found associated sound data. * 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 { public static void main(String[] args) throws IOException {
try (FileInputStream fis = new FileInputStream(args[0])) { try (FileInputStream fis = new FileInputStream(args[0])) {
try (HSLFSlideShow ppt = new HSLFSlideShow(fis)) { try (HSLFSlideShow ppt = new HSLFSlideShow(fis)) {
@ -54,7 +57,7 @@ public class SoundFinder {
* @return 0-based reference to a sound in the sound collection * @return 0-based reference to a sound in the sound collection
* or -1 if the shape is not associated with a sound * 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; int soundRef = -1;
//dive into the shape container and search for InteractiveInfoAtom //dive into the shape container and search for InteractiveInfoAtom
InteractiveInfoAtom info = shape.getClientDataRecord(RecordTypes.InteractiveInfo.typeID); InteractiveInfoAtom info = shape.getClientDataRecord(RecordTypes.InteractiveInfo.typeID);

View File

@ -19,15 +19,13 @@
package org.apache.poi.xssf.eventusermodel.examples; package org.apache.poi.xssf.eventusermodel.examples;
import java.io.FileInputStream;
import java.io.InputStream; 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.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource; import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource;
import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFReader.SheetIterator; 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. * An example that loads a password protected workbook and counts the sheets.
@ -37,23 +35,16 @@ import org.apache.poi.xssf.eventusermodel.XSSFReader.SheetIterator;
* <li><code>AesZipFileZipEntrySource</code> is used to ensure that temp files are encrypted. * <li><code>AesZipFileZipEntrySource</code> is used to ensure that temp files are encrypted.
* </ul><p> * </ul><p>
*/ */
public class LoadPasswordProtectedXlsxStreaming { public final class LoadPasswordProtectedXlsxStreaming {
public static void main(String[] args) throws Exception { private LoadPasswordProtectedXlsxStreaming() {
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();
} }
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); try (AesZipFileZipEntrySource source = AesZipFileZipEntrySource.createZipEntrySource(inputStream);
OPCPackage pkg = OPCPackage.open(source)) { OPCPackage pkg = OPCPackage.open(source)) {
XSSFReader reader = new XSSFReader(pkg); XSSFReader reader = new XSSFReader(pkg);

View File

@ -22,10 +22,12 @@ package org.apache.poi.xssf.usermodel.examples;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream; import java.io.InputStream;
import org.apache.poi.crypt.examples.EncryptionUtils;
import org.apache.poi.examples.util.TempFileUtils; import org.apache.poi.examples.util.TempFileUtils;
import org.apache.poi.openxml4j.opc.OPCPackage; 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.crypt.temp.AesZipFileZipEntrySource;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/** /**
@ -35,9 +37,17 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
* <li><code>AesZipFileZipEntrySource</code> is used to ensure that temp files are encrypted. * <li><code>AesZipFileZipEntrySource</code> is used to ensure that temp files are encrypted.
* </ul><p> * </ul><p>
*/ */
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 { 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) { if(args.length != 2) {
throw new IllegalArgumentException("Expected 2 params: filename and password"); throw new IllegalArgumentException("Expected 2 params: filename and password");
} }
@ -45,13 +55,21 @@ public class LoadPasswordProtectedXlsx {
String filename = args[0]; String filename = args[0];
String password = args[1]; String password = args[1];
try (FileInputStream fis = new FileInputStream(filename); try (FileInputStream fis = new FileInputStream(filename);
InputStream unencryptedStream = EncryptionUtils.decrypt(fis, password)) { POIFSFileSystem fs = new POIFSFileSystem(fis)) {
printSheetCount(unencryptedStream); 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(); 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); try (AesZipFileZipEntrySource source = AesZipFileZipEntrySource.createZipEntrySource(inputStream);
OPCPackage pkg = OPCPackage.open(source); OPCPackage pkg = OPCPackage.open(source);
XSSFWorkbook workbook = new XSSFWorkbook(pkg)) { XSSFWorkbook workbook = new XSSFWorkbook(pkg)) {

View File

@ -18,8 +18,8 @@ package org.apache.poi.hpsf;
import org.apache.poi.util.IOUtils; import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Internal; import org.apache.poi.util.Internal;
import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.LittleEndianByteArrayInputStream; import org.apache.poi.util.LittleEndianByteArrayInputStream;
import org.apache.poi.util.LittleEndianByteArrayOutputStream;
import org.apache.poi.util.LittleEndianConsts; import org.apache.poi.util.LittleEndianConsts;
import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger; import org.apache.poi.util.POILogger;
@ -39,7 +39,7 @@ public class ClipboardData {
int size = lei.readInt(); int size = lei.readInt();
if ( size < 4 ) { if ( size < 4 ) {
String msg = String msg =
"ClipboardData at offset "+offset+" size less than 4 bytes "+ "ClipboardData at offset "+offset+" size less than 4 bytes "+
"(doesn't even have format field!). Setting to format == 0 and hope for the best"; "(doesn't even have format field!). Setting to format == 0 and hope for the best";
LOG.log( POILogger.WARN, msg); LOG.log( POILogger.WARN, msg);
@ -59,15 +59,10 @@ public class ClipboardData {
public byte[] toByteArray() { public byte[] toByteArray() {
byte[] result = new byte[LittleEndianConsts.INT_SIZE*2+_value.length]; byte[] result = new byte[LittleEndianConsts.INT_SIZE*2+_value.length];
LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(result,0); LittleEndian.putInt(result, 0, LittleEndianConsts.INT_SIZE + _value.length);
try { LittleEndian.putInt(result, 4, _format);
bos.writeInt(LittleEndianConsts.INT_SIZE + _value.length); System.arraycopy(_value, 0, result, 8, _value.length);
bos.writeInt(_format); return result;
bos.write(_value);
return result;
} finally {
IOUtils.closeQuietly(bos);
}
} }
public void setValue( byte[] value ) { public void setValue( byte[] value ) {

View File

@ -23,7 +23,7 @@ import java.io.InputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import org.apache.poi.poifs.filesystem.DirectoryEntry; 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.poifs.filesystem.DocumentInputStream;
import org.apache.poi.util.LittleEndianInputStream; import org.apache.poi.util.LittleEndianInputStream;
@ -36,7 +36,7 @@ public class PropertySetFactory {
* Creates the most specific {@link PropertySet} from an entry * Creates the most specific {@link PropertySet} from an entry
* in the specified POIFS Directory. This is preferrably a {@link * in the specified POIFS Directory. This is preferrably a {@link
* DocumentSummaryInformation} or a {@link SummaryInformation}. If * 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, * exception is thrown. If no entry is found with the given name,
* an exception is thrown. * an exception is thrown.
* *
@ -52,19 +52,10 @@ public class PropertySetFactory {
*/ */
public static PropertySet create(final DirectoryEntry dir, final String name) public static PropertySet create(final DirectoryEntry dir, final String name)
throws FileNotFoundException, NoPropertySetStreamException, IOException, UnsupportedEncodingException { throws FileNotFoundException, NoPropertySetStreamException, IOException, UnsupportedEncodingException {
InputStream inp = null; try (DocumentInputStream inp = ((DirectoryNode)dir).createDocumentInputStream(name)) {
try { return create(inp);
DocumentEntry entry = (DocumentEntry)dir.getEntry(name); } catch (MarkUnsupportedException e) {
inp = new DocumentInputStream(entry); return null;
try {
return create(inp);
} catch (MarkUnsupportedException e) {
return null;
}
} finally {
if (inp != null) {
inp.close();
}
} }
} }
@ -96,18 +87,18 @@ public class PropertySetFactory {
byte[] clsIdBuf = new byte[ClassID.LENGTH]; byte[] clsIdBuf = new byte[ClassID.LENGTH];
leis.readFully(clsIdBuf); leis.readFully(clsIdBuf);
int sectionCount = (int)leis.readUInt(); int sectionCount = (int)leis.readUInt();
if (byteOrder != PropertySet.BYTE_ORDER_ASSERTION || if (byteOrder != PropertySet.BYTE_ORDER_ASSERTION ||
format != PropertySet.FORMAT_ASSERTION || format != PropertySet.FORMAT_ASSERTION ||
sectionCount < 0) { sectionCount < 0) {
throw new NoPropertySetStreamException(); throw new NoPropertySetStreamException();
} }
if (sectionCount > 0) { if (sectionCount > 0) {
leis.readFully(clsIdBuf); leis.readFully(clsIdBuf);
} }
stream.reset(); stream.reset();
ClassID clsId = new ClassID(clsIdBuf, 0); ClassID clsId = new ClassID(clsIdBuf, 0);
if (sectionCount > 0 && PropertySet.matchesSummary(clsId, SummaryInformation.FORMAT_ID)) { if (sectionCount > 0 && PropertySet.matchesSummary(clsId, SummaryInformation.FORMAT_ID)) {
return new SummaryInformation(stream); return new SummaryInformation(stream);

View File

@ -19,6 +19,7 @@ package org.apache.poi.hssf.dev;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -393,21 +394,10 @@ public final class BiffViewer {
// args = new String[] { "--out", "", }; // args = new String[] { "--out", "", };
CommandArgs cmdArgs = CommandArgs.parse(args); CommandArgs cmdArgs = CommandArgs.parse(args);
PrintWriter pw; try (POIFSFileSystem fs = new POIFSFileSystem(cmdArgs.getFile(), true);
if (cmdArgs.shouldOutputToFile()) { InputStream is = getPOIFSInputStream(fs);
OutputStream os = new FileOutputStream(cmdArgs.getFile().getAbsolutePath() + ".out"); PrintWriter pw = getOutputStream(cmdArgs.shouldOutputToFile() ? cmdArgs.getFile().getAbsolutePath() : null)
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);
if (cmdArgs.shouldOutputRawHexOnly()) { if (cmdArgs.shouldOutputRawHexOnly()) {
byte[] data = IOUtils.toByteArray(is); byte[] data = IOUtils.toByteArray(is);
HexDump.dump(data, 0, System.out, 0); HexDump.dump(data, 0, System.out, 0);
@ -417,13 +407,21 @@ public final class BiffViewer {
runBiffViewer(pw, is, dumpInterpretedRecords, dumpHex, dumpInterpretedRecords, runBiffViewer(pw, is, dumpInterpretedRecords, dumpHex, dumpInterpretedRecords,
cmdArgs.suppressHeader()); 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 { static InputStream getPOIFSInputStream(POIFSFileSystem fs) throws IOException {
String workbookName = HSSFWorkbook.getWorkbookDirEntryName(fs.getRoot()); String workbookName = HSSFWorkbook.getWorkbookDirEntryName(fs.getRoot());
return fs.createDocumentInputStream(workbookName); return fs.createDocumentInputStream(workbookName);

View File

@ -15,175 +15,98 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.poifs.filesystem; package org.apache.poi.poifs.filesystem;
import java.io.File; 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.POILogFactory;
import org.apache.poi.util.POILogger; import org.apache.poi.util.POILogger;
/** /**
* Class POIFSDocumentPath * 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 static final POILogger log = POILogFactory.getLogger(POIFSDocumentPath.class);
private final String[] components; private final String[] components;
private int hashcode; //lazy-compute hashCode private int hashcode; //lazy-compute hashCode
/** /**
* constructor for the path of a document that is not in the root * simple constructor for the path of a document that is in the root of the POIFSFileSystem.
* of the POIFSFileSystem * The constructor that takes an array of Strings can also be used to create such a
*
* @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.
* <p>
* 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
* POIFSDocumentPath by passing it a null or empty String array * POIFSDocumentPath by passing it a null or empty String array
*/ */
public POIFSDocumentPath() {
public POIFSDocumentPath() components = new String[0];
{
this.components = new String[ 0 ];
} }
/** /**
* constructor that adds additional subdirectories to an existing * constructor for the path of a document that is not in the root of the POIFSFileSystem
* path *
* @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. <p> 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 path the existing path
* @param components the additional subdirectory names to be added * @param components the additional subdirectory names to be added
* *
* @exception IllegalArgumentException if any of the Strings in * @exception IllegalArgumentException
* components is null or zero * if any of the Strings in components is null or zero length
* 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, // TODO: Although the Javadoc says empty strings are forbidden, the adapted legacy
final String [] components) // implementation allowed it in case a path was specified...
throws IllegalArgumentException Predicate<String> p = (path != null) ? Objects::isNull : (s) -> (s == null || s.isEmpty());
{ if (Stream.of(s2).anyMatch(p)) {
if (components == null) throw new IllegalArgumentException("components cannot contain null or empty strings");
{
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 ];
}
} }
this.components = Stream.concat(Stream.of(s1),Stream.of(s2)).toArray(String[]::new);
} }
/** /**
* equality. Two POIFSDocumentPath instances are equal if they * Two POIFSDocumentPath instances are equal if they have the same number of component Strings,
* have the same number of component Strings, and if each * and if each component String is equal to its corresponding component String
* component String is equal to its coresponding component String
* *
* @param o the object we're checking equality for * @param o the object we're checking equality for
* *
* @return true if the object is equal to this object * @return true if the object is equal to this object
*/ */
public boolean equals(final Object o) public boolean equals(final Object o) {
{ if (this == o) {
boolean rval = false; return true;
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;
}
}
}
}
} }
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 * @return hashcode
*/ */
public int hashCode() public int hashCode() {
{ return (hashcode == 0) ? (hashcode = Arrays.hashCode(components)) : 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;
} }
/** /**
* @return the number of components * @return the number of components
*/ */
public int length() {
public int length()
{
return components.length; return components.length;
} }
@ -228,10 +135,7 @@ public class POIFSDocumentPath
* *
* @exception ArrayIndexOutOfBoundsException if n &lt; 0 or n >= length() * @exception ArrayIndexOutOfBoundsException if n &lt; 0 or n >= length()
*/ */
public String getComponent(int n) throws ArrayIndexOutOfBoundsException {
public String getComponent(int n)
throws ArrayIndexOutOfBoundsException
{
return components[ n ]; return components[ n ];
} }
@ -242,21 +146,10 @@ public class POIFSDocumentPath
* @since 2002-01-24 * @since 2002-01-24
* @return path of parent, or null if this path is the root path * @return path of parent, or null if this path is the root path
*/ */
public POIFSDocumentPath getParent() {
public POIFSDocumentPath getParent() return (components.length == 0) ? null : new POIFSDocumentPath(Arrays.copyOf(components, components.length - 1));
{
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);
} }
/** /**
* <p>Returns the last name in the document path's name sequence. * <p>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.</p> * If the document path's name sequence is empty, then the empty string is returned.</p>
@ -264,13 +157,8 @@ public class POIFSDocumentPath
* @since 2016-04-09 * @since 2016-04-09
* @return The last name in the document path's name sequence, or empty string if this is the root path * @return The last name in the document path's name sequence, or empty string if this is the root path
*/ */
public String getName() {
public String getName() return components.length == 0 ? "" : components[components.length - 1];
{
if (components.length == 0) {
return "";
}
return components[components.length - 1];
} }
/** /**
@ -281,22 +169,8 @@ public class POIFSDocumentPath
* *
* @since 2002-01-24 * @since 2002-01-24
*/ */
public String toString() {
public String toString() return File.separatorChar + String.join(String.valueOf(File.separatorChar), components);
{
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();
} }
} // end public class POIFSDocumentPath }

View File

@ -17,13 +17,9 @@
package org.apache.poi.util; package org.apache.poi.util;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -31,7 +27,7 @@ import java.nio.charset.StandardCharsets;
* dump data in hexadecimal format * dump data in hexadecimal format
*/ */
@Internal @Internal
public class HexDump { public final class HexDump {
public static final String EOL = System.getProperty("line.separator"); public static final String EOL = System.getProperty("line.separator");
public static final Charset UTF8 = StandardCharsets.UTF_8; 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) { public static String dump(final byte [] data, final long offset, final int index) {
return dump(data, offset, index, Integer.MAX_VALUE); return dump(data, offset, index, Integer.MAX_VALUE);
} }
/** /**
* dump an array of bytes to a String * 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) int data_length = (length == Integer.MAX_VALUE || length < 0 || index+length < 0)
? data.length ? data.length
: Math.min(data.length,index+length); : Math.min(data.length,index+length);
if ((index < 0) || (index >= data.length)) { if ((index < 0) || (index >= data.length)) {
String err = "illegal index: "+index+" into array of length "+data.length; String err = "illegal index: "+index+" into array of length "+data.length;
throw new ArrayIndexOutOfBoundsException(err); throw new ArrayIndexOutOfBoundsException(err);
} }
long display_offset = offset + index; long display_offset = offset + index;
StringBuilder buffer = new StringBuilder(74); StringBuilder buffer = new StringBuilder(74);
for (int j = index; j < data_length; j += 16) { for (int j = index; j < data_length; j += 16) {
int chars_read = data_length - j; int chars_read = data_length - j;
if (chars_read > 16) { if (chars_read > 16) {
chars_read = 16; chars_read = 16;
} }
writeHex(buffer, display_offset, 8, ""); writeHex(buffer, display_offset, 8, "");
for (int k = 0; k < 16; k++) { for (int k = 0; k < 16; k++) {
if (k < chars_read) { if (k < chars_read) {
@ -168,7 +164,7 @@ public class HexDump {
if (Character.isISOControl(charB)) { if (Character.isISOControl(charB)) {
return '.'; return '.';
} }
switch (charB) { switch (charB) {
// printable, but not compilable with current compiler encoding // printable, but not compilable with current compiler encoding
case 0xFF: case 0xFF:
@ -180,7 +176,7 @@ public class HexDump {
} }
return charB; return charB;
} }
/** /**
* Converts the parameter to a hex value. * Converts the parameter to a hex value.
* *
@ -205,58 +201,6 @@ public class HexDump {
return retVal.toString(); 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();
}
/**
* <p>Converts the parameter to a hex value breaking the results into
* lines.</p>
*
* @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. * Converts the parameter to a hex value.
* *
@ -305,57 +249,6 @@ public class HexDump {
return sb.toString(); 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 <code>bytesToDump</code> 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' * @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"); writeHex(sb, value, 16, "0x");
return sb.toString(); return sb.toString();
} }
/** /**
* @return string of 8 (zero padded) uppercase hex chars and prefixed with '0x' * @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"); writeHex(sb, value & 0xFFFFFFFFL, 8, "0x");
return sb.toString(); return sb.toString();
} }
/** /**
* @return string of 4 (zero padded) uppercase hex chars and prefixed with '0x' * @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"); writeHex(sb, value & 0xFFFFL, 4, "0x");
return sb.toString(); return sb.toString();
} }
/** /**
* @return string of 2 (zero padded) uppercase hex chars and prefixed with '0x' * @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"); writeHex(sb, value & 0xFFL, 2, "0x");
return sb.toString(); return sb.toString();
} }
/** /**
* @see Integer#toHexString(int) * @see Integer#toHexString(int)
* @see Long#toHexString(long) * @see Long#toHexString(long)
@ -406,13 +299,5 @@ public class HexDump {
acc >>>= 4; acc >>>= 4;
} }
sb.append(buf); 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));
} }
} }

View File

@ -55,7 +55,6 @@ import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFTestHelper; import org.apache.poi.hssf.usermodel.HSSFTestHelper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.util.HexDump;
import org.junit.Test; import org.junit.Test;
public class TestDrawingAggregate { public class TestDrawingAggregate {
@ -231,7 +230,7 @@ public class TestDrawingAggregate {
for(EscherRecord r : records) { for(EscherRecord r : records) {
out.write(r.serialize()); out.write(r.serialize());
} }
assertEquals(HexDump.toHex(dgBytes, 10), HexDump.toHex(out.toByteArray(), 10)); assertArrayEquals(dgBytes, out.toByteArray());
} }
/** /**

View File

@ -22,7 +22,11 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; 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.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
@ -35,12 +39,7 @@ public class TestHexDump {
@BeforeClass @BeforeClass
public static void setUp() throws UnsupportedEncodingException { public static void setUp() throws UnsupportedEncodingException {
SYSTEM_OUT = System.out; SYSTEM_OUT = System.out;
System.setOut(new PrintStream(new OutputStream() { System.setOut(new PrintStream(new OutputStream() {public void write(int b) {}}, false, "UTF-8"));
@Override
public void write(int b) throws IOException {
}
}, false, "UTF-8"));
} }
@AfterClass @AfterClass
@ -153,10 +152,6 @@ public class TestHexDump {
public void testToHex() { public void testToHex() {
assertEquals("000A", HexDump.toHex((short)0xA)); 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("0A", HexDump.toHex((byte)0xA));
assertEquals("0000000A", HexDump.toHex(0xA)); assertEquals("0000000A", HexDump.toHex(0xA));
@ -164,12 +159,6 @@ public class TestHexDump {
assertEquals("[0A]", HexDump.toHex(new byte[] { 0xA })); assertEquals("[0A]", HexDump.toHex(new byte[] { 0xA }));
assertEquals("[0A, 0B]", HexDump.toHex(new byte[] { 0xA, 0xB })); 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("FFFF", HexDump.toHex((short)0xFFFF));
assertEquals("00000000000004D2", HexDump.toHex(1234L)); assertEquals("00000000000004D2", HexDump.toHex(1234L));
@ -185,7 +174,7 @@ public class TestHexDump {
} }
@Test @Test
public void testDumpToString() throws Exception { public void testDumpToString() {
byte[] testArray = testArray(); byte[] testArray = testArray();
String dump = HexDump.dump(testArray, 0, 0); String dump = HexDump.dump(testArray, 0, 0);
//System.out.println("Hex: \n" + dump); //System.out.println("Hex: \n" + dump);
@ -199,93 +188,37 @@ public class TestHexDump {
} }
@Test(expected=ArrayIndexOutOfBoundsException.class) @Test(expected=ArrayIndexOutOfBoundsException.class)
public void testDumpToStringOutOfIndex1() throws Exception { public void testDumpToStringOutOfIndex1() {
HexDump.dump(new byte[1], 0, -1); HexDump.dump(new byte[1], 0, -1);
} }
@Test(expected=ArrayIndexOutOfBoundsException.class) @Test(expected=ArrayIndexOutOfBoundsException.class)
public void testDumpToStringOutOfIndex2() throws Exception { public void testDumpToStringOutOfIndex2() {
HexDump.dump(new byte[1], 0, 2); HexDump.dump(new byte[1], 0, 2);
} }
@Test(expected=ArrayIndexOutOfBoundsException.class) @Test(expected=ArrayIndexOutOfBoundsException.class)
public void testDumpToStringOutOfIndex3() throws Exception { public void testDumpToStringOutOfIndex3() {
HexDump.dump(new byte[1], 0, 1); HexDump.dump(new byte[1], 0, 1);
} }
@Test @Test
public void testDumpToStringNoDataEOL1() throws Exception { public void testDumpToStringNoDataEOL1() {
HexDump.dump(new byte[0], 0, 1); HexDump.dump(new byte[0], 0, 1);
} }
@Test @Test
public void testDumpToStringNoDataEOL2() throws Exception { public void testDumpToStringNoDataEOL2() {
HexDump.dump(new byte[0], 0, 0); 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() { private static byte[] testArray() {
byte[] testArray = new byte[ 256 ]; byte[] testArray = new byte[ 256 ];
for (int j = 0; j < 256; j++) { for (int j = 0; j < 256; j++) {
testArray[ j ] = ( byte ) j; testArray[ j ] = ( byte ) j;
} }
return testArray; return testArray;
} }
} }