+++ /dev/null
-/*
- * ====================================================================
- * 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);
- }
- }
-}
package org.apache.poi.crypt.examples;
-import java.io.BufferedReader;
-import java.io.Closeable;
import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.security.GeneralSecurityException;
+import java.util.Optional;
+import java.util.function.Predicate;
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo;
/**
* Tries a list of possible passwords for an OOXML protected file
- *
+ *
* Note that this isn't very fast, and is aimed at when you have
* just a few passwords to check.
* For serious processing, you'd be best off grabbing the hash
* out with POI or office2john.py, then running that against
* "John The Ripper" or GPU enabled version of "hashcat"
*/
-public class OOXMLPasswordsTry implements Closeable {
- private POIFSFileSystem fs;
- private EncryptionInfo info;
- private Decryptor d;
-
- private OOXMLPasswordsTry(POIFSFileSystem fs) throws IOException {
- info = new EncryptionInfo(fs);
- d = Decryptor.getInstance(info);
- this.fs = fs;
- }
- private OOXMLPasswordsTry(File file) throws IOException {
- this(new POIFSFileSystem(file, true));
- }
- private OOXMLPasswordsTry(InputStream is) throws IOException {
- this(new POIFSFileSystem(is));
- }
-
- public void close() throws IOException {
- fs.close();
- }
-
- public String tryAll(File wordfile) throws IOException, GeneralSecurityException {
- String valid = null;
- // Load
- try (BufferedReader r = new BufferedReader(new FileReader(wordfile))) {
- long start = System.currentTimeMillis();
- int count = 0;
-
- // Try each password in turn, reporting progress
- String password;
- while ((password = r.readLine()) != null) {
- if (isValid(password)) {
- valid = password;
- break;
- }
- count++;
+public final class OOXMLPasswordsTry {
- if (count % 1000 == 0) {
- int secs = (int) ((System.currentTimeMillis() - start) / 1000);
- System.out.println("Done " + count + " passwords, " +
- secs + " seconds, last password " + password);
- }
- }
+ private OOXMLPasswordsTry() {}
- }
- // Tidy and return (null if no match)
- return valid;
- }
- public boolean isValid(String password) throws GeneralSecurityException {
- return d.verifyPassword(password);
- }
-
+ @SuppressWarnings({"java:S106","java:S4823"})
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("Use:");
System.err.println(" OOXMLPasswordsTry <file.ooxml> <wordlist>");
System.exit(1);
}
- File ooxml = new File(args[0]);
- File words = new File(args[1]);
-
+ String ooxml = args[0], words = args[1];
+
System.out.println("Trying passwords from " + words + " against " + ooxml);
System.out.println();
- String password;
- try (OOXMLPasswordsTry pt = new OOXMLPasswordsTry(ooxml)) {
- password = pt.tryAll(words);
+ try (POIFSFileSystem fs = new POIFSFileSystem(new File(ooxml), true)) {
+ EncryptionInfo info = new EncryptionInfo(fs);
+ Decryptor d = Decryptor.getInstance(info);
+
+ final long start = System.currentTimeMillis();
+ final int[] count = { 0 };
+ Predicate<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) {
- System.out.println("Error - No password matched");
- } else {
- System.out.println("Password found!");
- System.out.println(password);
+ }
+
+ private static boolean isValid(Decryptor dec, String password) {
+ try {
+ return dec.verifyPassword(password);
+ } catch (GeneralSecurityException e) {
+ return false;
}
}
}
package org.apache.poi.examples.util;
import java.io.File;
-import java.io.IOException;
import org.apache.poi.util.TempFile;
-public class TempFileUtils {
+public final class TempFileUtils {
private TempFileUtils() {
}
-
- public static void checkTempFiles() throws IOException {
+
+ @SuppressWarnings("java:S106")
+ public static void checkTempFiles() {
String tmpDir = System.getProperty(TempFile.JAVA_IO_TMPDIR) + "/poifiles";
File tempDir = new File(tmpDir);
if(tempDir.exists()) {
package org.apache.poi.hpsf.examples;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
-import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import org.apache.poi.poifs.filesystem.EntryUtils;
import org.apache.poi.poifs.filesystem.POIFSDocumentPath;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
+import org.apache.poi.util.IOUtils;
import org.apache.poi.util.TempFile;
/**
* with the same attributes, and the sections must contain the same properties.
* Details like the ordering of the properties do not matter.</p>
*/
+@SuppressWarnings({"java:S106","java:S4823"})
public final class CopyCompare {
private CopyCompare() {}
* @throws UnsupportedEncodingException if a character encoding is not
* supported.
*/
- public static void main(final String[] args)
- throws UnsupportedEncodingException, IOException {
+ public static void main(final String[] args) throws IOException {
String originalFileName = null;
String copyFileName = null;
* PropertySet#PropertySet(PropertySet)} constructor.</p>
*/
static class CopyFile implements POIFSReaderListener {
- private String dstName;
- private OutputStream out;
- private POIFSFileSystem poiFs;
+ private final String dstName;
+ private final POIFSFileSystem poiFs;
/**
* "event" object. */
final POIFSDocumentPath path = event.getPath();
final String name = event.getName();
- final DocumentInputStream stream = event.getStream();
Throwable t = null;
- try {
+ try (final DocumentInputStream stream = event.getStream()) {
/* Find out whether the current document is a property set
* stream or not. */
if (stream != null && PropertySet.isPropertySetStream(stream)) {
/* Yes, the current document is a property set stream.
* Let's create a PropertySet instance from it. */
- PropertySet ps = null;
- try {
- ps = PropertySetFactory.create(stream);
- } catch (NoPropertySetStreamException ex) {
- /* This exception will not be thrown because we already
- * checked above. */
- }
+ PropertySet ps = PropertySetFactory.create(stream);
/* Copy the property set to the destination POI file
* system. */
* copy it unmodified to the destination POIFS. */
copy(poiFs, path, name, stream);
}
- } catch (MarkUnsupportedException | WritingNotSupportedException | IOException ex) {
+ } catch (MarkUnsupportedException | WritingNotSupportedException | IOException | NoPropertySetStreamException ex) {
t = ex;
}
// create the directories to the document
final DirectoryEntry de = getPath(poiFs, path);
// check the parameters after the directories have been created
- if (stream == null || name == null) {
- // Empty directory
- return;
- }
- final ByteArrayOutputStream out = new ByteArrayOutputStream();
- int c;
- while ((c = stream.read()) != -1) {
- out.write(c);
+ if (stream != null && name != null) {
+ byte[] data = IOUtils.toByteArray(stream);
+ de.createDocument(name, new ByteArrayInputStream(data));
}
- 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();
+ try (OutputStream fos = new FileOutputStream(dstName)) {
+ poiFs.writeFilesystem(fos);
+ }
}
/* Check whether this directory has already been created. */
final String s = path.toString();
DirectoryEntry de = paths.get(s);
- if (de != null)
+ if (de != null) {
/* Yes: return the corresponding DirectoryEntry. */
return de;
+ }
/* No: We have to create the directory - or return the root's
* DirectoryEntry. */
* ensure that the parent directory exists: */
de = getPath(poiFs, path.getParent());
/* Now create the target directory: */
- de = de.createDirectory(path.getComponent
- (path.length() - 1));
+ de = de.createDirectory(path.getComponent(path.length() - 1));
}
paths.put(s, de);
return de;
*
* </ol>
*/
-public class ModifyDocumentSummaryInformation {
+@SuppressWarnings({"java:S106","java:S4823"})
+public final class ModifyDocumentSummaryInformation {
+
+ private ModifyDocumentSummaryInformation() {}
/**
* <p>Main method - see class description.</p>
// There is no summary information yet. We have to create a new one
si = PropertySetFactory.newSummaryInformation();
}
+ assert(si != null);
/* Change the author to "Rainer Klute". Any former author value will
* be lost. If there has been no author yet, it will be created. */
* new one. */
dsi = PropertySetFactory.newDocumentSummaryInformation();
}
+ assert(dsi != null);
/* Change the category to "POI example". Any former category value will
* be lost. If there has been no category yet, it will be created. */
import org.apache.poi.hpsf.Section;
import org.apache.poi.poifs.eventfilesystem.POIFSReader;
import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;
-import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
-import org.apache.poi.util.HexDump;
/**
* <p>Sample application showing how to read a document's custom property set.
*
* <p>Explanations can be found in the HPSF HOW-TO.</p>
*/
+@SuppressWarnings({"java:S106","java:S4823"})
public final class ReadCustomPropertySets {
private ReadCustomPropertySets() {}
* @param args Command-line arguments (unused).
* @throws IOException if any I/O exception occurs.
*/
- public static void main(final String[] args)
- throws IOException
- {
+ public static void main(final String[] args) throws IOException {
final String filename = args[0];
POIFSReader r = new POIFSReader();
/* Register a listener for *all* documents. */
- r.registerListener(new MyPOIFSReaderListener());
+ r.registerListener(ReadCustomPropertySets::processPOIFSReaderEvent);
r.read(new File(filename));
}
- static class MyPOIFSReaderListener implements POIFSReaderListener
- {
- @Override
- public void processPOIFSReaderEvent(final POIFSReaderEvent event)
- {
- PropertySet ps;
- try
- {
- ps = PropertySetFactory.create(event.getStream());
- }
- catch (NoPropertySetStreamException ex)
- {
- out("No property set stream: \"" + event.getPath() +
- event.getName() + "\"");
- return;
- }
- catch (Exception ex)
- {
- throw new RuntimeException
- ("Property set stream \"" +
- event.getPath() + event.getName() + "\": " + ex);
- }
+ public static void processPOIFSReaderEvent(final POIFSReaderEvent event) {
+ final String streamName = event.getPath() + event.getName();
+ PropertySet ps;
+ try {
+ ps = PropertySetFactory.create(event.getStream());
+ } catch (NoPropertySetStreamException ex) {
+ out("No property set stream: \"" + streamName + "\"");
+ return;
+ } catch (Exception ex) {
+ throw new RuntimeException("Property set stream \"" + streamName + "\": " + ex);
+ }
- /* Print the name of the property set stream: */
- out("Property set stream \"" + event.getPath() +
- event.getName() + "\":");
-
- /* Print the number of sections: */
- final long sectionCount = ps.getSectionCount();
- out(" No. of sections: " + sectionCount);
-
- /* Print the list of sections: */
- List<Section> sections = ps.getSections();
- int nr = 0;
- for (Section sec : sections) {
- /* Print a single section: */
- out(" Section " + nr++ + ":");
- String s = hex(sec.getFormatID().getBytes());
- s = s.substring(0, s.length() - 1);
- out(" Format ID: " + s);
-
- /* Print the number of properties in this section. */
- int propertyCount = sec.getPropertyCount();
- out(" No. of properties: " + propertyCount);
-
- /* Print the properties: */
- Property[] properties = sec.getProperties();
- for (Property p : properties) {
- /* Print a single property: */
- long id = p.getID();
- long type = p.getType();
- Object value = p.getValue();
- out(" Property ID: " + id + ", type: " + type +
- ", value: " + value);
- }
+ /* Print the name of the property set stream: */
+ out("Property set stream \"" + streamName + "\":");
+
+ /* Print the number of sections: */
+ final long sectionCount = ps.getSectionCount();
+ out(" No. of sections: " + sectionCount);
+
+ /* Print the list of sections: */
+ List<Section> sections = ps.getSections();
+ int nr = 0;
+ for (Section sec : sections) {
+ /* Print a single section: */
+ out(" Section " + nr++ + ":");
+ String s = sec.getFormatID().toString();
+ s = s.substring(0, s.length() - 1);
+ out(" Format ID: " + s);
+
+ /* Print the number of properties in this section. */
+ int propertyCount = sec.getPropertyCount();
+ out(" No. of properties: " + propertyCount);
+
+ /* Print the properties: */
+ Property[] properties = sec.getProperties();
+ for (Property p : properties) {
+ /* Print a single property: */
+ long id = p.getID();
+ long type = p.getType();
+ Object value = p.getValue();
+ out(" Property ID: " + id + ", type: " + type +
+ ", value: " + value);
}
}
}
- private static void out(final String msg)
- {
+ private static void out(final String msg) {
System.out.println(msg);
}
-
- private static String hex(final byte[] bytes)
- {
- return HexDump.dump(bytes, 0L, 0);
- }
-
}
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.eventfilesystem.POIFSReader;
import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;
-import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
/**
* <p>Sample application showing how to read a OLE 2 document's
*
* <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() {}
/**
* be the name of a POI filesystem to read.
* @throws IOException if any I/O exception occurs.
*/
- public static void main(final String[] args) throws IOException
- {
+ public static void main(final String[] args) throws IOException {
final String filename = args[0];
POIFSReader r = new POIFSReader();
- r.registerListener(new MyPOIFSReaderListener(), SummaryInformation.DEFAULT_STREAM_NAME);
+ r.registerListener(ReadTitle::processPOIFSReaderEvent, SummaryInformation.DEFAULT_STREAM_NAME);
r.read(new File(filename));
}
- static class MyPOIFSReaderListener implements POIFSReaderListener
- {
- @Override
- public void processPOIFSReaderEvent(final POIFSReaderEvent event)
- {
- SummaryInformation si;
- try
- {
- si = (SummaryInformation)
- PropertySetFactory.create(event.getStream());
- }
- catch (Exception ex)
- {
- throw new RuntimeException
- ("Property set stream \"" +
- event.getPath() + event.getName() + "\": " + ex);
- }
- final String title = si.getTitle();
- if (title != null)
- System.out.println("Title: \"" + title + "\"");
- else
- System.out.println("Document has no title.");
+ private static void processPOIFSReaderEvent(final POIFSReaderEvent event) {
+ SummaryInformation si;
+ try {
+ si = (SummaryInformation) PropertySetFactory.create(event.getStream());
+ } catch (Exception ex) {
+ throw new RuntimeException("Property set stream \"" + event.getPath() + event.getName() + "\": " + ex);
}
+ final String title = si.getTitle();
+ System.out.println(title != null ? "Title: \"" + title + "\"" : "Document has no title.");
}
-
}
package org.apache.poi.hpsf.examples;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.util.HashMap;
-import java.util.Map;
import org.apache.poi.hpsf.HPSFRuntimeException;
import org.apache.poi.hpsf.MarkUnsupportedException;
import org.apache.poi.hpsf.wellknown.PropertyIDMap;
import org.apache.poi.poifs.eventfilesystem.POIFSReader;
import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;
-import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.POIFSDocumentPath;
* <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
* different ways:</p>
- *
+ *
* <ul>
- *
+ *
* <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
* set (see classes {@link SummaryInformation} and {@link PropertySet}), write
* the author and title properties into it and write the property set back into
* the POI filesystem.</p></li>
- *
+ *
* <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
* to the destination POIFS, except for the summary information stream. The
* it to the destination POIFS. It there are several summary information streams
* in the original POIFS - e.g. in subordinate directories - they are modified
* just the same.</p></li>
- *
+ *
* </ul>
- *
+ *
* <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 name of the output POIFS as the second command-line argument. The
* encounters a summary information stream it reads its properties. Then it sets
* the "author" and "title" properties to new values and writes the modified
* summary information stream into the output file.</p>
- *
+ *
* <p>Further explanations can be found in the HPSF HOW-TO.</p>
*/
+@SuppressWarnings({"java:S106","java:S4823"})
public final class WriteAuthorAndTitle {
private WriteAuthorAndTitle() {}
* be the name of a POI filesystem to read.
* @throws IOException if any I/O exception occurs.
*/
- public static void main(final String[] args) throws IOException
- {
+ public static void main(final String[] args) throws IOException {
/* Check whether we have exactly two command-line arguments. */
- if (args.length != 2)
- {
- System.err.println("Usage: " + WriteAuthorAndTitle.class.getName() +
- " originPOIFS destinationPOIFS");
+ if (args.length != 2) {
+ System.err.println("Usage: WriteAuthorAndTitle originPOIFS destinationPOIFS");
System.exit(1);
}
-
+
/* Read the names of the origin and destination POI filesystems. */
- final String srcName = args[0];
- final String dstName = args[1];
+ final String srcName = args[0], dstName = args[1];
/* Read the origin POIFS using the eventing API. The real work is done
* in the class ModifySICopyTheRest which is registered here as a
* POIFSReader. */
- final POIFSReader r = new POIFSReader();
- final ModifySICopyTheRest msrl = new ModifySICopyTheRest(dstName);
- r.registerListener(msrl);
- r.read(new File(srcName));
-
- /* Write the new POIFS to disk. */
- msrl.close();
+ try (POIFSFileSystem poifs = new POIFSFileSystem();
+ OutputStream out = new FileOutputStream(dstName)) {
+ final POIFSReader r = new POIFSReader();
+ r.registerListener((e) -> handleEvent(poifs, e));
+ r.read(new File(srcName));
+
+ /* Write the new POIFS to disk. */
+ 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
- * 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>
+ * The method is called by POI's eventing API for each file in the origin POIFS.
*/
- static class ModifySICopyTheRest implements POIFSReaderListener
- {
- private String dstName;
- private OutputStream out;
- private POIFSFileSystem poiFs;
-
-
- /**
- * The constructor of a {@link ModifySICopyTheRest} instance creates
- * the target POIFS. It also stores the name of the file the POIFS will
- * be written to once it is complete.
- *
- * @param dstName The name of the disk file the destination POIFS is to
- * be written to.
- */
- ModifySICopyTheRest(final String dstName)
- {
- this.dstName = dstName;
- poiFs = new POIFSFileSystem();
- }
-
-
- /**
- * The method is called by POI's eventing API for each file in the
- * origin POIFS.
- */
- @Override
- public void processPOIFSReaderEvent(final POIFSReaderEvent event)
- {
- /* The following declarations are shortcuts for accessing the
- * "event" object. */
- final POIFSDocumentPath path = event.getPath();
- final String name = event.getName();
- final DocumentInputStream stream = event.getStream();
-
- Throwable t = null;
-
- try {
- /* Find out whether the current document is a property set
- * stream or not. */
- if (PropertySet.isPropertySetStream(stream)) {
- try {
- /* Yes, the current document is a property set stream.
- * Let's create a PropertySet instance from it. */
- PropertySet ps = PropertySetFactory.create(stream);
-
- /* Now we know that we really have a property set. The next
- * step is to find out whether it is a summary information
- * or not. */
- if (ps.isSummaryInformation()) {
- /* Yes, it is a summary information. We will modify it
- * and write the result to the destination POIFS. */
- editSI(poiFs, path, name, ps);
- } else {
- /* No, it is not a summary information. We don't care
- * about its internals and copy it unmodified to the
- * destination POIFS. */
- copy(poiFs, path, name, ps);
- }
- } catch (NoPropertySetStreamException ex) {
- /* This exception will not be thrown because we already
- * checked above. */
- }
- } else {
- /* No, the current document is not a property set stream. We
- * copy it unmodified to the destination POIFS. */
- copy(poiFs, event.getPath(), event.getName(), stream);
+ private static void handleEvent(final POIFSFileSystem poiFs, final POIFSReaderEvent event) {
+ // The following declarations are shortcuts for accessing the "event" object.
+ final DocumentInputStream stream = event.getStream();
+
+ try {
+ final InputStreamSupplier isSup;
+
+ // Find out whether the current document is a property set stream or not.
+ if (PropertySet.isPropertySetStream(stream)) {
+ // Yes, the current document is a property set stream. Let's create a PropertySet instance from it.
+ PropertySet ps = PropertySetFactory.create(stream);
+
+ // Now we know that we really have a property set.
+ // The next step is to find out whether it is a summary information or not.
+ if (ps.isSummaryInformation()) {
+ // Create a mutable property set as a copy of the original read-only property set.
+ ps = new PropertySet(ps);
+
+ // Retrieve the section containing the properties to modify.
+ // A summary information property set contains exactly one section.
+ final Section s = ps.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");
}
- } catch (MarkUnsupportedException | WritingNotSupportedException | IOException ex) {
- t = ex;
- }
- /* According to the definition of the processPOIFSReaderEvent method
- * we cannot pass checked exceptions to the caller. The following
- * lines check whether a checked exception occurred and throws an
- * unchecked exception. The message of that exception is that of
- * the underlying checked exception. */
- if (t != null) {
- throw new HPSFRuntimeException("Could not read file \"" + path + "/" + name, t);
+ 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;
}
- }
-
-
- /**
- * <p>Receives a summary information property set modifies (or creates)
- * its "author" and "title" properties and writes the result under the
- * same path and name as the origin to a destination POI filesystem.</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<>();
+ try (InputStream is = isSup.get()) {
+ final POIFSDocumentPath path = event.getPath();
+ // Ensures that the directory hierarchy for a document in a POI fileystem is in place.
+ // Get the root directory. It does not have to be created since it always exists in a POIFS.
+ DirectoryEntry de = poiFs.getRoot();
- /**
- * <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));
+ for (int i=0; i<path.length(); i++) {
+ String subDir = path.getComponent(i);
+ de = (de.hasEntry(subDir)) ? (DirectoryEntry)de.getEntry(subDir) : de.createDirectory(subDir);
}
- paths.put(s, de);
- return de;
- }
- 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);
+
+ de.createDocument(event.getName(), is);
}
+
+ } 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);
}
}
-
}
* <p>This class is a simple sample application showing how to create a property
* 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>
*
- * @param args Command-line arguments. The first and only command-line
+ * @param args Command-line arguments. The first and only command-line
* argument is the name of the POI file system to create.
* @throws IOException if any I/O exception occurs.
- * @throws WritingNotSupportedException if HPSF does not (yet) support
+ * @throws WritingNotSupportedException if HPSF does not (yet) support
* writing a certain property type.
*/
public static void main(final String[] args)
/* Check whether we have exactly one command-line argument. */
if (args.length != 1)
{
- System.err.println("Usage: " + WriteTitle.class.getName() +
- "destinationPOIFS");
+ System.err.println("Usage: " + WriteTitle.class.getName() + "destinationPOIFS");
System.exit(1);
}
* SectionIDMap.SUMMARY_INFORMATION_ID. */
ms.setFormatID(SummaryInformation.FORMAT_ID);
- /* Create an empty property. */
+ /* Create an empty property. */
final Property p = new Property();
/* Fill the property with appropriate settings so that it specifies the
/* Place the property into the section. */
ms.setProperty(p);
- /* Create the POI file system the property set is to be written to. */
- try (final POIFSFileSystem poiFs = new POIFSFileSystem()) {
- /* For writing the property set into a POI file system it has to be
- * handed over to the POIFS.createDocument() method as an input stream
- * which produces the bytes making out the property set stream. */
- final InputStream is = mps.toInputStream();
+ /* Create the POI file system the property set is to be written to.
+ * For writing the property set into a POI file system it has to be
+ * handed over to the POIFS.createDocument() method as an input stream
+ * which produces the bytes making out the property set stream. */
+ try (final POIFSFileSystem poiFs = new POIFSFileSystem();
+ final InputStream is = mps.toInputStream();
+ final FileOutputStream fos = new FileOutputStream(fileName)) {
/* Create the summary information property set in the POI file
* system. It is given the default name most (if not all) summary
poiFs.createDocument(is, SummaryInformation.DEFAULT_STREAM_NAME);
/* Write the whole POI file system to a disk file. */
- try (FileOutputStream fos = new FileOutputStream(fileName)) {
- poiFs.writeFilesystem(fos);
- }
+ poiFs.writeFilesystem(fos);
}
}
}
@SuppressWarnings("java:S1192")
public final class ApacheconEU08 {
+ private ApacheconEU08() {}
+
public static void main(String[] args) throws IOException {
+ // use HSLFSlideShow or XMLSlideShow
try (SlideShow<?,?> ppt = new HSLFSlideShow()) {
- // SlideShow<?,?> ppt = new XMLSlideShow();
ppt.setPageSize(new Dimension(720, 540));
slide1(ppt);
graphics.setFont(new Font("Arial", Font.BOLD, 10));
for (int i = 0, idx = 1; i < def.length; i+=2, idx++) {
graphics.setColor(Color.black);
- int width = ((Integer)def[i+1]).intValue();
+ int width = (Integer) def[i + 1];
graphics.drawString("Q" + idx, x-20, y+20);
graphics.drawString(width + "%", x + width + 10, y + 20);
graphics.setColor((Color)def[i]);
/**
* Demonstrates how to create hyperlinks in PowerPoint presentations
*/
-public abstract class CreateHyperlink {
-
+public final class CreateHyperlink {
+
+ private CreateHyperlink() {}
+
public static void main(String[] args) throws IOException {
try (HSLFSlideShow ppt = new HSLFSlideShow()) {
HSLFSlide slideA = ppt.createSlide();
import java.io.FileInputStream;
import java.io.FileOutputStream;
+import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hslf.usermodel.HSLFObjectData;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
+import org.apache.poi.util.IOUtils;
/**
* Demonstrates how you can extract misc embedded data from a ppt file
*/
+@SuppressWarnings({"java:S106","java:S4823"})
public final class DataExtraction {
+ private DataExtraction() {}
+
public static void main(String[] args) throws Exception {
if (args.length == 0) {
return;
}
- try (FileInputStream is = new FileInputStream(args[0]);
- HSLFSlideShow ppt = new HSLFSlideShow(is)) {
+ try (FileInputStream fis = new FileInputStream(args[0]);
+ HSLFSlideShow ppt = new HSLFSlideShow(fis)) {
//extract all sound files embedded in this presentation
HSLFSoundData[] sound = ppt.getSoundData();
for (HSLFSoundData aSound : sound) {
- String type = aSound.getSoundType(); //*.wav
- String name = aSound.getSoundName(); //typically file name
- byte[] data = aSound.getData(); //raw bytes
-
- //save the sound on disk
- try (FileOutputStream out = new FileOutputStream(name + type)) {
- out.write(data);
- }
+ handleSound(aSound);
}
int oleIdx = -1, picIdx = -1;
HSLFObjectShape ole = (HSLFObjectShape) shape;
HSLFObjectData data = ole.getObjectData();
String name = ole.getInstanceName();
- if ("Worksheet".equals(name)) {
-
- //read xls
- @SuppressWarnings({"unused", "resource"})
- HSSFWorkbook wb = new HSSFWorkbook(data.getInputStream());
-
- } else if ("Document".equals(name)) {
- try (HWPFDocument doc = new HWPFDocument(data.getInputStream())) {
+ switch (name == null ? "" : name) {
+ case "Worksheet":
+ //read xls
+ handleWorkbook(data, name, oleIdx);
+ break;
+ case "Document":
//read the word document
- Range r = doc.getRange();
- for (int k = 0; k < r.numParagraphs(); k++) {
- Paragraph p = r.getParagraph(k);
- System.out.println(p.text());
- }
-
- //save on disk
- try (FileOutputStream out = new FileOutputStream(name + "-(" + (oleIdx) + ").doc")) {
- doc.write(out);
- }
- }
- } else {
- try (FileOutputStream out = new FileOutputStream(ole.getProgId() + "-" + (oleIdx + 1) + ".dat");
- InputStream dis = data.getInputStream()) {
- byte[] chunk = new byte[2048];
- int count;
- while ((count = dis.read(chunk)) >= 0) {
- out.write(chunk, 0, count);
- }
- }
+ handleDocument(data, name, oleIdx);
+ break;
+ default:
+ handleUnknown(data, ole.getProgId(), oleIdx);
+ break;
}
}
picIdx++;
HSLFPictureShape p = (HSLFPictureShape) shape;
HSLFPictureData data = p.getPictureData();
- String ext = data.getType().extension;
- try (FileOutputStream out = new FileOutputStream("pict-" + picIdx + ext)) {
- out.write(data.getData());
- }
+ handlePicture(data, picIdx);
}
}
}
}
}
+ private static void handleWorkbook(HSLFObjectData data, String name, int oleIdx) throws IOException {
+ try (InputStream is = data.getInputStream();
+ HSSFWorkbook wb = new HSSFWorkbook(is);
+ FileOutputStream out = new FileOutputStream(name + "-(" + (oleIdx) + ").xls")) {
+ wb.write(out);
+ }
+ }
+
+ private static void handleDocument(HSLFObjectData data, String name, int oleIdx) throws IOException {
+ try (InputStream is = data.getInputStream();
+ HWPFDocument doc = new HWPFDocument(is);
+ FileOutputStream out = new FileOutputStream(name + "-(" + (oleIdx) + ").doc")) {
+ Range r = doc.getRange();
+ for (int k = 0; k < r.numParagraphs(); k++) {
+ Paragraph p = r.getParagraph(k);
+ System.out.println(p.text());
+ }
+
+ //save on disk
+ doc.write(out);
+ }
+ }
+
+ private static void handleUnknown(HSLFObjectData data, String name, int oleIdx) throws IOException {
+ try (InputStream is = data.getInputStream();
+ FileOutputStream out = new FileOutputStream(name + "-" + (oleIdx + 1) + ".dat")) {
+ IOUtils.copy(is, out);
+ }
+ }
+
+ private static void handlePicture(HSLFPictureData data, int picIdx) throws IOException {
+ String ext = data.getType().extension;
+ try (FileOutputStream out = new FileOutputStream("pict-" + picIdx + ext)) {
+ out.write(data.getData());
+ }
+ }
+
+ private static void handleSound(HSLFSoundData aSound) throws IOException {
+ String type = aSound.getSoundType(); //*.wav
+ String name = aSound.getSoundName(); //typically file name
+
+ //save the sound on disk
+ try (FileOutputStream out = new FileOutputStream(name + type)) {
+ out.write(aSound.getData());
+ }
+ }
+
private static void usage(){
System.out.println("Usage: DataExtraction ppt");
}
import java.awt.Rectangle;
import java.io.FileOutputStream;
-import org.apache.poi.hslf.model.PPGraphics2D;
import org.apache.poi.hslf.usermodel.HSLFGroupShape;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
+import org.apache.poi.sl.draw.SLGraphics;
/**
* Demonstrates how to draw into a slide using the HSLF Graphics2D driver.
- *
- * @author Yegor Kozlov
*/
public final class Graphics2DDemo {
+ private Graphics2DDemo() {}
+
/**
* A simple bar chart demo
*/
public static void main(String[] args) throws Exception {
- try (HSLFSlideShow ppt = new HSLFSlideShow()) {
+ try (HSLFSlideShow ppt = new HSLFSlideShow();
+ FileOutputStream out = new FileOutputStream("hslf-graphics.ppt")) {
//bar chart data. The first value is the bar color, the second is the width
Object[] def = new Object[]{
Color.yellow, 40,
group.setAnchor(bounds);
group.setInteriorAnchor(new Rectangle(0, 0, 100, 100));
slide.addShape(group);
- Graphics2D graphics = new PPGraphics2D(group);
+ Graphics2D graphics = new SLGraphics(group);
//draw a simple bar graph
int x = 10, y = 10;
graphics.setFont(new Font("Arial", Font.BOLD, 10));
for (int i = 0, idx = 1; i < def.length; i += 2, idx++) {
graphics.setColor(Color.black);
- int width = ((Integer) def[i + 1]).intValue();
+ int width = (Integer) def[i + 1];
graphics.drawString("Q" + idx, x - 5, y + 10);
graphics.drawString(width + "%", x + width + 3, y + 10);
graphics.setColor((Color) def[i]);
graphics.draw(group.getInteriorAnchor());
graphics.drawString("Performance", x + 30, y + 10);
- try (FileOutputStream out = new FileOutputStream("hslf-graphics.ppt")) {
- ppt.write(out);
- }
+ ppt.write(out);
}
}
}
/**
* Demonstrates how to set headers / footers
*/
-public abstract class HeadersFootersDemo {
+public final class HeadersFootersDemo {
+ private HeadersFootersDemo() {}
+
public static void main(String[] args) throws IOException {
try (HSLFSlideShow ppt = new HSLFSlideShow()) {
HeadersFooters slideHeaders = ppt.getSlideHeadersFooters();
import java.util.Locale;
import org.apache.poi.hslf.usermodel.HSLFHyperlink;
-import org.apache.poi.hslf.usermodel.HSLFShape;
import org.apache.poi.hslf.usermodel.HSLFSimpleShape;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
/**
* Demonstrates how to read hyperlinks from a presentation
*/
+@SuppressWarnings({"java:S106", "java:S4823"})
public final class Hyperlinks {
+ private Hyperlinks() {}
+
public static void main(String[] args) throws Exception {
for (String arg : args) {
try (FileInputStream is = new FileInputStream(arg);
- HSLFSlideShow ppt = new HSLFSlideShow(is)) {
+ HSLFSlideShow ppt = new HSLFSlideShow(is)) {
for (HSLFSlide slide : ppt.getSlides()) {
System.out.println("\nslide " + slide.getSlideNumber());
// read hyperlinks from the slide's text runs
System.out.println("- reading hyperlinks from the text runs");
- for (List<HSLFTextParagraph> paras : slide.getTextParagraphs()) {
- for (HSLFTextParagraph para : paras) {
- for (HSLFTextRun run : para) {
- HSLFHyperlink link = run.getHyperlink();
- if (link != null) {
- System.out.println(toStr(link, run.getRawText()));
- }
- }
- }
- }
+ slide.getTextParagraphs().stream().
+ flatMap(List::stream).
+ map(HSLFTextParagraph::getTextRuns).
+ flatMap(List::stream).
+ forEach(run -> out(run.getHyperlink(), run));
// in PowerPoint you can assign a hyperlink to a shape without text,
// for example to a Line object. The code below demonstrates how to
// read such hyperlinks
System.out.println("- reading hyperlinks from the slide's shapes");
- for (HSLFShape sh : slide.getShapes()) {
- if (sh instanceof HSLFSimpleShape) {
- HSLFHyperlink link = ((HSLFSimpleShape) sh).getHyperlink();
- if (link != null) {
- System.out.println(toStr(link, null));
- }
- }
- }
+ slide.getShapes().stream().
+ filter(sh -> sh instanceof HSLFSimpleShape).
+ forEach(sh -> out(((HSLFSimpleShape) sh).getHyperlink(), null));
}
}
}
- }
+ }
- static String toStr(HSLFHyperlink link, String rawText) {
+ private static void out(HSLFHyperlink link, HSLFTextRun run) {
+ if (link == null) {
+ return;
+ }
+ String rawText = run == null ? null : run.getRawText();
//in ppt end index is inclusive
String formatStr = "title: %1$s, address: %2$s" + (rawText == null ? "" : ", start: %3$s, end: %4$s, substring: %5$s");
- return String.format(Locale.ROOT, formatStr, link.getLabel(), link.getAddress(), link.getStartIndex(), link.getEndIndex(), rawText);
+ String line = String.format(Locale.ROOT, formatStr, link.getLabel(), link.getAddress(), link.getStartIndex(), link.getEndIndex(), rawText);
+ System.out.println(line);
}
}
/**
* For each slide iterate over shapes and found associated sound data.
*/
-public class SoundFinder {
+@SuppressWarnings({"java:S106", "java:S4823"})
+public final class SoundFinder {
+ private SoundFinder() {}
+
public static void main(String[] args) throws IOException {
try (FileInputStream fis = new FileInputStream(args[0])) {
try (HSLFSlideShow ppt = new HSLFSlideShow(fis)) {
* @return 0-based reference to a sound in the sound collection
* or -1 if the shape is not associated with a sound
*/
- protected static int getSoundReference(HSLFShape shape){
+ private static int getSoundReference(HSLFShape shape){
int soundRef = -1;
//dive into the shape container and search for InteractiveInfoAtom
InteractiveInfoAtom info = shape.getClientDataRecord(RecordTypes.InteractiveInfo.typeID);
package org.apache.poi.xssf.eventusermodel.examples;
-import java.io.FileInputStream;
import java.io.InputStream;
-import org.apache.poi.crypt.examples.EncryptionUtils;
-import org.apache.poi.examples.util.TempFileUtils;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFReader.SheetIterator;
+import org.apache.poi.xssf.usermodel.examples.LoadPasswordProtectedXlsx;
/**
* An example that loads a password protected workbook and counts the sheets.
* <li><code>AesZipFileZipEntrySource</code> is used to ensure that temp files are encrypted.
* </ul><p>
*/
-public class LoadPasswordProtectedXlsxStreaming {
+public final class LoadPasswordProtectedXlsxStreaming {
+
+ private LoadPasswordProtectedXlsxStreaming() {
+ }
public static void main(String[] args) throws Exception {
- if(args.length != 2) {
- throw new IllegalArgumentException("Expected 2 params: filename and password");
- }
- TempFileUtils.checkTempFiles();
- String filename = args[0];
- String password = args[1];
- try (FileInputStream fis = new FileInputStream(filename);
- InputStream unencryptedStream = EncryptionUtils.decrypt(fis, password)) {
- printSheetCount(unencryptedStream);
- }
- TempFileUtils.checkTempFiles();
+ LoadPasswordProtectedXlsx.execute(args, LoadPasswordProtectedXlsxStreaming::printSheetCount);
}
- public static void printSheetCount(final InputStream inputStream) throws Exception {
+ private static void printSheetCount(final InputStream inputStream) throws Exception {
try (AesZipFileZipEntrySource source = AesZipFileZipEntrySource.createZipEntrySource(inputStream);
OPCPackage pkg = OPCPackage.open(source)) {
XSSFReader reader = new XSSFReader(pkg);
import java.io.FileInputStream;
import java.io.InputStream;
-import org.apache.poi.crypt.examples.EncryptionUtils;
import org.apache.poi.examples.util.TempFileUtils;
import org.apache.poi.openxml4j.opc.OPCPackage;
+import org.apache.poi.poifs.crypt.Decryptor;
+import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource;
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* <li><code>AesZipFileZipEntrySource</code> is used to ensure that temp files are encrypted.
* </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 {
+ execute(args, LoadPasswordProtectedXlsx::printSheetCount);
+ }
+
+ public static void execute(String[] args, EncryptionHandler handler) throws Exception {
if(args.length != 2) {
throw new IllegalArgumentException("Expected 2 params: filename and password");
}
String filename = args[0];
String password = args[1];
try (FileInputStream fis = new FileInputStream(filename);
- InputStream unencryptedStream = EncryptionUtils.decrypt(fis, password)) {
- printSheetCount(unencryptedStream);
+ POIFSFileSystem fs = new POIFSFileSystem(fis)) {
+ EncryptionInfo info = new EncryptionInfo(fs);
+ Decryptor d = Decryptor.getInstance(info);
+ if (!d.verifyPassword(password)) {
+ throw new RuntimeException("incorrect password");
+ }
+ try (InputStream unencryptedStream = d.getDataStream(fs)) {
+ handler.handle(unencryptedStream);
+ }
}
TempFileUtils.checkTempFiles();
}
-
- public static void printSheetCount(final InputStream inputStream) throws Exception {
+
+
+ private static void printSheetCount(final InputStream inputStream) throws Exception {
try (AesZipFileZipEntrySource source = AesZipFileZipEntrySource.createZipEntrySource(inputStream);
OPCPackage pkg = OPCPackage.open(source);
XSSFWorkbook workbook = new XSSFWorkbook(pkg)) {
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Internal;
+import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.LittleEndianByteArrayInputStream;
-import org.apache.poi.util.LittleEndianByteArrayOutputStream;
import org.apache.poi.util.LittleEndianConsts;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
int size = lei.readInt();
if ( size < 4 ) {
- String msg =
+ String msg =
"ClipboardData at offset "+offset+" size less than 4 bytes "+
"(doesn't even have format field!). Setting to format == 0 and hope for the best";
LOG.log( POILogger.WARN, msg);
public byte[] toByteArray() {
byte[] result = new byte[LittleEndianConsts.INT_SIZE*2+_value.length];
- LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(result,0);
- try {
- bos.writeInt(LittleEndianConsts.INT_SIZE + _value.length);
- bos.writeInt(_format);
- bos.write(_value);
- return result;
- } finally {
- IOUtils.closeQuietly(bos);
- }
+ LittleEndian.putInt(result, 0, LittleEndianConsts.INT_SIZE + _value.length);
+ LittleEndian.putInt(result, 4, _format);
+ System.arraycopy(_value, 0, result, 8, _value.length);
+ return result;
}
public void setValue( byte[] value ) {
import java.io.UnsupportedEncodingException;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
-import org.apache.poi.poifs.filesystem.DocumentEntry;
+import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.util.LittleEndianInputStream;
* Creates the most specific {@link PropertySet} from an entry
* in the specified POIFS Directory. This is preferrably a {@link
* DocumentSummaryInformation} or a {@link SummaryInformation}. If
- * the specified entry does not contain a property set stream, an
+ * the specified entry does not contain a property set stream, an
* exception is thrown. If no entry is found with the given name,
* an exception is thrown.
*
*/
public static PropertySet create(final DirectoryEntry dir, final String name)
throws FileNotFoundException, NoPropertySetStreamException, IOException, UnsupportedEncodingException {
- InputStream inp = null;
- try {
- DocumentEntry entry = (DocumentEntry)dir.getEntry(name);
- inp = new DocumentInputStream(entry);
- try {
- return create(inp);
- } catch (MarkUnsupportedException e) {
- return null;
- }
- } finally {
- if (inp != null) {
- inp.close();
- }
+ try (DocumentInputStream inp = ((DirectoryNode)dir).createDocumentInputStream(name)) {
+ return create(inp);
+ } catch (MarkUnsupportedException e) {
+ return null;
}
}
byte[] clsIdBuf = new byte[ClassID.LENGTH];
leis.readFully(clsIdBuf);
int sectionCount = (int)leis.readUInt();
-
+
if (byteOrder != PropertySet.BYTE_ORDER_ASSERTION ||
format != PropertySet.FORMAT_ASSERTION ||
sectionCount < 0) {
throw new NoPropertySetStreamException();
}
-
+
if (sectionCount > 0) {
leis.readFully(clsIdBuf);
}
stream.reset();
-
+
ClassID clsId = new ClassID(clsIdBuf, 0);
if (sectionCount > 0 && PropertySet.matchesSummary(clsId, SummaryInformation.FORMAT_ID)) {
return new SummaryInformation(stream);
import java.io.DataInputStream;
import java.io.File;
+import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
// args = new String[] { "--out", "", };
CommandArgs cmdArgs = CommandArgs.parse(args);
- PrintWriter pw;
- if (cmdArgs.shouldOutputToFile()) {
- OutputStream os = new FileOutputStream(cmdArgs.getFile().getAbsolutePath() + ".out");
- pw = new PrintWriter(new OutputStreamWriter(os, StringUtil.UTF8));
- } else {
- // Use the system default encoding when sending to System Out
- pw = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset()));
- }
-
- POIFSFileSystem fs = null;
- InputStream is = null;
- try {
- fs = new POIFSFileSystem(cmdArgs.getFile(), true);
- is = getPOIFSInputStream(fs);
-
+ try (POIFSFileSystem fs = new POIFSFileSystem(cmdArgs.getFile(), true);
+ InputStream is = getPOIFSInputStream(fs);
+ PrintWriter pw = getOutputStream(cmdArgs.shouldOutputToFile() ? cmdArgs.getFile().getAbsolutePath() : null)
+ ) {
if (cmdArgs.shouldOutputRawHexOnly()) {
byte[] data = IOUtils.toByteArray(is);
HexDump.dump(data, 0, System.out, 0);
runBiffViewer(pw, is, dumpInterpretedRecords, dumpHex, dumpInterpretedRecords,
cmdArgs.suppressHeader());
}
- } finally {
- IOUtils.closeQuietly(is);
- IOUtils.closeQuietly(fs);
- IOUtils.closeQuietly(pw);
}
}
+ static PrintWriter getOutputStream(String outputPath) throws FileNotFoundException {
+ // Use the system default encoding when sending to System Out
+ OutputStream os = System.out;
+ Charset cs = Charset.defaultCharset();
+ if (outputPath != null) {
+ cs = StringUtil.UTF8;
+ os = new FileOutputStream(outputPath + ".out");
+ }
+ return new PrintWriter(new OutputStreamWriter(os, cs));
+ }
+
+
static InputStream getPOIFSInputStream(POIFSFileSystem fs) throws IOException {
String workbookName = HSSFWorkbook.getWorkbookDirEntryName(fs.getRoot());
return fs.createDocumentInputStream(workbookName);
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.filesystem;
import java.io.File;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
/**
* Class POIFSDocumentPath
- *
- * @author Marc Johnson (mjohnson at apache dot org)
- * @version %I%, %G%
*/
-public class POIFSDocumentPath
-{
+public class POIFSDocumentPath {
+
private static final POILogger log = POILogFactory.getLogger(POIFSDocumentPath.class);
-
+
private final String[] components;
private int hashcode; //lazy-compute hashCode
/**
- * constructor for the path of a document that is not in the root
- * of the POIFSFileSystem
- *
- * @param components the Strings making up the path to a document.
- * The Strings must be ordered as they appear in
- * the directory hierarchy of the the document
- * -- the first string must be the name of a
- * directory in the root of the POIFSFileSystem,
- * and every Nth (for N > 1) string thereafter
- * must be the name of a directory in the
- * directory identified by the (N-1)th string.
- * <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
+ * simple constructor for the path of a document that is in the root of the POIFSFileSystem.
+ * The constructor that takes an array of Strings can also be used to create such a
+ * POIFSDocumentPath by passing it a null or empty String array
*/
-
- public POIFSDocumentPath(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 ];
- }
- }
+ public POIFSDocumentPath() {
+ components = new String[0];
}
/**
- * 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
+ * constructor for the path of a document that is not in the root of the POIFSFileSystem
+ *
+ * @param components the Strings making up the path to a document.
+ * The Strings must be ordered as they appear in the directory hierarchy of the the document.
+ * The first string must be the name of a directory in the root of the POIFSFileSystem, and
+ * every Nth (for N > 1) string thereafter must be the name of a directory in the directory
+ * identified by the (N-1)th string. <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()
- {
- this.components = new String[ 0 ];
+ public POIFSDocumentPath(final String [] components) throws IllegalArgumentException {
+ this(null, components);
}
/**
- * constructor that adds additional subdirectories to an existing
- * path
+ * constructor that adds additional subdirectories to an existing path
*
* @param path the existing path
* @param components the additional subdirectory names to be added
*
- * @exception IllegalArgumentException if any of the Strings in
- * components is null or zero
- * length
+ * @exception IllegalArgumentException
+ * if any of the Strings in components is null or zero length
*/
-
- public POIFSDocumentPath(final POIFSDocumentPath path,
- final String [] components)
- throws IllegalArgumentException
- {
- if (components == null)
- {
- this.components = new String[ path.components.length ];
- }
- else
- {
- this.components =
- new String[ path.components.length + components.length ];
- }
- System.arraycopy(path.components, 0, this.components, 0, path.components.length);
- if (components != null)
- {
- for (int j = 0; j < components.length; j++)
- {
- if (components[ j ] == null)
- {
- throw new IllegalArgumentException(
- "components cannot contain null");
- }
- if (components[ j ].length() == 0)
- {
- log.log(POILogger.WARN, "Directory under " + path + " has an empty name, " +
- "not all OLE2 readers will handle this file correctly!");
- }
-
- this.components[ j + path.components.length ] =
- components[ j ];
- }
+ 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;
+
+ // TODO: Although the Javadoc says empty strings are forbidden, the adapted legacy
+ // implementation allowed it in case a path was specified...
+ Predicate<String> p = (path != null) ? Objects::isNull : (s) -> (s == null || s.isEmpty());
+ if (Stream.of(s2).anyMatch(p)) {
+ throw new IllegalArgumentException("components cannot contain null or empty strings");
}
+
+ this.components = Stream.concat(Stream.of(s1),Stream.of(s2)).toArray(String[]::new);
}
/**
- * equality. Two POIFSDocumentPath instances are equal if they
- * have the same number of component Strings, and if each
- * component String is equal to its coresponding component String
+ * Two POIFSDocumentPath instances are equal if they have the same number of component Strings,
+ * and if each component String is equal to its corresponding component String
*
* @param o the object we're checking equality for
*
* @return true if the object is equal to this object
*/
- public boolean equals(final Object o)
- {
- boolean rval = false;
-
- if ((o != null) && (o.getClass() == this.getClass()))
- {
- if (this == o)
- {
- rval = true;
- }
- else
- {
- POIFSDocumentPath path = ( POIFSDocumentPath ) o;
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
- 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;
- }
- }
- }
- }
+ if ((o != null) && (o.getClass() == this.getClass())) {
+ POIFSDocumentPath path = ( POIFSDocumentPath ) o;
+ return Arrays.equals(this.components, path.components);
}
- return rval;
+ return false;
}
/**
* @return hashcode
*/
- public int hashCode()
- {
- if (hashcode == 0)
- {
- hashcode = computeHashCode();
- }
- return hashcode;
- }
-
- private int computeHashCode() {
- int code = 0;
- for (int j = 0; j < components.length; j++)
- {
- code += components[ j ].hashCode();
- }
- return code;
+ public int hashCode() {
+ return (hashcode == 0) ? (hashcode = Arrays.hashCode(components)) : hashcode;
}
/**
* @return the number of components
*/
-
- public int length()
- {
+ public int length() {
return components.length;
}
*
* @exception ArrayIndexOutOfBoundsException if n < 0 or n >= length()
*/
-
- public String getComponent(int n)
- throws ArrayIndexOutOfBoundsException
- {
+ public String getComponent(int n) throws ArrayIndexOutOfBoundsException {
return components[ n ];
}
* @since 2002-01-24
* @return path of parent, or null if this path is the root path
*/
-
- public POIFSDocumentPath getParent()
- {
- final int length = components.length - 1;
-
- if (length < 0)
- {
- return null;
- }
- String[] parentComponents = new String[ length ];
- System.arraycopy(components, 0, parentComponents, 0, length);
-
- return new POIFSDocumentPath(parentComponents);
+ public POIFSDocumentPath getParent() {
+ return (components.length == 0) ? null : new POIFSDocumentPath(Arrays.copyOf(components, components.length - 1));
}
-
+
/**
* <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>
* @since 2016-04-09
* @return The last name in the document path's name sequence, or empty string if this is the root path
*/
-
- public String getName()
- {
- if (components.length == 0) {
- return "";
- }
- return components[components.length - 1];
+ public String getName() {
+ return components.length == 0 ? "" : components[components.length - 1];
}
/**
*
* @since 2002-01-24
*/
-
- public String toString()
- {
- final StringBuilder b = new StringBuilder();
- final int l = length();
-
- b.append(File.separatorChar);
- for (int i = 0; i < l; i++)
- {
- b.append(getComponent(i));
- if (i < l - 1)
- {
- b.append(File.separatorChar);
- }
- }
- return b.toString();
+ public String toString() {
+ return File.separatorChar + String.join(String.valueOf(File.separatorChar), components);
}
-} // end public class POIFSDocumentPath
+}
package org.apache.poi.util;
-import java.io.ByteArrayOutputStream;
-import java.io.FileInputStream;
import java.io.IOException;
-import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
-import java.io.PrintStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
* dump data in hexadecimal format
*/
@Internal
-public class HexDump {
+public final class HexDump {
public static final String EOL = System.getProperty("line.separator");
public static final Charset UTF8 = StandardCharsets.UTF_8;
public static String dump(final byte [] data, final long offset, final int index) {
return dump(data, offset, index, Integer.MAX_VALUE);
- }
-
+ }
+
/**
* dump an array of bytes to a String
*
int data_length = (length == Integer.MAX_VALUE || length < 0 || index+length < 0)
? data.length
: Math.min(data.length,index+length);
-
-
+
+
if ((index < 0) || (index >= data.length)) {
String err = "illegal index: "+index+" into array of length "+data.length;
throw new ArrayIndexOutOfBoundsException(err);
}
-
+
long display_offset = offset + index;
StringBuilder buffer = new StringBuilder(74);
-
+
for (int j = index; j < data_length; j += 16) {
int chars_read = data_length - j;
if (chars_read > 16) {
chars_read = 16;
}
-
+
writeHex(buffer, display_offset, 8, "");
for (int k = 0; k < 16; k++) {
if (k < chars_read) {
if (Character.isISOControl(charB)) {
return '.';
}
-
+
switch (charB) {
// printable, but not compilable with current compiler encoding
case 0xFF:
}
return charB;
}
-
+
/**
* Converts the parameter to a hex value.
*
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.
*
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'
*/
writeHex(sb, value, 16, "0x");
return sb.toString();
}
-
+
/**
* @return string of 8 (zero padded) uppercase hex chars and prefixed with '0x'
*/
writeHex(sb, value & 0xFFFFFFFFL, 8, "0x");
return sb.toString();
}
-
+
/**
* @return string of 4 (zero padded) uppercase hex chars and prefixed with '0x'
*/
writeHex(sb, value & 0xFFFFL, 4, "0x");
return sb.toString();
}
-
+
/**
* @return string of 2 (zero padded) uppercase hex chars and prefixed with '0x'
*/
writeHex(sb, value & 0xFFL, 2, "0x");
return sb.toString();
}
-
+
/**
* @see Integer#toHexString(int)
* @see Long#toHexString(long)
acc >>>= 4;
}
sb.append(buf);
- }
-
-
- public static void main(String[] args) throws IOException {
- InputStream in = new FileInputStream(args[0]);
- byte[] b = IOUtils.toByteArray(in);
- in.close();
- System.out.println(HexDump.dump(b, 0, 0));
}
}
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFTestHelper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.util.HexDump;
import org.junit.Test;
public class TestDrawingAggregate {
for(EscherRecord r : records) {
out.write(r.serialize());
}
- assertEquals(HexDump.toHex(dgBytes, 10), HexDump.toHex(out.toByteArray(), 10));
+ assertArrayEquals(dgBytes, out.toByteArray());
}
/**
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import java.io.*;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.io.UnsupportedEncodingException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@BeforeClass
public static void setUp() throws UnsupportedEncodingException {
SYSTEM_OUT = System.out;
- System.setOut(new PrintStream(new OutputStream() {
- @Override
- public void write(int b) throws IOException {
-
- }
- }, false, "UTF-8"));
+ System.setOut(new PrintStream(new OutputStream() {public void write(int b) {}}, false, "UTF-8"));
}
@AfterClass
public void testToHex() {
assertEquals("000A", HexDump.toHex((short)0xA));
- assertEquals("[]", HexDump.toHex(new short[] { }));
- assertEquals("[000A]", HexDump.toHex(new short[] { 0xA }));
- assertEquals("[000A, 000B]", HexDump.toHex(new short[] { 0xA, 0xB }));
-
assertEquals("0A", HexDump.toHex((byte)0xA));
assertEquals("0000000A", HexDump.toHex(0xA));
assertEquals("[0A]", HexDump.toHex(new byte[] { 0xA }));
assertEquals("[0A, 0B]", HexDump.toHex(new byte[] { 0xA, 0xB }));
- assertEquals(": 0", HexDump.toHex(new byte[] { }, 10));
- assertEquals("0: 0A", HexDump.toHex(new byte[] { 0xA }, 10));
- assertEquals("0: 0A, 0B", HexDump.toHex(new byte[] { 0xA, 0xB }, 10));
- assertEquals("0: 0A, 0B\n2: 0C, 0D", HexDump.toHex(new byte[] { 0xA, 0xB, 0xC, 0xD }, 2));
- assertEquals("0: 0A, 0B\n2: 0C, 0D\n4: 0E, 0F", HexDump.toHex(new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0xF }, 2));
-
assertEquals("FFFF", HexDump.toHex((short)0xFFFF));
assertEquals("00000000000004D2", HexDump.toHex(1234L));
}
@Test
- public void testDumpToString() throws Exception {
+ public void testDumpToString() {
byte[] testArray = testArray();
String dump = HexDump.dump(testArray, 0, 0);
//System.out.println("Hex: \n" + dump);
}
@Test(expected=ArrayIndexOutOfBoundsException.class)
- public void testDumpToStringOutOfIndex1() throws Exception {
+ public void testDumpToStringOutOfIndex1() {
HexDump.dump(new byte[1], 0, -1);
}
@Test(expected=ArrayIndexOutOfBoundsException.class)
- public void testDumpToStringOutOfIndex2() throws Exception {
+ public void testDumpToStringOutOfIndex2() {
HexDump.dump(new byte[1], 0, 2);
}
@Test(expected=ArrayIndexOutOfBoundsException.class)
- public void testDumpToStringOutOfIndex3() throws Exception {
+ public void testDumpToStringOutOfIndex3() {
HexDump.dump(new byte[1], 0, 1);
}
@Test
- public void testDumpToStringNoDataEOL1() throws Exception {
+ public void testDumpToStringNoDataEOL1() {
HexDump.dump(new byte[0], 0, 1);
}
@Test
- public void testDumpToStringNoDataEOL2() throws Exception {
+ public void testDumpToStringNoDataEOL2() {
HexDump.dump(new byte[0], 0, 0);
}
- @Test
- public void testDumpToPrintStream() throws IOException {
- byte[] testArray = testArray();
- ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
- PrintStream out = new PrintStream(byteOut,true,LocaleUtil.CHARSET_1252.name());
- ByteArrayInputStream byteIn = new ByteArrayInputStream(testArray);
- byteIn.mark(256);
- String str;
-
- byteIn.reset();
- byteOut.reset();
- HexDump.dump(byteIn, out, 0, 256);
- str = new String(byteOut.toByteArray(), LocaleUtil.CHARSET_1252);
- assertTrue("Had: \n" + str, str.contains("0123456789:;<=>?"));
-
- // test with more than we have
- byteIn.reset();
- byteOut.reset();
- HexDump.dump(byteIn, out, 0, 1000);
- str = new String(byteOut.toByteArray(), LocaleUtil.CHARSET_1252);
- assertTrue("Had: \n" + str, str.contains("0123456789:;<=>?"));
-
- // test with -1
- byteIn.reset();
- byteOut.reset();
- HexDump.dump(byteIn, out, 0, -1);
- str = new String(byteOut.toByteArray(), LocaleUtil.CHARSET_1252);
- assertTrue("Had: \n" + str, str.contains("0123456789:;<=>?"));
-
- byteIn.reset();
- byteOut.reset();
- HexDump.dump(byteIn, out, 1, 235);
- str = new String(byteOut.toByteArray(), LocaleUtil.CHARSET_1252);
- assertTrue("Line contents should be moved by one now, but Had: \n" + str,
- str.contains("123456789:;<=>?@"));
-
- byteIn.close();
- byteOut.close();
- }
-
- @Test
- public void testMain() throws Exception {
- File file = TempFile.createTempFile("HexDump", ".dat");
- try {
- try (FileOutputStream out = new FileOutputStream(file)) {
- IOUtils.copy(new ByteArrayInputStream("teststring".getBytes(LocaleUtil.CHARSET_1252)), out);
- }
- assertTrue(file.exists());
- assertTrue(file.length() > 0);
-
- HexDump.main(new String[] { file.getAbsolutePath() });
- } finally {
- assertTrue(file.exists() && file.delete());
- }
- }
-
private static byte[] testArray() {
byte[] testArray = new byte[ 256 ];
for (int j = 0; j < 256; j++) {
testArray[ j ] = ( byte ) j;
}
-
+
return testArray;
}
}