==================================================================== */\r
package org.apache.poi.xssf.usermodel.examples;\r
\r
+import java.io.Closeable;\r
import java.io.InputStream;\r
\r
-import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;\r
+import org.apache.poi.hslf.usermodel.HSLFSlideShow;\r
import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
import org.apache.poi.hwpf.HWPFDocument;\r
-import org.apache.poi.openxml4j.opc.OPCPackage;\r
import org.apache.poi.openxml4j.opc.PackagePart;\r
-import org.apache.poi.xslf.usermodel.XSLFSlideShow;\r
+import org.apache.poi.xslf.usermodel.XMLSlideShow;\r
import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
import org.apache.poi.xwpf.usermodel.XWPFDocument;\r
\r
XSSFWorkbook workbook = new XSSFWorkbook(args[0]);\r
for (PackagePart pPart : workbook.getAllEmbedds()) {\r
String contentType = pPart.getContentType();\r
+ InputStream is = pPart.getInputStream();\r
+ Closeable document;\r
if (contentType.equals("application/vnd.ms-excel")) {\r
// Excel Workbook - either binary or OpenXML\r
- HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());\r
- embeddedWorkbook.close();\r
+ document = new HSSFWorkbook(is);\r
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {\r
// Excel Workbook - OpenXML file format\r
- XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream());\r
- embeddedWorkbook.close();\r
+ document = new XSSFWorkbook(is);\r
} else if (contentType.equals("application/msword")) {\r
// Word Document - binary (OLE2CDF) file format\r
- HWPFDocument document = new HWPFDocument(pPart.getInputStream());\r
- document.close();\r
+ document = new HWPFDocument(is);\r
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {\r
// Word Document - OpenXML file format\r
- XWPFDocument document = new XWPFDocument(pPart.getInputStream());\r
- document.close();\r
+ document = new XWPFDocument(is);\r
} else if (contentType.equals("application/vnd.ms-powerpoint")) {\r
// PowerPoint Document - binary file format\r
- HSLFSlideShowImpl slideShow = new HSLFSlideShowImpl(pPart.getInputStream());\r
- slideShow.close();\r
+ document = new HSLFSlideShow(is);\r
} else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {\r
// PowerPoint Document - OpenXML file format\r
- OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());\r
- XSLFSlideShow slideShow = new XSLFSlideShow(docPackage);\r
- slideShow.close();\r
+ document = new XMLSlideShow(is);\r
} else {\r
// Any other type of embedded object.\r
- System.out.println("Unknown Embedded Document: " + contentType);\r
- InputStream inputStream = pPart.getInputStream();\r
- inputStream.close();\r
+ document = is;\r
}\r
+ document.close();\r
+ is.close();\r
}\r
workbook.close();\r
}\r
handleWorkbook(wb);
// TODO: some documents fail currently...
+ // Note - as of Bugzilla 48036 (svn r828244, r828247) POI is capable of evaluating
+ // IntesectionPtg. However it is still not capable of parsing it.
+ // So FormulaEvalTestData.xls now contains a few formulas that produce errors here.
//HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb);
//evaluator.evaluateAll();
package org.apache.poi.hssf.usermodel;
-import org.apache.poi.hssf.model.HSSFFormulaParser;
import org.apache.poi.hssf.model.InternalWorkbook;
import org.apache.poi.hssf.record.NameRecord;
import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
import org.apache.poi.ss.formula.EvaluationName;
import org.apache.poi.ss.formula.EvaluationSheet;
import org.apache.poi.ss.formula.EvaluationWorkbook;
-import org.apache.poi.ss.formula.FormulaParseException;
import org.apache.poi.ss.formula.FormulaParsingWorkbook;
import org.apache.poi.ss.formula.FormulaRenderingWorkbook;
-import org.apache.poi.ss.formula.FormulaType;
import org.apache.poi.ss.formula.SheetIdentifier;
import org.apache.poi.ss.formula.SheetRangeIdentifier;
import org.apache.poi.ss.formula.ptg.Area3DPtg;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.util.Internal;
-import org.apache.poi.util.POILogFactory;
-import org.apache.poi.util.POILogger;
/**
* Internal POI use only
*/
@Internal
public final class HSSFEvaluationWorkbook implements FormulaRenderingWorkbook, EvaluationWorkbook, FormulaParsingWorkbook {
- private static POILogger logger = POILogFactory.getLogger(HSSFEvaluationWorkbook.class);
private final HSSFWorkbook _uBook;
private final InternalWorkbook _iBook;
* @param sheetIndex the 0-based index of the sheet this formula belongs to.
* The sheet index is required to resolve sheet-level names. <code>-1</code> means workbook-global names
*/
+ @Override
public EvaluationName getName(String name, int sheetIndex) {
for(int i=0; i < _iBook.getNumNames(); i++) {
NameRecord nr = _iBook.getNameRecord(i);
}
@Override
- @SuppressWarnings("unused")
public Ptg[] getFormulaTokens(EvaluationCell evalCell) {
HSSFCell cell = ((HSSFEvaluationCell)evalCell).getHSSFCell();
- if (false) {
- // re-parsing the formula text also works, but is a waste of time
- // It is useful from time to time to run all unit tests with this code
- // to make sure that all formulas POI can evaluate can also be parsed.
- try {
- return HSSFFormulaParser.parse(cell.getCellFormula(), _uBook, FormulaType.CELL, _uBook.getSheetIndex(cell.getSheet()));
- } catch (FormulaParseException e) {
- // Note - as of Bugzilla 48036 (svn r828244, r828247) POI is capable of evaluating
- // IntesectionPtg. However it is still not capable of parsing it.
- // So FormulaEvalTestData.xls now contains a few formulas that produce errors here.
- logger.log( POILogger.ERROR, e.getMessage());
- }
- }
+ // re-parsing the formula text also works, but is a waste of time
+ // return HSSFFormulaParser.parse(cell.getCellFormula(), _uBook, FormulaType.CELL, _uBook.getSheetIndex(cell.getSheet()));
+ // It is useful within the tests to make sure that all formulas POI can evaluate can also be parsed.
+ // see HSSFFileHandler.handleFile instead
FormulaRecordAggregate fra = (FormulaRecordAggregate) cell.getCellValueRecord();
return fra.getFormulaTokens();
}
_nameRecord = nameRecord;
_index = index;
}
+ @Override
public Ptg[] getNameDefinition() {
return _nameRecord.getNameDefinition();
}
+ @Override
public String getNameText() {
return _nameRecord.getNameText();
}
+ @Override
public boolean hasFormula() {
return _nameRecord.hasFormula();
}
+ @Override
public boolean isFunctionName() {
return _nameRecord.isFunctionName();
}
+ @Override
public boolean isRange() {
return _nameRecord.hasFormula(); // TODO - is this right?
}
+ @Override
public NamePtg createPtg() {
return new NamePtg(_index);
}
initCipherForBlock(cipher, index);\r
\r
if (lastIndex != index) {\r
- super.skip((index - lastIndex) << chunkBits);\r
+ long skipN = (index - lastIndex) << chunkBits;\r
+ if (super.skip(skipN) < skipN) {\r
+ throw new EOFException("buffer underrun");\r
+ };\r
}\r
\r
lastIndex = index + 1;\r
package org.apache.poi.poifs.crypt.cryptoapi;\r
\r
import java.io.ByteArrayOutputStream;\r
+import java.io.EOFException;\r
import java.io.IOException;\r
import java.io.InputStream;\r
import java.security.GeneralSecurityException;\r
dis.close();\r
CryptoAPIDocumentInputStream sbis = new CryptoAPIDocumentInputStream(this, bos.toByteArray());\r
LittleEndianInputStream leis = new LittleEndianInputStream(sbis);\r
- int streamDescriptorArrayOffset = (int) leis.readUInt();\r
- /* int streamDescriptorArraySize = (int) */ leis.readUInt();\r
- sbis.skip(streamDescriptorArrayOffset - 8L);\r
- sbis.setBlock(0);\r
- int encryptedStreamDescriptorCount = (int) leis.readUInt();\r
- StreamDescriptorEntry entries[] = new StreamDescriptorEntry[encryptedStreamDescriptorCount];\r
- for (int i = 0; i < encryptedStreamDescriptorCount; i++) {\r
- StreamDescriptorEntry entry = new StreamDescriptorEntry();\r
- entries[i] = entry;\r
- entry.streamOffset = (int) leis.readUInt();\r
- entry.streamSize = (int) leis.readUInt();\r
- entry.block = leis.readUShort();\r
- int nameSize = leis.readUByte();\r
- entry.flags = leis.readUByte();\r
- // boolean isStream = StreamDescriptorEntry.flagStream.isSet(entry.flags);\r
- entry.reserved2 = leis.readInt();\r
- entry.streamName = StringUtil.readUnicodeLE(leis, nameSize);\r
- leis.readShort();\r
- assert(entry.streamName.length() == nameSize);\r
- }\r
-\r
- for (StreamDescriptorEntry entry : entries) {\r
- sbis.seek(entry.streamOffset);\r
- sbis.setBlock(entry.block);\r
- InputStream is = new BoundedInputStream(sbis, entry.streamSize);\r
- fsOut.createDocument(is, entry.streamName);\r
- is.close();\r
+ try {\r
+ int streamDescriptorArrayOffset = (int) leis.readUInt();\r
+ /* int streamDescriptorArraySize = (int) */ leis.readUInt();\r
+ long skipN = streamDescriptorArrayOffset - 8L;\r
+ if (sbis.skip(skipN) < skipN) {\r
+ throw new EOFException("buffer underrun");\r
+ }\r
+ sbis.setBlock(0);\r
+ int encryptedStreamDescriptorCount = (int) leis.readUInt();\r
+ StreamDescriptorEntry entries[] = new StreamDescriptorEntry[encryptedStreamDescriptorCount];\r
+ for (int i = 0; i < encryptedStreamDescriptorCount; i++) {\r
+ StreamDescriptorEntry entry = new StreamDescriptorEntry();\r
+ entries[i] = entry;\r
+ entry.streamOffset = (int) leis.readUInt();\r
+ entry.streamSize = (int) leis.readUInt();\r
+ entry.block = leis.readUShort();\r
+ int nameSize = leis.readUByte();\r
+ entry.flags = leis.readUByte();\r
+ // boolean isStream = StreamDescriptorEntry.flagStream.isSet(entry.flags);\r
+ entry.reserved2 = leis.readInt();\r
+ entry.streamName = StringUtil.readUnicodeLE(leis, nameSize);\r
+ leis.readShort();\r
+ assert(entry.streamName.length() == nameSize);\r
+ }\r
+ \r
+ for (StreamDescriptorEntry entry : entries) {\r
+ sbis.seek(entry.streamOffset);\r
+ sbis.setBlock(entry.block);\r
+ InputStream is = new BoundedInputStream(sbis, entry.streamSize);\r
+ fsOut.createDocument(is, entry.streamName);\r
+ is.close();\r
+ }\r
+ } finally {\r
+ IOUtils.closeQuietly(leis);\r
+ IOUtils.closeQuietly(sbis);\r
}\r
-\r
- leis.close();\r
- sbis.close();\r
sbis = null;\r
return fsOut;\r
}\r
import org.apache.poi.openxml4j.util.ZipFileZipEntrySource;
import org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource;
import org.apache.poi.openxml4j.util.ZipSecureFile.ThresholdInputStream;
+import org.apache.poi.util.IOUtils;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.apache.poi.util.TempFile;
private static final String MIMETYPE = "mimetype";
private static final String SETTINGS_XML = "settings.xml";
- private static final POILogger logger = POILogFactory.getLogger(ZipPackage.class);
+ private static final POILogger LOG = POILogFactory.getLogger(ZipPackage.class);
/**
* Zip archive, as either a file on disk,
try {
this.contentTypeManager = new ZipContentTypeManager(null, this);
} catch (InvalidFormatException e) {
- logger.log(POILogger.WARN,"Could not parse ZipPackage", e);
+ LOG.log(POILogger.WARN,"Could not parse ZipPackage", e);
}
}
try {
this.zipArchive = new ZipInputStreamZipEntrySource(zis);
} catch (final IOException e) {
- try {
- zis.close();
- } catch (final IOException e2) {
- throw new IOException("Failed to close zip input stream while cleaning up. " + e.getMessage(), e2);
- }
+ IOUtils.closeQuietly(zis);
throw new IOException("Failed to read zip entry source", e);
}
}
if (access == PackageAccess.WRITE) {
throw new InvalidOperationException("Can't open the specified file: '" + file + "'", e);
}
- logger.log(POILogger.ERROR, "Error in zip file "+file+" - falling back to stream processing (i.e. ignoring zip central directory)");
+ LOG.log(POILogger.ERROR, "Error in zip file "+file+" - falling back to stream processing (i.e. ignoring zip central directory)");
ze = openZipEntrySourceStream(file);
}
this.zipArchive = ze;
// read from the file input stream
return openZipEntrySourceStream(fis);
} catch (final Exception e) {
- try {
- // abort: close the file input stream
- fis.close();
- } catch (final IOException e2) {
- throw new InvalidOperationException("Could not close the specified file input stream from file: '" + file + "'", e2);
+ // abort: close the file input stream
+ IOUtils.closeQuietly(fis);
+ if (e instanceof InvalidOperationException) {
+ throw (InvalidOperationException)e;
+ } else {
+ throw new InvalidOperationException("Failed to read the file input stream from file: '" + file + "'", e);
}
- throw new InvalidOperationException("Failed to read the file input stream from file: '" + file + "'", e);
}
}
// read from the zip input stream
return openZipEntrySourceStream(zis);
} catch (final Exception e) {
- try {
- // abort: close the zip input stream
- zis.close();
- } catch (final IOException e2) {
- throw new InvalidOperationException("Failed to read the zip entry source stream and could not close the zip input stream", e2);
+ // abort: close the zip input stream
+ IOUtils.closeQuietly(zis);
+ if (e instanceof InvalidOperationException) {
+ throw (InvalidOperationException)e;
+ } else {
+ throw new InvalidOperationException("Failed to read the zip entry source stream", e);
}
- throw new InvalidOperationException("Failed to read the zip entry source stream", e);
}
}
// Fallback exception
throw new InvalidFormatException(
- "Package should contain a content type part [M1.13]");
+ "Package should contain a content type part [M1.13]");
}
// Now create all the relationships
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
PackagePartName partName = buildPartName(entry);
- if(partName == null) continue;
+ if(partName == null) {
+ continue;
+ }
// Only proceed for Relationships at this stage
String contentType = contentTypeManager.getContentType(partName);
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
PackagePartName partName = buildPartName(entry);
- if(partName == null) continue;
+ if(partName == null) {
+ continue;
+ }
String contentType = contentTypeManager.getContentType(partName);
if (contentType != null && contentType.equals(ContentTypes.RELATIONSHIPS_PART)) {
}
} else {
throw new InvalidFormatException(
- "The part "
- + partName.getURI().getPath()
- + " does not have any content type ! Rule: Package require content types when retrieving a part from a package. [M.1.14]");
+ "The part " + partName.getURI().getPath()
+ + " does not have any content type ! Rule: Package require content types when retrieving a part from a package. [M.1.14]");
}
}
.getOPCNameFromZipItemName(entry.getName()));
} catch (Exception e) {
// We assume we can continue, even in degraded mode ...
- logger.log(POILogger.WARN,"Entry "
+ LOG.log(POILogger.WARN,"Entry "
+ entry.getName()
+ " is not valid, so this part won't be add to the package.", e);
return null;
@Override
protected PackagePart createPartImpl(PackagePartName partName,
String contentType, boolean loadRelationships) {
- if (contentType == null)
+ if (contentType == null) {
throw new IllegalArgumentException("contentType");
+ }
- if (partName == null)
+ if (partName == null) {
throw new IllegalArgumentException("partName");
+ }
try {
- return new MemoryPackagePart(this, partName, contentType,
- loadRelationships);
+ return new MemoryPackagePart(this, partName, contentType, loadRelationships);
} catch (InvalidFormatException e) {
- logger.log(POILogger.WARN, e);
+ LOG.log(POILogger.WARN, e);
return null;
}
}
*/
@Override
protected void removePartImpl(PackagePartName partName) {
- if (partName == null)
+ if (partName == null) {
throw new IllegalArgumentException("partUri");
+ }
}
/**
// Flush the package
flush();
+ if (this.originalPackagePath == null || "".equals(this.originalPackagePath)) {
+ return;
+ }
+
// Save the content
- if (this.originalPackagePath != null
- && !"".equals(this.originalPackagePath)) {
- File targetFile = new File(this.originalPackagePath);
- if (targetFile.exists()) {
- // Case of a package previously open
-
- File tempFile = TempFile.createTempFile(
- generateTempFileName(FileHelper
- .getDirectory(targetFile)), ".tmp");
-
- // Save the final package to a temporary file
- try {
- save(tempFile);
- } finally {
- try {
- // Close the current zip file, so we can
- // overwrite it on all platforms
- this.zipArchive.close();
- // Copy the new file over the old one
- FileHelper.copyFile(tempFile, targetFile);
- } finally {
- // Either the save operation succeed or not, we delete the
- // temporary file
- if (!tempFile.delete()) {
- logger
- .log(POILogger.WARN,"The temporary file: '"
- + targetFile.getAbsolutePath()
- + "' cannot be deleted ! Make sure that no other application use it.");
- }
- }
+ File targetFile = new File(this.originalPackagePath);
+ if (!targetFile.exists()) {
+ throw new InvalidOperationException(
+ "Can't close a package not previously open with the open() method !");
+ }
+
+ // Case of a package previously open
+ String tempFileName = generateTempFileName(FileHelper.getDirectory(targetFile));
+ File tempFile = TempFile.createTempFile(tempFileName, ".tmp");
+
+ // Save the final package to a temporary file
+ try {
+ save(tempFile);
+ } finally {
+ // Close the current zip file, so we can overwrite it on all platforms
+ IOUtils.closeQuietly(this.zipArchive);
+ try {
+ // Copy the new file over the old one
+ FileHelper.copyFile(tempFile, targetFile);
+ } finally {
+ // Either the save operation succeed or not, we delete the temporary file
+ if (!tempFile.delete()) {
+ LOG.log(POILogger.WARN, "The temporary file: '"
+ + targetFile.getAbsolutePath()
+ + "' cannot be deleted ! Make sure that no other application use it.");
}
- } else {
- throw new InvalidOperationException(
- "Can't close a package not previously open with the open() method !");
}
- }
+ }
}
/**
@Override
protected void revertImpl() {
try {
- if (this.zipArchive != null)
- this.zipArchive.close();
+ if (this.zipArchive != null) {
+ this.zipArchive.close();
+ }
} catch (IOException e) {
// Do nothing, user dont have to know
}
final ZipOutputStream zos;
try {
- if (!(outputStream instanceof ZipOutputStream))
- zos = new ZipOutputStream(outputStream);
- else
- zos = (ZipOutputStream) outputStream;
+ if (!(outputStream instanceof ZipOutputStream)) {
+ zos = new ZipOutputStream(outputStream);
+ } else {
+ zos = (ZipOutputStream) outputStream;
+ }
// If the core properties part does not exist in the part list,
// we save it as well
if (this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size() == 0 &&
this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES_ECMA376).size() == 0 ) {
- logger.log(POILogger.DEBUG,"Save core properties part");
+ LOG.log(POILogger.DEBUG,"Save core properties part");
// Ensure that core properties are added if missing
getPackageProperties();
}
// Save package relationships part.
- logger.log(POILogger.DEBUG,"Save package relationships");
+ LOG.log(POILogger.DEBUG,"Save package relationships");
ZipPartMarshaller.marshallRelationshipPart(this.getRelationships(),
PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME,
zos);
// Save content type part.
- logger.log(POILogger.DEBUG,"Save content types part");
+ LOG.log(POILogger.DEBUG,"Save content types part");
this.contentTypeManager.save(zos);
// Save parts.
for (PackagePart part : getParts()) {
// If the part is a relationship part, we don't save it, it's
// the source part that will do the job.
- if (part.isRelationshipPart())
- continue;
-
- logger.log(POILogger.DEBUG,"Save part '"
- + ZipHelper.getZipItemNameFromOPCName(part
- .getPartName().getName()) + "'");
- PartMarshaller marshaller = partMarshallers
- .get(part._contentType);
+ if (part.isRelationshipPart()) {
+ continue;
+ }
+
+ final PackagePartName ppn = part.getPartName();
+ LOG.log(POILogger.DEBUG,"Save part '" + ZipHelper.getZipItemNameFromOPCName(ppn.getName()) + "'");
+ PartMarshaller marshaller = partMarshallers.get(part._contentType);
+ String errMsg = "The part " + ppn.getURI() + " failed to be saved in the stream with marshaller ";
+
if (marshaller != null) {
if (!marshaller.marshall(part, zos)) {
- throw new OpenXML4JException(
- "The part "
- + part.getPartName().getURI()
- + " fail to be saved in the stream with marshaller "
- + marshaller);
+ throw new OpenXML4JException(errMsg + marshaller);
}
} else {
- if (!defaultPartMarshaller.marshall(part, zos))
- throw new OpenXML4JException(
- "The part "
- + part.getPartName().getURI()
- + " fail to be saved in the stream with marshaller "
- + defaultPartMarshaller);
+ if (!defaultPartMarshaller.marshall(part, zos)) {
+ throw new OpenXML4JException(errMsg + defaultPartMarshaller);
+ }
}
}
zos.close();
throw e;
} catch (Exception e) {
throw new OpenXML4JRuntimeException(
- "Fail to save: an error occurs while saving the package : "
- + e.getMessage(), e);
+ "Fail to save: an error occurs while saving the package : "
+ + e.getMessage(), e);
}
}
* and {@link #setMinInflateRatio(double)}.\r
*/\r
public class ZipSecureFile extends ZipFile {\r
- private final static POILogger logger = POILogFactory.getLogger(ZipSecureFile.class);\r
+ private static final POILogger LOG = POILogFactory.getLogger(ZipSecureFile.class);\r
\r
private static double MIN_INFLATE_RATIO = 0.01d;\r
private static long MAX_ENTRY_SIZE = 0xFFFFFFFFL;\r
public static ThresholdInputStream addThreshold(final InputStream zipIS) throws IOException {\r
ThresholdInputStream newInner;\r
if (zipIS instanceof InflaterInputStream) {\r
- newInner = AccessController.doPrivileged(new PrivilegedAction<ThresholdInputStream>() {\r
+ newInner = AccessController.doPrivileged(new PrivilegedAction<ThresholdInputStream>() { // NOSONAR\r
@SuppressForbidden("TODO: Fix this to not use reflection (it will break in Java 9)! " +\r
- "Better would be to wrap *before* instead of tyring to insert wrapper afterwards.")\r
+ "Better would be to wrap *before* instead of trying to insert wrapper afterwards.")\r
public ThresholdInputStream run() {\r
try {\r
Field f = FilterInputStream.class.getDeclaredField("in");\r
f.set(zipIS, newInner);\r
return newInner;\r
} catch (Exception ex) {\r
- logger.log(POILogger.WARN, "SecurityManager doesn't allow manipulation via reflection for zipbomb detection - continue with original input stream", ex);\r
+ LOG.log(POILogger.WARN, "SecurityManager doesn't allow manipulation via reflection for zipbomb detection - continue with original input stream", ex);\r
}\r
return null;\r
}\r
// FIXME: A better exception class (IOException?) and message should be raised
// indicating that the document could not be written because the output stream is closed.
// see {@link org.apache.poi.openxml4j.opc.ZipPackage#saveImpl(java.io.OutputStream)}
- if (e.getMessage().matches("Fail to save: an error occurs while saving the package : The part .+ fail to be saved in the stream with marshaller .+")) {
+ if (e.getMessage().matches("Fail to save: an error occurs while saving the package : The part .+ failed to be saved in the stream with marshaller .+")) {
// expected
} else {
throw e;
thread.setContextClassLoader(cl.getParent());
XMLSlideShow ppt = new XMLSlideShow(is);
ppt.getSlides().get(0).getShapes();
+ ppt.close();
} finally {
thread.setContextClassLoader(cl);
is.close();
POIXMLTypeLoader.setClassLoader(cl);
XMLSlideShow ppt = new XMLSlideShow(is);
ppt.getSlides().get(0).getShapes();
+ ppt.close();
} finally {
thread.setContextClassLoader(cl);
POIXMLTypeLoader.setClassLoader(null);
import org.apache.poi.hwpf.sprm.SprmBuffer;
import org.apache.poi.util.Internal;
import org.apache.poi.util.LittleEndian;
+import org.apache.poi.util.RecordFormatException;
/**
* Represents a CHP fkp. The style properties for paragraph and character runs
* {@link #CHPFormattedDiskPage(byte[], int, CharIndexTranslator)}
* instead
*/
+ @Deprecated
public CHPFormattedDiskPage( byte[] documentStream, int offset, int fcMin,
TextPieceTable tpt )
{
* @param index The index of the chpx to get.
* @return a chpx grpprl.
*/
+ @Override
protected byte[] getGrpprl(int index)
{
int chpxOffset = 2 * LittleEndian.getUByte(_fkp, _offset + (((_crun + 1) * 4) + index));
// the grpprl size byte and the grpprl.
totalSize += ( FC_SIZE + 2 + grpprlLength );
// if size is uneven we will have to add one so the first grpprl
- // falls
- // on a word boundary
+ // falls on a word boundary
if ( totalSize > 511 + ( index % 2 ) )
{
totalSize -= ( FC_SIZE + 2 + grpprlLength );
}
}
+ if (index == 0) {
+ throw new RecordFormatException("empty grpprl entry.");
+ }
+
// see if we couldn't fit some
if ( index != size )
{
offsetOffset = ( FC_SIZE * index ) + FC_SIZE;
// grpprlOffset = offsetOffset + index + (grpprlOffset % 2);
- CHPX chpx = null;
- for ( int x = 0; x < index; x++ )
- {
- chpx = _chpxList.get( x );
- byte[] grpprl = chpx.getGrpprl();
-
- LittleEndian.putInt( buf, fcOffset,
- translator.getByteIndex( chpx.getStart() ) );
+ int chpxEnd = 0;
+ for ( CHPX chpx : _chpxList.subList(0, index)) {
+ int chpxStart = translator.getByteIndex( chpx.getStart() );
+ chpxEnd = translator.getByteIndex( chpx.getEnd() );
+ LittleEndian.putInt( buf, fcOffset, chpxStart );
+ byte[] grpprl = chpx.getGrpprl();
grpprlOffset -= ( 1 + grpprl.length );
grpprlOffset -= ( grpprlOffset % 2 );
buf[offsetOffset] = (byte) ( grpprlOffset / 2 );
fcOffset += FC_SIZE;
}
// put the last chpx's end in
- LittleEndian.putInt( buf, fcOffset,
- translator.getByteIndex( chpx.getEnd() ) );
+ LittleEndian.putInt( buf, fcOffset, chpxEnd );
return buf;
}
* front that relate to an array of arbitrary data structures in the back.
* <p>
* See page 184 of official documentation for details
- *
- * @author Ryan Ackley
*/
public final class PlexOfCps {
private int _iMac;
- private int _offset;
private int _cbStruct;
private List<GenericPropertyNode> _props;
byte[] buf = new byte[bufSize];
- GenericPropertyNode node = null;
+ int nodeEnd = 0;
for (int x = 0; x < size; x++) {
- node = _props.get(x);
-
+ GenericPropertyNode node = _props.get(x);
+ nodeEnd = node.getEnd();
+
// put the starting offset of the property into the plcf.
- LittleEndian.putInt(buf, (LittleEndian.INT_SIZE * x),
- node.getStart());
+ LittleEndian.putInt(buf, (LittleEndian.INT_SIZE * x), node.getStart());
// put the struct into the plcf
- System.arraycopy(node.getBytes(), 0, buf, cpBufSize
- + (x * _cbStruct), _cbStruct);
+ System.arraycopy(node.getBytes(), 0, buf, cpBufSize + (x * _cbStruct), _cbStruct);
}
// put the ending offset of the last property into the plcf.
- LittleEndian.putInt(buf, LittleEndian.INT_SIZE * size, node.getEnd());
+ LittleEndian.putInt(buf, LittleEndian.INT_SIZE * size, nodeEnd);
return buf;
}
* DataStream
*/
public Picture( int dataBlockStartOfsset, byte[] _dataStream, boolean fillBytes ) { // NOSONAR
- _picfAndOfficeArtData = new PICFAndOfficeArtData( _dataStream,
- dataBlockStartOfsset );
+ _picfAndOfficeArtData = new PICFAndOfficeArtData( _dataStream, dataBlockStartOfsset );
_picf = _picfAndOfficeArtData.getPicf();
this.dataBlockStartOfsset = dataBlockStartOfsset;
- if ( _picfAndOfficeArtData != null && _picfAndOfficeArtData.getBlipRecords() != null) {
+ if ( _picfAndOfficeArtData.getBlipRecords() != null) {
_blipRecords = _picfAndOfficeArtData.getBlipRecords();
} else {
_blipRecords = Collections.emptyList();