import org.openxmlformats.schemas.presentationml.x2006.main.STTLTimeNodeRestartType;
import org.openxmlformats.schemas.presentationml.x2006.main.STTLTimeNodeType;
-public class LinkVideoToPptx {
- public static void main(String[] args) throws IOException, URISyntaxException {
- XMLSlideShow pptx = new XMLSlideShow();
-
- String videoFileName = "file_example_MP4_640_3MG.mp4";
- XSLFSlide slide1 = pptx.createSlide();
-
- PackagePart pp = slide1.getPackagePart();
- URI mp4uri = new URI("./"+videoFileName);
- PackageRelationship prsEmbed1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.microsoft.com/office/2007/relationships/media");
- PackageRelationship prsExec1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video");
-
-
- File previewJpg = new File("preview.jpg");
- XSLFPictureData snap = pptx.addPicture(previewJpg, PictureData.PictureType.JPEG);
- XSLFPictureShape pic1 = slide1.createPicture(snap);
- pic1.setAnchor(new Rectangle(100, 100, 500, 400));
-
- CTPicture xpic1 = (CTPicture)pic1.getXmlObject();
- CTHyperlink link1 = xpic1.getNvPicPr().getCNvPr().addNewHlinkClick();
- link1.setId("");
- link1.setAction("ppaction://media");
-
-
- CTApplicationNonVisualDrawingProps nvPr = xpic1.getNvPicPr().getNvPr();
- nvPr.addNewVideoFile().setLink(prsExec1.getId());
- CTExtension ext = nvPr.addNewExtLst().addNewExt();
- ext.setUri("{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}");
-
- String p14Ns = "http://schemas.microsoft.com/office/powerpoint/2010/main";
- XmlCursor cur = ext.newCursor();
- cur.toEndToken();
- cur.beginElement(new QName(p14Ns, "media", "p14"));
- cur.insertNamespace("p14", p14Ns);
- cur.insertAttributeWithValue(new QName(CORE_PROPERTIES_ECMA376_NS, "link"), prsEmbed1.getId());
- cur.dispose();
-
-
- CTSlide xslide = slide1.getXmlObject();
- CTTimeNodeList ctnl;
- if (!xslide.isSetTiming()) {
- CTTLCommonTimeNodeData ctn = xslide.addNewTiming().addNewTnLst().addNewPar().addNewCTn();
- ctn.setDur(STTLTimeIndefinite.INDEFINITE);
- ctn.setRestart(STTLTimeNodeRestartType.NEVER);
- ctn.setNodeType(STTLTimeNodeType.TM_ROOT);
- ctnl = ctn.addNewChildTnLst();
- } else {
- ctnl = xslide.getTiming().getTnLst().getParArray(0).getCTn().getChildTnLst();
- }
- CTTLCommonMediaNodeData cmedia = ctnl.addNewVideo().addNewCMediaNode();
- cmedia.setVol(80000);
- CTTLCommonTimeNodeData ctn = cmedia.addNewCTn();
- ctn.setFill(STTLTimeNodeFillType.HOLD);
- ctn.setDisplay(false);
- ctn.addNewStCondLst().addNewCond().setDelay(STTLTimeIndefinite.INDEFINITE);
- cmedia.addNewTgtEl().addNewSpTgt().setSpid(pic1.getShapeId());
+public final class LinkVideoToPptx {
+ private LinkVideoToPptx() {}
-
- try (FileOutputStream fos = new FileOutputStream("mp4test/mp4test-poi.pptx")) {
- pptx.write(fos);
+ public static void main(String[] args) throws IOException, URISyntaxException {
+ try (XMLSlideShow pptx = new XMLSlideShow()) {
+
+ String videoFileName = "file_example_MP4_640_3MG.mp4";
+ XSLFSlide slide1 = pptx.createSlide();
+
+ PackagePart pp = slide1.getPackagePart();
+ URI mp4uri = new URI("./" + videoFileName);
+ PackageRelationship prsEmbed1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.microsoft.com/office/2007/relationships/media");
+ PackageRelationship prsExec1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video");
+
+
+ File previewJpg = new File("preview.jpg");
+ XSLFPictureData snap = pptx.addPicture(previewJpg, PictureData.PictureType.JPEG);
+ XSLFPictureShape pic1 = slide1.createPicture(snap);
+ pic1.setAnchor(new Rectangle(100, 100, 500, 400));
+
+ CTPicture xpic1 = (CTPicture) pic1.getXmlObject();
+ CTHyperlink link1 = xpic1.getNvPicPr().getCNvPr().addNewHlinkClick();
+ link1.setId("");
+ link1.setAction("ppaction://media");
+
+
+ CTApplicationNonVisualDrawingProps nvPr = xpic1.getNvPicPr().getNvPr();
+ nvPr.addNewVideoFile().setLink(prsExec1.getId());
+ CTExtension ext = nvPr.addNewExtLst().addNewExt();
+ ext.setUri("{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}");
+
+ String p14Ns = "http://schemas.microsoft.com/office/powerpoint/2010/main";
+ XmlCursor cur = ext.newCursor();
+ cur.toEndToken();
+ cur.beginElement(new QName(p14Ns, "media", "p14"));
+ cur.insertNamespace("p14", p14Ns);
+ cur.insertAttributeWithValue(new QName(CORE_PROPERTIES_ECMA376_NS, "link"), prsEmbed1.getId());
+ cur.dispose();
+
+
+ CTSlide xslide = slide1.getXmlObject();
+ CTTimeNodeList ctnl;
+ if (!xslide.isSetTiming()) {
+ CTTLCommonTimeNodeData ctn = xslide.addNewTiming().addNewTnLst().addNewPar().addNewCTn();
+ ctn.setDur(STTLTimeIndefinite.INDEFINITE);
+ ctn.setRestart(STTLTimeNodeRestartType.NEVER);
+ ctn.setNodeType(STTLTimeNodeType.TM_ROOT);
+ ctnl = ctn.addNewChildTnLst();
+ } else {
+ ctnl = xslide.getTiming().getTnLst().getParArray(0).getCTn().getChildTnLst();
+ }
+ CTTLCommonMediaNodeData cmedia = ctnl.addNewVideo().addNewCMediaNode();
+ cmedia.setVol(80000);
+ CTTLCommonTimeNodeData ctn = cmedia.addNewCTn();
+ ctn.setFill(STTLTimeNodeFillType.HOLD);
+ ctn.setDisplay(false);
+ ctn.addNewStCondLst().addNewCond().setDelay(STTLTimeIndefinite.INDEFINITE);
+ cmedia.addNewTgtEl().addNewSpTgt().setSpid(pic1.getShapeId());
+
+
+ try (FileOutputStream fos = new FileOutputStream("mp4test/mp4test-poi.pptx")) {
+ pptx.write(fos);
+ }
}
}
}
/**
* This class encapsulates the Strings necessary to create the User Defined
* Function instances that will be passed to POI's Evaluator instance.
- *
+ *
* @author Jon Svede ( jon [at] loquatic [dot] com )
* @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
*
*/
public class ExcelAntUserDefinedFunction extends Typedef {
-
- public String functionAlias ;
-
- public String className ;
-
+ private String functionAlias ;
+
+ private String className ;
+
+
public ExcelAntUserDefinedFunction() {}
protected String getFunctionAlias() {
return createExtractor(file, getCurrentUserPassword());
}
+ @SuppressWarnings({"java:S2095"})
public static POITextExtractor createExtractor(File file, String password) throws IOException {
if (file.length() == 0) {
throw new EmptyFileException();
}
public static void removeProvider(Class<? extends ExtractorProvider> provider){
- Singleton.INSTANCE.provider.removeIf(p -> p.getClass().getName().equals(provider.getName()));
+ Singleton.INSTANCE.provider.removeIf(p -> p.getClass().isAssignableFrom(provider));
}
}
return FileMagic.OLE2 == fm;
}
+ @SuppressWarnings({"java:S2095"})
@Override
public POITextExtractor create(File file, String password) throws IOException {
return create(new POIFSFileSystem(file, true).getRoot(), password);
public static void main(String[] args) throws Exception {
boolean initDrawing = false;
boolean saveToMemory = false;
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
for(String filename : args) {
if(filename.equals("-dg")) {
initDrawing = true;
saveToMemory = true;
} else {
System.out.print("reading " + filename + "...");
- FileInputStream is = new FileInputStream(filename);
- HSSFWorkbook wb = new HSSFWorkbook(is);
- try {
+ try (FileInputStream is = new FileInputStream(filename);
+ HSSFWorkbook wb = new HSSFWorkbook(is)) {
System.out.println("done");
-
+
for(int i = 0; i < wb.getNumberOfSheets(); i++){
HSSFSheet sheet = wb.getSheetAt(i);
if(initDrawing) {
}
}
- OutputStream os;
- if (saveToMemory) {
- bos.reset();
- os = bos;
- } else {
- String outputFile = filename.replace(".xls", "-saved.xls");
+ String outputFile = filename.replace(".xls", "-saved.xls");
+ if (!saveToMemory) {
System.out.print("saving to " + outputFile + "...");
- os = new FileOutputStream(outputFile);
}
-
- try {
+
+ try (OutputStream os = saveToMemory ? new ByteArrayOutputStream() : new FileOutputStream(outputFile)) {
wb.write(os);
- } finally {
- os.close();
}
System.out.println("done");
- } finally {
- wb.close();
- is.close();
}
}
}
// Can be a few short if new sheets were added
if(records.getTabpos() > 0) {
TabIdRecord tir = ( TabIdRecord ) records.get(records.getTabpos());
- if(tir._tabids.length < boundsheets.size()) {
+ if(tir.getTabIdSize() < boundsheets.size()) {
fixTabIdRecord();
}
}
*/
public final class GridsetRecord extends StandardRecord {
public static final short sid = 0x82;
- public short field_1_gridset_flag;
+ private short field_1_gridset_flag;
public GridsetRecord() {}
public static final class Break implements GenericRecord {
public static final int ENCODED_SIZE = 6;
- public int main;
- public int subFrom;
- public int subTo;
+ private int main;
+ private int subFrom;
+ private int subTo;
public Break(Break other) {
main = other.main;
subTo = in.readUShort();
}
+ public int getMain() {
+ return main;
+ }
+
+ public int getSubFrom() {
+ return subFrom;
+ }
+
+ public int getSubTo() {
+ return subTo;
+ }
+
public void serialize(LittleEndianOutput out) {
out.writeShort(main + 1);
out.writeShort(subFrom);
public final class PrecisionRecord extends StandardRecord {
public static final short sid = 0xE;
- public short field_1_precision;
+ private short field_1_precision;
public PrecisionRecord() {}
public static final short sid = 0x013D;
private static final short[] EMPTY_SHORT_ARRAY = { };
- public short[] _tabids;
+ private short[] _tabids;
public TabIdRecord() {
_tabids = EMPTY_SHORT_ARRAY;
}
}
+ public int getTabIdSize() {
+ return _tabids.length;
+ }
+
+ public short getTabIdAt(int index) {
+ return _tabids[index];
+ }
+
protected int getDataSize() {
return _tabids.length * 2;
}
/**
* @param sid the record sid
- *
+ *
* @return <code>true</code> if the specified Record sid is one belonging to the
* 'Page Settings Block'.
*/
while(iterator.hasNext())
{
PageBreakRecord.Break breakItem = iterator.next();
- int breakLocation = breakItem.main;
+ int breakLocation = breakItem.getMain();
boolean inStart = (breakLocation >= start);
boolean inEnd = (breakLocation <= stop);
if(inStart && inEnd) {
iterator = shiftedBreak.iterator();
while (iterator.hasNext()) {
PageBreakRecord.Break breakItem = iterator.next();
- breaks.removeBreak(breakItem.main);
- breaks.addBreak((short)(breakItem.main+count), breakItem.subFrom, breakItem.subTo);
+ breaks.removeBreak(breakItem.getMain());
+ breaks.addBreak((short)(breakItem.getMain()+count), breakItem.getSubFrom(), breakItem.getSubTo());
}
}
/**
* Queries if the specified row has a page break
- *
+ *
* @param row the row to check for
- *
+ *
* @return true if the specified row has a page break
*/
public boolean isRowBroken(int row) {
/**
* Queries if the specified column has a page break
- *
+ *
* @param column the column to check for
*
* @return <code>true</code> if the specified column has a page break
/**
* HEADERFOOTER is new in 2007. Some apps seem to have scattered this record long after
* the {@link PageSettingsBlock} where it belongs.
- *
+ *
* @param rec the HeaderFooterRecord to set
*/
public void addLateHeaderFooter(HeaderFooterRecord rec) {
* This method reads PageSettingsBlock records from the supplied RecordStream until the first
* non-PageSettingsBlock record is encountered. As each record is read, it is incorporated
* into this PageSettingsBlock.<p>
- *
+ *
* The latest Excel version seems to write the PageSettingsBlock uninterrupted. However there
* are several examples (that Excel reads OK) where these records are not written together:
- *
+ *
* <ul>
* <li><b>HEADER_FOOTER(0x089C) after WINDOW2</b> - This record is new in 2007. Some apps
* seem to have scattered this record long after the PageSettingsBlock where it belongs
* This happens in the test sample file "NoGutsRecords.xls" and "WORKBOOK_in_capitals.xls"</li>
* <li><b>Margins after DIMENSION</b> - All of PSB should be before DIMENSION. (Bug-47199)</li>
* </ul>
- *
+ *
* These were probably written by other applications (or earlier versions of Excel). It was
* decided to not write specific code for detecting each of these cases. POI now tolerates
* PageSettingsBlock records scattered all over the sheet record stream, and in any order, but
* were when they were originally read.
*
* @param rs the RecordStream to read from
- *
+ *
* @throws org.apache.poi.util.RecordFormatException if any PSB record encountered has the same type (sid) as
* a record that is already part of this PageSettingsBlock
*/
public int hashCode() {
return Objects.hash(phoneticTextFirstCharacterOffset, realTextFirstCharacterOffset, realTextLength);
}
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ PhRun phRun = (PhRun) o;
+ return phoneticTextFirstCharacterOffset == phRun.phoneticTextFirstCharacterOffset
+ && realTextFirstCharacterOffset == phRun.realTextFirstCharacterOffset
+ && realTextLength == phRun.realTextLength;
+ }
}
int END_OF_CHAIN = -2;
/** Indicates the sector is not used (0xFFFFFFFF) */
int UNUSED_BLOCK = -1;
-
- /** The first 4 bytes of an OOXML file, used in detection */
- byte[] OOXML_FILE_HEADER =
- new byte[] { 0x50, 0x4b, 0x03, 0x04 };
- /** The first 5 bytes of a raw XML file, used in detection */
- byte[] RAW_XML_FILE_HEADER =
- new byte[] { 0x3c, 0x3f, 0x78, 0x6d, 0x6c };
-} // end public interface POIFSConstants;
+}
}
}
+ @SuppressWarnings({"java:S2095"})
@Override
public InputStream getDataStream(DirectoryNode dir) throws IOException, GeneralSecurityException {
DocumentInputStream dis = dir.createDocumentInputStream(DEFAULT_POIFS_ENTRY);
}
@Override
- @SuppressWarnings("resource")
+ @SuppressWarnings({"java:S2095","resource"})
public ChunkedCipherInputStream getDataStream(DirectoryNode dir) throws IOException,
GeneralSecurityException {
DocumentInputStream dis = dir.createDocumentInputStream(DEFAULT_POIFS_ENTRY);
package org.apache.poi.poifs.filesystem;
-import static org.apache.poi.poifs.common.POIFSConstants.OOXML_FILE_HEADER;
-import static org.apache.poi.poifs.common.POIFSConstants.RAW_XML_FILE_HEADER;
-
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
public enum FileMagic {
/** OLE2 / BIFF8+ stream used for Office 97 and higher documents */
OLE2(HeaderBlockConstants._signature),
- /** OOXML / ZIP stream */
- OOXML(OOXML_FILE_HEADER),
- /** XML file */
- XML(RAW_XML_FILE_HEADER),
+ /** OOXML / ZIP stream - The first 4 bytes of an OOXML file, used in detection */
+ OOXML(0x50, 0x4b, 0x03, 0x04),
+ /** XML file - The first 5 bytes of a raw XML file, used in detection */
+ XML(0x3c, 0x3f, 0x78, 0x6d, 0x6c),
/** BIFF2 raw stream - for Excel 2 */
- BIFF2(new byte[]{
+ BIFF2(
0x09, 0x00, // sid=0x0009
0x04, 0x00, // size=0x0004
0x00, 0x00, // unused
'?', 0x00 // '?' = multiple values
- }),
+ ),
/** BIFF3 raw stream - for Excel 3 */
- BIFF3(new byte[]{
+ BIFF3(
0x09, 0x02, // sid=0x0209
0x06, 0x00, // size=0x0006
0x00, 0x00, // unused
'?', 0x00 // '?' = multiple values
- }),
+ ),
/** BIFF4 raw stream - for Excel 4 */
BIFF4(new byte[]{
0x09, 0x04, // sid=0x0409
HTML("<!DOCTYP",
"<html","\n\r<html","\r\n<html","\r<html","\n<html",
"<HTML","\r\n<HTML","\n\r<HTML","\r<HTML","\n<HTML"),
- WORD2(new byte[]{ (byte)0xdb, (byte)0xa5, 0x2d, 0x00}),
+ WORD2(0xdb, 0xa5, 0x2d, 0x00),
/** JPEG image */
JPEG(
new byte[]{ (byte)0xFF, (byte)0xD8, (byte)0xFF, (byte)0xDB },
/** GIF image */
GIF("GIF87a","GIF89a"),
/** PNG Image */
- PNG(new byte[]{ (byte)0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A }),
+ PNG(0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A),
/** TIFF Image */
TIFF("II*\u0000", "MM\u0000*" ),
/** WMF image with a placeable header */
- WMF(new byte[]{ (byte)0xD7, (byte)0xCD, (byte)0xC6, (byte)0x9A }),
+ WMF(0xD7, 0xCD, 0xC6, 0x9A),
/** EMF image */
- EMF(new byte[]{
- 1, 0, 0, 0,
+ EMF(1, 0, 0, 0,
'?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?',
'?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?',
- ' ', 'E', 'M', 'F'
- }),
+ ' ', 'E', 'M', 'F'),
/** BMP image */
- BMP(new byte[]{'B','M'}),
+ BMP('B','M'),
// keep UNKNOWN always as last enum!
/** UNKNOWN magic */
UNKNOWN(new byte[0]);
LittleEndian.putLong(this.magic[0], 0, magic);
}
+ FileMagic(int... magic) {
+ byte[] one = new byte[magic.length];
+ for (int i=0; i<magic.length; i++) {
+ one[i] = (byte)(magic[i] & 0xFF);
+ }
+ this.magic = new byte[][]{ one };
+ }
+
FileMagic(byte[]... magic) {
this.magic = magic;
}
this(channel, null, readOnly, false);
}
+ @SuppressWarnings("java:S2095")
private POIFSFileSystem(FileChannel channel, File srcFile, boolean readOnly, boolean closeChannelOnError)
throws IOException {
this(false);
penY -= line.getLayout().getAscent();
}
- penX = x + (isHSLF ? leftMargin : leftMargin);
+ penX = x + leftMargin;
if (lastLine == null) {
if (!isEmptyParagraph()) {
// TODO: find out character style for empty, but bulleted/numbered lines
Singleton.INSTANCE.provider.add(provider);
}
- public static void removeProvider(Class<? extends SlideShowProvider> provider){
- Singleton.INSTANCE.provider.removeIf(p -> p.getClass().getName().equals(provider.getName()));
+ public static void removeProvider(Class<? extends SlideShowProvider<?,?>> provider){
+ Singleton.INSTANCE.provider.removeIf(p -> p.getClass().isAssignableFrom(provider));
}
}
package org.apache.poi.ss.formula;
public class SheetIdentifier {
- public String _bookName;
- public NameIdentifier _sheetIdentifier;
+ private final String _bookName;
+ private final NameIdentifier _sheetIdentifier;
public SheetIdentifier(String bookName, NameIdentifier sheetIdentifier) {
_bookName = bookName;
package org.apache.poi.ss.formula;
public class SheetRangeIdentifier extends SheetIdentifier {
- public NameIdentifier _lastSheetIdentifier;
+ private final NameIdentifier _lastSheetIdentifier;
public SheetRangeIdentifier(String bookName, NameIdentifier firstSheetIdentifier, NameIdentifier lastSheetIdentifier) {
super(bookName, firstSheetIdentifier);
/** day of month */
public final int day;
/** milliseconds since 1970 */
- public long tsMilliseconds;
+ public final long tsMilliseconds;
public SimpleDate(Calendar cal) {
year = cal.get(Calendar.YEAR);
}
public enum FUNCTION {INTERCEPT, SLOPE}
- public FUNCTION function;
+ private final FUNCTION function;
public LinearRegressionFunction(FUNCTION function) {
this.function = function;
*/
public final class Trend implements Function {
- MatrixFunction.MutableValueCollector collector = new MatrixFunction.MutableValueCollector(false, false);
private static final class TrendResults {
- public double[] vals;
- public int resultWidth;
- public int resultHeight;
+ private final double[] vals;
+ private final int resultWidth;
+ private final int resultHeight;
public TrendResults(double[] vals, int resultWidth, int resultHeight) {
this.vals = vals;
}
double[] oneD = new double[twoD.length * twoD[0].length];
for (int i = 0; i < twoD.length; i++) {
- System.arraycopy(twoD[i], 0, oneD, i * twoD[0].length + 0, twoD[0].length);
+ System.arraycopy(twoD[i], 0, oneD, i * twoD[0].length, twoD[0].length);
}
return oneD;
}
if(isAllColumnsSame(x)){
double[] result = new double[newX.length];
double avg = Arrays.stream(y).average().orElse(0);
- for(int i = 0; i < result.length; i++) result[i] = avg;
+ Arrays.fill(result, avg);
return new TrendResults(result, resultWidth, resultHeight);
}
}
public static void removeProvider(Class<? extends WorkbookProvider> provider){
- Singleton.INSTANCE.provider.removeIf(p -> p.getClass().getName().equals(provider.getName()));
+ Singleton.INSTANCE.provider.removeIf(p -> p.getClass().isAssignableFrom(provider));
}
}
package org.apache.poi.ss.util.cellwalk;
+import static org.apache.commons.math3.util.ArithmeticUtils.addAndCheck;
+import static org.apache.commons.math3.util.ArithmeticUtils.mulAndCheck;
+import static org.apache.commons.math3.util.ArithmeticUtils.subAndCheck;
+
import org.apache.commons.math3.util.ArithmeticUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
/**
* Traverse cell range.
- *
- * @author Roman Kashitsyn
*/
public class CellWalk {
- private Sheet sheet;
- private CellRangeAddress range;
+ private final Sheet sheet;
+ private final CellRangeAddress range;
private boolean traverseEmptyCells;
int lastColumn = range.getLastColumn();
final int width = lastColumn - firstColumn + 1;
SimpleCellWalkContext ctx = new SimpleCellWalkContext();
- Row currentRow = null;
- Cell currentCell = null;
+ Row currentRow;
+ Cell currentCell;
for (ctx.rowNumber = firstRow; ctx.rowNumber <= lastRow; ++ctx.rowNumber) {
currentRow = sheet.getRow(ctx.rowNumber);
continue;
}
- long rowSize = ArithmeticUtils.mulAndCheck(
- (long)ArithmeticUtils.subAndCheck(ctx.rowNumber, firstRow), (long)width);
+ long rowSize = mulAndCheck(subAndCheck(ctx.rowNumber, firstRow), (long)width);
- ctx.ordinalNumber = ArithmeticUtils.addAndCheck(rowSize, (ctx.colNumber - firstColumn + 1));
+ ctx.ordinalNumber = addAndCheck(rowSize, (ctx.colNumber - firstColumn + 1));
handler.onCell(currentCell, ctx);
}
/**
* Inner class to hold walk context.
- *
- * @author Roman Kashitsyn
*/
private static class SimpleCellWalkContext implements CellWalkContext {
- public long ordinalNumber;
- public int rowNumber;
- public int colNumber;
+ private long ordinalNumber;
+ private int rowNumber;
+ private int colNumber;
@Override
public long getOrdinalNumber() {
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.util;
import java.io.File;
}
public static void main( String[] args ) throws IOException {
- OutputStreamWriter osw = new OutputStreamWriter(System.out, Charset.defaultCharset());
- PrintWriter pw = new PrintWriter(osw);
- POIFSFileSystem fs = new POIFSFileSystem(new File(args[0]));
- HSSFWorkbook wb = new HSSFWorkbook(fs);
- try {
+ try (OutputStreamWriter osw = new OutputStreamWriter(System.out, Charset.defaultCharset());
+ PrintWriter pw = new PrintWriter(osw);
+ POIFSFileSystem fs = new POIFSFileSystem(new File(args[0]));
+ HSSFWorkbook wb = new HSSFWorkbook(fs)) {
+
pw.println( "Drawing group:" );
wb.dumpDrawingGroupRecords(true);
-
+
int i = 1;
for (Sheet sheet : wb)
{
pw.println( "Sheet " + i + "(" + sheet.getSheetName() + "):" );
((HSSFSheet) sheet).dumpDrawingRecords(true, pw);
}
- } finally {
- wb.close();
- fs.close();
}
}
}
* @return A byte array with the read bytes.
* @throws IOException If reading data fails or EOF is encountered too early for the given length.
*/
- public static byte[] toByteArray(InputStream stream, final long length, final int maxLength) throws IOException {
+ public static byte[] toByteArray(InputStream stream, final int length, final int maxLength) throws IOException {
if (length < 0L || maxLength < 0L) {
throw new RecordFormatException("Can't allocate an array of length < 0");
}
- if (length > (long)Integer.MAX_VALUE) {
- throw new RecordFormatException("Can't allocate an array > "+Integer.MAX_VALUE);
- }
+ // if (length > (long)Integer.MAX_VALUE) {
+ // throw new RecordFormatException("Can't allocate an array > "+Integer.MAX_VALUE);
+ // }
if ((length != Integer.MAX_VALUE) || (maxLength != Integer.MAX_VALUE)) {
checkLength(length, maxLength);
}
return ExtractorFactory.createExtractor(f, password);
}
-
OPCPackage pkg = null;
try {
pkg = OPCPackage.open(f.toString(), PackageAccess.READ);
} catch (InvalidFormatException ife) {
throw new IOException(ife);
} catch (IOException e) {
- pkg.revert();
+ if (pkg != null) {
+ pkg.revert();
+ }
throw e;
}
}
import java.util.LinkedList;
import java.util.ListIterator;
-/**
- * <p>
- * 24.08.2009<br>
- * </p>
- *
- * @author Stefan Stern<br>
- */
-
public class IdentifierManager {
public static final long MAX_ID = Long.MAX_VALUE - 1;
-
public static final long MIN_ID = 0L;
- /**
- *
- */
private final long upperbound;
-
- /**
- *
- */
private final long lowerbound;
/**
if (lowerbound > upperbound) {
throw new IllegalArgumentException("lowerbound must not be greater than upperbound, had " + lowerbound + " and " + upperbound);
}
- else if (lowerbound < MIN_ID) {
+ else if (lowerbound < MIN_ID) {
String message = "lowerbound must be greater than or equal to " + Long.toString(MIN_ID);
throw new IllegalArgumentException(message);
}
throw new IllegalArgumentException("Value for parameter 'id' was out of bounds, had " + id + ", but should be within [" + lowerbound + ":" + upperbound + "]");
}
verifyIdentifiersLeft();
-
+
if (id == upperbound) {
Segment lastSegment = segments.getLast();
if (lastSegment.end == upperbound) {
}
/**
- * @return a new identifier.
+ * @return a new identifier.
* @throws IllegalStateException if no more identifiers are available, then an Exception is raised.
*/
public long reserveNew() {
}
/**
- *
+ *
*/
private void verifyIdentifiersLeft() {
if (segments.isEmpty()) {
}
private static class Segment {
+ private long start;
+ private long end;
public Segment(long start, long end) {
this.start = start;
this.end = end;
}
- public long start;
- public long end;
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#toString()
- */
public String toString() {
return "[" + start + "; " + end + "]";
}
int mpos = measurer.getPosition();
int limit = text.indexOf('\n', mpos);
limit = (limit == -1) ? text.length() : limit+1;
- TextLayout textLayout = measurer.nextLayout(bi.getWidth()-10, limit, false);
+ TextLayout textLayout = measurer.nextLayout(bi.getWidth()-10f, limit, false);
if (lineNr != 1) {
y += textLayout.getAscent();
}
SPLINE_START("SplineStart", SplineStart::new)
;
- public String rowType;
- public Function<RowType, ? extends GeometryRow> constructor;
+ private final String rowType;
+ private final Function<RowType, ? extends GeometryRow> constructor;
GeometryRowTypes(String rowType, Function<RowType, ? extends GeometryRow> constructor) {
this.rowType = rowType;
ANNOTATION("Annotation", GenericSection::new),
ACTION_TAG("ActionTag", GenericSection::new);
- public String sectionType;
- public BiFunction<SectionType, XDGFSheet, ? extends XDGFSection> constructor;
+ private final String sectionType;
+ private final BiFunction<SectionType, XDGFSheet, ? extends XDGFSection> constructor;
XDGFSectionTypes(String sectionType, BiFunction<SectionType, XDGFSheet, ? extends XDGFSection> constructor) {
this.sectionType = sectionType;
_master = (EllipticalArcTo) row;
}
- public static int draw;
-
@Override
public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) {
log.println( "finalize():" );
g2D.dispose();
dispose();
+ super.finalize();
}
public Shape getClip() {
*/
@Internal
class XSSFBCellHeader {
- public static int length = 8;
+ public static final int length = 8;
/**
*
public void clearAllCachedResultValues() {
_tableCache = null;
}
-
+
private int convertFromExternalSheetIndex(int externSheetIndex) {
return externSheetIndex;
}
List<ExternalLinksTable> tables = _uBook.getExternalLinksTable();
int index = findExternalLinkIndex(bookName, tables);
if (index != -1) return index;
-
+
// Is it an absolute file reference?
if (bookName.startsWith("'file:///") && bookName.endsWith("'")) {
String relBookName = bookName.substring(bookName.lastIndexOf('/')+1);
relBookName = relBookName.substring(0, relBookName.length()-1); // Trailing '
-
+
// Try with this name
index = findExternalLinkIndex(relBookName, tables);
if (index != -1) return index;
-
+
// If we get here, it's got no associated proper links yet
// So, add the missing reference and return
// Note - this is really rather nasty...
tables.add(fakeLinkTable);
return tables.size(); // 1 based results, 0 = current workbook
}
-
+
// Not properly referenced
throw new RuntimeException("Book not linked for filename " + bookName);
}
* @param sheetIndex index of sheet if named range scope is limited to one sheet
* if named range scope is global to the workbook, sheetIndex is -1.
* @return If name is a named range in the workbook, returns
- * EvaluationName corresponding to that named range
+ * EvaluationName corresponding to that named range
* Returns null if there is no named range with the same name and scope in the workbook
*/
@Override
XSSFName nm = _uBook.getNameAt(i);
String nameText = nm.getNameName();
int nameSheetindex = nm.getSheetIndex();
- if (name.equalsIgnoreCase(nameText) &&
+ if (name.equalsIgnoreCase(nameText) &&
(nameSheetindex == -1 || nameSheetindex == sheetIndex)) {
return new Name(nm, i, this);
}
public String getSheetName(int sheetIndex) {
return _uBook.getSheetName(sheetIndex);
}
-
+
@Override
public ExternalName getExternalName(int externSheetIndex, int externNameIndex) {
throw new IllegalStateException("HSSF-style external references are not supported for XSSF");
// External reference - reference is 1 based, link table is 0 based
int linkNumber = externalWorkbookNumber - 1;
ExternalLinksTable linkTable = _uBook.getExternalLinksTable().get(linkNumber);
-
+
for (org.apache.poi.ss.usermodel.Name name : linkTable.getDefinedNames()) {
if (name.getNameName().equals(nameName)) {
// HSSF returns one sheet higher than normal, and various bits
// of the code assume that. So, make us match that behaviour!
int nameSheetIndex = name.getSheetIndex() + 1;
-
+
// TODO Return a more specialised form of this, see bug #56752
// Should include the cached values, for in case that book isn't available
// Should support XSSF stuff lookups
int nameIdx = _uBook.getNameIndex(nameName);
return new ExternalName(nameName, nameIdx, 0); // TODO Is this right?
}
-
+
}
/**
if (func != null) {
return new NameXPxg(null, name);
}
-
+
// Otherwise, try it as a named range
if (sheet == null) {
if (!_uBook.getNames(name).isEmpty()) {
}
return null;
}
- if (sheet._sheetIdentifier == null) {
+ if (sheet.getSheetIdentifier() == null) {
// Workbook + Named Range only
- int bookIndex = resolveBookIndex(sheet._bookName);
+ int bookIndex = resolveBookIndex(sheet.getBookName());
return new NameXPxg(bookIndex, null, name);
}
// Use the sheetname and process
- String sheetName = sheet._sheetIdentifier.getName();
-
- if (sheet._bookName != null) {
- int bookIndex = resolveBookIndex(sheet._bookName);
+ String sheetName = sheet.getSheetIdentifier().getName();
+
+ if (sheet.getBookName() != null) {
+ int bookIndex = resolveBookIndex(sheet.getBookName());
return new NameXPxg(bookIndex, sheetName, name);
} else {
return new NameXPxg(sheetName, name);
}
@Override
public Ptg get3DReferencePtg(CellReference cell, SheetIdentifier sheet) {
- if (sheet._bookName != null) {
- int bookIndex = resolveBookIndex(sheet._bookName);
+ if (sheet.getBookName() != null) {
+ int bookIndex = resolveBookIndex(sheet.getBookName());
return new Ref3DPxg(bookIndex, sheet, cell);
} else {
return new Ref3DPxg(sheet, cell);
}
@Override
public Ptg get3DReferencePtg(AreaReference area, SheetIdentifier sheet) {
- if (sheet._bookName != null) {
- int bookIndex = resolveBookIndex(sheet._bookName);
+ if (sheet.getBookName() != null) {
+ int bookIndex = resolveBookIndex(sheet.getBookName());
return new Area3DPxg(bookIndex, sheet, area);
} else {
return new Area3DPxg(sheet, area);
public String resolveNameXText(NameXPtg n) {
int idx = n.getNameIndex();
String name = null;
-
+
// First, try to find it as a User Defined Function
IndexedUDFFinder udfFinder = (IndexedUDFFinder)getUDFFinder();
name = udfFinder.getFunctionName(idx);
if (name != null) return name;
-
+
// Otherwise, try it as a named range
XSSFName xname = _uBook.getNameAt(idx);
if (xname != null) {
name = xname.getNameName();
}
-
+
return name;
}
// Internal reference
workbookName = null;
}
-
+
if (lastSheetName == null || firstSheetName.equals(lastSheetName)) {
return new ExternalSheet(workbookName, firstSheetName);
} else {
* Tables are cached for performance (formula evaluation looks them up by name repeatedly).
* After the first table lookup, adding or removing a table from the document structure will cause trouble.
* This is meant to be used on documents whose structure is essentially static at the point formulas are evaluated.
- *
+ *
* @param name the data table name (case-insensitive)
* @return The Data table in the workbook named <tt>name</tt>, or <tt>null</tt> if no table is named <tt>name</tt>.
* @since 3.15 beta 2
String lname = caseInsensitive(name);
return getTableCache().get(lname);
}
-
+
@Override
public UDFFinder getUDFFinder(){
return _uBook.getUDFFinder();
@Test
public void testPOIFSInvalid() {
- IOException ex = assertThrows(
- IOException.class,
- () -> ExtractorFactory.createExtractor(new POIFSFileSystem(txt))
- );
+ // Not really an Extractor test, but we'll leave it to test POIFS reaction anyway ...
+ IOException ex = assertThrows(IOException.class, () -> new POIFSFileSystem(txt));
assertTrue(ex.getMessage().contains("Invalid header signature; read 0x3D20726F68747541, expected 0xE11AB1A1E011CFD0"));
}
return FileMagic.OLE2 == fm;
}
+ @SuppressWarnings("java:S2095")
@Override
public POITextExtractor create(File file, String password) throws IOException {
return create(new POIFSFileSystem(file, true).getRoot(), password);
size += LittleEndianConsts.INT_SIZE;
}
- brushBytes = IOUtils.toByteArray(leis, dataSize-size, MAX_OBJECT_SIZE);
+ brushBytes = IOUtils.toByteArray(leis, (int)(dataSize-size), MAX_OBJECT_SIZE);
return dataSize;
}
// If the CMAP_LOOKUP flag in the optionsFlags field is set, each value in this array specifies a
// Unicode character. Otherwise, each value specifies an index to a character glyph in the EmfPlusFont
// object specified by the ObjectId value in Flags field.
- byte[] glyphBuf = IOUtils.toByteArray(leis, glyphCount*2L, MAX_OBJECT_SIZE);
+ byte[] glyphBuf = IOUtils.toByteArray(leis, glyphCount*2, MAX_OBJECT_SIZE);
glyphs = StringUtil.getFromUnicodeLE(glyphBuf);
size += glyphBuf.length;
long size = graphicsVersion.init(leis);
- objectDataBytes = IOUtils.toByteArray(leis, dataSize - size, MAX_OBJECT_SIZE);
+ objectDataBytes = IOUtils.toByteArray(leis, (int)(dataSize - size), MAX_OBJECT_SIZE);
return dataSize;
}
private final byte[] _header;
// Links to our more interesting children
- public org.apache.poi.hslf.record.RecordAtom embedAtom;
+ private org.apache.poi.hslf.record.RecordAtom embedAtom;
private ExOleObjAtom oleObjAtom;
private CString menuName;
private CString progId;
public final class TextHeaderAtom extends RecordAtom implements ParentAwareRecord {
public static final long _type = RecordTypes.TextHeaderAtom.typeID;
private byte[] _header;
- public org.apache.poi.hslf.record.RecordContainer parentRecord;
+ private org.apache.poi.hslf.record.RecordContainer parentRecord;
/** The kind of text it is */
private int textType;
* This is in WMF Format. You'll probably want to pass it to Apache Batik to
* turn it into a SVG that you can then display.
*/
- public ByteChunk attachRenderingWMF;
+ private ByteChunk attachRenderingWMF;
/**
* What the POIFS name of this attachment is.
*/
- private String poifsName;
+ private final String poifsName;
/** Holds all the chunks that were found. */
- private List<Chunk> allChunks = new ArrayList<>();
+ private final List<Chunk> allChunks = new ArrayList<>();
public AttachmentChunks(String poifsName) {
this.poifsName = poifsName;
PS_PUBLIC_STRINGS("00020329-0000-0000-C000-000000000046"),
PS_INTERNET_HEADERS("00020386-0000-0000-C000-000000000046");
- public ClassID classID;
+ private final ClassID classID;
PropertySetType(String uuid) {
classID = new ClassID(uuid);
}
+
+ public ClassID getClassID() {
+ return classID;
+ }
}
public enum PredefinedPropertySet {
PSETID_XML_EXTRACTED_ENTITIES("23239608-685D-4732-9C55-4C95CB4E8E33"),
PSETID_ATTACHMENT("96357F7F-59E1-47D0-99A7-46515C183B54");
- public ClassID classID;
+ private final ClassID classID;
PredefinedPropertySet(String uuid) {
classID = new ClassID(uuid);
}
+
+ public ClassID getClassID() {
+ return classID;
+ }
}
private ByteChunk guidStream;
/**
* Collection of convenience chunks for the Recip(ient) part of an outlook file.
- *
+ *
* If a message has multiple recipients, there will be several of these.
*/
public final class RecipientChunks implements ChunkGroupWithProperties {
public static final MAPIProperty RECIPIENT_DISPLAY_NAME = MAPIProperty.RECIPIENT_DISPLAY_NAME;
/** Our 0 based position in the list of recipients */
- public int recipientNumber;
+ private int recipientNumber;
/** TODO */
- public ByteChunk recipientSearchChunk;
+ private ByteChunk recipientSearchChunk;
/**
* The "name", which could be their name if an internal person, or their
* email address if an external person
*/
- public StringChunk recipientNameChunk;
+ private StringChunk recipientNameChunk;
/**
* The email address of the recipient, which could be in SMTP or SEARCH
* format, but isn't always present...
*/
- public StringChunk recipientEmailChunk;
+ private StringChunk recipientEmailChunk;
/**
* The smtp destination email address of the recipient, but isn't always
* present...
*/
- public StringChunk recipientSMTPChunk;
+ private StringChunk recipientSMTPChunk;
/**
* Normally EX or SMTP. Will generally affect where the email address ends
* up.
*/
- public StringChunk deliveryTypeChunk;
+ private StringChunk deliveryTypeChunk;
/**
* The display name of the recipient. Normally seems to hold the same value
* as in recipientNameChunk
*/
- public StringChunk recipientDisplayNameChunk;
+ private StringChunk recipientDisplayNameChunk;
/**
* Holds the fixed sized properties, and the pointers to the data of
* variable sized ones
}
}
+ public int getRecipientNumber() {
+ return recipientNumber;
+ }
+
+ public ByteChunk getRecipientSearchChunk() {
+ return recipientSearchChunk;
+ }
+
+ public StringChunk getRecipientNameChunk() {
+ return recipientNameChunk;
+ }
+
+ public StringChunk getRecipientEmailChunk() {
+ return recipientEmailChunk;
+ }
+
+ public StringChunk getRecipientSMTPChunk() {
+ return recipientSMTPChunk;
+ }
+
+ public StringChunk getDeliveryTypeChunk() {
+ return deliveryTypeChunk;
+ }
+
+ public StringChunk getRecipientDisplayNameChunk() {
+ return recipientDisplayNameChunk;
+ }
+
/**
* Tries to find their name, in whichever chunk holds it.
*/
protected Paint getHatchedFill() {
HwmfDrawProperties prop = getProperties();
BufferedImage pattern = getPatternFromLong(
- prop.getBrushHatch().pattern,
+ prop.getBrushHatch().getPattern(),
prop.getBackgroundColor().getColor(),
prop.getBrushColor().getColor(),
prop.getBkMode() == HwmfBkMode.TRANSPARENT
/** 1, Pixel is always 1 */
R2_WHITE(0x0010, HwmfBinaryRasterOp::R2_WHITE);
- public int opIndex;
- private BiConsumer<int[],int[]> op;
+ private final int opIndex;
+ private final BiConsumer<int[],int[]> op;
HwmfBinaryRasterOp(int opIndex, BiConsumer<int[],int[]> op) {
this.opIndex = opIndex;
this.op = op;
}
+ public int getOpIndex() {
+ return opIndex;
+ }
+
public static HwmfBinaryRasterOp valueOf(int opIndex) {
for (HwmfBinaryRasterOp bb : HwmfBinaryRasterOp.values()) {
if (bb.opIndex == opIndex) {
MXDC_ESCAPE(0x101A, WmfEscapeUnknownData::new),
/** Enables applications to include private procedures and other arbitrary data in documents. */
SPCLPASSTHROUGH2(0x11D8, WmfEscapeUnknownData::new);
-
- public int flag;
- public final Supplier<? extends HwmfEscape.HwmfEscapeData> constructor;
+
+ private final int flag;
+ private final Supplier<? extends HwmfEscape.HwmfEscapeData> constructor;
EscapeFunction(int flag, Supplier<? extends HwmfEscape.HwmfEscapeData> constructor) {
this.constructor = constructor;
}
+ public int getFlag() {
+ return flag;
+ }
+
+ public Supplier<? extends HwmfEscapeData> getConstructor() {
+ return constructor;
+ }
+
static EscapeFunction valueOf(int flag) {
for (EscapeFunction hs : values()) {
if (hs.flag == flag) return hs;
return null;
}
}
-
+
public interface HwmfEscapeData {
public int init(LittleEndianInputStream leis, long recordSize, EscapeFunction escapeFunction) throws IOException;
}
/**
- * A 16-bit unsigned integer that defines the escape function. The
+ * A 16-bit unsigned integer that defines the escape function. The
* value MUST be from the MetafileEscapes enumeration.
*/
private EscapeFunction escapeFunction;
public HwmfRecordType getWmfRecordType() {
return HwmfRecordType.escape;
}
-
+
@Override
public int init(LittleEndianInputStream leis, long recordSize, int recordFunction) throws IOException {
escapeFunction = EscapeFunction.valueOf(leis.readUShort());
@Override
public void draw(HwmfGraphics ctx) {
-
+
}
-
+
public String toString() {
return GenericRecordJsonWriter.marshal(this);
}
@Override
public int init(LittleEndianInputStream leis, long recordSize, EscapeFunction escapeFunction) throws IOException {
this.escapeFunction = escapeFunction;
- escapeDataBytes = IOUtils.toByteArray(leis,recordSize,MAX_OBJECT_SIZE);
+ escapeDataBytes = IOUtils.toByteArray(leis,(int)recordSize,MAX_OBJECT_SIZE);
return (int)recordSize;
}
if (commentIdentifier != EMF_COMMENT_IDENTIFIER) {
// there are some WMF implementation using this record as a MFCOMMENT or similar
// if the commentIdentifier doesn't match, then return immediately
- emfData = IOUtils.toByteArray(leis, recordSize-LittleEndianConsts.INT_SIZE, MAX_OBJECT_SIZE);
+ emfData = IOUtils.toByteArray(leis, (int)(recordSize-LittleEndianConsts.INT_SIZE), MAX_OBJECT_SIZE);
remainingBytes = emfData.length;
return (int)recordSize;
}
HS_DITHEREDBKCLR(0x000B, 0xAA55AA55AA55AA55L)
;
- int flag;
- public long pattern;
+ private final int flag;
+ private final long pattern;
HwmfHatchStyle(int flag, long pattern) {
this.flag = flag;
this.pattern = pattern;
}
+ public int getFlag() {
+ return flag;
+ }
+
+ public long getPattern() {
+ return pattern;
+ }
+
public static HwmfHatchStyle valueOf(int flag) {
for (HwmfHatchStyle hs : values()) {
if (hs.flag == flag) return hs;
public final int wmfFlag;
public final float[] dashes;
+
HwmfLineDash(int wmfFlag, float... dashes) {
this.wmfFlag = wmfFlag;
this.dashes = dashes;
private static final String OPS = "nxoa";
- public int opValue;
+ private final int opValue;
HwmfTernaryRasterOp(int opValue) {
this.opValue=opValue;
import org.apache.poi.util.Beta;
@Beta
-public interface FontReplacer
-{
- public class Triplet
- {
+public interface FontReplacer {
+ class Triplet {
public String fontName;
public boolean bold;
public boolean italic;
}
- public Triplet update( Triplet original );
+ Triplet update(Triplet original);
}
private static final POILogger log = POILogFactory
.getLogger( Picture.class );
- public static final byte[] COMPRESSED1 = { (byte) 0xFE, 0x78, (byte) 0xDA };
+ private static final byte[] COMPRESSED1 = { (byte) 0xFE, 0x78, (byte) 0xDA };
- public static final byte[] COMPRESSED2 = { (byte) 0xFE, 0x78, (byte) 0x9C };
+ private static final byte[] COMPRESSED2 = { (byte) 0xFE, 0x78, (byte) 0x9C };
- public static final byte[] IHDR = new byte[] { 'I', 'H', 'D', 'R' };
+ private static final byte[] IHDR = new byte[] { 'I', 'H', 'D', 'R' };
@Deprecated
private static final byte[] PNG = new byte[] { (byte) 0x89, 0x50, 0x4E,
} else {
_blipRecords = Collections.emptyList();
}
-
+
if ( fillBytes ) {
fillImageContent();
}
{
/*
* http://www.codecomments.com/archive281-2004-3-158083.html
- *
+ *
* Algorithm proposed by Patrick TJ McPhee:
- *
+ *
* read 2 bytes make sure they are 'ffd8'x repeatedly: read 2 bytes make
* sure the first one is 'ff'x if the second one is 'd9'x stop else if
* the second one is c0 or c2 (or possibly other values ...) skip 2
* bytes read one byte into depth read two bytes into height read two
* bytes into width else read two bytes into length skip forward
* length-2 bytes
- *
+ *
* Also used Ruby code snippet from:
* http://www.bigbold.com/snippets/posts/show/805 for reference
*/
/**
* Gets the initial width of the picture, in twips, prior to cropping or
* scaling.
- *
+ *
* @return the initial width of the picture in twips
*/
public int getDxaGoal()
/**
* Gets the initial height of the picture, in twips, prior to cropping or
* scaling.
- *
+ *
* @return the initial width of the picture in twips
*/
public int getDyaGoal()
/**
* Returns the MIME type for the image
- *
+ *
* @return MIME-type for known types of image or "image/unknown" if unknown
*/
public String getMimeType()
/**
* Returns picture's content as stored in the Word file, i.e. possibly in
* compressed form.
- *
+ *
* @return picture's content as it stored in Word file or an empty byte array
* if it cannot be read.
*/
EscherBlipRecord blip = ( (EscherBSERecord) escherRecord ).getBlipRecord();
if (blip != null) {
return blip.getPicturedata();
-
+
}
}
return new byte[0];
}
/**
- *
+ *
* @return size in bytes of the picture
*/
public int getSize()
}
return width;
}
-
+
/**
* returns the description stored in the alternative text
- *
+ *
* @return pictue description
*/
public String getDescription()
/**
* tries to suggest extension for picture's file by matching signatures of
* popular image formats to first bytes of picture's contents
- *
+ *
* @return suggested file extension
*/
public String suggestFileExtension()
* Tries to suggest a filename: hex representation of picture structure
* offset in "Data" stream plus extension that is tried to determine from
* first byte of picture's content.
- *
+ *
* @return suggested file name
*/
public String suggestFullFileName()
* Writes Picture's content bytes to specified OutputStream. Is useful when
* there is need to write picture bytes directly to stream, omitting its
* representation in memory as distinct byte array.
- *
+ *
* @param out
* a stream to write to
* @throws IOException
@Test
public void testEncoding() throws Exception {
assertEquals(2, cyrillic.getRecipientDetailsChunks().length);
- assertEquals("CP1252", cyrillic.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding());
- assertEquals("CP1252", cyrillic.getRecipientDetailsChunks()[1].recipientDisplayNameChunk.get7BitEncoding());
+ assertEquals("CP1252", cyrillic.getRecipientDetailsChunks()[0].getRecipientDisplayNameChunk().get7BitEncoding());
+ assertEquals("CP1252", cyrillic.getRecipientDetailsChunks()[1].getRecipientDisplayNameChunk().get7BitEncoding());
cyrillic.guess7BitEncoding();
- assertEquals("Cp1251", cyrillic.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding());
- assertEquals("Cp1251", cyrillic.getRecipientDetailsChunks()[1].recipientDisplayNameChunk.get7BitEncoding());
+ assertEquals("Cp1251", cyrillic.getRecipientDetailsChunks()[0].getRecipientDisplayNameChunk().get7BitEncoding());
+ assertEquals("Cp1251", cyrillic.getRecipientDetailsChunks()[1].getRecipientDisplayNameChunk().get7BitEncoding());
// Override it, check it's taken
cyrillic.set7BitEncoding("UTF-8");
- assertEquals("UTF-8", cyrillic.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding());
- assertEquals("UTF-8", cyrillic.getRecipientDetailsChunks()[1].recipientDisplayNameChunk.get7BitEncoding());
+ assertEquals("UTF-8", cyrillic.getRecipientDetailsChunks()[0].getRecipientDisplayNameChunk().get7BitEncoding());
+ assertEquals("UTF-8", cyrillic.getRecipientDetailsChunks()[1].getRecipientDisplayNameChunk().get7BitEncoding());
// Check with a file that has no headers
assertTrue(html.contains("text/html; charset=big5"), "Charset not found:\n" + html);
// Defaults to CP1251
- assertEquals("CP1252", chinese.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding());
+ assertEquals("CP1252", chinese.getRecipientDetailsChunks()[0].getRecipientDisplayNameChunk().get7BitEncoding());
// But after guessing goes to the correct one, cp950 (Windows Traditional Chinese)
chinese.guess7BitEncoding();
- assertEquals("cp950", chinese.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding());
+ assertEquals("cp950", chinese.getRecipientDetailsChunks()[0].getRecipientDisplayNameChunk().get7BitEncoding());
}
}
*/
@Test
public void testReadKeywords() {
- long keywordsPropTag = keywordsMsg.getNameIdChunks().getPropertyTag(PS_PUBLIC_STRINGS.classID, "Keywords", 0);
+ long keywordsPropTag = keywordsMsg.getNameIdChunks().getPropertyTag(PS_PUBLIC_STRINGS.getClassID(), "Keywords", 0);
assertEquals(0x8003, keywordsPropTag);
String[] exp = { "TODO", "Currently Important", "Currently To Do", "Test" };
String[] act = getValues(keywordsPropTag);
*/
@Test
public void testCurrentVersionName() {
- long testPropTag = keywordsMsg.getNameIdChunks().getPropertyTag(PSETID_COMMON.classID, null, 0x8554);
+ long testPropTag = keywordsMsg.getNameIdChunks().getPropertyTag(PSETID_COMMON.getClassID(), null, 0x8554);
assertEquals(0x8006, testPropTag);
String[] exp = { "16.0" };
String[] act = getValues(testPropTag);
new RecipientChunks("__recip_version1.0_#00000000"),
};
Arrays.sort(chunks, new RecipientChunksSorter());
- assertEquals(0, chunks[0].recipientNumber);
- assertEquals(1, chunks[1].recipientNumber);
+ assertEquals(0, chunks[0].getRecipientNumber());
+ assertEquals(1, chunks[1].getRecipientNumber());
// Lots, with gaps
chunks = new RecipientChunks[] {
new RecipientChunks("__recip_version1.0_#00000000"),
};
Arrays.sort(chunks, new RecipientChunksSorter());
- assertEquals(0, chunks[0].recipientNumber);
- assertEquals(1, chunks[1].recipientNumber);
- assertEquals(5, chunks[2].recipientNumber);
- assertEquals(9, chunks[3].recipientNumber);
- assertEquals(0xFF, chunks[4].recipientNumber);
- assertEquals(0x205, chunks[5].recipientNumber);
- assertEquals(0x404, chunks[6].recipientNumber);
- assertEquals(0x20001, chunks[7].recipientNumber);
+ assertEquals(0, chunks[0].getRecipientNumber());
+ assertEquals(1, chunks[1].getRecipientNumber());
+ assertEquals(5, chunks[2].getRecipientNumber());
+ assertEquals(9, chunks[3].getRecipientNumber());
+ assertEquals(0xFF, chunks[4].getRecipientNumber());
+ assertEquals(0x205, chunks[5].getRecipientNumber());
+ assertEquals(0x404, chunks[6].getRecipientNumber());
+ assertEquals(0x20001, chunks[7].getRecipientNumber());
}
}
assertTrue(groups[2] instanceof NameIdChunks);
RecipientChunks recips = (RecipientChunks)groups[1];
- assertEquals("kevin.roast@alfresco.org", recips.recipientSMTPChunk.getValue());
+ assertEquals("kevin.roast@alfresco.org", recips.getRecipientSMTPChunk().getValue());
assertEquals("/O=HOSTEDSERVICE2/OU=FIRST ADMINISTRATIVE GROUP/CN=RECIPIENTS/CN=Kevin.roast@ben",
- recips.recipientEmailChunk.getValue());
+ recips.getRecipientEmailChunk().getValue());
- String search = new String(recips.recipientSearchChunk.getValue(), StandardCharsets.US_ASCII);
+ String search = new String(recips.getRecipientSearchChunk().getValue(), StandardCharsets.US_ASCII);
assertEquals("CN=KEVIN.ROAST@BEN\0", search.substring(search.length()-19));
// Now via MAPIMessage
assertNotNull(msg.getRecipientDetailsChunks());
assertEquals(1, msg.getRecipientDetailsChunks().length);
- assertEquals("kevin.roast@alfresco.org", msg.getRecipientDetailsChunks()[0].recipientSMTPChunk.getValue());
+ assertEquals("kevin.roast@alfresco.org", msg.getRecipientDetailsChunks()[0].getRecipientSMTPChunk().getValue());
assertEquals("kevin.roast@alfresco.org", msg.getRecipientDetailsChunks()[0].getRecipientEmailAddress());
assertEquals("Kevin Roast", msg.getRecipientDetailsChunks()[0].getRecipientName());
assertEquals("kevin.roast@alfresco.org", msg.getRecipientEmailAddress());
// Try both SMTP and EX files for recipient
- assertEquals("EX", msg.getRecipientDetailsChunks()[0].deliveryTypeChunk.getValue());
- assertEquals("kevin.roast@alfresco.org", msg.getRecipientDetailsChunks()[0].recipientSMTPChunk.getValue());
+ assertEquals("EX", msg.getRecipientDetailsChunks()[0].getDeliveryTypeChunk().getValue());
+ assertEquals("kevin.roast@alfresco.org", msg.getRecipientDetailsChunks()[0].getRecipientSMTPChunk().getValue());
assertEquals("/O=HOSTEDSERVICE2/OU=FIRST ADMINISTRATIVE GROUP/CN=RECIPIENTS/CN=Kevin.roast@ben",
- msg.getRecipientDetailsChunks()[0].recipientEmailChunk.getValue());
+ msg.getRecipientDetailsChunks()[0].getRecipientEmailChunk().getValue());
msg.close();
simple.close();
assertNotNull(msg.getRecipientDetailsChunks());
assertEquals(1, msg.getRecipientDetailsChunks().length);
- assertEquals("SMTP", msg.getRecipientDetailsChunks()[0].deliveryTypeChunk.getValue());
- assertNull(msg.getRecipientDetailsChunks()[0].recipientSMTPChunk);
- assertNull(msg.getRecipientDetailsChunks()[0].recipientNameChunk);
- assertEquals("travis@overwrittenstack.com", msg.getRecipientDetailsChunks()[0].recipientEmailChunk.getValue());
+ assertEquals("SMTP", msg.getRecipientDetailsChunks()[0].getDeliveryTypeChunk().getValue());
+ assertNull(msg.getRecipientDetailsChunks()[0].getRecipientSMTPChunk());
+ assertNull(msg.getRecipientDetailsChunks()[0].getRecipientNameChunk());
+ assertEquals("travis@overwrittenstack.com", msg.getRecipientDetailsChunks()[0].getRecipientEmailChunk().getValue());
assertEquals("travis@overwrittenstack.com", msg.getRecipientEmailAddress());
msg.close();
(RecipientChunks)groups[7],
};
assertEquals(6, chunks.length);
- assertEquals(0, chunks[0].recipientNumber);
- assertEquals(2, chunks[1].recipientNumber);
- assertEquals(4, chunks[2].recipientNumber);
- assertEquals(5, chunks[3].recipientNumber);
- assertEquals(3, chunks[4].recipientNumber);
- assertEquals(1, chunks[5].recipientNumber);
+ assertEquals(0, chunks[0].getRecipientNumber());
+ assertEquals(2, chunks[1].getRecipientNumber());
+ assertEquals(4, chunks[2].getRecipientNumber());
+ assertEquals(5, chunks[3].getRecipientNumber());
+ assertEquals(3, chunks[4].getRecipientNumber());
+ assertEquals(1, chunks[5].getRecipientNumber());
// Check
assertEquals("'Ashutosh Dandavate'", chunks[0].getRecipientName());
}
}
assertNotNull(tr);
- assertEquals(1, tr._tabids.length);
- assertEquals(0, tr._tabids[0]);
+ assertEquals(1, tr.getTabIdSize());
+ assertEquals(0, tr.getTabIdAt(0));
// Ensure the print setup
assertEquals("new_sheet!$A$1:$C$1", wb2.getPrintArea(0));
HSSFSheet example3 = wb.getSheet("Example 3");
HSSFCell ex3cell = example3.getRow(5).getCell(2);
fe.evaluate(ex3cell);
- assertEquals(8,8, ex3cell.getNumericCellValue());
+ assertEquals(8.8, ex3cell.getNumericCellValue(), 0);
HSSFSheet example4 = wb.getSheet("Example 4");
HSSFCell ex4cell = example4.getRow(8).getCell(2);