]> source.dussan.org Git - poi.git/commitdiff
Changed CRLF to LF in .java base src files. Minor reformatting fixes.
authorJosh Micich <josh@apache.org>
Tue, 19 May 2009 16:29:51 +0000 (16:29 +0000)
committerJosh Micich <josh@apache.org>
Tue, 19 May 2009 16:29:51 +0000 (16:29 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@776377 13f79535-47bb-0310-9956-ffa450edef68

54 files changed:
src/java/org/apache/poi/ddf/EscherPictBlip.java
src/java/org/apache/poi/hssf/model/HSSFFormulaParser.java
src/java/org/apache/poi/hssf/record/ArrayRecord.java
src/java/org/apache/poi/hssf/record/CellRecord.java
src/java/org/apache/poi/hssf/record/HeaderFooterBase.java
src/java/org/apache/poi/hssf/record/StandardRecord.java
src/java/org/apache/poi/hssf/record/aggregates/ChartSubstreamRecordAggregate.java
src/java/org/apache/poi/hssf/record/aggregates/DataValidityTable.java
src/java/org/apache/poi/hssf/record/aggregates/RecordAggregate.java
src/java/org/apache/poi/hssf/record/cont/ContinuableRecord.java
src/java/org/apache/poi/hssf/record/cont/ContinuableRecordOutput.java
src/java/org/apache/poi/hssf/record/cont/UnknownLengthRecordOutput.java
src/java/org/apache/poi/hssf/record/formula/Area2DPtgBase.java
src/java/org/apache/poi/hssf/record/formula/RefPtg.java
src/java/org/apache/poi/hssf/record/formula/ScalarConstantPtg.java
src/java/org/apache/poi/hssf/record/formula/eval/RefEvalBase.java
src/java/org/apache/poi/hssf/usermodel/HSSFEvaluationWorkbook.java
src/java/org/apache/poi/hssf/usermodel/HSSFFormulaEvaluator.java
src/java/org/apache/poi/hssf/usermodel/HSSFHyperlink.java
src/java/org/apache/poi/hssf/usermodel/HSSFSheetConditionalFormatting.java
src/java/org/apache/poi/hssf/util/CellRangeAddress.java
src/java/org/apache/poi/hssf/util/CellRangeAddress8Bit.java
src/java/org/apache/poi/poifs/dev/POIFSDump.java
src/java/org/apache/poi/ss/SpreadsheetVersion.java
src/java/org/apache/poi/ss/formula/CellEvaluationFrame.java
src/java/org/apache/poi/ss/formula/EvaluationName.java
src/java/org/apache/poi/ss/formula/EvaluationWorkbook.java
src/java/org/apache/poi/ss/formula/Formula.java
src/java/org/apache/poi/ss/formula/FormulaParsingWorkbook.java
src/java/org/apache/poi/ss/formula/FormulaRenderer.java
src/java/org/apache/poi/ss/formula/FormulaRenderingWorkbook.java
src/java/org/apache/poi/ss/formula/FormulaType.java
src/java/org/apache/poi/ss/formula/LazyRefEval.java
src/java/org/apache/poi/ss/formula/SheetRefEvaluator.java
src/java/org/apache/poi/ss/formula/WorkbookDependentFormula.java
src/java/org/apache/poi/ss/formula/eval/NotImplementedException.java
src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationCell.java
src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationSheet.java
src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationWorkbook.java
src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluator.java
src/java/org/apache/poi/ss/usermodel/CellValue.java
src/java/org/apache/poi/ss/usermodel/ClientAnchor.java
src/java/org/apache/poi/ss/usermodel/DataFormatter.java
src/java/org/apache/poi/ss/usermodel/Drawing.java
src/java/org/apache/poi/ss/usermodel/FormulaError.java
src/java/org/apache/poi/ss/usermodel/HorizontalAlignment.java
src/java/org/apache/poi/ss/usermodel/Picture.java
src/java/org/apache/poi/ss/usermodel/ShapeTypes.java
src/java/org/apache/poi/ss/usermodel/VerticalAlignment.java
src/java/org/apache/poi/util/DelayableLittleEndianOutput.java
src/java/org/apache/poi/util/LittleEndianInput.java
src/java/org/apache/poi/util/LittleEndianInputStream.java
src/java/org/apache/poi/util/LittleEndianOutput.java
src/java/org/apache/poi/util/LittleEndianOutputStream.java

index 5920d97b98180454fbfd1555e7e8459055154740..8ab6d8c5c16ea8dc61859b8b65ab740db063a95f 100644 (file)
-/*\r
-* Licensed to the Apache Software Foundation (ASF) under one or more\r
-* contributor license agreements.  See the NOTICE file distributed with\r
-* this work for additional information regarding copyright ownership.\r
-* The ASF licenses this file to You under the Apache License, Version 2.0\r
-* (the "License"); you may not use this file except in compliance with\r
-* the License.  You may obtain a copy of the License at\r
-*\r
-*     http://www.apache.org/licenses/LICENSE-2.0\r
-*\r
-* Unless required by applicable law or agreed to in writing, software\r
-* distributed under the License is distributed on an "AS IS" BASIS,\r
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-* See the License for the specific language governing permissions and\r
-* limitations under the License.\r
-*/\r
-package org.apache.poi.ddf;\r
-\r
-import org.apache.poi.util.HexDump;\r
-import org.apache.poi.util.LittleEndian;\r
-import org.apache.poi.util.POILogFactory;\r
-import org.apache.poi.util.POILogger;\r
-\r
-import java.awt.Dimension;\r
-import java.awt.Rectangle;\r
-import java.io.ByteArrayInputStream;\r
-import java.io.ByteArrayOutputStream;\r
-import java.io.IOException;\r
-import java.util.zip.InflaterInputStream;\r
-\r
-/**\r
- * @author Daniel Noll\r
- * @version $Id$\r
- */\r
-public class EscherPictBlip\r
-        extends EscherBlipRecord\r
-{\r
-    private static final POILogger log = POILogFactory.getLogger(EscherPictBlip.class);\r
-\r
-    public static final short RECORD_ID_EMF = (short) 0xF018 + 2;\r
-    public static final short RECORD_ID_WMF = (short) 0xF018 + 3;\r
-    public static final short RECORD_ID_PICT = (short) 0xF018 + 4;\r
-\r
-    private static final int HEADER_SIZE = 8;\r
-\r
-    private byte[] field_1_UID;\r
-    private int field_2_cb;\r
-    private int field_3_rcBounds_x1;\r
-    private int field_3_rcBounds_y1;\r
-    private int field_3_rcBounds_x2;\r
-    private int field_3_rcBounds_y2;\r
-    private int field_4_ptSize_w;\r
-    private int field_4_ptSize_h;\r
-    private int field_5_cbSave;\r
-    private byte field_6_fCompression;\r
-    private byte field_7_fFilter;\r
-\r
-    private byte[] raw_pictureData;\r
-\r
-    /**\r
-     * This method deserializes the record from a byte array.\r
-     *\r
-     * @param data          The byte array containing the escher record information\r
-     * @param offset        The starting offset into <code>data</code>.\r
-     * @param recordFactory May be null since this is not a container record.\r
-     * @return The number of bytes read from the byte array.\r
-     */\r
-    public int fillFields( byte[] data, int offset, EscherRecordFactory recordFactory )\r
-    {\r
-        int bytesAfterHeader = readHeader( data, offset );\r
-        int pos = offset + HEADER_SIZE;\r
-\r
-        field_1_UID = new byte[16];\r
-        System.arraycopy( data, pos, field_1_UID, 0, 16 ); pos += 16;\r
-        field_2_cb = LittleEndian.getInt( data, pos ); pos += 4;\r
-        field_3_rcBounds_x1 = LittleEndian.getInt( data, pos ); pos += 4;\r
-        field_3_rcBounds_y1 = LittleEndian.getInt( data, pos ); pos += 4;\r
-        field_3_rcBounds_x2 = LittleEndian.getInt( data, pos ); pos += 4;\r
-        field_3_rcBounds_y2 = LittleEndian.getInt( data, pos ); pos += 4;\r
-        field_4_ptSize_w = LittleEndian.getInt( data, pos ); pos += 4;\r
-        field_4_ptSize_h = LittleEndian.getInt( data, pos ); pos += 4;\r
-        field_5_cbSave = LittleEndian.getInt( data, pos ); pos += 4;\r
-        field_6_fCompression = data[pos]; pos++;\r
-        field_7_fFilter = data[pos]; pos++;\r
-\r
-        raw_pictureData = new byte[field_5_cbSave];\r
-        System.arraycopy( data, pos, raw_pictureData, 0, field_5_cbSave );\r
-\r
-        // 0 means DEFLATE compression\r
-        // 0xFE means no compression\r
-        if (field_6_fCompression == 0)\r
-        {\r
-            field_pictureData = inflatePictureData(raw_pictureData);\r
-        }\r
-        else\r
-        {\r
-            field_pictureData = raw_pictureData;\r
-        }\r
-\r
-        return bytesAfterHeader + HEADER_SIZE;\r
-    }\r
-    \r
-    /**\r
-     * Serializes the record to an existing byte array.\r
-     *\r
-     * @param offset    the offset within the byte array\r
-     * @param data      the data array to serialize to\r
-     * @param listener  a listener for begin and end serialization events.  This\r
-     *                  is useful because the serialization is\r
-     *                  hierarchical/recursive and sometimes you need to be able\r
-     *                  break into that.\r
-     * @return the number of bytes written.\r
-     */\r
-    public int serialize( int offset, byte[] data, EscherSerializationListener listener )\r
-    {\r
-        listener.beforeRecordSerialize(offset, getRecordId(), this);\r
-\r
-        int pos = offset;\r
-        LittleEndian.putShort( data, pos, getOptions() ); pos += 2;\r
-        LittleEndian.putShort( data, pos, getRecordId() ); pos += 2;\r
-        LittleEndian.putInt( data, getRecordSize() - HEADER_SIZE ); pos += 4;\r
-\r
-        System.arraycopy( field_1_UID, 0, data, pos, 16 ); pos += 16;\r
-        LittleEndian.putInt( data, pos, field_2_cb ); pos += 4;\r
-        LittleEndian.putInt( data, pos, field_3_rcBounds_x1 ); pos += 4;\r
-        LittleEndian.putInt( data, pos, field_3_rcBounds_y1 ); pos += 4;\r
-        LittleEndian.putInt( data, pos, field_3_rcBounds_x2 ); pos += 4;\r
-        LittleEndian.putInt( data, pos, field_3_rcBounds_y2 ); pos += 4;\r
-        LittleEndian.putInt( data, pos, field_4_ptSize_w ); pos += 4;\r
-        LittleEndian.putInt( data, pos, field_4_ptSize_h ); pos += 4;\r
-        LittleEndian.putInt( data, pos, field_5_cbSave ); pos += 4;\r
-        data[pos] = field_6_fCompression; pos++;\r
-        data[pos] = field_7_fFilter; pos++;\r
-\r
-        System.arraycopy( raw_pictureData, 0, data, pos, raw_pictureData.length );\r
-\r
-        listener.afterRecordSerialize(offset + getRecordSize(), getRecordId(), getRecordSize(), this);\r
-        return HEADER_SIZE + 16 + 1 + raw_pictureData.length;\r
-    }\r
-\r
-    /**\r
-     * Decompresses the provided data, returning the inflated result.\r
-     *\r
-     * @param data the deflated picture data.\r
-     * @return the inflated picture data.\r
-     */\r
-    private static byte[] inflatePictureData(byte[] data)\r
-    {\r
-        try\r
-        {\r
-            InflaterInputStream in = new InflaterInputStream(\r
-                new ByteArrayInputStream( data ) );\r
-            ByteArrayOutputStream out = new ByteArrayOutputStream();\r
-            byte[] buf = new byte[4096];\r
-            int readBytes;\r
-            while ((readBytes = in.read(buf)) > 0)\r
-            {\r
-                out.write(buf, 0, readBytes);\r
-            }\r
-            return out.toByteArray();\r
-        }\r
-        catch ( IOException e )\r
-        {\r
-            log.log(POILogger.INFO, "Possibly corrupt compression or non-compressed data", e);\r
-            return data;\r
-        }\r
-    }\r
-\r
-    /**\r
-     * Returns the number of bytes that are required to serialize this record.\r
-     *\r
-     * @return Number of bytes\r
-     */\r
-    public int getRecordSize()\r
-    {\r
-        return 8 + 50 + raw_pictureData.length;\r
-    }\r
-\r
-    public byte[] getUID()\r
-    {\r
-        return field_1_UID;\r
-    }\r
-\r
-    public void setUID( byte[] field_1_UID )\r
-    {\r
-        this.field_1_UID = field_1_UID;\r
-    }\r
-\r
-    public int getUncompressedSize()\r
-    {\r
-        return field_2_cb;\r
-    }\r
-\r
-    public void setUncompressedSize(int uncompressedSize)\r
-    {\r
-        field_2_cb = uncompressedSize;\r
-    }\r
-\r
-    public Rectangle getBounds()\r
-    {\r
-        return new Rectangle(field_3_rcBounds_x1,\r
-                             field_3_rcBounds_y1,\r
-                             field_3_rcBounds_x2 - field_3_rcBounds_x1,\r
-                             field_3_rcBounds_y2 - field_3_rcBounds_y1);\r
-    }\r
-\r
-    public void setBounds(Rectangle bounds)\r
-    {\r
-        field_3_rcBounds_x1 = bounds.x;\r
-        field_3_rcBounds_y1 = bounds.y;\r
-        field_3_rcBounds_x2 = bounds.x + bounds.width;\r
-        field_3_rcBounds_y2 = bounds.y + bounds.height;\r
-    }\r
-\r
-    public Dimension getSizeEMU()\r
-    {\r
-        return new Dimension(field_4_ptSize_w, field_4_ptSize_h);\r
-    }\r
-\r
-    public void setSizeEMU(Dimension sizeEMU)\r
-    {\r
-        field_4_ptSize_w = sizeEMU.width;\r
-        field_4_ptSize_h = sizeEMU.height;\r
-    }\r
-\r
-    public int getCompressedSize()\r
-    {\r
-        return field_5_cbSave;\r
-    }\r
-\r
-    public void setCompressedSize(int compressedSize)\r
-    {\r
-        field_5_cbSave = compressedSize;\r
-    }\r
-\r
-    public boolean isCompressed()\r
-    {\r
-        return (field_6_fCompression == 0);\r
-    }\r
-\r
-    public void setCompressed(boolean compressed)\r
-    {\r
-        field_6_fCompression = compressed ? 0 : (byte)0xFE;\r
-    }\r
-\r
-    // filtering is always 254 according to available docs, so no point giving it a setter method.\r
-\r
-    public String toString()\r
-    {\r
-        String nl = System.getProperty( "line.separator" );\r
-\r
-        String extraData;\r
-        ByteArrayOutputStream b = new ByteArrayOutputStream();\r
-        try\r
-        {\r
-            HexDump.dump( this.field_pictureData, 0, b, 0 );\r
-            extraData = b.toString();\r
-        }\r
-        catch ( Exception e )\r
-        {\r
-            extraData = e.toString();\r
-        }\r
-        return getClass().getName() + ":" + nl +\r
-                "  RecordId: 0x" + HexDump.toHex( getRecordId() ) + nl +\r
-                "  Options: 0x" + HexDump.toHex( getOptions() ) + nl +\r
-                "  UID: 0x" + HexDump.toHex( field_1_UID ) + nl +\r
-                "  Uncompressed Size: " + HexDump.toHex( field_2_cb ) + nl +\r
-                "  Bounds: " + getBounds() + nl +\r
-                "  Size in EMU: " + getSizeEMU() + nl +\r
-                "  Compressed Size: " + HexDump.toHex( field_5_cbSave ) + nl +\r
-                "  Compression: " + HexDump.toHex( field_6_fCompression ) + nl +\r
-                "  Filter: " + HexDump.toHex( field_7_fFilter ) + nl +\r
-                "  Extra Data:" + nl + extraData;\r
-    }\r
-\r
-}\r
+/*
+* 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.ddf;
+
+import org.apache.poi.util.HexDump;
+import org.apache.poi.util.LittleEndian;
+import org.apache.poi.util.POILogFactory;
+import org.apache.poi.util.POILogger;
+
+import java.awt.Dimension;
+import java.awt.Rectangle;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.zip.InflaterInputStream;
+
+/**
+ * @author Daniel Noll
+ * @version $Id$
+ */
+public class EscherPictBlip
+        extends EscherBlipRecord
+{
+    private static final POILogger log = POILogFactory.getLogger(EscherPictBlip.class);
+
+    public static final short RECORD_ID_EMF = (short) 0xF018 + 2;
+    public static final short RECORD_ID_WMF = (short) 0xF018 + 3;
+    public static final short RECORD_ID_PICT = (short) 0xF018 + 4;
+
+    private static final int HEADER_SIZE = 8;
+
+    private byte[] field_1_UID;
+    private int field_2_cb;
+    private int field_3_rcBounds_x1;
+    private int field_3_rcBounds_y1;
+    private int field_3_rcBounds_x2;
+    private int field_3_rcBounds_y2;
+    private int field_4_ptSize_w;
+    private int field_4_ptSize_h;
+    private int field_5_cbSave;
+    private byte field_6_fCompression;
+    private byte field_7_fFilter;
+
+    private byte[] raw_pictureData;
+
+    /**
+     * This method deserializes the record from a byte array.
+     *
+     * @param data          The byte array containing the escher record information
+     * @param offset        The starting offset into <code>data</code>.
+     * @param recordFactory May be null since this is not a container record.
+     * @return The number of bytes read from the byte array.
+     */
+    public int fillFields( byte[] data, int offset, EscherRecordFactory recordFactory )
+    {
+        int bytesAfterHeader = readHeader( data, offset );
+        int pos = offset + HEADER_SIZE;
+
+        field_1_UID = new byte[16];
+        System.arraycopy( data, pos, field_1_UID, 0, 16 ); pos += 16;
+        field_2_cb = LittleEndian.getInt( data, pos ); pos += 4;
+        field_3_rcBounds_x1 = LittleEndian.getInt( data, pos ); pos += 4;
+        field_3_rcBounds_y1 = LittleEndian.getInt( data, pos ); pos += 4;
+        field_3_rcBounds_x2 = LittleEndian.getInt( data, pos ); pos += 4;
+        field_3_rcBounds_y2 = LittleEndian.getInt( data, pos ); pos += 4;
+        field_4_ptSize_w = LittleEndian.getInt( data, pos ); pos += 4;
+        field_4_ptSize_h = LittleEndian.getInt( data, pos ); pos += 4;
+        field_5_cbSave = LittleEndian.getInt( data, pos ); pos += 4;
+        field_6_fCompression = data[pos]; pos++;
+        field_7_fFilter = data[pos]; pos++;
+
+        raw_pictureData = new byte[field_5_cbSave];
+        System.arraycopy( data, pos, raw_pictureData, 0, field_5_cbSave );
+
+        // 0 means DEFLATE compression
+        // 0xFE means no compression
+        if (field_6_fCompression == 0)
+        {
+            field_pictureData = inflatePictureData(raw_pictureData);
+        }
+        else
+        {
+            field_pictureData = raw_pictureData;
+        }
+
+        return bytesAfterHeader + HEADER_SIZE;
+    }
+
+    /**
+     * Serializes the record to an existing byte array.
+     *
+     * @param offset    the offset within the byte array
+     * @param data      the data array to serialize to
+     * @param listener  a listener for begin and end serialization events.  This
+     *                  is useful because the serialization is
+     *                  hierarchical/recursive and sometimes you need to be able
+     *                  break into that.
+     * @return the number of bytes written.
+     */
+    public int serialize( int offset, byte[] data, EscherSerializationListener listener )
+    {
+        listener.beforeRecordSerialize(offset, getRecordId(), this);
+
+        int pos = offset;
+        LittleEndian.putShort( data, pos, getOptions() ); pos += 2;
+        LittleEndian.putShort( data, pos, getRecordId() ); pos += 2;
+        LittleEndian.putInt( data, getRecordSize() - HEADER_SIZE ); pos += 4;
+
+        System.arraycopy( field_1_UID, 0, data, pos, 16 ); pos += 16;
+        LittleEndian.putInt( data, pos, field_2_cb ); pos += 4;
+        LittleEndian.putInt( data, pos, field_3_rcBounds_x1 ); pos += 4;
+        LittleEndian.putInt( data, pos, field_3_rcBounds_y1 ); pos += 4;
+        LittleEndian.putInt( data, pos, field_3_rcBounds_x2 ); pos += 4;
+        LittleEndian.putInt( data, pos, field_3_rcBounds_y2 ); pos += 4;
+        LittleEndian.putInt( data, pos, field_4_ptSize_w ); pos += 4;
+        LittleEndian.putInt( data, pos, field_4_ptSize_h ); pos += 4;
+        LittleEndian.putInt( data, pos, field_5_cbSave ); pos += 4;
+        data[pos] = field_6_fCompression; pos++;
+        data[pos] = field_7_fFilter; pos++;
+
+        System.arraycopy( raw_pictureData, 0, data, pos, raw_pictureData.length );
+
+        listener.afterRecordSerialize(offset + getRecordSize(), getRecordId(), getRecordSize(), this);
+        return HEADER_SIZE + 16 + 1 + raw_pictureData.length;
+    }
+
+    /**
+     * Decompresses the provided data, returning the inflated result.
+     *
+     * @param data the deflated picture data.
+     * @return the inflated picture data.
+     */
+    private static byte[] inflatePictureData(byte[] data)
+    {
+        try
+        {
+            InflaterInputStream in = new InflaterInputStream(
+                new ByteArrayInputStream( data ) );
+            ByteArrayOutputStream out = new ByteArrayOutputStream();
+            byte[] buf = new byte[4096];
+            int readBytes;
+            while ((readBytes = in.read(buf)) > 0)
+            {
+                out.write(buf, 0, readBytes);
+            }
+            return out.toByteArray();
+        }
+        catch ( IOException e )
+        {
+            log.log(POILogger.INFO, "Possibly corrupt compression or non-compressed data", e);
+            return data;
+        }
+    }
+
+    /**
+     * Returns the number of bytes that are required to serialize this record.
+     *
+     * @return Number of bytes
+     */
+    public int getRecordSize()
+    {
+        return 8 + 50 + raw_pictureData.length;
+    }
+
+    public byte[] getUID()
+    {
+        return field_1_UID;
+    }
+
+    public void setUID( byte[] field_1_UID )
+    {
+        this.field_1_UID = field_1_UID;
+    }
+
+    public int getUncompressedSize()
+    {
+        return field_2_cb;
+    }
+
+    public void setUncompressedSize(int uncompressedSize)
+    {
+        field_2_cb = uncompressedSize;
+    }
+
+    public Rectangle getBounds()
+    {
+        return new Rectangle(field_3_rcBounds_x1,
+                             field_3_rcBounds_y1,
+                             field_3_rcBounds_x2 - field_3_rcBounds_x1,
+                             field_3_rcBounds_y2 - field_3_rcBounds_y1);
+    }
+
+    public void setBounds(Rectangle bounds)
+    {
+        field_3_rcBounds_x1 = bounds.x;
+        field_3_rcBounds_y1 = bounds.y;
+        field_3_rcBounds_x2 = bounds.x + bounds.width;
+        field_3_rcBounds_y2 = bounds.y + bounds.height;
+    }
+
+    public Dimension getSizeEMU()
+    {
+        return new Dimension(field_4_ptSize_w, field_4_ptSize_h);
+    }
+
+    public void setSizeEMU(Dimension sizeEMU)
+    {
+        field_4_ptSize_w = sizeEMU.width;
+        field_4_ptSize_h = sizeEMU.height;
+    }
+
+    public int getCompressedSize()
+    {
+        return field_5_cbSave;
+    }
+
+    public void setCompressedSize(int compressedSize)
+    {
+        field_5_cbSave = compressedSize;
+    }
+
+    public boolean isCompressed()
+    {
+        return (field_6_fCompression == 0);
+    }
+
+    public void setCompressed(boolean compressed)
+    {
+        field_6_fCompression = compressed ? 0 : (byte)0xFE;
+    }
+
+    // filtering is always 254 according to available docs, so no point giving it a setter method.
+
+    public String toString()
+    {
+        String nl = System.getProperty( "line.separator" );
+
+        String extraData;
+        ByteArrayOutputStream b = new ByteArrayOutputStream();
+        try
+        {
+            HexDump.dump( this.field_pictureData, 0, b, 0 );
+            extraData = b.toString();
+        }
+        catch ( Exception e )
+        {
+            extraData = e.toString();
+        }
+        return getClass().getName() + ":" + nl +
+                "  RecordId: 0x" + HexDump.toHex( getRecordId() ) + nl +
+                "  Options: 0x" + HexDump.toHex( getOptions() ) + nl +
+                "  UID: 0x" + HexDump.toHex( field_1_UID ) + nl +
+                "  Uncompressed Size: " + HexDump.toHex( field_2_cb ) + nl +
+                "  Bounds: " + getBounds() + nl +
+                "  Size in EMU: " + getSizeEMU() + nl +
+                "  Compressed Size: " + HexDump.toHex( field_5_cbSave ) + nl +
+                "  Compression: " + HexDump.toHex( field_6_fCompression ) + nl +
+                "  Filter: " + HexDump.toHex( field_7_fFilter ) + nl +
+                "  Extra Data:" + nl + extraData;
+    }
+
+}
index f24441841b211f19d7ca47c21e5f6faf486ce0fc..026590d71d02844622bb8b873a7e853859b279ff 100644 (file)
@@ -1,82 +1,82 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.model;\r
-\r
-import org.apache.poi.hssf.record.formula.Ptg;\r
-import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;\r
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
-import org.apache.poi.ss.formula.FormulaParser;\r
-import org.apache.poi.ss.formula.FormulaParsingWorkbook;\r
-import org.apache.poi.ss.formula.FormulaRenderer;\r
-import org.apache.poi.ss.formula.FormulaType;\r
-\r
-/**\r
- * HSSF wrapper for the {@link FormulaParser} and {@link FormulaRenderer} \r
- * \r
- * @author Josh Micich\r
- */\r
-public final class HSSFFormulaParser {\r
-\r
-       private static FormulaParsingWorkbook createParsingWorkbook(HSSFWorkbook book) {\r
-               return HSSFEvaluationWorkbook.create(book);\r
-       }\r
-\r
-       private HSSFFormulaParser() {\r
-               // no instances of this class\r
-       }\r
-\r
-       /**\r
-        * Convenience method for parsing cell formulas. see {@link #parse(String, HSSFWorkbook, int)}\r
-        */\r
-       public static Ptg[] parse(String formula, HSSFWorkbook workbook) {\r
-        return parse(formula, workbook, FormulaType.CELL);\r
-       }\r
-\r
-       /**\r
-        * @param formulaType a constant from {@link FormulaType}\r
-        * @return the parsed formula tokens\r
-        */\r
-       public static Ptg[] parse(String formula, HSSFWorkbook workbook, int formulaType) {\r
-               return parse(formula, workbook, formulaType, -1);\r
-       }\r
-\r
-    /**\r
-     * @param formula     the formula to parse\r
-     * @param workbook    the parent workbook\r
-     * @param formulaType a constant from {@link FormulaType}\r
-     * @param sheetIndex  the 0-based index of the sheet this formula belongs to.\r
-     * The sheet index is required to resolve sheet-level names. <code>-1</code> means that\r
-     * the scope of the name will be ignored and  the parser will match named ranges only by name\r
-     *\r
-     * @return the parsed formula tokens\r
-     */\r
-    public static Ptg[] parse(String formula, HSSFWorkbook workbook, int formulaType, int sheetIndex) {\r
-        return FormulaParser.parse(formula, createParsingWorkbook(workbook), formulaType, sheetIndex);\r
-    }\r
-\r
-       /**\r
-        * Static method to convert an array of {@link Ptg}s in RPN order\r
-        * to a human readable string format in infix mode.\r
-        * @param book  used for defined names and 3D references\r
-        * @param ptgs  must not be <code>null</code>\r
-        * @return a human readable String\r
-        */\r
-       public static String toFormulaString(HSSFWorkbook book, Ptg[] ptgs) {\r
-               return FormulaRenderer.toFormulaString(HSSFEvaluationWorkbook.create(book), ptgs);\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.model;
+
+import org.apache.poi.hssf.record.formula.Ptg;
+import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.formula.FormulaParser;
+import org.apache.poi.ss.formula.FormulaParsingWorkbook;
+import org.apache.poi.ss.formula.FormulaRenderer;
+import org.apache.poi.ss.formula.FormulaType;
+
+/**
+ * HSSF wrapper for the {@link FormulaParser} and {@link FormulaRenderer}
+ *
+ * @author Josh Micich
+ */
+public final class HSSFFormulaParser {
+
+       private static FormulaParsingWorkbook createParsingWorkbook(HSSFWorkbook book) {
+               return HSSFEvaluationWorkbook.create(book);
+       }
+
+       private HSSFFormulaParser() {
+               // no instances of this class
+       }
+
+       /**
+        * Convenience method for parsing cell formulas. see {@link #parse(String, HSSFWorkbook, int)}
+        */
+       public static Ptg[] parse(String formula, HSSFWorkbook workbook) {
+               return parse(formula, workbook, FormulaType.CELL);
+       }
+
+       /**
+        * @param formulaType a constant from {@link FormulaType}
+        * @return the parsed formula tokens
+        */
+       public static Ptg[] parse(String formula, HSSFWorkbook workbook, int formulaType) {
+               return parse(formula, workbook, formulaType, -1);
+       }
+
+       /**
+        * @param formula     the formula to parse
+        * @param workbook    the parent workbook
+        * @param formulaType a constant from {@link FormulaType}
+        * @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 that
+        * the scope of the name will be ignored and  the parser will match named ranges only by name
+        *
+        * @return the parsed formula tokens
+        */
+       public static Ptg[] parse(String formula, HSSFWorkbook workbook, int formulaType, int sheetIndex) {
+               return FormulaParser.parse(formula, createParsingWorkbook(workbook), formulaType, sheetIndex);
+       }
+
+       /**
+        * Static method to convert an array of {@link Ptg}s in RPN order
+        * to a human readable string format in infix mode.
+        * @param book  used for defined names and 3D references
+        * @param ptgs  must not be <code>null</code>
+        * @return a human readable String
+        */
+       public static String toFormulaString(HSSFWorkbook book, Ptg[] ptgs) {
+               return FormulaRenderer.toFormulaString(HSSFEvaluationWorkbook.create(book), ptgs);
+       }
+}
index 35239bb23852791d1b2c1ee6c582ccaa19fdda89..0cf6f44e05296c4d2a44a17ac3febacbe3b2803d 100644 (file)
@@ -1,87 +1,87 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record;\r
-\r
-import org.apache.poi.hssf.record.formula.Ptg;\r
-import org.apache.poi.ss.formula.Formula;\r
-import org.apache.poi.util.HexDump;\r
-import org.apache.poi.util.LittleEndianOutput;\r
-\r
-/**\r
- * ARRAY (0x0221)<p/>\r
- * \r
- * Treated in a similar way to SharedFormulaRecord\r
- * \r
- * @author Josh Micich\r
- */            \r
-public final class ArrayRecord extends SharedValueRecordBase {\r
-\r
-       public final static short sid = 0x0221;\r
-       private static final int OPT_ALWAYS_RECALCULATE = 0x0001;\r
-       private static final int OPT_CALCULATE_ON_OPEN  = 0x0002;\r
-       \r
-       private int     _options;\r
-       private int _field3notUsed;\r
-       private Formula _formula;\r
-\r
-       public ArrayRecord(RecordInputStream in) {\r
-               super(in);\r
-               _options = in.readUShort();\r
-               _field3notUsed = in.readInt();\r
-               int formulaTokenLen = in.readUShort();\r
-               int totalFormulaLen = in.available();\r
-               _formula = Formula.read(formulaTokenLen, in, totalFormulaLen);\r
-       }\r
-\r
-       public boolean isAlwaysRecalculate() {\r
-               return (_options & OPT_ALWAYS_RECALCULATE) != 0;\r
-       }\r
-       public boolean isCalculateOnOpen() {\r
-               return (_options & OPT_CALCULATE_ON_OPEN) != 0;\r
-       }\r
-\r
-       protected int getExtraDataSize() {\r
-               return 2 + 4\r
-                       + _formula.getEncodedSize();\r
-       }\r
-       protected void serializeExtraData(LittleEndianOutput out) {\r
-               out.writeShort(_options);\r
-               out.writeInt(_field3notUsed);\r
-               _formula.serialize(out);\r
-       }\r
-\r
-       public short getSid() {\r
-               return sid;\r
-       }\r
-\r
-       public String toString() {\r
-               StringBuffer sb = new StringBuffer();\r
-               sb.append(getClass().getName()).append(" [ARRAY]\n");\r
-               sb.append(" range=").append(getRange().toString()).append("\n");\r
-               sb.append(" options=").append(HexDump.shortToHex(_options)).append("\n");\r
-               sb.append(" notUsed=").append(HexDump.intToHex(_field3notUsed)).append("\n");\r
-               sb.append(" formula:").append("\n");\r
-               Ptg[] ptgs = _formula.getTokens();\r
-               for (int i = 0; i < ptgs.length; i++) {\r
-                       Ptg ptg = ptgs[i];\r
-                       sb.append(ptg.toString()).append(ptg.getRVAType()).append("\n");\r
-               }\r
-               sb.append("]");\r
-               return sb.toString();\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.record;
+
+import org.apache.poi.hssf.record.formula.Ptg;
+import org.apache.poi.ss.formula.Formula;
+import org.apache.poi.util.HexDump;
+import org.apache.poi.util.LittleEndianOutput;
+
+/**
+ * ARRAY (0x0221)<p/>
+ *
+ * Treated in a similar way to SharedFormulaRecord
+ *
+ * @author Josh Micich
+ */
+public final class ArrayRecord extends SharedValueRecordBase {
+
+       public final static short sid = 0x0221;
+       private static final int OPT_ALWAYS_RECALCULATE = 0x0001;
+       private static final int OPT_CALCULATE_ON_OPEN  = 0x0002;
+
+       private int     _options;
+       private int _field3notUsed;
+       private Formula _formula;
+
+       public ArrayRecord(RecordInputStream in) {
+               super(in);
+               _options = in.readUShort();
+               _field3notUsed = in.readInt();
+               int formulaTokenLen = in.readUShort();
+               int totalFormulaLen = in.available();
+               _formula = Formula.read(formulaTokenLen, in, totalFormulaLen);
+       }
+
+       public boolean isAlwaysRecalculate() {
+               return (_options & OPT_ALWAYS_RECALCULATE) != 0;
+       }
+       public boolean isCalculateOnOpen() {
+               return (_options & OPT_CALCULATE_ON_OPEN) != 0;
+       }
+
+       protected int getExtraDataSize() {
+               return 2 + 4
+                       + _formula.getEncodedSize();
+       }
+       protected void serializeExtraData(LittleEndianOutput out) {
+               out.writeShort(_options);
+               out.writeInt(_field3notUsed);
+               _formula.serialize(out);
+       }
+
+       public short getSid() {
+               return sid;
+       }
+
+       public String toString() {
+               StringBuffer sb = new StringBuffer();
+               sb.append(getClass().getName()).append(" [ARRAY]\n");
+               sb.append(" range=").append(getRange().toString()).append("\n");
+               sb.append(" options=").append(HexDump.shortToHex(_options)).append("\n");
+               sb.append(" notUsed=").append(HexDump.intToHex(_field3notUsed)).append("\n");
+               sb.append(" formula:").append("\n");
+               Ptg[] ptgs = _formula.getTokens();
+               for (int i = 0; i < ptgs.length; i++) {
+                       Ptg ptg = ptgs[i];
+                       sb.append(ptg.toString()).append(ptg.getRVAType()).append("\n");
+               }
+               sb.append("]");
+               return sb.toString();
+       }
+}
index 5f0646a9a043bebc1c5c4329e760122a27898fca..9d9ed4fc9a19bbab50ff39f6eccc4d16c8f95e80 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record;\r
-\r
-import org.apache.poi.util.HexDump;\r
-import org.apache.poi.util.LittleEndianOutput;\r
-\r
-/**\r
- * Base class for all cell value records (implementors of {@link CellValueRecordInterface}).\r
- * Subclasses are expected to manage the cell data values (of various types). \r
- * \r
- * @author Josh Micich\r
- */\r
-public abstract class CellRecord extends StandardRecord implements CellValueRecordInterface {\r
-       private int _rowIndex;\r
-       private int _columnIndex;\r
-       private int _formatIndex;\r
-\r
-       protected CellRecord() {\r
-               // fields uninitialised\r
-       }\r
-\r
-       protected CellRecord(RecordInputStream in) {\r
-               _rowIndex = in.readUShort();\r
-               _columnIndex = in.readUShort();\r
-               _formatIndex = in.readUShort();\r
-       }\r
-\r
-       public final void setRow(int row) {\r
-               _rowIndex = row;\r
-       }\r
-\r
-       public final void setColumn(short col) {\r
-               _columnIndex = col;\r
-       }\r
-\r
-       /**\r
-        * set the index to the ExtendedFormat\r
-        * \r
-        * @see org.apache.poi.hssf.record.ExtendedFormatRecord\r
-        * @param xf index to the XF record\r
-        */\r
-       public final void setXFIndex(short xf) {\r
-               _formatIndex = xf;\r
-       }\r
-\r
-       public final int getRow() {\r
-               return _rowIndex;\r
-       }\r
-\r
-       public final short getColumn() {\r
-               return (short) _columnIndex;\r
-       }\r
-\r
-       /**\r
-        * get the index to the ExtendedFormat\r
-        * \r
-        * @see org.apache.poi.hssf.record.ExtendedFormatRecord\r
-        * @return index to the XF record\r
-        */\r
-       public final short getXFIndex() {\r
-               return (short) _formatIndex;\r
-       }\r
-\r
-       public final String toString() {\r
-               StringBuilder sb = new StringBuilder();\r
-               String recordName = getRecordName();\r
-\r
-               sb.append("[").append(recordName).append("]\n");\r
-               sb.append("    .row    = ").append(HexDump.shortToHex(getRow())).append("\n");\r
-               sb.append("    .col    = ").append(HexDump.shortToHex(getColumn())).append("\n");\r
-               sb.append("    .xfindex= ").append(HexDump.shortToHex(getXFIndex())).append("\n");\r
-               appendValueText(sb);\r
-               sb.append("\n");\r
-               sb.append("[/").append(recordName).append("]\n");\r
-               return sb.toString();\r
-       }\r
-\r
-       /**\r
-        * Append specific debug info (used by {@link #toString()} for the value\r
-        * contained in this record. Trailing new-line should not be appended\r
-        * (superclass does that).\r
-        */\r
-       protected abstract void appendValueText(StringBuilder sb);\r
-\r
-       /**\r
-        * Gets the debug info BIFF record type name (used by {@link #toString()}.\r
-        */\r
-       protected abstract String getRecordName();\r
-\r
-       /**\r
-        * writes out the value data for this cell record\r
-        */\r
-       protected abstract void serializeValue(LittleEndianOutput out);\r
-\r
-       /**\r
-        * @return the size (in bytes) of the value data for this cell record\r
-        */\r
-       protected abstract int getValueDataSize();\r
-\r
-       public final void serialize(LittleEndianOutput out) {\r
-               out.writeShort(getRow());\r
-               out.writeShort(getColumn());\r
-               out.writeShort(getXFIndex());\r
-               serializeValue(out);\r
-       }\r
-\r
-       protected final int getDataSize() {\r
-               return 6 + getValueDataSize();\r
-       }\r
-\r
-       protected final void copyBaseFields(CellRecord rec) {\r
-               rec._rowIndex = _rowIndex;\r
-               rec._columnIndex = _columnIndex;\r
-               rec._formatIndex = _formatIndex;\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.record;
+
+import org.apache.poi.util.HexDump;
+import org.apache.poi.util.LittleEndianOutput;
+
+/**
+ * Base class for all cell value records (implementors of {@link CellValueRecordInterface}).
+ * Subclasses are expected to manage the cell data values (of various types).
+ *
+ * @author Josh Micich
+ */
+public abstract class CellRecord extends StandardRecord implements CellValueRecordInterface {
+       private int _rowIndex;
+       private int _columnIndex;
+       private int _formatIndex;
+
+       protected CellRecord() {
+               // fields uninitialised
+       }
+
+       protected CellRecord(RecordInputStream in) {
+               _rowIndex = in.readUShort();
+               _columnIndex = in.readUShort();
+               _formatIndex = in.readUShort();
+       }
+
+       public final void setRow(int row) {
+               _rowIndex = row;
+       }
+
+       public final void setColumn(short col) {
+               _columnIndex = col;
+       }
+
+       /**
+        * set the index to the ExtendedFormat
+        *
+        * @see org.apache.poi.hssf.record.ExtendedFormatRecord
+        * @param xf index to the XF record
+        */
+       public final void setXFIndex(short xf) {
+               _formatIndex = xf;
+       }
+
+       public final int getRow() {
+               return _rowIndex;
+       }
+
+       public final short getColumn() {
+               return (short) _columnIndex;
+       }
+
+       /**
+        * get the index to the ExtendedFormat
+        *
+        * @see org.apache.poi.hssf.record.ExtendedFormatRecord
+        * @return index to the XF record
+        */
+       public final short getXFIndex() {
+               return (short) _formatIndex;
+       }
+
+       public final String toString() {
+               StringBuilder sb = new StringBuilder();
+               String recordName = getRecordName();
+
+               sb.append("[").append(recordName).append("]\n");
+               sb.append("    .row    = ").append(HexDump.shortToHex(getRow())).append("\n");
+               sb.append("    .col    = ").append(HexDump.shortToHex(getColumn())).append("\n");
+               sb.append("    .xfindex= ").append(HexDump.shortToHex(getXFIndex())).append("\n");
+               appendValueText(sb);
+               sb.append("\n");
+               sb.append("[/").append(recordName).append("]\n");
+               return sb.toString();
+       }
+
+       /**
+        * Append specific debug info (used by {@link #toString()} for the value
+        * contained in this record. Trailing new-line should not be appended
+        * (superclass does that).
+        */
+       protected abstract void appendValueText(StringBuilder sb);
+
+       /**
+        * Gets the debug info BIFF record type name (used by {@link #toString()}.
+        */
+       protected abstract String getRecordName();
+
+       /**
+        * writes out the value data for this cell record
+        */
+       protected abstract void serializeValue(LittleEndianOutput out);
+
+       /**
+        * @return the size (in bytes) of the value data for this cell record
+        */
+       protected abstract int getValueDataSize();
+
+       public final void serialize(LittleEndianOutput out) {
+               out.writeShort(getRow());
+               out.writeShort(getColumn());
+               out.writeShort(getXFIndex());
+               serializeValue(out);
+       }
+
+       protected final int getDataSize() {
+               return 6 + getValueDataSize();
+       }
+
+       protected final void copyBaseFields(CellRecord rec) {
+               rec._rowIndex = _rowIndex;
+               rec._columnIndex = _columnIndex;
+               rec._formatIndex = _formatIndex;
+       }
+}
index 92ccf944f1060fc4d67a304a353a0efefdac544c..84678b7b65be2e37f1bcd6bce936778b87d6f7a2 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record;\r
-\r
-import org.apache.poi.util.LittleEndianOutput;\r
-import org.apache.poi.util.StringUtil;\r
-\r
-/**\r
- * Common header/footer base class\r
- * \r
- * @author Josh Micich\r
- */\r
-abstract class HeaderFooterBase extends StandardRecord {\r
-       private boolean field_2_hasMultibyte;\r
-       private String field_3_text;\r
-\r
-       protected HeaderFooterBase(String text) {\r
-               setText(text);\r
-       }\r
-\r
-       protected HeaderFooterBase(RecordInputStream in) {\r
-               if (in.remaining() > 0) {\r
-                       int field_1_footer_len = in.readShort();\r
-                       field_2_hasMultibyte = in.readByte() != 0x00;\r
-\r
-                       if (field_2_hasMultibyte) {\r
-                               field_3_text = in.readUnicodeLEString(field_1_footer_len);\r
-                       } else {\r
-                               field_3_text = in.readCompressedUnicode(field_1_footer_len);\r
-                       }\r
-               } else {\r
-                       // Note - this is unusual: when the text is empty string, the whole record is empty (just the 4 byte BIFF header)\r
-                       field_3_text = "";\r
-               }\r
-       }\r
-\r
-       /**\r
-        * set the footer string\r
-        * \r
-        * @param text string to display\r
-        */\r
-       public final void setText(String text) {\r
-               if (text == null) {\r
-                       throw new IllegalArgumentException("text must not be null");\r
-               }\r
-               field_2_hasMultibyte = StringUtil.hasMultibyte(text);\r
-               field_3_text = text;\r
-               \r
-               // Check it'll fit into the space in the record\r
-               if (field_2_hasMultibyte) {\r
-                       if (field_3_text.length() > 127) {\r
-                               throw new IllegalArgumentException(\r
-                                               "Footer string too long (limit is 127 for unicode strings)");\r
-                       }\r
-               } else {\r
-                       if (field_3_text.length() > 255) {\r
-                               throw new IllegalArgumentException(\r
-                                               "Footer string too long (limit is 255 for non-unicode strings)");\r
-                       }\r
-               }\r
-       }\r
-\r
-       /**\r
-        * get the length of the footer string\r
-        * \r
-        * @return length of the footer string\r
-        */\r
-       private int getTextLength() {\r
-               return field_3_text.length();\r
-       }\r
-\r
-       public final String getText() {\r
-               return field_3_text;\r
-       }\r
-\r
-       public final void serialize(LittleEndianOutput out) {\r
-               if (getTextLength() > 0) {\r
-                       out.writeShort(getTextLength());\r
-                       out.writeByte(field_2_hasMultibyte ? 0x01 : 0x00);\r
-                       if (field_2_hasMultibyte) {\r
-                               StringUtil.putUnicodeLE(field_3_text, out);\r
-                       } else {\r
-                               StringUtil.putCompressedUnicode(field_3_text, out);\r
-                       }\r
-               }\r
-       }\r
-\r
-       protected final int getDataSize() {\r
-               if (getTextLength() < 1) {\r
-                       return 0;\r
-               }\r
-               return 3 + getTextLength() * (field_2_hasMultibyte ? 2 : 1);\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.record;
+
+import org.apache.poi.util.LittleEndianOutput;
+import org.apache.poi.util.StringUtil;
+
+/**
+ * Common header/footer base class
+ *
+ * @author Josh Micich
+ */
+abstract class HeaderFooterBase extends StandardRecord {
+       private boolean field_2_hasMultibyte;
+       private String field_3_text;
+
+       protected HeaderFooterBase(String text) {
+               setText(text);
+       }
+
+       protected HeaderFooterBase(RecordInputStream in) {
+               if (in.remaining() > 0) {
+                       int field_1_footer_len = in.readShort();
+                       field_2_hasMultibyte = in.readByte() != 0x00;
+
+                       if (field_2_hasMultibyte) {
+                               field_3_text = in.readUnicodeLEString(field_1_footer_len);
+                       } else {
+                               field_3_text = in.readCompressedUnicode(field_1_footer_len);
+                       }
+               } else {
+                       // Note - this is unusual: when the text is empty string, the whole record is empty (just the 4 byte BIFF header)
+                       field_3_text = "";
+               }
+       }
+
+       /**
+        * set the footer string
+        *
+        * @param text string to display
+        */
+       public final void setText(String text) {
+               if (text == null) {
+                       throw new IllegalArgumentException("text must not be null");
+               }
+               field_2_hasMultibyte = StringUtil.hasMultibyte(text);
+               field_3_text = text;
+
+               // Check it'll fit into the space in the record
+               if (field_2_hasMultibyte) {
+                       if (field_3_text.length() > 127) {
+                               throw new IllegalArgumentException(
+                                               "Footer string too long (limit is 127 for unicode strings)");
+                       }
+               } else {
+                       if (field_3_text.length() > 255) {
+                               throw new IllegalArgumentException(
+                                               "Footer string too long (limit is 255 for non-unicode strings)");
+                       }
+               }
+       }
+
+       /**
+        * get the length of the footer string
+        *
+        * @return length of the footer string
+        */
+       private int getTextLength() {
+               return field_3_text.length();
+       }
+
+       public final String getText() {
+               return field_3_text;
+       }
+
+       public final void serialize(LittleEndianOutput out) {
+               if (getTextLength() > 0) {
+                       out.writeShort(getTextLength());
+                       out.writeByte(field_2_hasMultibyte ? 0x01 : 0x00);
+                       if (field_2_hasMultibyte) {
+                               StringUtil.putUnicodeLE(field_3_text, out);
+                       } else {
+                               StringUtil.putCompressedUnicode(field_3_text, out);
+                       }
+               }
+       }
+
+       protected final int getDataSize() {
+               if (getTextLength() < 1) {
+                       return 0;
+               }
+               return 3 + getTextLength() * (field_2_hasMultibyte ? 2 : 1);
+       }
+}
index 20fe141054ccb92b216164f61ee54baeacfd1c6b..347578c872713da1c5a5db529afe41253be50204 100644 (file)
@@ -1,57 +1,57 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record;\r
-\r
-import org.apache.poi.util.LittleEndianByteArrayOutputStream;\r
-import org.apache.poi.util.LittleEndianOutput;\r
-\r
-/**\r
- * Subclasses of this class (the majority of BIFF records) are non-continuable.  This allows for\r
- * some simplification of serialization logic\r
- * \r
- * @author Josh Micich\r
- */\r
-public abstract class StandardRecord extends Record {\r
-       protected abstract int getDataSize();\r
-       public final int getRecordSize() {\r
-               return 4 + getDataSize();\r
-       }\r
-       @Override\r
-       public final int serialize(int offset, byte[] data) {\r
-               int dataSize = getDataSize();\r
-               int recSize = 4 + dataSize;\r
-               LittleEndianByteArrayOutputStream out = new LittleEndianByteArrayOutputStream(data, offset, recSize);\r
-               out.writeShort(getSid());\r
-               out.writeShort(dataSize);\r
-               serialize(out);\r
-               if (out.getWriteIndex() - offset != recSize) {\r
-                       throw new IllegalStateException("Error in serialization of (" + getClass().getName() + "): "\r
-                                       + "Incorrect number of bytes written - expected " \r
-                                       + recSize + " but got " + (out.getWriteIndex() - offset));\r
-               }\r
-               return recSize;\r
-       }\r
-\r
-       /**\r
-        * Write the data content of this BIFF record.  The 'ushort sid' and 'ushort size' header fields\r
-        * have already been written by the superclass.<br/>\r
-        * \r
-        * The subclass must write the exact number of bytes as reported by {@link org.apache.poi.hssf.record.Record#getRecordSize()}}\r
-        */\r
-       protected abstract void serialize(LittleEndianOutput out);\r
-}\r
+/* ====================================================================
+   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.hssf.record;
+
+import org.apache.poi.util.LittleEndianByteArrayOutputStream;
+import org.apache.poi.util.LittleEndianOutput;
+
+/**
+ * Subclasses of this class (the majority of BIFF records) are non-continuable.  This allows for
+ * some simplification of serialization logic
+ *
+ * @author Josh Micich
+ */
+public abstract class StandardRecord extends Record {
+       protected abstract int getDataSize();
+       public final int getRecordSize() {
+               return 4 + getDataSize();
+       }
+       @Override
+       public final int serialize(int offset, byte[] data) {
+               int dataSize = getDataSize();
+               int recSize = 4 + dataSize;
+               LittleEndianByteArrayOutputStream out = new LittleEndianByteArrayOutputStream(data, offset, recSize);
+               out.writeShort(getSid());
+               out.writeShort(dataSize);
+               serialize(out);
+               if (out.getWriteIndex() - offset != recSize) {
+                       throw new IllegalStateException("Error in serialization of (" + getClass().getName() + "): "
+                                       + "Incorrect number of bytes written - expected "
+                                       + recSize + " but got " + (out.getWriteIndex() - offset));
+               }
+               return recSize;
+       }
+
+       /**
+        * Write the data content of this BIFF record.  The 'ushort sid' and 'ushort size' header fields
+        * have already been written by the superclass.<br/>
+        *
+        * The subclass must write the exact number of bytes as reported by {@link org.apache.poi.hssf.record.Record#getRecordSize()}}
+        */
+       protected abstract void serialize(LittleEndianOutput out);
+}
index 9b1d14d5624d18876fe635b7c2050bcf2f06f70f..a891488b9fe7e73c0c5c08f68bb31327c03c5f02 100644 (file)
@@ -1,87 +1,87 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record.aggregates;\r
-\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-\r
-import org.apache.poi.hssf.model.RecordStream;\r
-import org.apache.poi.hssf.record.BOFRecord;\r
-import org.apache.poi.hssf.record.EOFRecord;\r
-import org.apache.poi.hssf.record.Record;\r
-import org.apache.poi.hssf.record.RecordBase;\r
-import org.apache.poi.hssf.record.UnknownRecord;\r
-\r
-/**\r
- * Manages the all the records associated with a chart sub-stream.<br/>\r
- * Includes the initial {@link BOFRecord} and final {@link EOFRecord}.\r
- * \r
- * @author Josh Micich\r
- */\r
-public final class ChartSubstreamRecordAggregate extends RecordAggregate {\r
-\r
-       private final BOFRecord _bofRec;\r
-       /**\r
-        * All the records between BOF and EOF\r
-        */\r
-       private final List<RecordBase> _recs;\r
-       private PageSettingsBlock _psBlock;\r
-\r
-       public ChartSubstreamRecordAggregate(RecordStream rs) {\r
-               _bofRec = (BOFRecord) rs.getNext();\r
-               List<RecordBase> temp = new ArrayList<RecordBase>();\r
-               while (rs.peekNextClass() != EOFRecord.class) {\r
-                       if (PageSettingsBlock.isComponentRecord(rs.peekNextSid())) {\r
-                               if (_psBlock != null) {\r
-                                       if (rs.peekNextSid() == UnknownRecord.HEADER_FOOTER_089C) {\r
-                                               // test samples: 45538_classic_Footer.xls, 45538_classic_Header.xls\r
-                                               _psBlock.addLateHeaderFooter(rs.getNext());\r
-                                               continue;\r
-                                       }\r
-                                       throw new IllegalStateException(\r
-                                                       "Found more than one PageSettingsBlock in chart sub-stream");\r
-                               }\r
-                               _psBlock = new PageSettingsBlock(rs);\r
-                               temp.add(_psBlock);\r
-                               continue;\r
-                       }\r
-                       temp.add(rs.getNext());\r
-               }\r
-               _recs = temp;\r
-               Record eof = rs.getNext(); // no need to save EOF in field\r
-               if (!(eof instanceof EOFRecord)) {\r
-                       throw new IllegalStateException("Bad chart EOF");\r
-               }\r
-       }\r
-\r
-       public void visitContainedRecords(RecordVisitor rv) {\r
-               if (_recs.isEmpty()) {\r
-                       return;\r
-               }\r
-               rv.visitRecord(_bofRec);\r
-               for (int i = 0; i < _recs.size(); i++) {\r
-                       RecordBase rb = _recs.get(i);\r
-                       if (rb instanceof RecordAggregate) {\r
-                               ((RecordAggregate) rb).visitContainedRecords(rv);\r
-                       } else {\r
-                               rv.visitRecord((Record) rb);\r
-                       }\r
-               }\r
-               rv.visitRecord(EOFRecord.instance);\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.record.aggregates;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.poi.hssf.model.RecordStream;
+import org.apache.poi.hssf.record.BOFRecord;
+import org.apache.poi.hssf.record.EOFRecord;
+import org.apache.poi.hssf.record.Record;
+import org.apache.poi.hssf.record.RecordBase;
+import org.apache.poi.hssf.record.UnknownRecord;
+
+/**
+ * Manages the all the records associated with a chart sub-stream.<br/>
+ * Includes the initial {@link BOFRecord} and final {@link EOFRecord}.
+ *
+ * @author Josh Micich
+ */
+public final class ChartSubstreamRecordAggregate extends RecordAggregate {
+
+       private final BOFRecord _bofRec;
+       /**
+        * All the records between BOF and EOF
+        */
+       private final List<RecordBase> _recs;
+       private PageSettingsBlock _psBlock;
+
+       public ChartSubstreamRecordAggregate(RecordStream rs) {
+               _bofRec = (BOFRecord) rs.getNext();
+               List<RecordBase> temp = new ArrayList<RecordBase>();
+               while (rs.peekNextClass() != EOFRecord.class) {
+                       if (PageSettingsBlock.isComponentRecord(rs.peekNextSid())) {
+                               if (_psBlock != null) {
+                                       if (rs.peekNextSid() == UnknownRecord.HEADER_FOOTER_089C) {
+                                               // test samples: 45538_classic_Footer.xls, 45538_classic_Header.xls
+                                               _psBlock.addLateHeaderFooter(rs.getNext());
+                                               continue;
+                                       }
+                                       throw new IllegalStateException(
+                                                       "Found more than one PageSettingsBlock in chart sub-stream");
+                               }
+                               _psBlock = new PageSettingsBlock(rs);
+                               temp.add(_psBlock);
+                               continue;
+                       }
+                       temp.add(rs.getNext());
+               }
+               _recs = temp;
+               Record eof = rs.getNext(); // no need to save EOF in field
+               if (!(eof instanceof EOFRecord)) {
+                       throw new IllegalStateException("Bad chart EOF");
+               }
+       }
+
+       public void visitContainedRecords(RecordVisitor rv) {
+               if (_recs.isEmpty()) {
+                       return;
+               }
+               rv.visitRecord(_bofRec);
+               for (int i = 0; i < _recs.size(); i++) {
+                       RecordBase rb = _recs.get(i);
+                       if (rb instanceof RecordAggregate) {
+                               ((RecordAggregate) rb).visitContainedRecords(rv);
+                       } else {
+                               rv.visitRecord((Record) rb);
+                       }
+               }
+               rv.visitRecord(EOFRecord.instance);
+       }
+}
index f4861b011b64ad17b8deec7983d97a72a0735df5..e2dfcd6d35370b13095fc0c1321af6212f8868d4 100644 (file)
@@ -1,70 +1,70 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record.aggregates;\r
-\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-\r
-import org.apache.poi.hssf.model.RecordStream;\r
-import org.apache.poi.hssf.record.DVALRecord;\r
-import org.apache.poi.hssf.record.DVRecord;\r
-import org.apache.poi.hssf.record.Record;\r
-\r
-/**\r
- * Manages the DVALRecord and DVRecords for a single sheet<br/>\r
- * See OOO excelfileformat.pdf section 4.14\r
- * @author Josh Micich\r
- */\r
-public final class DataValidityTable extends RecordAggregate {\r
-\r
-       private final DVALRecord _headerRec;\r
-       /**\r
-        * The list of data validations for the current sheet.\r
-        * Note - this may be empty (contrary to OOO documentation)\r
-        */\r
-       private final List _validationList;\r
-\r
-       public DataValidityTable(RecordStream rs) {\r
-               _headerRec = (DVALRecord) rs.getNext();\r
-               List temp = new ArrayList();\r
-               while (rs.peekNextClass() == DVRecord.class) {\r
-                       temp.add(rs.getNext());\r
-               }\r
-               _validationList = temp;\r
-       }\r
-\r
-       public DataValidityTable() {\r
-               _headerRec = new DVALRecord();\r
-               _validationList = new ArrayList();\r
-       }\r
-\r
-       public void visitContainedRecords(RecordVisitor rv) {\r
-               if (_validationList.isEmpty()) {\r
-                       return;\r
-               }\r
-               rv.visitRecord(_headerRec);\r
-               for (int i = 0; i < _validationList.size(); i++) {\r
-                       rv.visitRecord((Record) _validationList.get(i));\r
-               }\r
-       }\r
-       \r
-       public void addDataValidation(DVRecord dvRecord) {\r
-               _validationList.add(dvRecord);\r
-               _headerRec.setDVRecNo(_validationList.size());\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.record.aggregates;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.poi.hssf.model.RecordStream;
+import org.apache.poi.hssf.record.DVALRecord;
+import org.apache.poi.hssf.record.DVRecord;
+import org.apache.poi.hssf.record.Record;
+
+/**
+ * Manages the DVALRecord and DVRecords for a single sheet<br/>
+ * See OOO excelfileformat.pdf section 4.14
+ * @author Josh Micich
+ */
+public final class DataValidityTable extends RecordAggregate {
+
+       private final DVALRecord _headerRec;
+       /**
+        * The list of data validations for the current sheet.
+        * Note - this may be empty (contrary to OOO documentation)
+        */
+       private final List _validationList;
+
+       public DataValidityTable(RecordStream rs) {
+               _headerRec = (DVALRecord) rs.getNext();
+               List temp = new ArrayList();
+               while (rs.peekNextClass() == DVRecord.class) {
+                       temp.add(rs.getNext());
+               }
+               _validationList = temp;
+       }
+
+       public DataValidityTable() {
+               _headerRec = new DVALRecord();
+               _validationList = new ArrayList();
+       }
+
+       public void visitContainedRecords(RecordVisitor rv) {
+               if (_validationList.isEmpty()) {
+                       return;
+               }
+               rv.visitRecord(_headerRec);
+               for (int i = 0; i < _validationList.size(); i++) {
+                       rv.visitRecord((Record) _validationList.get(i));
+               }
+       }
+
+       public void addDataValidation(DVRecord dvRecord) {
+               _validationList.add(dvRecord);
+               _headerRec.setDVRecNo(_validationList.size());
+       }
+}
index 6eefb30e1c8b44131ca16e28f57718d42c28989c..fd458df967561c3d6f8a8dd3f7a7aa0a638af518 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record.aggregates;\r
-\r
-import org.apache.poi.hssf.record.Record;\r
-import org.apache.poi.hssf.record.RecordBase;\r
-\r
-/**\r
- * <tt>RecordAggregate</tt>s are groups of of BIFF <tt>Record</tt>s that are typically stored \r
- * together and/or updated together.  Workbook / Sheet records are typically stored in a sequential\r
- * list, which does not provide much structure to coordinate updates.\r
- * \r
- * @author Josh Micich\r
- */\r
-public abstract class RecordAggregate extends RecordBase {\r
-\r
-       /**\r
-        * Visit each of the atomic BIFF records contained in this {@link RecordAggregate} in the order\r
-        * that they should be written to file.  Implementors may or may not return the actual \r
-        * {@link Record}s being used to manage POI's internal implementation.  Callers should not\r
-        * assume either way, and therefore only attempt to modify those {@link Record}s after cloning\r
-        */\r
-       public abstract void visitContainedRecords(RecordVisitor rv);\r
-       \r
-       public final int serialize(int offset, byte[] data) {\r
-               SerializingRecordVisitor srv = new SerializingRecordVisitor(data, offset);\r
-               visitContainedRecords(srv);\r
-               return srv.countBytesWritten();\r
-       }\r
-       public int getRecordSize() {\r
-               RecordSizingVisitor rsv = new RecordSizingVisitor();\r
-               visitContainedRecords(rsv);\r
-               return rsv.getTotalSize();\r
-       }\r
-       \r
-       public interface RecordVisitor {\r
-               /**\r
-                * Implementors may call non-mutating methods on Record r.\r
-                * @param r must not be <code>null</code>\r
-                */\r
-               void visitRecord(Record r);\r
-       }\r
-       \r
-       private static final class SerializingRecordVisitor implements RecordVisitor {\r
-\r
-               private final byte[] _data;\r
-               private final int _startOffset;\r
-               private int _countBytesWritten;\r
-\r
-               public SerializingRecordVisitor(byte[] data, int startOffset) {\r
-                       _data = data;\r
-                       _startOffset = startOffset;\r
-                       _countBytesWritten = 0;\r
-               }\r
-               public int countBytesWritten() {\r
-                       return _countBytesWritten;\r
-               }\r
-               public void visitRecord(Record r) {\r
-                       int currentOffset = _startOffset + _countBytesWritten;\r
-                       _countBytesWritten += r.serialize(currentOffset, _data);\r
-               }\r
-       }\r
-       private static final class RecordSizingVisitor implements RecordVisitor {\r
-\r
-               private int _totalSize;\r
-               \r
-               public RecordSizingVisitor() {\r
-                       _totalSize = 0;\r
-               }\r
-               public int getTotalSize() {\r
-                       return _totalSize;\r
-               }\r
-               public void visitRecord(Record r) {\r
-                       _totalSize += r.getRecordSize();\r
-               }\r
-       }\r
-       /**\r
-        * A wrapper for {@link RecordVisitor} which accumulates the sizes of all\r
-        * records visited.\r
-        */\r
-       public static final class PositionTrackingVisitor implements RecordVisitor {\r
-               private final RecordVisitor _rv;\r
-               private int _position;\r
-\r
-               public PositionTrackingVisitor(RecordVisitor rv, int initialPosition) {\r
-                       _rv = rv;\r
-                       _position = initialPosition;\r
-               }\r
-               public void visitRecord(Record r) {\r
-                       _position += r.getRecordSize();\r
-                       _rv.visitRecord(r);\r
-               }\r
-               public void setPosition(int position) {\r
-                       _position = position;\r
-               }\r
-               public int getPosition() {\r
-                       return _position;\r
-               }\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.record.aggregates;
+
+import org.apache.poi.hssf.record.Record;
+import org.apache.poi.hssf.record.RecordBase;
+
+/**
+ * <tt>RecordAggregate</tt>s are groups of of BIFF <tt>Record</tt>s that are typically stored
+ * together and/or updated together.  Workbook / Sheet records are typically stored in a sequential
+ * list, which does not provide much structure to coordinate updates.
+ *
+ * @author Josh Micich
+ */
+public abstract class RecordAggregate extends RecordBase {
+
+       /**
+        * Visit each of the atomic BIFF records contained in this {@link RecordAggregate} in the order
+        * that they should be written to file.  Implementors may or may not return the actual
+        * {@link Record}s being used to manage POI's internal implementation.  Callers should not
+        * assume either way, and therefore only attempt to modify those {@link Record}s after cloning
+        */
+       public abstract void visitContainedRecords(RecordVisitor rv);
+
+       public final int serialize(int offset, byte[] data) {
+               SerializingRecordVisitor srv = new SerializingRecordVisitor(data, offset);
+               visitContainedRecords(srv);
+               return srv.countBytesWritten();
+       }
+       public int getRecordSize() {
+               RecordSizingVisitor rsv = new RecordSizingVisitor();
+               visitContainedRecords(rsv);
+               return rsv.getTotalSize();
+       }
+
+       public interface RecordVisitor {
+               /**
+                * Implementors may call non-mutating methods on Record r.
+                * @param r must not be <code>null</code>
+                */
+               void visitRecord(Record r);
+       }
+
+       private static final class SerializingRecordVisitor implements RecordVisitor {
+
+               private final byte[] _data;
+               private final int _startOffset;
+               private int _countBytesWritten;
+
+               public SerializingRecordVisitor(byte[] data, int startOffset) {
+                       _data = data;
+                       _startOffset = startOffset;
+                       _countBytesWritten = 0;
+               }
+               public int countBytesWritten() {
+                       return _countBytesWritten;
+               }
+               public void visitRecord(Record r) {
+                       int currentOffset = _startOffset + _countBytesWritten;
+                       _countBytesWritten += r.serialize(currentOffset, _data);
+               }
+       }
+       private static final class RecordSizingVisitor implements RecordVisitor {
+
+               private int _totalSize;
+
+               public RecordSizingVisitor() {
+                       _totalSize = 0;
+               }
+               public int getTotalSize() {
+                       return _totalSize;
+               }
+               public void visitRecord(Record r) {
+                       _totalSize += r.getRecordSize();
+               }
+       }
+       /**
+        * A wrapper for {@link RecordVisitor} which accumulates the sizes of all
+        * records visited.
+        */
+       public static final class PositionTrackingVisitor implements RecordVisitor {
+               private final RecordVisitor _rv;
+               private int _position;
+
+               public PositionTrackingVisitor(RecordVisitor rv, int initialPosition) {
+                       _rv = rv;
+                       _position = initialPosition;
+               }
+               public void visitRecord(Record r) {
+                       _position += r.getRecordSize();
+                       _rv.visitRecord(r);
+               }
+               public void setPosition(int position) {
+                       _position = position;
+               }
+               public int getPosition() {
+                       return _position;
+               }
+       }
+}
index 01fedd0294b18aa11913b3881dc4a86ad08ae4e8..3048054418fc028b1d7aa588b36f46ceacc78ca9 100644 (file)
@@ -1,69 +1,69 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record.cont;\r
-\r
-import org.apache.poi.hssf.record.ContinueRecord;\r
-import org.apache.poi.hssf.record.Record;\r
-import org.apache.poi.util.LittleEndianByteArrayOutputStream;\r
-import org.apache.poi.util.LittleEndianOutput;\r
-\r
-/**\r
- * Common superclass of all records that can produce {@link ContinueRecord}s while being serialized.\r
- * \r
- * @author Josh Micich\r
- */\r
-public abstract class ContinuableRecord extends Record {\r
-\r
-       protected ContinuableRecord() {\r
-               // no fields to initialise \r
-       }\r
-       /**\r
-        * Serializes this record's content to the supplied data output.<br/>\r
-        * The standard BIFF header (ushort sid, ushort size) has been handled by the superclass, so \r
-        * only BIFF data should be written by this method.  Simple data types can be written with the\r
-        * standard {@link LittleEndianOutput} methods.  Methods from {@link ContinuableRecordOutput} \r
-        * can be used to serialize strings (with {@link ContinueRecord}s being written as required).\r
-        * If necessary, implementors can explicitly start {@link ContinueRecord}s (regardless of the\r
-        * amount of remaining space).\r
-        * \r
-        * @param out a data output stream\r
-        */\r
-       protected abstract void serialize(ContinuableRecordOutput out);\r
-\r
-\r
-       /**\r
-        * @return the total length of the encoded record(s) \r
-        * (Note - if any {@link ContinueRecord} is required, this result includes the\r
-        * size of those too)\r
-        */\r
-       public final int getRecordSize() {\r
-               ContinuableRecordOutput out = ContinuableRecordOutput.createForCountingOnly();\r
-               serialize(out);\r
-               out.terminate();\r
-               return out.getTotalSize();\r
-       }\r
-\r
-       public final int serialize(int offset, byte[] data) {\r
-\r
-               LittleEndianOutput leo = new LittleEndianByteArrayOutputStream(data, offset);\r
-               ContinuableRecordOutput out = new ContinuableRecordOutput(leo, getSid());\r
-               serialize(out);\r
-               out.terminate();\r
-               return out.getTotalSize();\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.record.cont;
+
+import org.apache.poi.hssf.record.ContinueRecord;
+import org.apache.poi.hssf.record.Record;
+import org.apache.poi.util.LittleEndianByteArrayOutputStream;
+import org.apache.poi.util.LittleEndianOutput;
+
+/**
+ * Common superclass of all records that can produce {@link ContinueRecord}s while being serialized.
+ *
+ * @author Josh Micich
+ */
+public abstract class ContinuableRecord extends Record {
+
+       protected ContinuableRecord() {
+               // no fields to initialise
+       }
+       /**
+        * Serializes this record's content to the supplied data output.<br/>
+        * The standard BIFF header (ushort sid, ushort size) has been handled by the superclass, so
+        * only BIFF data should be written by this method.  Simple data types can be written with the
+        * standard {@link LittleEndianOutput} methods.  Methods from {@link ContinuableRecordOutput}
+        * can be used to serialize strings (with {@link ContinueRecord}s being written as required).
+        * If necessary, implementors can explicitly start {@link ContinueRecord}s (regardless of the
+        * amount of remaining space).
+        *
+        * @param out a data output stream
+        */
+       protected abstract void serialize(ContinuableRecordOutput out);
+
+
+       /**
+        * @return the total length of the encoded record(s)
+        * (Note - if any {@link ContinueRecord} is required, this result includes the
+        * size of those too)
+        */
+       public final int getRecordSize() {
+               ContinuableRecordOutput out = ContinuableRecordOutput.createForCountingOnly();
+               serialize(out);
+               out.terminate();
+               return out.getTotalSize();
+       }
+
+       public final int serialize(int offset, byte[] data) {
+
+               LittleEndianOutput leo = new LittleEndianByteArrayOutputStream(data, offset);
+               ContinuableRecordOutput out = new ContinuableRecordOutput(leo, getSid());
+               serialize(out);
+               out.terminate();
+               return out.getTotalSize();
+       }
+}
index 5d540365b7e22a90ab5b6f74dba6a7004fdd4faa..26946c7ccaf988a4a2ffb93d3f5418696ec6055a 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record.cont;\r
-\r
-import org.apache.poi.hssf.record.ContinueRecord;\r
-import org.apache.poi.util.DelayableLittleEndianOutput;\r
-import org.apache.poi.util.LittleEndianOutput;\r
-import org.apache.poi.util.StringUtil;\r
-\r
-/**\r
- * An augmented {@link LittleEndianOutput} used for serialization of {@link ContinuableRecord}s.\r
- * This class keeps track of how much remaining space is available in the current BIFF record and\r
- * can start new {@link ContinueRecord}s as required. \r
- * \r
- * @author Josh Micich\r
- */\r
-public final class ContinuableRecordOutput implements LittleEndianOutput {\r
-       \r
-       private final LittleEndianOutput _out;\r
-       private UnknownLengthRecordOutput _ulrOutput;\r
-       private int _totalPreviousRecordsSize;\r
-\r
-       ContinuableRecordOutput(LittleEndianOutput out, int sid) {\r
-               _ulrOutput = new UnknownLengthRecordOutput(out, sid);\r
-               _out = out;\r
-               _totalPreviousRecordsSize = 0;\r
-       }\r
-       \r
-       public static ContinuableRecordOutput createForCountingOnly() {\r
-               return new ContinuableRecordOutput(NOPOutput, -777); // fake sid\r
-       }\r
-\r
-       /**\r
-        * @return total number of bytes written so far (including all BIFF headers) \r
-        */\r
-       public int getTotalSize() {\r
-               return _totalPreviousRecordsSize + _ulrOutput.getTotalSize();\r
-       }\r
-       /**\r
-        * Terminates the last record (also updates its 'ushort size' field)\r
-        */\r
-       void terminate() {\r
-               _ulrOutput.terminate();\r
-       }\r
-       /**\r
-        * @return number of remaining bytes of space in current record\r
-        */\r
-       public int getAvailableSpace() {\r
-               return _ulrOutput.getAvailableSpace();\r
-       }\r
-       \r
-       /**\r
-        * Terminates the current record and starts a new {@link ContinueRecord} (regardless\r
-        * of how much space is still available in the current record).\r
-        */\r
-       public void writeContinue() {\r
-               _ulrOutput.terminate();\r
-               _totalPreviousRecordsSize += _ulrOutput.getTotalSize();\r
-               _ulrOutput = new UnknownLengthRecordOutput(_out, ContinueRecord.sid);\r
-       }\r
-       public void writeContinueIfRequired(int requiredContinuousSize) {\r
-               if (_ulrOutput.getAvailableSpace() < requiredContinuousSize) {\r
-                       writeContinue();\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Writes the 'optionFlags' byte and encoded character data of a unicode string.  This includes:\r
-        * <ul>\r
-        * <li>byte optionFlags</li>\r
-        * <li>encoded character data (in "ISO-8859-1" or "UTF-16LE" encoding)</li>\r
-        * </ul>\r
-        * \r
-        * Notes:\r
-        * <ul>\r
-        * <li>The value of the 'is16bitEncoded' flag is determined by the actual character data \r
-        * of <tt>text</tt></li>\r
-        * <li>The string options flag is never separated (by a {@link ContinueRecord}) from the\r
-        * first chunk of character data it refers to.</li>\r
-        * <li>The 'ushort length' field is assumed to have been explicitly written earlier.  Hence, \r
-        * there may be an intervening {@link ContinueRecord}</li>\r
-        * </ul>\r
-        */\r
-       public void writeStringData(String text) {\r
-               boolean is16bitEncoded = StringUtil.hasMultibyte(text);\r
-               // calculate total size of the header and first encoded char\r
-               int keepTogetherSize = 1 + 1; // ushort len, at least one character byte\r
-               int optionFlags = 0x00;\r
-               if (is16bitEncoded) {\r
-                       optionFlags |= 0x01;\r
-                       keepTogetherSize += 1; // one extra byte for first char\r
-               }\r
-               writeContinueIfRequired(keepTogetherSize);\r
-               writeByte(optionFlags);\r
-               writeCharacterData(text, is16bitEncoded);\r
-       }\r
-       /**\r
-        * Writes a unicode string complete with header and character data.  This includes:\r
-        * <ul>\r
-        * <li>ushort length</li>\r
-        * <li>byte optionFlags</li>\r
-        * <li>ushort numberOfRichTextRuns (optional)</li>\r
-        * <li>ushort extendedDataSize (optional)</li>\r
-        * <li>encoded character data (in "ISO-8859-1" or "UTF-16LE" encoding)</li>\r
-        * </ul>\r
-        * \r
-        * The following bits of the 'optionFlags' byte will be set as appropriate:\r
-        * <table border='1'>\r
-        * <tr><th>Mask</th><th>Description</th></tr>\r
-        * <tr><td>0x01</td><td>is16bitEncoded</td></tr>\r
-        * <tr><td>0x04</td><td>hasExtendedData</td></tr>\r
-        * <tr><td>0x08</td><td>isRichText</td></tr>\r
-        * </table>\r
-        * Notes:\r
-        * <ul> \r
-        * <li>The value of the 'is16bitEncoded' flag is determined by the actual character data \r
-        * of <tt>text</tt></li>\r
-        * <li>The string header fields are never separated (by a {@link ContinueRecord}) from the\r
-        * first chunk of character data (i.e. the first character is always encoded in the same\r
-        * record as the string header).</li>\r
-        * </ul>\r
-        */\r
-       public void writeString(String text, int numberOfRichTextRuns, int extendedDataSize) {\r
-               boolean is16bitEncoded = StringUtil.hasMultibyte(text);\r
-               // calculate total size of the header and first encoded char\r
-               int keepTogetherSize = 2 + 1 + 1; // ushort len, byte optionFlags, at least one character byte\r
-               int optionFlags = 0x00;\r
-               if (is16bitEncoded) {\r
-                       optionFlags |= 0x01;\r
-                       keepTogetherSize += 1; // one extra byte for first char\r
-               }\r
-               if (numberOfRichTextRuns > 0) {\r
-                       optionFlags |= 0x08;\r
-                       keepTogetherSize += 2;\r
-               }\r
-               if (extendedDataSize > 0) {\r
-                       optionFlags |= 0x04;\r
-                       keepTogetherSize += 4;\r
-               }\r
-               writeContinueIfRequired(keepTogetherSize);\r
-               writeShort(text.length());\r
-               writeByte(optionFlags);\r
-               if (numberOfRichTextRuns > 0) {\r
-                       writeShort(numberOfRichTextRuns);\r
-               }\r
-               if (extendedDataSize > 0) {\r
-                       writeInt(extendedDataSize);\r
-               }\r
-               writeCharacterData(text, is16bitEncoded);\r
-       }\r
-\r
-\r
-       private void writeCharacterData(String text, boolean is16bitEncoded) {\r
-               int nChars = text.length();\r
-               int i=0;\r
-               if (is16bitEncoded) {\r
-                       while(true) {\r
-                               int nWritableChars = Math.min(nChars-i, _ulrOutput.getAvailableSpace() / 2);\r
-                               for ( ; nWritableChars > 0; nWritableChars--) {\r
-                                       _ulrOutput.writeShort(text.charAt(i++));\r
-                               }\r
-                               if (i >= nChars) {\r
-                                       break;\r
-                               }\r
-                               writeContinue();\r
-                               writeByte(0x01); \r
-                       }\r
-               } else {\r
-                       while(true) {\r
-                               int nWritableChars = Math.min(nChars-i, _ulrOutput.getAvailableSpace() / 1);\r
-                               for ( ; nWritableChars > 0; nWritableChars--) {\r
-                                       _ulrOutput.writeByte(text.charAt(i++));\r
-                               }\r
-                               if (i >= nChars) {\r
-                                       break;\r
-                               }\r
-                               writeContinue();\r
-                               writeByte(0x00); \r
-                       }\r
-               }\r
-       }\r
-\r
-       public void write(byte[] b) {\r
-               writeContinueIfRequired(b.length);\r
-               _ulrOutput.write(b);\r
-       }\r
-       public void write(byte[] b, int offset, int len) {\r
-               writeContinueIfRequired(len);\r
-               _ulrOutput.write(b, offset, len);\r
-       }\r
-       public void writeByte(int v) {\r
-               writeContinueIfRequired(1);\r
-               _ulrOutput.writeByte(v);\r
-       }\r
-       public void writeDouble(double v) {\r
-               writeContinueIfRequired(8);\r
-               _ulrOutput.writeDouble(v);\r
-       }\r
-       public void writeInt(int v) {\r
-               writeContinueIfRequired(4);\r
-               _ulrOutput.writeInt(v);\r
-       }\r
-       public void writeLong(long v) {\r
-               writeContinueIfRequired(8);\r
-               _ulrOutput.writeLong(v);\r
-       }\r
-       public void writeShort(int v) {\r
-               writeContinueIfRequired(2);\r
-               _ulrOutput.writeShort(v);\r
-       }\r
-       \r
-       /**\r
-        * Allows optimised usage of {@link ContinuableRecordOutput} for sizing purposes only.\r
-        */\r
-    private static final LittleEndianOutput NOPOutput = new DelayableLittleEndianOutput() {\r
-\r
-               public LittleEndianOutput createDelayedOutput(int size) {\r
-                       return this;\r
-               }\r
-               public void write(byte[] b) {\r
-                       // does nothing\r
-               }\r
-               public void write(byte[] b, int offset, int len) {\r
-                       // does nothing\r
-               }\r
-               public void writeByte(int v) {\r
-                       // does nothing\r
-               }\r
-               public void writeDouble(double v) {\r
-                       // does nothing\r
-               }\r
-               public void writeInt(int v) {\r
-                       // does nothing\r
-               }\r
-               public void writeLong(long v) {\r
-                       // does nothing\r
-               }\r
-               public void writeShort(int v) {\r
-                       // does nothing\r
-               }\r
-    };\r
-}\r
+/* ====================================================================
+   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.hssf.record.cont;
+
+import org.apache.poi.hssf.record.ContinueRecord;
+import org.apache.poi.util.DelayableLittleEndianOutput;
+import org.apache.poi.util.LittleEndianOutput;
+import org.apache.poi.util.StringUtil;
+
+/**
+ * An augmented {@link LittleEndianOutput} used for serialization of {@link ContinuableRecord}s.
+ * This class keeps track of how much remaining space is available in the current BIFF record and
+ * can start new {@link ContinueRecord}s as required.
+ *
+ * @author Josh Micich
+ */
+public final class ContinuableRecordOutput implements LittleEndianOutput {
+
+       private final LittleEndianOutput _out;
+       private UnknownLengthRecordOutput _ulrOutput;
+       private int _totalPreviousRecordsSize;
+
+       ContinuableRecordOutput(LittleEndianOutput out, int sid) {
+               _ulrOutput = new UnknownLengthRecordOutput(out, sid);
+               _out = out;
+               _totalPreviousRecordsSize = 0;
+       }
+
+       public static ContinuableRecordOutput createForCountingOnly() {
+               return new ContinuableRecordOutput(NOPOutput, -777); // fake sid
+       }
+
+       /**
+        * @return total number of bytes written so far (including all BIFF headers)
+        */
+       public int getTotalSize() {
+               return _totalPreviousRecordsSize + _ulrOutput.getTotalSize();
+       }
+       /**
+        * Terminates the last record (also updates its 'ushort size' field)
+        */
+       void terminate() {
+               _ulrOutput.terminate();
+       }
+       /**
+        * @return number of remaining bytes of space in current record
+        */
+       public int getAvailableSpace() {
+               return _ulrOutput.getAvailableSpace();
+       }
+
+       /**
+        * Terminates the current record and starts a new {@link ContinueRecord} (regardless
+        * of how much space is still available in the current record).
+        */
+       public void writeContinue() {
+               _ulrOutput.terminate();
+               _totalPreviousRecordsSize += _ulrOutput.getTotalSize();
+               _ulrOutput = new UnknownLengthRecordOutput(_out, ContinueRecord.sid);
+       }
+       public void writeContinueIfRequired(int requiredContinuousSize) {
+               if (_ulrOutput.getAvailableSpace() < requiredContinuousSize) {
+                       writeContinue();
+               }
+       }
+
+       /**
+        * Writes the 'optionFlags' byte and encoded character data of a unicode string.  This includes:
+        * <ul>
+        * <li>byte optionFlags</li>
+        * <li>encoded character data (in "ISO-8859-1" or "UTF-16LE" encoding)</li>
+        * </ul>
+        *
+        * Notes:
+        * <ul>
+        * <li>The value of the 'is16bitEncoded' flag is determined by the actual character data
+        * of <tt>text</tt></li>
+        * <li>The string options flag is never separated (by a {@link ContinueRecord}) from the
+        * first chunk of character data it refers to.</li>
+        * <li>The 'ushort length' field is assumed to have been explicitly written earlier.  Hence,
+        * there may be an intervening {@link ContinueRecord}</li>
+        * </ul>
+        */
+       public void writeStringData(String text) {
+               boolean is16bitEncoded = StringUtil.hasMultibyte(text);
+               // calculate total size of the header and first encoded char
+               int keepTogetherSize = 1 + 1; // ushort len, at least one character byte
+               int optionFlags = 0x00;
+               if (is16bitEncoded) {
+                       optionFlags |= 0x01;
+                       keepTogetherSize += 1; // one extra byte for first char
+               }
+               writeContinueIfRequired(keepTogetherSize);
+               writeByte(optionFlags);
+               writeCharacterData(text, is16bitEncoded);
+       }
+       /**
+        * Writes a unicode string complete with header and character data.  This includes:
+        * <ul>
+        * <li>ushort length</li>
+        * <li>byte optionFlags</li>
+        * <li>ushort numberOfRichTextRuns (optional)</li>
+        * <li>ushort extendedDataSize (optional)</li>
+        * <li>encoded character data (in "ISO-8859-1" or "UTF-16LE" encoding)</li>
+        * </ul>
+        *
+        * The following bits of the 'optionFlags' byte will be set as appropriate:
+        * <table border='1'>
+        * <tr><th>Mask</th><th>Description</th></tr>
+        * <tr><td>0x01</td><td>is16bitEncoded</td></tr>
+        * <tr><td>0x04</td><td>hasExtendedData</td></tr>
+        * <tr><td>0x08</td><td>isRichText</td></tr>
+        * </table>
+        * Notes:
+        * <ul>
+        * <li>The value of the 'is16bitEncoded' flag is determined by the actual character data
+        * of <tt>text</tt></li>
+        * <li>The string header fields are never separated (by a {@link ContinueRecord}) from the
+        * first chunk of character data (i.e. the first character is always encoded in the same
+        * record as the string header).</li>
+        * </ul>
+        */
+       public void writeString(String text, int numberOfRichTextRuns, int extendedDataSize) {
+               boolean is16bitEncoded = StringUtil.hasMultibyte(text);
+               // calculate total size of the header and first encoded char
+               int keepTogetherSize = 2 + 1 + 1; // ushort len, byte optionFlags, at least one character byte
+               int optionFlags = 0x00;
+               if (is16bitEncoded) {
+                       optionFlags |= 0x01;
+                       keepTogetherSize += 1; // one extra byte for first char
+               }
+               if (numberOfRichTextRuns > 0) {
+                       optionFlags |= 0x08;
+                       keepTogetherSize += 2;
+               }
+               if (extendedDataSize > 0) {
+                       optionFlags |= 0x04;
+                       keepTogetherSize += 4;
+               }
+               writeContinueIfRequired(keepTogetherSize);
+               writeShort(text.length());
+               writeByte(optionFlags);
+               if (numberOfRichTextRuns > 0) {
+                       writeShort(numberOfRichTextRuns);
+               }
+               if (extendedDataSize > 0) {
+                       writeInt(extendedDataSize);
+               }
+               writeCharacterData(text, is16bitEncoded);
+       }
+
+
+       private void writeCharacterData(String text, boolean is16bitEncoded) {
+               int nChars = text.length();
+               int i=0;
+               if (is16bitEncoded) {
+                       while(true) {
+                               int nWritableChars = Math.min(nChars-i, _ulrOutput.getAvailableSpace() / 2);
+                               for ( ; nWritableChars > 0; nWritableChars--) {
+                                       _ulrOutput.writeShort(text.charAt(i++));
+                               }
+                               if (i >= nChars) {
+                                       break;
+                               }
+                               writeContinue();
+                               writeByte(0x01);
+                       }
+               } else {
+                       while(true) {
+                               int nWritableChars = Math.min(nChars-i, _ulrOutput.getAvailableSpace() / 1);
+                               for ( ; nWritableChars > 0; nWritableChars--) {
+                                       _ulrOutput.writeByte(text.charAt(i++));
+                               }
+                               if (i >= nChars) {
+                                       break;
+                               }
+                               writeContinue();
+                               writeByte(0x00);
+                       }
+               }
+       }
+
+       public void write(byte[] b) {
+               writeContinueIfRequired(b.length);
+               _ulrOutput.write(b);
+       }
+       public void write(byte[] b, int offset, int len) {
+               writeContinueIfRequired(len);
+               _ulrOutput.write(b, offset, len);
+       }
+       public void writeByte(int v) {
+               writeContinueIfRequired(1);
+               _ulrOutput.writeByte(v);
+       }
+       public void writeDouble(double v) {
+               writeContinueIfRequired(8);
+               _ulrOutput.writeDouble(v);
+       }
+       public void writeInt(int v) {
+               writeContinueIfRequired(4);
+               _ulrOutput.writeInt(v);
+       }
+       public void writeLong(long v) {
+               writeContinueIfRequired(8);
+               _ulrOutput.writeLong(v);
+       }
+       public void writeShort(int v) {
+               writeContinueIfRequired(2);
+               _ulrOutput.writeShort(v);
+       }
+
+       /**
+        * Allows optimised usage of {@link ContinuableRecordOutput} for sizing purposes only.
+        */
+       private static final LittleEndianOutput NOPOutput = new DelayableLittleEndianOutput() {
+
+               public LittleEndianOutput createDelayedOutput(int size) {
+                       return this;
+               }
+               public void write(byte[] b) {
+                       // does nothing
+               }
+               public void write(byte[] b, int offset, int len) {
+                       // does nothing
+               }
+               public void writeByte(int v) {
+                       // does nothing
+               }
+               public void writeDouble(double v) {
+                       // does nothing
+               }
+               public void writeInt(int v) {
+                       // does nothing
+               }
+               public void writeLong(long v) {
+                       // does nothing
+               }
+               public void writeShort(int v) {
+                       // does nothing
+               }
+       };
+}
index 9209566c239c088cc78811b120c35daf1e8968a4..322a5208fc58a8f839c9efb3e169864f28fa84b0 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record.cont;\r
-\r
-import org.apache.poi.hssf.record.RecordInputStream;\r
-import org.apache.poi.util.DelayableLittleEndianOutput;\r
-import org.apache.poi.util.LittleEndianByteArrayOutputStream;\r
-import org.apache.poi.util.LittleEndianOutput;\r
-/**\r
- * Allows the writing of BIFF records when the 'ushort size' header field is not known in advance.\r
- * When the client is finished writing data, it calls {@link #terminate()}, at which point this \r
- * class updates the 'ushort size' with its final value. \r
- * \r
- * @author Josh Micich\r
- */\r
-final class UnknownLengthRecordOutput implements LittleEndianOutput {\r
-       private static final int MAX_DATA_SIZE = RecordInputStream.MAX_RECORD_DATA_SIZE;\r
-\r
-       private final LittleEndianOutput _originalOut;\r
-       /** for writing the 'ushort size'  field once its value is known */\r
-       private final LittleEndianOutput _dataSizeOutput;\r
-       private final byte[] _byteBuffer;\r
-       private LittleEndianOutput _out;\r
-       private int _size;\r
-       \r
-       public UnknownLengthRecordOutput(LittleEndianOutput out, int sid) {\r
-               _originalOut = out;\r
-               out.writeShort(sid);\r
-               if (out instanceof DelayableLittleEndianOutput) {\r
-                       // optimisation\r
-                       DelayableLittleEndianOutput dleo = (DelayableLittleEndianOutput) out;\r
-                       _dataSizeOutput = dleo.createDelayedOutput(2);\r
-                       _byteBuffer = null;\r
-                       _out = out;\r
-               } else {\r
-                       // otherwise temporarily write all subsequent data to a buffer\r
-                       _dataSizeOutput = out;\r
-                       _byteBuffer = new byte[RecordInputStream.MAX_RECORD_DATA_SIZE];\r
-                       _out = new LittleEndianByteArrayOutputStream(_byteBuffer, 0);\r
-               }\r
-       }\r
-       /**\r
-        * includes 4 byte header\r
-        */\r
-       public int getTotalSize() {\r
-               return 4 + _size;\r
-       }\r
-       public int getAvailableSpace() {\r
-               if (_out == null) {\r
-                       throw new IllegalStateException("Record already terminated");\r
-               }\r
-               return MAX_DATA_SIZE - _size;\r
-       }\r
-       /**\r
-        * Finishes writing the current record and updates 'ushort size' field.<br/>\r
-        * After this method is called, only {@link #getTotalSize()} may be called.\r
-        */\r
-       public void terminate() {\r
-               if (_out == null) {\r
-                       throw new IllegalStateException("Record already terminated");\r
-               }\r
-               _dataSizeOutput.writeShort(_size);\r
-               if (_byteBuffer != null) {\r
-                       _originalOut.write(_byteBuffer, 0, _size);\r
-                       _out = null;\r
-                       return;\r
-               }\r
-               _out = null;\r
-       }\r
-       \r
-       public void write(byte[] b) {\r
-               _out.write(b);\r
-               _size += b.length;\r
-       }\r
-       public void write(byte[] b, int offset, int len) {\r
-               _out.write(b, offset, len);\r
-               _size += len;\r
-       }\r
-       public void writeByte(int v) {\r
-               _out.writeByte(v);\r
-               _size += 1;\r
-       }\r
-       public void writeDouble(double v) {\r
-               _out.writeDouble(v);\r
-               _size += 8;\r
-       }\r
-       public void writeInt(int v) {\r
-               _out.writeInt(v);\r
-               _size += 4;\r
-       }\r
-       public void writeLong(long v) {\r
-               _out.writeLong(v);\r
-               _size += 8;\r
-       }\r
-       public void writeShort(int v) {\r
-               _out.writeShort(v);\r
-               _size += 2;\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.record.cont;
+
+import org.apache.poi.hssf.record.RecordInputStream;
+import org.apache.poi.util.DelayableLittleEndianOutput;
+import org.apache.poi.util.LittleEndianByteArrayOutputStream;
+import org.apache.poi.util.LittleEndianOutput;
+/**
+ * Allows the writing of BIFF records when the 'ushort size' header field is not known in advance.
+ * When the client is finished writing data, it calls {@link #terminate()}, at which point this
+ * class updates the 'ushort size' with its final value.
+ *
+ * @author Josh Micich
+ */
+final class UnknownLengthRecordOutput implements LittleEndianOutput {
+       private static final int MAX_DATA_SIZE = RecordInputStream.MAX_RECORD_DATA_SIZE;
+
+       private final LittleEndianOutput _originalOut;
+       /** for writing the 'ushort size'  field once its value is known */
+       private final LittleEndianOutput _dataSizeOutput;
+       private final byte[] _byteBuffer;
+       private LittleEndianOutput _out;
+       private int _size;
+
+       public UnknownLengthRecordOutput(LittleEndianOutput out, int sid) {
+               _originalOut = out;
+               out.writeShort(sid);
+               if (out instanceof DelayableLittleEndianOutput) {
+                       // optimisation
+                       DelayableLittleEndianOutput dleo = (DelayableLittleEndianOutput) out;
+                       _dataSizeOutput = dleo.createDelayedOutput(2);
+                       _byteBuffer = null;
+                       _out = out;
+               } else {
+                       // otherwise temporarily write all subsequent data to a buffer
+                       _dataSizeOutput = out;
+                       _byteBuffer = new byte[RecordInputStream.MAX_RECORD_DATA_SIZE];
+                       _out = new LittleEndianByteArrayOutputStream(_byteBuffer, 0);
+               }
+       }
+       /**
+        * includes 4 byte header
+        */
+       public int getTotalSize() {
+               return 4 + _size;
+       }
+       public int getAvailableSpace() {
+               if (_out == null) {
+                       throw new IllegalStateException("Record already terminated");
+               }
+               return MAX_DATA_SIZE - _size;
+       }
+       /**
+        * Finishes writing the current record and updates 'ushort size' field.<br/>
+        * After this method is called, only {@link #getTotalSize()} may be called.
+        */
+       public void terminate() {
+               if (_out == null) {
+                       throw new IllegalStateException("Record already terminated");
+               }
+               _dataSizeOutput.writeShort(_size);
+               if (_byteBuffer != null) {
+                       _originalOut.write(_byteBuffer, 0, _size);
+                       _out = null;
+                       return;
+               }
+               _out = null;
+       }
+
+       public void write(byte[] b) {
+               _out.write(b);
+               _size += b.length;
+       }
+       public void write(byte[] b, int offset, int len) {
+               _out.write(b, offset, len);
+               _size += len;
+       }
+       public void writeByte(int v) {
+               _out.writeByte(v);
+               _size += 1;
+       }
+       public void writeDouble(double v) {
+               _out.writeDouble(v);
+               _size += 8;
+       }
+       public void writeInt(int v) {
+               _out.writeInt(v);
+               _size += 4;
+       }
+       public void writeLong(long v) {
+               _out.writeLong(v);
+               _size += 8;
+       }
+       public void writeShort(int v) {
+               _out.writeShort(v);
+               _size += 2;
+       }
+}
index 57f2c919dbb1227daf81553690ce035332d59d28..6383bb066182e9d19258f2f9afe9b39a268615b8 100644 (file)
@@ -1,64 +1,64 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record.formula;\r
-\r
-import org.apache.poi.ss.util.AreaReference;\r
-import org.apache.poi.util.LittleEndianInput;\r
-import org.apache.poi.util.LittleEndianOutput;\r
-\r
-/**\r
- * Common superclass of 2-D area refs\r
- */\r
-public abstract class Area2DPtgBase extends AreaPtgBase {\r
-       private final static int SIZE = 9;\r
-\r
-       protected Area2DPtgBase(int firstRow, int lastRow, int firstColumn, int lastColumn, boolean firstRowRelative, boolean lastRowRelative, boolean firstColRelative, boolean lastColRelative) {\r
-               super(firstRow, lastRow, firstColumn, lastColumn, firstRowRelative, lastRowRelative, firstColRelative, lastColRelative);\r
-       }\r
-       protected Area2DPtgBase(AreaReference ar) {\r
-               super(ar);\r
-       }\r
-\r
-       protected Area2DPtgBase(LittleEndianInput in)  {\r
-               readCoordinates(in);\r
-       }\r
-\r
-       protected abstract byte getSid();\r
-\r
-       public final void write(LittleEndianOutput out) {\r
-               out.writeByte(getSid() + getPtgClass());\r
-               writeCoordinates(out);\r
-       }\r
-\r
-       public final int getSize() {\r
-               return SIZE;\r
-       }\r
-\r
-       public final String toFormulaString() {\r
-               return formatReferenceAsString();\r
-       }\r
-\r
-       public final String toString() {\r
-               StringBuffer sb = new StringBuffer();\r
-               sb.append(getClass().getName());\r
-               sb.append(" [");\r
-               sb.append(formatReferenceAsString());\r
-               sb.append("]");\r
-               return sb.toString();\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.record.formula;
+
+import org.apache.poi.ss.util.AreaReference;
+import org.apache.poi.util.LittleEndianInput;
+import org.apache.poi.util.LittleEndianOutput;
+
+/**
+ * Common superclass of 2-D area refs
+ */
+public abstract class Area2DPtgBase extends AreaPtgBase {
+       private final static int SIZE = 9;
+
+       protected Area2DPtgBase(int firstRow, int lastRow, int firstColumn, int lastColumn, boolean firstRowRelative, boolean lastRowRelative, boolean firstColRelative, boolean lastColRelative) {
+               super(firstRow, lastRow, firstColumn, lastColumn, firstRowRelative, lastRowRelative, firstColRelative, lastColRelative);
+       }
+       protected Area2DPtgBase(AreaReference ar) {
+               super(ar);
+       }
+
+       protected Area2DPtgBase(LittleEndianInput in)  {
+               readCoordinates(in);
+       }
+
+       protected abstract byte getSid();
+
+       public final void write(LittleEndianOutput out) {
+               out.writeByte(getSid() + getPtgClass());
+               writeCoordinates(out);
+       }
+
+       public final int getSize() {
+               return SIZE;
+       }
+
+       public final String toFormulaString() {
+               return formatReferenceAsString();
+       }
+
+       public final String toString() {
+               StringBuffer sb = new StringBuffer();
+               sb.append(getClass().getName());
+               sb.append(" [");
+               sb.append(formatReferenceAsString());
+               sb.append("]");
+               return sb.toString();
+       }
+}
index 859d0ff0a0a21e453f828326e529174f4af0526e..68b96d9bf56c8ac094b2c973ca2ec25df489d8a3 100644 (file)
@@ -1,54 +1,54 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record.formula;\r
-\r
-import org.apache.poi.ss.util.CellReference;\r
-import org.apache.poi.util.LittleEndianInput;\r
-\r
-/**\r
- * ReferencePtg - handles references (such as A1, A2, IA4)\r
- * @author  Andrew C. Oliver (acoliver@apache.org)\r
- * @author Jason Height (jheight at chariot dot net dot au)\r
- */\r
-public final class RefPtg extends Ref2DPtgBase {\r
-       public final static byte sid = 0x24;\r
-\r
-       /**\r
-        * Takes in a String representation of a cell reference and fills out the\r
-        * numeric fields.\r
-        */\r
-       public RefPtg(String cellref) {\r
-               super(new CellReference(cellref));\r
-       }\r
-\r
-       public RefPtg(int row, int column, boolean isRowRelative, boolean isColumnRelative) {\r
-               super(row, column, isRowRelative, isColumnRelative);\r
-       }\r
-\r
-       public RefPtg(LittleEndianInput in)  {\r
-               super(in);\r
-       }\r
-\r
-       public RefPtg(CellReference cr) {\r
-               super(cr);\r
-       }\r
-\r
-       protected byte getSid() {\r
-               return sid;\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.record.formula;
+
+import org.apache.poi.ss.util.CellReference;
+import org.apache.poi.util.LittleEndianInput;
+
+/**
+ * ReferencePtg - handles references (such as A1, A2, IA4)
+ * @author  Andrew C. Oliver (acoliver@apache.org)
+ * @author Jason Height (jheight at chariot dot net dot au)
+ */
+public final class RefPtg extends Ref2DPtgBase {
+       public final static byte sid = 0x24;
+
+       /**
+        * Takes in a String representation of a cell reference and fills out the
+        * numeric fields.
+        */
+       public RefPtg(String cellref) {
+               super(new CellReference(cellref));
+       }
+
+       public RefPtg(int row, int column, boolean isRowRelative, boolean isColumnRelative) {
+               super(row, column, isRowRelative, isColumnRelative);
+       }
+
+       public RefPtg(LittleEndianInput in)  {
+               super(in);
+       }
+
+       public RefPtg(CellReference cr) {
+               super(cr);
+       }
+
+       protected byte getSid() {
+               return sid;
+       }
+}
index 869e38d2e08f5022ae0fe9a4bd69887a6d5699a9..b36f4978e2f0fbf552c201fdd3b7dc8629e49365 100644 (file)
@@ -1,40 +1,40 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record.formula;\r
-\r
-\r
-/**\r
- * @author Josh Micich\r
- */\r
-abstract class ScalarConstantPtg extends Ptg {\r
-       public boolean isBaseToken() {\r
-               return true;\r
-       }\r
-\r
-       public final byte getDefaultOperandClass() {\r
-               return Ptg.CLASS_VALUE;\r
-       }\r
-\r
-       public final String toString() {\r
-               StringBuffer sb = new StringBuffer(64);\r
-               sb.append(getClass().getName()).append(" [");\r
-               sb.append(toFormulaString());\r
-               sb.append("]");\r
-               return sb.toString();\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.record.formula;
+
+
+/**
+ * @author Josh Micich
+ */
+abstract class ScalarConstantPtg extends Ptg {
+       public boolean isBaseToken() {
+               return true;
+       }
+
+       public final byte getDefaultOperandClass() {
+               return Ptg.CLASS_VALUE;
+       }
+
+       public final String toString() {
+               StringBuffer sb = new StringBuffer(64);
+               sb.append(getClass().getName()).append(" [");
+               sb.append(toFormulaString());
+               sb.append("]");
+               return sb.toString();
+       }
+}
index 6012e1b98373912fc9da0cab102b81742edb57e5..32cdc72e17cd6b30b9d5121f841c7690c8bb6c3f 100644 (file)
@@ -1,40 +1,40 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.record.formula.eval;\r
-\r
-/**\r
- * Common base class for implementors of {@link RefEval}\r
- *\r
- * @author Josh Micich\r
- */\r
-public abstract class RefEvalBase implements RefEval {\r
-\r
-       private final int _rowIndex;\r
-       private final int _columnIndex;\r
-\r
-       protected RefEvalBase(int rowIndex, int columnIndex) {\r
-               _rowIndex = rowIndex;\r
-               _columnIndex = columnIndex;\r
-       }\r
-       public final int getRow() {\r
-               return _rowIndex;\r
-       }\r
-       public final int getColumn() {\r
-               return _columnIndex;\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.record.formula.eval;
+
+/**
+ * Common base class for implementors of {@link RefEval}
+ *
+ * @author Josh Micich
+ */
+public abstract class RefEvalBase implements RefEval {
+
+       private final int _rowIndex;
+       private final int _columnIndex;
+
+       protected RefEvalBase(int rowIndex, int columnIndex) {
+               _rowIndex = rowIndex;
+               _columnIndex = columnIndex;
+       }
+       public final int getRow() {
+               return _rowIndex;
+       }
+       public final int getColumn() {
+               return _columnIndex;
+       }
+}
index 10805658a75a2b87b1ef3350364261f7e9b39035..968daef664525930c24cf0ad972ce6b308c47758 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.usermodel;\r
-\r
-import org.apache.poi.hssf.model.HSSFFormulaParser;\r
-import org.apache.poi.hssf.model.Workbook;\r
-import org.apache.poi.hssf.record.NameRecord;\r
-import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;\r
-import org.apache.poi.hssf.record.formula.NamePtg;\r
-import org.apache.poi.hssf.record.formula.NameXPtg;\r
-import org.apache.poi.hssf.record.formula.Ptg;\r
-import org.apache.poi.ss.formula.*;\r
-import org.apache.poi.ss.SpreadsheetVersion;\r
-\r
-/**\r
- * Internal POI use only\r
- * \r
- * @author Josh Micich\r
- */\r
-public final class HSSFEvaluationWorkbook implements FormulaRenderingWorkbook, EvaluationWorkbook, FormulaParsingWorkbook {\r
-\r
-    private final HSSFWorkbook _uBook;\r
-    private final Workbook _iBook;\r
-\r
-    public static HSSFEvaluationWorkbook create(HSSFWorkbook book) {\r
-        if (book == null) {\r
-            return null;\r
-        }\r
-        return new HSSFEvaluationWorkbook(book);\r
-    }\r
-\r
-    private HSSFEvaluationWorkbook(HSSFWorkbook book) {\r
-        _uBook = book;\r
-        _iBook = book.getWorkbook();\r
-    }\r
-\r
-    public int getExternalSheetIndex(String sheetName) {\r
-        int sheetIndex = _uBook.getSheetIndex(sheetName);\r
-        return _iBook.checkExternSheet(sheetIndex);\r
-    }\r
-    public int getExternalSheetIndex(String workbookName, String sheetName) {\r
-        return _iBook.getExternalSheetIndex(workbookName, sheetName);\r
-    }\r
-\r
-    public NameXPtg getNameXPtg(String name) {\r
-        return _iBook.getNameXPtg(name);\r
-    }\r
-\r
-    /**\r
-     * Lookup a named range by its name.\r
-     *\r
-     * @param name the name to search\r
-     * @param sheetIndex  the 0-based index of the sheet this formula belongs to.\r
-     * The sheet index is required to resolve sheet-level names. <code>-1</code> means workbook-global names\r
-      */\r
-    public EvaluationName getName(String name, int sheetIndex) {\r
-        for(int i=0; i < _iBook.getNumNames(); i++) {\r
-            NameRecord nr = _iBook.getNameRecord(i);\r
-            if (nr.getSheetNumber() == sheetIndex+1 && name.equalsIgnoreCase(nr.getNameText())) {\r
-                return new Name(nr, i);\r
-            }\r
-        }\r
-        return sheetIndex == -1 ? null : getName(name, -1);\r
-    }\r
-\r
-    public int getSheetIndex(EvaluationSheet evalSheet) {\r
-        HSSFSheet sheet = ((HSSFEvaluationSheet)evalSheet).getHSSFSheet();\r
-        return _uBook.getSheetIndex(sheet);\r
-    }\r
-    public int getSheetIndex(String sheetName) {\r
-        return _uBook.getSheetIndex(sheetName);\r
-    }\r
-\r
-    public String getSheetName(int sheetIndex) {\r
-        return _uBook.getSheetName(sheetIndex);\r
-    }\r
-\r
-    public EvaluationSheet getSheet(int sheetIndex) {\r
-        return new HSSFEvaluationSheet(_uBook.getSheetAt(sheetIndex));\r
-    }\r
-    public int convertFromExternSheetIndex(int externSheetIndex) {\r
-        return _iBook.getSheetIndexFromExternSheetIndex(externSheetIndex);\r
-    }\r
-\r
-    public ExternalSheet getExternalSheet(int externSheetIndex) {\r
-        return _iBook.getExternalSheet(externSheetIndex);\r
-    }\r
-\r
-    public String resolveNameXText(NameXPtg n) {\r
-        return _iBook.resolveNameXText(n.getSheetRefIndex(), n.getNameIndex());\r
-    }\r
-\r
-    public String getSheetNameByExternSheet(int externSheetIndex) {\r
-        return _iBook.findSheetNameFromExternSheet(externSheetIndex);\r
-    }\r
-    public String getNameText(NamePtg namePtg) {\r
-        return _iBook.getNameRecord(namePtg.getIndex()).getNameText();\r
-    }\r
-    public EvaluationName getName(NamePtg namePtg) {\r
-        int ix = namePtg.getIndex();\r
-        return new Name(_iBook.getNameRecord(ix), ix);\r
-    }\r
-    public Ptg[] getFormulaTokens(EvaluationCell evalCell) {\r
-        HSSFCell cell = ((HSSFEvaluationCell)evalCell).getHSSFCell();\r
-        if (false) {\r
-            // re-parsing the formula text also works, but is a waste of time\r
-            // It is useful from time to time to run all unit tests with this code\r
-            // to make sure that all formulas POI can evaluate can also be parsed.\r
-            return HSSFFormulaParser.parse(cell.getCellFormula(), _uBook, FormulaType.CELL, _uBook.getSheetIndex(cell.getSheet()));\r
-        }\r
-        FormulaRecordAggregate fra = (FormulaRecordAggregate) cell.getCellValueRecord();\r
-        return fra.getFormulaTokens();\r
-    }\r
-\r
-    private static final class Name implements EvaluationName {\r
-\r
-        private final NameRecord _nameRecord;\r
-        private final int _index;\r
-\r
-        public Name(NameRecord nameRecord, int index) {\r
-            _nameRecord = nameRecord;\r
-            _index = index;\r
-        }\r
-        public Ptg[] getNameDefinition() {\r
-            return _nameRecord.getNameDefinition();\r
-        }\r
-        public String getNameText() {\r
-            return _nameRecord.getNameText();\r
-        }\r
-        public boolean hasFormula() {\r
-            return _nameRecord.hasFormula();\r
-        }\r
-        public boolean isFunctionName() {\r
-            return _nameRecord.isFunctionName();\r
-        }\r
-        public boolean isRange() {\r
-            return _nameRecord.hasFormula(); // TODO - is this right?\r
-        }\r
-        public NamePtg createPtg() {\r
-            return new NamePtg(_index);\r
-        }\r
-    }\r
-\r
-    public SpreadsheetVersion getSpreadsheetVersion(){\r
-        return SpreadsheetVersion.EXCEL97;    \r
-    }\r
-}\r
+/* ====================================================================
+   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.hssf.usermodel;
+
+import org.apache.poi.hssf.model.HSSFFormulaParser;
+import org.apache.poi.hssf.model.Workbook;
+import org.apache.poi.hssf.record.NameRecord;
+import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
+import org.apache.poi.hssf.record.formula.NamePtg;
+import org.apache.poi.hssf.record.formula.NameXPtg;
+import org.apache.poi.hssf.record.formula.Ptg;
+import org.apache.poi.ss.formula.*;
+import org.apache.poi.ss.SpreadsheetVersion;
+
+/**
+ * Internal POI use only
+ *
+ * @author Josh Micich
+ */
+public final class HSSFEvaluationWorkbook implements FormulaRenderingWorkbook, EvaluationWorkbook, FormulaParsingWorkbook {
+
+    private final HSSFWorkbook _uBook;
+    private final Workbook _iBook;
+
+    public static HSSFEvaluationWorkbook create(HSSFWorkbook book) {
+        if (book == null) {
+            return null;
+        }
+        return new HSSFEvaluationWorkbook(book);
+    }
+
+    private HSSFEvaluationWorkbook(HSSFWorkbook book) {
+        _uBook = book;
+        _iBook = book.getWorkbook();
+    }
+
+    public int getExternalSheetIndex(String sheetName) {
+        int sheetIndex = _uBook.getSheetIndex(sheetName);
+        return _iBook.checkExternSheet(sheetIndex);
+    }
+    public int getExternalSheetIndex(String workbookName, String sheetName) {
+        return _iBook.getExternalSheetIndex(workbookName, sheetName);
+    }
+
+    public NameXPtg getNameXPtg(String name) {
+        return _iBook.getNameXPtg(name);
+    }
+
+    /**
+     * Lookup a named range by its name.
+     *
+     * @param name the name to search
+     * @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
+      */
+    public EvaluationName getName(String name, int sheetIndex) {
+        for(int i=0; i < _iBook.getNumNames(); i++) {
+            NameRecord nr = _iBook.getNameRecord(i);
+            if (nr.getSheetNumber() == sheetIndex+1 && name.equalsIgnoreCase(nr.getNameText())) {
+                return new Name(nr, i);
+            }
+        }
+        return sheetIndex == -1 ? null : getName(name, -1);
+    }
+
+    public int getSheetIndex(EvaluationSheet evalSheet) {
+        HSSFSheet sheet = ((HSSFEvaluationSheet)evalSheet).getHSSFSheet();
+        return _uBook.getSheetIndex(sheet);
+    }
+    public int getSheetIndex(String sheetName) {
+        return _uBook.getSheetIndex(sheetName);
+    }
+
+    public String getSheetName(int sheetIndex) {
+        return _uBook.getSheetName(sheetIndex);
+    }
+
+    public EvaluationSheet getSheet(int sheetIndex) {
+        return new HSSFEvaluationSheet(_uBook.getSheetAt(sheetIndex));
+    }
+    public int convertFromExternSheetIndex(int externSheetIndex) {
+        return _iBook.getSheetIndexFromExternSheetIndex(externSheetIndex);
+    }
+
+    public ExternalSheet getExternalSheet(int externSheetIndex) {
+        return _iBook.getExternalSheet(externSheetIndex);
+    }
+
+    public String resolveNameXText(NameXPtg n) {
+        return _iBook.resolveNameXText(n.getSheetRefIndex(), n.getNameIndex());
+    }
+
+    public String getSheetNameByExternSheet(int externSheetIndex) {
+        return _iBook.findSheetNameFromExternSheet(externSheetIndex);
+    }
+    public String getNameText(NamePtg namePtg) {
+        return _iBook.getNameRecord(namePtg.getIndex()).getNameText();
+    }
+    public EvaluationName getName(NamePtg namePtg) {
+        int ix = namePtg.getIndex();
+        return new Name(_iBook.getNameRecord(ix), ix);
+    }
+    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.
+            return HSSFFormulaParser.parse(cell.getCellFormula(), _uBook, FormulaType.CELL, _uBook.getSheetIndex(cell.getSheet()));
+        }
+        FormulaRecordAggregate fra = (FormulaRecordAggregate) cell.getCellValueRecord();
+        return fra.getFormulaTokens();
+    }
+
+    private static final class Name implements EvaluationName {
+
+        private final NameRecord _nameRecord;
+        private final int _index;
+
+        public Name(NameRecord nameRecord, int index) {
+            _nameRecord = nameRecord;
+            _index = index;
+        }
+        public Ptg[] getNameDefinition() {
+            return _nameRecord.getNameDefinition();
+        }
+        public String getNameText() {
+            return _nameRecord.getNameText();
+        }
+        public boolean hasFormula() {
+            return _nameRecord.hasFormula();
+        }
+        public boolean isFunctionName() {
+            return _nameRecord.isFunctionName();
+        }
+        public boolean isRange() {
+            return _nameRecord.hasFormula(); // TODO - is this right?
+        }
+        public NamePtg createPtg() {
+            return new NamePtg(_index);
+        }
+    }
+
+    public SpreadsheetVersion getSpreadsheetVersion(){
+        return SpreadsheetVersion.EXCEL97;
+    }
+}
index aa1a0a5d04b9da666cf8ff192e6194caf8931a4b..a49fb9c684a71ddfd89bec04a176554b6017e86b 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.usermodel;\r
-\r
-import java.util.Iterator;\r
-\r
-import org.apache.poi.hssf.record.formula.eval.BoolEval;\r
-import org.apache.poi.hssf.record.formula.eval.ErrorEval;\r
-import org.apache.poi.hssf.record.formula.eval.NumberEval;\r
-import org.apache.poi.hssf.record.formula.eval.StringEval;\r
-import org.apache.poi.hssf.record.formula.eval.ValueEval;\r
-import org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment;\r
-import org.apache.poi.ss.formula.IStabilityClassifier;\r
-import org.apache.poi.ss.formula.WorkbookEvaluator;\r
-import org.apache.poi.ss.usermodel.Cell;\r
-import org.apache.poi.ss.usermodel.CellValue;\r
-import org.apache.poi.ss.usermodel.FormulaEvaluator;\r
-\r
-/**\r
- * Evaluates formula cells.<p/>\r
- *\r
- * For performance reasons, this class keeps a cache of all previously calculated intermediate\r
- * cell values.  Be sure to call {@link #clearAllCachedResultValues()} if any workbook cells are changed between\r
- * calls to evaluate~ methods on this class.\r
- *\r
- * @author Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt;\r
- * @author Josh Micich\r
- */\r
-public class HSSFFormulaEvaluator implements FormulaEvaluator  {\r
-\r
-       private WorkbookEvaluator _bookEvaluator;\r
-\r
-       /**\r
-        * @deprecated (Sep 2008) HSSFSheet parameter is ignored\r
-        */\r
-       public HSSFFormulaEvaluator(HSSFSheet sheet, HSSFWorkbook workbook) {\r
-               this(workbook);\r
-               if (false) {\r
-                       sheet.toString(); // suppress unused parameter compiler warning\r
-               }\r
-       }\r
-       public HSSFFormulaEvaluator(HSSFWorkbook workbook) {\r
-               this(workbook, null);\r
-       }\r
-       /**\r
-        * @param stabilityClassifier used to optimise caching performance. Pass <code>null</code>\r
-        * for the (conservative) assumption that any cell may have its definition changed after \r
-        * evaluation begins.\r
-        */\r
-       public HSSFFormulaEvaluator(HSSFWorkbook workbook, IStabilityClassifier stabilityClassifier) {\r
-               _bookEvaluator = new WorkbookEvaluator(HSSFEvaluationWorkbook.create(workbook), stabilityClassifier);\r
-       }\r
-\r
-       /**\r
-        * Coordinates several formula evaluators together so that formulas that involve external\r
-        * references can be evaluated.\r
-        * @param workbookNames the simple file names used to identify the workbooks in formulas\r
-        * with external links (for example "MyData.xls" as used in a formula "[MyData.xls]Sheet1!A1")\r
-        * @param evaluators all evaluators for the full set of workbooks required by the formulas.\r
-        */\r
-       public static void setupEnvironment(String[] workbookNames, HSSFFormulaEvaluator[] evaluators) {\r
-               WorkbookEvaluator[] wbEvals = new WorkbookEvaluator[evaluators.length];\r
-               for (int i = 0; i < wbEvals.length; i++) {\r
-                       wbEvals[i] = evaluators[i]._bookEvaluator;\r
-               }\r
-               CollaboratingWorkbooksEnvironment.setup(workbookNames, wbEvals);\r
-       }\r
-\r
-       /**\r
-        * Does nothing\r
-        * @deprecated (Aug 2008) - not needed, since the current row can be derived from the cell\r
-        */\r
-       public void setCurrentRow(HSSFRow row) {\r
-               // do nothing\r
-               if (false) {\r
-                       row.getClass(); // suppress unused parameter compiler warning\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Should be called whenever there are major changes (e.g. moving sheets) to input cells\r
-        * in the evaluated workbook.  If performance is not critical, a single call to this method\r
-        * may be used instead of many specific calls to the notify~ methods.\r
-        *\r
-        * Failure to call this method after changing cell values will cause incorrect behaviour\r
-        * of the evaluate~ methods of this class\r
-        */\r
-       public void clearAllCachedResultValues() {\r
-               _bookEvaluator.clearAllCachedResultValues();\r
-       }\r
-       /**\r
-        * Should be called to tell the cell value cache that the specified (value or formula) cell\r
-        * has changed.\r
-        * Failure to call this method after changing cell values will cause incorrect behaviour\r
-        * of the evaluate~ methods of this class\r
-        */\r
-       public void notifyUpdateCell(HSSFCell cell) {\r
-               _bookEvaluator.notifyUpdateCell(new HSSFEvaluationCell(cell));\r
-       }\r
-       /**\r
-        * Should be called to tell the cell value cache that the specified cell has just been\r
-        * deleted.\r
-        * Failure to call this method after changing cell values will cause incorrect behaviour\r
-        * of the evaluate~ methods of this class\r
-        */\r
-       public void notifyDeleteCell(HSSFCell cell) {\r
-               _bookEvaluator.notifyDeleteCell(new HSSFEvaluationCell(cell));\r
-       }\r
-       public void notifyDeleteCell(Cell cell) {\r
-               _bookEvaluator.notifyDeleteCell(new HSSFEvaluationCell((HSSFCell)cell));\r
-       }\r
-\r
-       /**\r
-        * Should be called to tell the cell value cache that the specified (value or formula) cell\r
-        * has changed.\r
-        * Failure to call this method after changing cell values will cause incorrect behaviour\r
-        * of the evaluate~ methods of this class\r
-        */\r
-       public void notifySetFormula(Cell cell) {\r
-               _bookEvaluator.notifyUpdateCell(new HSSFEvaluationCell((HSSFCell)cell));\r
-       }\r
-\r
-       /**\r
-        * If cell contains a formula, the formula is evaluated and returned,\r
-        * else the CellValue simply copies the appropriate cell value from\r
-        * the cell and also its cell type. This method should be preferred over\r
-        * evaluateInCell() when the call should not modify the contents of the\r
-        * original cell.\r
-        *\r
-        * @param cell may be <code>null</code> signifying that the cell is not present (or blank)\r
-        * @return <code>null</code> if the supplied cell is <code>null</code> or blank\r
-        */\r
-       public CellValue evaluate(Cell cell) {\r
-               if (cell == null) {\r
-                       return null;\r
-               }\r
-\r
-               switch (cell.getCellType()) {\r
-                       case HSSFCell.CELL_TYPE_BOOLEAN:\r
-                               return CellValue.valueOf(cell.getBooleanCellValue());\r
-                       case HSSFCell.CELL_TYPE_ERROR:\r
-                               return CellValue.getError(cell.getErrorCellValue());\r
-                       case HSSFCell.CELL_TYPE_FORMULA:\r
-                               return evaluateFormulaCellValue(cell);\r
-                       case HSSFCell.CELL_TYPE_NUMERIC:\r
-                               return new CellValue(cell.getNumericCellValue());\r
-                       case HSSFCell.CELL_TYPE_STRING:\r
-                               return new CellValue(cell.getRichStringCellValue().getString());\r
-                       case HSSFCell.CELL_TYPE_BLANK:\r
-                               return null;\r
-               }\r
-               throw new IllegalStateException("Bad cell type (" + cell.getCellType() + ")");\r
-       }\r
-\r
-\r
-       /**\r
-        * If cell contains formula, it evaluates the formula, and saves the result of the formula. The\r
-        * cell remains as a formula cell. If the cell does not contain formula, this method returns -1\r
-        * and leaves the cell unchanged.\r
-        *\r
-        * Note that the type of the <em>formula result</em> is returned, so you know what kind of\r
-        * cached formula result is also stored with  the formula.\r
-        * <pre>\r
-        * int evaluatedCellType = evaluator.evaluateFormulaCell(cell);\r
-        * </pre>\r
-        * Be aware that your cell will hold both the formula, and the result. If you want the cell\r
-        * replaced with the result of the formula, use {@link #evaluateInCell(org.apache.poi.ss.usermodel.Cell)}\r
-        * @param cell The cell to evaluate\r
-        * @return -1 for non-formula cells, or the type of the <em>formula result</em>\r
-        */\r
-       public int evaluateFormulaCell(Cell cell) {\r
-               if (cell == null || cell.getCellType() != HSSFCell.CELL_TYPE_FORMULA) {\r
-                       return -1;\r
-               }\r
-               CellValue cv = evaluateFormulaCellValue(cell);\r
-               // cell remains a formula cell, but the cached value is changed\r
-               setCellValue(cell, cv);\r
-               return cv.getCellType();\r
-       }\r
-\r
-       /**\r
-        * If cell contains formula, it evaluates the formula, and\r
-        *  puts the formula result back into the cell, in place\r
-        *  of the old formula.\r
-        * Else if cell does not contain formula, this method leaves\r
-        *  the cell unchanged.\r
-        * Note that the same instance of HSSFCell is returned to\r
-        * allow chained calls like:\r
-        * <pre>\r
-        * int evaluatedCellType = evaluator.evaluateInCell(cell).getCellType();\r
-        * </pre>\r
-        * Be aware that your cell value will be changed to hold the\r
-        *  result of the formula. If you simply want the formula\r
-        *  value computed for you, use {@link #evaluateFormulaCell(Cell)}}\r
-        */\r
-       public HSSFCell evaluateInCell(Cell cell) {\r
-               if (cell == null) {\r
-                       return null;\r
-               }\r
-               HSSFCell result = (HSSFCell) cell;\r
-               if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {\r
-                       CellValue cv = evaluateFormulaCellValue(cell);\r
-                       setCellValue(cell, cv);\r
-                       setCellType(cell, cv); // cell will no longer be a formula cell\r
-               }\r
-               return result;\r
-       }\r
-       private static void setCellType(Cell cell, CellValue cv) {\r
-               int cellType = cv.getCellType();\r
-               switch (cellType) {\r
-                       case HSSFCell.CELL_TYPE_BOOLEAN:\r
-                       case HSSFCell.CELL_TYPE_ERROR:\r
-                       case HSSFCell.CELL_TYPE_NUMERIC:\r
-                       case HSSFCell.CELL_TYPE_STRING:\r
-                               cell.setCellType(cellType);\r
-                               return;\r
-                       case HSSFCell.CELL_TYPE_BLANK:\r
-                               // never happens - blanks eventually get translated to zero\r
-                       case HSSFCell.CELL_TYPE_FORMULA:\r
-                               // this will never happen, we have already evaluated the formula\r
-               }\r
-               throw new IllegalStateException("Unexpected cell value type (" + cellType + ")");\r
-       }\r
-\r
-       private static void setCellValue(Cell cell, CellValue cv) {\r
-               int cellType = cv.getCellType();\r
-               switch (cellType) {\r
-                       case HSSFCell.CELL_TYPE_BOOLEAN:\r
-                               cell.setCellValue(cv.getBooleanValue());\r
-                               break;\r
-                       case HSSFCell.CELL_TYPE_ERROR:\r
-                               cell.setCellErrorValue(cv.getErrorValue());\r
-                               break;\r
-                       case HSSFCell.CELL_TYPE_NUMERIC:\r
-                               cell.setCellValue(cv.getNumberValue());\r
-                               break;\r
-                       case HSSFCell.CELL_TYPE_STRING:\r
-                               cell.setCellValue(new HSSFRichTextString(cv.getStringValue()));\r
-                               break;\r
-                       case HSSFCell.CELL_TYPE_BLANK:\r
-                               // never happens - blanks eventually get translated to zero\r
-                       case HSSFCell.CELL_TYPE_FORMULA:\r
-                               // this will never happen, we have already evaluated the formula\r
-                       default:\r
-                               throw new IllegalStateException("Unexpected cell value type (" + cellType + ")");\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Loops over all cells in all sheets of the supplied\r
-        *  workbook.\r
-        * For cells that contain formulas, their formulas are\r
-        *  evaluated, and the results are saved. These cells\r
-        *  remain as formula cells.\r
-        * For cells that do not contain formulas, no changes\r
-        *  are made.\r
-        * This is a helpful wrapper around looping over all\r
-        *  cells, and calling evaluateFormulaCell on each one.\r
-        */\r
-       public static void evaluateAllFormulaCells(HSSFWorkbook wb) {\r
-               HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb);\r
-               for(int i=0; i<wb.getNumberOfSheets(); i++) {\r
-                       HSSFSheet sheet = wb.getSheetAt(i);\r
-\r
-                       for (Iterator rit = sheet.rowIterator(); rit.hasNext();) {\r
-                               HSSFRow r = (HSSFRow)rit.next();\r
-\r
-                               for (Iterator cit = r.cellIterator(); cit.hasNext();) {\r
-                                       HSSFCell c = (HSSFCell)cit.next();\r
-                                       if (c.getCellType() == HSSFCell.CELL_TYPE_FORMULA)\r
-                                               evaluator.evaluateFormulaCell(c);\r
-                               }\r
-                       }\r
-               }\r
-       }\r
-\r
-       /**\r
-        * Returns a CellValue wrapper around the supplied ValueEval instance.\r
-        * @param eval\r
-        */\r
-       private CellValue evaluateFormulaCellValue(Cell cell) {\r
-               ValueEval eval = _bookEvaluator.evaluate(new HSSFEvaluationCell((HSSFCell)cell));\r
-               if (eval instanceof NumberEval) {\r
-                       NumberEval ne = (NumberEval) eval;\r
-                       return new CellValue(ne.getNumberValue());\r
-               }\r
-               if (eval instanceof BoolEval) {\r
-                       BoolEval be = (BoolEval) eval;\r
-                       return CellValue.valueOf(be.getBooleanValue());\r
-               }\r
-               if (eval instanceof StringEval) {\r
-                       StringEval ne = (StringEval) eval;\r
-                       return new CellValue(ne.getStringValue());\r
-               }\r
-               if (eval instanceof ErrorEval) {\r
-                       return CellValue.getError(((ErrorEval)eval).getErrorCode());\r
-               }\r
-               throw new RuntimeException("Unexpected eval class (" + eval.getClass().getName() + ")");\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.usermodel;
+
+import java.util.Iterator;
+
+import org.apache.poi.hssf.record.formula.eval.BoolEval;
+import org.apache.poi.hssf.record.formula.eval.ErrorEval;
+import org.apache.poi.hssf.record.formula.eval.NumberEval;
+import org.apache.poi.hssf.record.formula.eval.StringEval;
+import org.apache.poi.hssf.record.formula.eval.ValueEval;
+import org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment;
+import org.apache.poi.ss.formula.IStabilityClassifier;
+import org.apache.poi.ss.formula.WorkbookEvaluator;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellValue;
+import org.apache.poi.ss.usermodel.FormulaEvaluator;
+import org.apache.poi.ss.usermodel.Row;
+
+/**
+ * Evaluates formula cells.<p/>
+ *
+ * For performance reasons, this class keeps a cache of all previously calculated intermediate
+ * cell values.  Be sure to call {@link #clearAllCachedResultValues()} if any workbook cells are changed between
+ * calls to evaluate~ methods on this class.
+ *
+ * @author Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt;
+ * @author Josh Micich
+ */
+public class HSSFFormulaEvaluator implements FormulaEvaluator  {
+
+       private WorkbookEvaluator _bookEvaluator;
+
+       /**
+        * @deprecated (Sep 2008) HSSFSheet parameter is ignored
+        */
+       public HSSFFormulaEvaluator(HSSFSheet sheet, HSSFWorkbook workbook) {
+               this(workbook);
+               if (false) {
+                       sheet.toString(); // suppress unused parameter compiler warning
+               }
+       }
+       public HSSFFormulaEvaluator(HSSFWorkbook workbook) {
+               this(workbook, null);
+       }
+       /**
+        * @param stabilityClassifier used to optimise caching performance. Pass <code>null</code>
+        * for the (conservative) assumption that any cell may have its definition changed after
+        * evaluation begins.
+        */
+       public HSSFFormulaEvaluator(HSSFWorkbook workbook, IStabilityClassifier stabilityClassifier) {
+               _bookEvaluator = new WorkbookEvaluator(HSSFEvaluationWorkbook.create(workbook), stabilityClassifier);
+       }
+
+       /**
+        * Coordinates several formula evaluators together so that formulas that involve external
+        * references can be evaluated.
+        * @param workbookNames the simple file names used to identify the workbooks in formulas
+        * with external links (for example "MyData.xls" as used in a formula "[MyData.xls]Sheet1!A1")
+        * @param evaluators all evaluators for the full set of workbooks required by the formulas.
+        */
+       public static void setupEnvironment(String[] workbookNames, HSSFFormulaEvaluator[] evaluators) {
+               WorkbookEvaluator[] wbEvals = new WorkbookEvaluator[evaluators.length];
+               for (int i = 0; i < wbEvals.length; i++) {
+                       wbEvals[i] = evaluators[i]._bookEvaluator;
+               }
+               CollaboratingWorkbooksEnvironment.setup(workbookNames, wbEvals);
+       }
+
+       /**
+        * Does nothing
+        * @deprecated (Aug 2008) - not needed, since the current row can be derived from the cell
+        */
+       public void setCurrentRow(HSSFRow row) {
+               // do nothing
+               if (false) {
+                       row.getClass(); // suppress unused parameter compiler warning
+               }
+       }
+
+       /**
+        * Should be called whenever there are major changes (e.g. moving sheets) to input cells
+        * in the evaluated workbook.  If performance is not critical, a single call to this method
+        * may be used instead of many specific calls to the notify~ methods.
+        *
+        * Failure to call this method after changing cell values will cause incorrect behaviour
+        * of the evaluate~ methods of this class
+        */
+       public void clearAllCachedResultValues() {
+               _bookEvaluator.clearAllCachedResultValues();
+       }
+       /**
+        * Should be called to tell the cell value cache that the specified (value or formula) cell
+        * has changed.
+        * Failure to call this method after changing cell values will cause incorrect behaviour
+        * of the evaluate~ methods of this class
+        */
+       public void notifyUpdateCell(HSSFCell cell) {
+               _bookEvaluator.notifyUpdateCell(new HSSFEvaluationCell(cell));
+       }
+       /**
+        * Should be called to tell the cell value cache that the specified cell has just been
+        * deleted.
+        * Failure to call this method after changing cell values will cause incorrect behaviour
+        * of the evaluate~ methods of this class
+        */
+       public void notifyDeleteCell(HSSFCell cell) {
+               _bookEvaluator.notifyDeleteCell(new HSSFEvaluationCell(cell));
+       }
+       public void notifyDeleteCell(Cell cell) {
+               _bookEvaluator.notifyDeleteCell(new HSSFEvaluationCell((HSSFCell)cell));
+       }
+
+       /**
+        * Should be called to tell the cell value cache that the specified (value or formula) cell
+        * has changed.
+        * Failure to call this method after changing cell values will cause incorrect behaviour
+        * of the evaluate~ methods of this class
+        */
+       public void notifySetFormula(Cell cell) {
+               _bookEvaluator.notifyUpdateCell(new HSSFEvaluationCell((HSSFCell)cell));
+       }
+
+       /**
+        * If cell contains a formula, the formula is evaluated and returned,
+        * else the CellValue simply copies the appropriate cell value from
+        * the cell and also its cell type. This method should be preferred over
+        * evaluateInCell() when the call should not modify the contents of the
+        * original cell.
+        *
+        * @param cell may be <code>null</code> signifying that the cell is not present (or blank)
+        * @return <code>null</code> if the supplied cell is <code>null</code> or blank
+        */
+       public CellValue evaluate(Cell cell) {
+               if (cell == null) {
+                       return null;
+               }
+
+               switch (cell.getCellType()) {
+                       case HSSFCell.CELL_TYPE_BOOLEAN:
+                               return CellValue.valueOf(cell.getBooleanCellValue());
+                       case HSSFCell.CELL_TYPE_ERROR:
+                               return CellValue.getError(cell.getErrorCellValue());
+                       case HSSFCell.CELL_TYPE_FORMULA:
+                               return evaluateFormulaCellValue(cell);
+                       case HSSFCell.CELL_TYPE_NUMERIC:
+                               return new CellValue(cell.getNumericCellValue());
+                       case HSSFCell.CELL_TYPE_STRING:
+                               return new CellValue(cell.getRichStringCellValue().getString());
+                       case HSSFCell.CELL_TYPE_BLANK:
+                               return null;
+               }
+               throw new IllegalStateException("Bad cell type (" + cell.getCellType() + ")");
+       }
+
+
+       /**
+        * If cell contains formula, it evaluates the formula, and saves the result of the formula. The
+        * cell remains as a formula cell. If the cell does not contain formula, this method returns -1
+        * and leaves the cell unchanged.
+        *
+        * Note that the type of the <em>formula result</em> is returned, so you know what kind of
+        * cached formula result is also stored with  the formula.
+        * <pre>
+        * int evaluatedCellType = evaluator.evaluateFormulaCell(cell);
+        * </pre>
+        * Be aware that your cell will hold both the formula, and the result. If you want the cell
+        * replaced with the result of the formula, use {@link #evaluateInCell(org.apache.poi.ss.usermodel.Cell)}
+        * @param cell The cell to evaluate
+        * @return -1 for non-formula cells, or the type of the <em>formula result</em>
+        */
+       public int evaluateFormulaCell(Cell cell) {
+               if (cell == null || cell.getCellType() != HSSFCell.CELL_TYPE_FORMULA) {
+                       return -1;
+               }
+               CellValue cv = evaluateFormulaCellValue(cell);
+               // cell remains a formula cell, but the cached value is changed
+               setCellValue(cell, cv);
+               return cv.getCellType();
+       }
+
+       /**
+        * If cell contains formula, it evaluates the formula, and
+        *  puts the formula result back into the cell, in place
+        *  of the old formula.
+        * Else if cell does not contain formula, this method leaves
+        *  the cell unchanged.
+        * Note that the same instance of HSSFCell is returned to
+        * allow chained calls like:
+        * <pre>
+        * int evaluatedCellType = evaluator.evaluateInCell(cell).getCellType();
+        * </pre>
+        * Be aware that your cell value will be changed to hold the
+        *  result of the formula. If you simply want the formula
+        *  value computed for you, use {@link #evaluateFormulaCell(Cell)}}
+        */
+       public HSSFCell evaluateInCell(Cell cell) {
+               if (cell == null) {
+                       return null;
+               }
+               HSSFCell result = (HSSFCell) cell;
+               if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
+                       CellValue cv = evaluateFormulaCellValue(cell);
+                       setCellValue(cell, cv);
+                       setCellType(cell, cv); // cell will no longer be a formula cell
+               }
+               return result;
+       }
+       private static void setCellType(Cell cell, CellValue cv) {
+               int cellType = cv.getCellType();
+               switch (cellType) {
+                       case HSSFCell.CELL_TYPE_BOOLEAN:
+                       case HSSFCell.CELL_TYPE_ERROR:
+                       case HSSFCell.CELL_TYPE_NUMERIC:
+                       case HSSFCell.CELL_TYPE_STRING:
+                               cell.setCellType(cellType);
+                               return;
+                       case HSSFCell.CELL_TYPE_BLANK:
+                               // never happens - blanks eventually get translated to zero
+                       case HSSFCell.CELL_TYPE_FORMULA:
+                               // this will never happen, we have already evaluated the formula
+               }
+               throw new IllegalStateException("Unexpected cell value type (" + cellType + ")");
+       }
+
+       private static void setCellValue(Cell cell, CellValue cv) {
+               int cellType = cv.getCellType();
+               switch (cellType) {
+                       case HSSFCell.CELL_TYPE_BOOLEAN:
+                               cell.setCellValue(cv.getBooleanValue());
+                               break;
+                       case HSSFCell.CELL_TYPE_ERROR:
+                               cell.setCellErrorValue(cv.getErrorValue());
+                               break;
+                       case HSSFCell.CELL_TYPE_NUMERIC:
+                               cell.setCellValue(cv.getNumberValue());
+                               break;
+                       case HSSFCell.CELL_TYPE_STRING:
+                               cell.setCellValue(new HSSFRichTextString(cv.getStringValue()));
+                               break;
+                       case HSSFCell.CELL_TYPE_BLANK:
+                               // never happens - blanks eventually get translated to zero
+                       case HSSFCell.CELL_TYPE_FORMULA:
+                               // this will never happen, we have already evaluated the formula
+                       default:
+                               throw new IllegalStateException("Unexpected cell value type (" + cellType + ")");
+               }
+       }
+
+       /**
+        * Loops over all cells in all sheets of the supplied
+        *  workbook.
+        * For cells that contain formulas, their formulas are
+        *  evaluated, and the results are saved. These cells
+        *  remain as formula cells.
+        * For cells that do not contain formulas, no changes
+        *  are made.
+        * This is a helpful wrapper around looping over all
+        *  cells, and calling evaluateFormulaCell on each one.
+        */
+       public static void evaluateAllFormulaCells(HSSFWorkbook wb) {
+               HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb);
+               for(int i=0; i<wb.getNumberOfSheets(); i++) {
+                       HSSFSheet sheet = wb.getSheetAt(i);
+
+                       for (Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();) {
+                               Row r = rit.next();
+
+                               for (Iterator<Cell> cit = r.cellIterator(); cit.hasNext();) {
+                                       Cell c = cit.next();
+                                       if (c.getCellType() == HSSFCell.CELL_TYPE_FORMULA)
+                                               evaluator.evaluateFormulaCell(c);
+                               }
+                       }
+               }
+       }
+
+       /**
+        * Returns a CellValue wrapper around the supplied ValueEval instance.
+        * @param eval
+        */
+       private CellValue evaluateFormulaCellValue(Cell cell) {
+               ValueEval eval = _bookEvaluator.evaluate(new HSSFEvaluationCell((HSSFCell)cell));
+               if (eval instanceof NumberEval) {
+                       NumberEval ne = (NumberEval) eval;
+                       return new CellValue(ne.getNumberValue());
+               }
+               if (eval instanceof BoolEval) {
+                       BoolEval be = (BoolEval) eval;
+                       return CellValue.valueOf(be.getBooleanValue());
+               }
+               if (eval instanceof StringEval) {
+                       StringEval ne = (StringEval) eval;
+                       return new CellValue(ne.getStringValue());
+               }
+               if (eval instanceof ErrorEval) {
+                       return CellValue.getError(((ErrorEval)eval).getErrorCode());
+               }
+               throw new RuntimeException("Unexpected eval class (" + eval.getClass().getName() + ")");
+       }
+}
index 590e706b8bd784f6941e2f4d4ec9daf0a3d46935..9a812914d5b1134975c324154f13bcefabdab4d6 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.hssf.usermodel;\r
-\r
-import org.apache.poi.hssf.record.HyperlinkRecord;\r
-import org.apache.poi.ss.usermodel.Hyperlink;\r
-\r
-/**\r
- * Represents an Excel hyperlink.\r
- *\r
- * @author Yegor Kozlov (yegor at apache dot org)\r
- */\r
-public class HSSFHyperlink implements Hyperlink {\r
-\r
-    /**\r
-     * Link to a existing file or web page\r
-     */\r
-    public static final int LINK_URL = 1;\r
-\r
-    /**\r
-     * Link to a place in this document\r
-     */\r
-    public static final int LINK_DOCUMENT = 2;\r
-\r
-    /**\r
-     * Link to an E-mail address\r
-     */\r
-    public static final int LINK_EMAIL = 3;\r
-\r
-    /**\r
-     * Link to a file\r
-     */\r
-    public static final int LINK_FILE = 4;\r
-\r
-    /**\r
-     * Low-level record object that stores the actual hyperlink data\r
-     */\r
-    protected HyperlinkRecord record = null;\r
-\r
-    /**\r
-     * If we create a new hypelrink remember its type\r
-     */\r
-    protected int link_type;\r
-\r
-    /**\r
-     * Construct a new hyperlink\r
-     *\r
-     * @param type the type of hyperlink to create\r
-     */\r
-    public HSSFHyperlink( int type )\r
-    {\r
-        this.link_type = type;\r
-        record = new HyperlinkRecord();\r
-        switch(type){\r
-            case LINK_URL:\r
-            case LINK_EMAIL:\r
-                record.newUrlLink();\r
-                break;\r
-            case LINK_FILE:\r
-                record.newFileLink();\r
-                break;\r
-            case LINK_DOCUMENT:\r
-                record.newDocumentLink();\r
-                break;\r
-        }\r
-    }\r
-\r
-    /**\r
-     * Initialize the hyperlink by a <code>HyperlinkRecord</code> record\r
-     *\r
-     * @param record\r
-     */\r
-    protected HSSFHyperlink( HyperlinkRecord record )\r
-    {\r
-        this.record = record;\r
-    }\r
-\r
-    /**\r
-     * Return the row of the first cell that contains the hyperlink\r
-     *\r
-     * @return the 0-based row of the cell that contains the hyperlink\r
-     */\r
-    public int getFirstRow(){\r
-        return record.getFirstRow();\r
-    }\r
-\r
-    /**\r
-     * Set the row of the first cell that contains the hyperlink\r
-     *\r
-     * @param row the 0-based row of the first cell that contains the hyperlink\r
-     */\r
-    public void setFirstRow(int row){\r
-        record.setFirstRow(row);\r
-    }\r
-\r
-    /**\r
-     * Return the row of the last cell that contains the hyperlink\r
-     *\r
-     * @return the 0-based row of the last cell that contains the hyperlink\r
-     */\r
-    public int getLastRow(){\r
-        return record.getLastRow();\r
-    }\r
-\r
-    /**\r
-     * Set the row of the last cell that contains the hyperlink\r
-     *\r
-     * @param row the 0-based row of the last cell that contains the hyperlink\r
-     */\r
-    public void setLastRow(int row){\r
-        record.setLastRow(row);\r
-    }\r
-\r
-    /**\r
-     * Return the column of the first cell that contains the hyperlink\r
-     *\r
-     * @return the 0-based column of the first cell that contains the hyperlink\r
-     */\r
-    public int getFirstColumn(){\r
-        return record.getFirstColumn();\r
-    }\r
-\r
-    /**\r
-     * Set the column of the first cell that contains the hyperlink\r
-     *\r
-     * @param col the 0-based column of the first cell that contains the hyperlink\r
-     */\r
-    public void setFirstColumn(int col){\r
-        record.setFirstColumn((short)col);\r
-    }\r
-\r
-    /**\r
-     * Return the column of the last cell that contains the hyperlink\r
-     *\r
-     * @return the 0-based column of the last cell that contains the hyperlink\r
-     */\r
-    public int getLastColumn(){\r
-        return record.getLastColumn();\r
-    }\r
-\r
-    /**\r
-     * Set the column of the last cell that contains the hyperlink\r
-     *\r
-     * @param col the 0-based column of the last cell that contains the hyperlink\r
-     */\r
-    public void setLastColumn(int col){\r
-        record.setLastColumn((short)col);\r
-    }\r
-\r
-    /**\r
-     * Hypelink address. Depending on the hyperlink type it can be URL, e-mail, patrh to a file, etc.\r
-     *\r
-     * @return  the address of this hyperlink\r
-     */\r
-    public String getAddress(){\r
-        return record.getAddress();\r
-    }\r
-    public String getTextMark(){\r
-        return record.getTextMark();\r
-    }\r
-    public void setTextMark(String textMark) {\r
-        record.setTextMark(textMark);\r
-    }\r
-    public String getShortFilename(){\r
-        return record.getShortFilename();\r
-    }\r
-    public void setShortFilename(String shortFilename) {\r
-        record.setShortFilename(shortFilename);\r
-    }\r
-\r
-    /**\r
-     * Hypelink address. Depending on the hyperlink type it can be URL, e-mail, patrh to a file, etc.\r
-     *\r
-     * @param address  the address of this hyperlink\r
-     */\r
-    public void setAddress(String address){\r
-        record.setAddress(address);\r
-    }\r
-\r
-    /**\r
-     * Return text label for this hyperlink\r
-     *\r
-     * @return  text to display\r
-     */\r
-    public String getLabel(){\r
-        return record.getLabel();\r
-    }\r
-\r
-    /**\r
-     * Sets text label for this hyperlink\r
-     *\r
-     * @param label text label for this hyperlink\r
-     */\r
-    public void setLabel(String label){\r
-        record.setLabel(label);\r
-    }\r
-\r
-    /**\r
-     * Return the type of this hyperlink\r
-     *\r
-     * @return the type of this hyperlink\r
-     */\r
-    public int getType(){\r
-        return link_type;\r
-    }\r
-}\r
+/* ====================================================================
+   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.hssf.usermodel;
+
+import org.apache.poi.hssf.record.HyperlinkRecord;
+import org.apache.poi.ss.usermodel.Hyperlink;
+
+/**
+ * Represents an Excel hyperlink.
+ *
+ * @author Yegor Kozlov (yegor at apache dot org)
+ */
+public class HSSFHyperlink implements Hyperlink {
+
+    /**
+     * Link to a existing file or web page
+     */
+    public static final int LINK_URL = 1;
+
+    /**
+     * Link to a place in this document
+     */
+    public static final int LINK_DOCUMENT = 2;
+
+    /**
+     * Link to an E-mail address
+     */
+    public static final int LINK_EMAIL = 3;
+
+    /**
+     * Link to a file
+     */
+    public static final int LINK_FILE = 4;
+
+    /**
+     * Low-level record object that stores the actual hyperlink data
+     */
+    protected HyperlinkRecord record = null;
+
+    /**
+     * If we create a new hypelrink remember its type
+     */
+    protected int link_type;
+
+    /**
+     * Construct a new hyperlink
+     *
+     * @param type the type of hyperlink to create
+     */
+    public HSSFHyperlink( int type )
+    {
+        this.link_type = type;
+        record = new HyperlinkRecord();
+        switch(type){
+            case LINK_URL:
+            case LINK_EMAIL:
+                record.newUrlLink();
+                break;
+            case LINK_FILE:
+                record.newFileLink();
+                break;
+            case LINK_DOCUMENT:
+                record.newDocumentLink();
+                break;
+        }
+    }
+
+    /**
+     * Initialize the hyperlink by a <code>HyperlinkRecord</code> record
+     *
+     * @param record
+     */
+    protected HSSFHyperlink( HyperlinkRecord record )
+    {
+        this.record = record;
+    }
+
+    /**
+     * Return the row of the first cell that contains the hyperlink
+     *
+     * @return the 0-based row of the cell that contains the hyperlink
+     */
+    public int getFirstRow(){
+        return record.getFirstRow();
+    }
+
+    /**
+     * Set the row of the first cell that contains the hyperlink
+     *
+     * @param row the 0-based row of the first cell that contains the hyperlink
+     */
+    public void setFirstRow(int row){
+        record.setFirstRow(row);
+    }
+
+    /**
+     * Return the row of the last cell that contains the hyperlink
+     *
+     * @return the 0-based row of the last cell that contains the hyperlink
+     */
+    public int getLastRow(){
+        return record.getLastRow();
+    }
+
+    /**
+     * Set the row of the last cell that contains the hyperlink
+     *
+     * @param row the 0-based row of the last cell that contains the hyperlink
+     */
+    public void setLastRow(int row){
+        record.setLastRow(row);
+    }
+
+    /**
+     * Return the column of the first cell that contains the hyperlink
+     *
+     * @return the 0-based column of the first cell that contains the hyperlink
+     */
+    public int getFirstColumn(){
+        return record.getFirstColumn();
+    }
+
+    /**
+     * Set the column of the first cell that contains the hyperlink
+     *
+     * @param col the 0-based column of the first cell that contains the hyperlink
+     */
+    public void setFirstColumn(int col){
+        record.setFirstColumn((short)col);
+    }
+
+    /**
+     * Return the column of the last cell that contains the hyperlink
+     *
+     * @return the 0-based column of the last cell that contains the hyperlink
+     */
+    public int getLastColumn(){
+        return record.getLastColumn();
+    }
+
+    /**
+     * Set the column of the last cell that contains the hyperlink
+     *
+     * @param col the 0-based column of the last cell that contains the hyperlink
+     */
+    public void setLastColumn(int col){
+        record.setLastColumn((short)col);
+    }
+
+    /**
+     * Hypelink address. Depending on the hyperlink type it can be URL, e-mail, patrh to a file, etc.
+     *
+     * @return  the address of this hyperlink
+     */
+    public String getAddress(){
+        return record.getAddress();
+    }
+    public String getTextMark(){
+        return record.getTextMark();
+    }
+    public void setTextMark(String textMark) {
+        record.setTextMark(textMark);
+    }
+    public String getShortFilename(){
+        return record.getShortFilename();
+    }
+    public void setShortFilename(String shortFilename) {
+        record.setShortFilename(shortFilename);
+    }
+
+    /**
+     * Hypelink address. Depending on the hyperlink type it can be URL, e-mail, patrh to a file, etc.
+     *
+     * @param address  the address of this hyperlink
+     */
+    public void setAddress(String address){
+        record.setAddress(address);
+    }
+
+    /**
+     * Return text label for this hyperlink
+     *
+     * @return  text to display
+     */
+    public String getLabel(){
+        return record.getLabel();
+    }
+
+    /**
+     * Sets text label for this hyperlink
+     *
+     * @param label text label for this hyperlink
+     */
+    public void setLabel(String label){
+        record.setLabel(label);
+    }
+
+    /**
+     * Return the type of this hyperlink
+     *
+     * @return the type of this hyperlink
+     */
+    public int getType(){
+        return link_type;
+    }
+}
index ce6235a1af3325c64be3621f79c9eabf953998da..ab539c22de687ce32cb6b49929fe35d7e7837fb4 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.usermodel;\r
-\r
-import org.apache.poi.hssf.model.Sheet;\r
-import org.apache.poi.hssf.record.CFRuleRecord;\r
-import org.apache.poi.hssf.record.aggregates.CFRecordsAggregate;\r
-import org.apache.poi.hssf.record.aggregates.ConditionalFormattingTable;\r
-import org.apache.poi.ss.util.Region;\r
-import org.apache.poi.ss.util.CellRangeAddress;\r
-import org.apache.poi.ss.SpreadsheetVersion;\r
-\r
-/**\r
- * The 'Conditional Formatting' facet of <tt>HSSFSheet</tt>\r
- * \r
- * @author Dmitriy Kumshayev\r
- */\r
-public final class HSSFSheetConditionalFormatting {\r
-       \r
-    private final HSSFSheet _sheet;\r
-       private final ConditionalFormattingTable _conditionalFormattingTable;\r
-\r
-    /* package */ HSSFSheetConditionalFormatting(HSSFSheet sheet) {\r
-        _sheet = sheet;\r
-        _conditionalFormattingTable = sheet.getSheet().getConditionalFormattingTable();\r
-    }\r
-\r
-       /**\r
-        * A factory method allowing to create a conditional formatting rule\r
-        * with a cell comparison operator<p/>\r
-        * TODO - formulas containing cell references are currently not parsed properly \r
-        *\r
-        * @param comparisonOperation - a constant value from\r
-        *               <tt>{@link org.apache.poi.hssf.record.CFRuleRecord.ComparisonOperator}</tt>: <p>\r
-        * <ul>\r
-        *               <li>BETWEEN</li>\r
-        *               <li>NOT_BETWEEN</li>\r
-        *               <li>EQUAL</li>\r
-        *               <li>NOT_EQUAL</li>\r
-        *               <li>GT</li>\r
-        *               <li>LT</li>\r
-        *               <li>GE</li>\r
-        *               <li>LE</li>\r
-        * </ul>\r
-        * </p>\r
-        * @param formula1 - formula for the valued, compared with the cell\r
-        * @param formula2 - second formula (only used with\r
-        * {@link org.apache.poi.hssf.record.CFRuleRecord.ComparisonOperator#BETWEEN}) and\r
-        * {@link org.apache.poi.hssf.record.CFRuleRecord.ComparisonOperator#NOT_BETWEEN} operations)\r
-        */\r
-       public HSSFConditionalFormattingRule createConditionalFormattingRule(\r
-                       byte comparisonOperation,\r
-                       String formula1,\r
-                       String formula2) {\r
-\r
-               HSSFWorkbook wb = _sheet.getWorkbook();\r
-               CFRuleRecord rr = CFRuleRecord.create(_sheet, comparisonOperation, formula1, formula2);\r
-               return new HSSFConditionalFormattingRule(wb, rr);\r
-       }\r
-\r
-       /**\r
-        * A factory method allowing to create a conditional formatting rule with a formula.<br>\r
-        *\r
-        * The formatting rules are applied by Excel when the value of the formula not equal to 0.<p/>\r
-        * TODO - formulas containing cell references are currently not parsed properly\r
-        * @param formula - formula for the valued, compared with the cell\r
-        */\r
-       public HSSFConditionalFormattingRule createConditionalFormattingRule(String formula) {\r
-        HSSFWorkbook wb = _sheet.getWorkbook();\r
-               CFRuleRecord rr = CFRuleRecord.create(_sheet, formula);\r
-               return new HSSFConditionalFormattingRule(wb, rr);\r
-       }\r
-\r
-       /**\r
-        * Adds a copy of HSSFConditionalFormatting object to the sheet\r
-        * <p>This method could be used to copy HSSFConditionalFormatting object\r
-        * from one sheet to another. For example:\r
-        * <pre>\r
-        * HSSFConditionalFormatting cf = sheet.getConditionalFormattingAt(index);\r
-        * newSheet.addConditionalFormatting(cf);\r
-        * </pre>\r
-        *\r
-        * @param cf HSSFConditionalFormatting object\r
-        * @return index of the new Conditional Formatting object\r
-        */\r
-       public int addConditionalFormatting( HSSFConditionalFormatting cf ) {\r
-               CFRecordsAggregate cfraClone = cf.getCFRecordsAggregate().cloneCFAggregate();\r
-\r
-               return _conditionalFormattingTable.add(cfraClone);\r
-       }\r
-       /**\r
-        * @deprecated use <tt>CellRangeAddress</tt> instead of <tt>Region</tt>\r
-        */\r
-       public int addConditionalFormatting(Region[] regions, HSSFConditionalFormattingRule[] cfRules) {\r
-               return addConditionalFormatting(Region.convertRegionsToCellRanges(regions), cfRules);\r
-       }\r
-       /**\r
-        * Allows to add a new Conditional Formatting set to the sheet.\r
-        *\r
-        * @param regions - list of rectangular regions to apply conditional formatting rules\r
-        * @param cfRules - set of up to three conditional formatting rules\r
-        *\r
-        * @return index of the newly created Conditional Formatting object\r
-        */\r
-       public int addConditionalFormatting(CellRangeAddress[] regions, HSSFConditionalFormattingRule[] cfRules) {\r
-               if (regions == null) {\r
-                       throw new IllegalArgumentException("regions must not be null");\r
-               }\r
-        for(CellRangeAddress range : regions) range.validate(SpreadsheetVersion.EXCEL97);\r
-\r
-        if (cfRules == null) {\r
-                       throw new IllegalArgumentException("cfRules must not be null");\r
-               }\r
-               if (cfRules.length == 0) {\r
-                       throw new IllegalArgumentException("cfRules must not be empty");\r
-               }\r
-               if (cfRules.length > 3) {\r
-                       throw new IllegalArgumentException("Number of rules must not exceed 3");\r
-               }\r
-\r
-               CFRuleRecord[] rules = new CFRuleRecord[cfRules.length];\r
-               for (int i = 0; i != cfRules.length; i++) {\r
-                       rules[i] = cfRules[i].getCfRuleRecord();\r
-               }\r
-               CFRecordsAggregate cfra = new CFRecordsAggregate(regions, rules);\r
-               return _conditionalFormattingTable.add(cfra);\r
-       }\r
-\r
-       public int addConditionalFormatting(CellRangeAddress[] regions,\r
-                       HSSFConditionalFormattingRule rule1)\r
-       {\r
-               return addConditionalFormatting(regions,\r
-                               new HSSFConditionalFormattingRule[]\r
-                               {\r
-                                       rule1\r
-                               });\r
-       }\r
-\r
-       public int addConditionalFormatting(CellRangeAddress[] regions,\r
-                       HSSFConditionalFormattingRule rule1,\r
-                       HSSFConditionalFormattingRule rule2)\r
-       {\r
-               return addConditionalFormatting(regions,\r
-                               new HSSFConditionalFormattingRule[]\r
-                               {\r
-                                               rule1, rule2\r
-                               });\r
-       }\r
-\r
-       /**\r
-       * gets Conditional Formatting object at a particular index\r
-       * \r
-       * @param index\r
-       *                       of the Conditional Formatting object to fetch\r
-       * @return Conditional Formatting object\r
-       */\r
-       public HSSFConditionalFormatting getConditionalFormattingAt(int index) {\r
-               CFRecordsAggregate cf = _conditionalFormattingTable.get(index);\r
-               if (cf == null) {\r
-                       return null;\r
-               }\r
-               return new HSSFConditionalFormatting(_sheet.getWorkbook(), cf);\r
-       }\r
-\r
-       /**\r
-       * @return number of Conditional Formatting objects of the sheet\r
-       */\r
-       public int getNumConditionalFormattings() {\r
-               return _conditionalFormattingTable.size();\r
-       }\r
-\r
-       /**\r
-       * removes a Conditional Formatting object by index\r
-       * @param index of a Conditional Formatting object to remove\r
-       */\r
-       public void removeConditionalFormatting(int index) {\r
-               _conditionalFormattingTable.remove(index);\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.usermodel;
+
+import org.apache.poi.hssf.record.CFRuleRecord;
+import org.apache.poi.hssf.record.aggregates.CFRecordsAggregate;
+import org.apache.poi.hssf.record.aggregates.ConditionalFormattingTable;
+import org.apache.poi.ss.util.Region;
+import org.apache.poi.ss.util.CellRangeAddress;
+import org.apache.poi.ss.SpreadsheetVersion;
+
+/**
+ * The 'Conditional Formatting' facet of <tt>HSSFSheet</tt>
+ *
+ * @author Dmitriy Kumshayev
+ */
+public final class HSSFSheetConditionalFormatting {
+
+       private final HSSFSheet _sheet;
+       private final ConditionalFormattingTable _conditionalFormattingTable;
+
+       /* package */ HSSFSheetConditionalFormatting(HSSFSheet sheet) {
+               _sheet = sheet;
+               _conditionalFormattingTable = sheet.getSheet().getConditionalFormattingTable();
+       }
+
+       /**
+        * A factory method allowing to create a conditional formatting rule
+        * with a cell comparison operator<p/>
+        * TODO - formulas containing cell references are currently not parsed properly
+        *
+        * @param comparisonOperation - a constant value from
+        *               <tt>{@link org.apache.poi.hssf.record.CFRuleRecord.ComparisonOperator}</tt>: <p>
+        * <ul>
+        *               <li>BETWEEN</li>
+        *               <li>NOT_BETWEEN</li>
+        *               <li>EQUAL</li>
+        *               <li>NOT_EQUAL</li>
+        *               <li>GT</li>
+        *               <li>LT</li>
+        *               <li>GE</li>
+        *               <li>LE</li>
+        * </ul>
+        * </p>
+        * @param formula1 - formula for the valued, compared with the cell
+        * @param formula2 - second formula (only used with
+        * {@link org.apache.poi.hssf.record.CFRuleRecord.ComparisonOperator#BETWEEN}) and
+        * {@link org.apache.poi.hssf.record.CFRuleRecord.ComparisonOperator#NOT_BETWEEN} operations)
+        */
+       public HSSFConditionalFormattingRule createConditionalFormattingRule(
+                       byte comparisonOperation,
+                       String formula1,
+                       String formula2) {
+
+               HSSFWorkbook wb = _sheet.getWorkbook();
+               CFRuleRecord rr = CFRuleRecord.create(_sheet, comparisonOperation, formula1, formula2);
+               return new HSSFConditionalFormattingRule(wb, rr);
+       }
+
+       /**
+        * A factory method allowing to create a conditional formatting rule with a formula.<br>
+        *
+        * The formatting rules are applied by Excel when the value of the formula not equal to 0.<p/>
+        * TODO - formulas containing cell references are currently not parsed properly
+        * @param formula - formula for the valued, compared with the cell
+        */
+       public HSSFConditionalFormattingRule createConditionalFormattingRule(String formula) {
+               HSSFWorkbook wb = _sheet.getWorkbook();
+               CFRuleRecord rr = CFRuleRecord.create(_sheet, formula);
+               return new HSSFConditionalFormattingRule(wb, rr);
+       }
+
+       /**
+        * Adds a copy of HSSFConditionalFormatting object to the sheet
+        * <p>This method could be used to copy HSSFConditionalFormatting object
+        * from one sheet to another. For example:
+        * <pre>
+        * HSSFConditionalFormatting cf = sheet.getConditionalFormattingAt(index);
+        * newSheet.addConditionalFormatting(cf);
+        * </pre>
+        *
+        * @param cf HSSFConditionalFormatting object
+        * @return index of the new Conditional Formatting object
+        */
+       public int addConditionalFormatting( HSSFConditionalFormatting cf ) {
+               CFRecordsAggregate cfraClone = cf.getCFRecordsAggregate().cloneCFAggregate();
+
+               return _conditionalFormattingTable.add(cfraClone);
+       }
+       /**
+        * @deprecated use <tt>CellRangeAddress</tt> instead of <tt>Region</tt>
+        */
+       public int addConditionalFormatting(Region[] regions, HSSFConditionalFormattingRule[] cfRules) {
+               return addConditionalFormatting(Region.convertRegionsToCellRanges(regions), cfRules);
+       }
+       /**
+        * Allows to add a new Conditional Formatting set to the sheet.
+        *
+        * @param regions - list of rectangular regions to apply conditional formatting rules
+        * @param cfRules - set of up to three conditional formatting rules
+        *
+        * @return index of the newly created Conditional Formatting object
+        */
+       public int addConditionalFormatting(CellRangeAddress[] regions, HSSFConditionalFormattingRule[] cfRules) {
+               if (regions == null) {
+                       throw new IllegalArgumentException("regions must not be null");
+               }
+               for(CellRangeAddress range : regions) range.validate(SpreadsheetVersion.EXCEL97);
+
+               if (cfRules == null) {
+                       throw new IllegalArgumentException("cfRules must not be null");
+               }
+               if (cfRules.length == 0) {
+                       throw new IllegalArgumentException("cfRules must not be empty");
+               }
+               if (cfRules.length > 3) {
+                       throw new IllegalArgumentException("Number of rules must not exceed 3");
+               }
+
+               CFRuleRecord[] rules = new CFRuleRecord[cfRules.length];
+               for (int i = 0; i != cfRules.length; i++) {
+                       rules[i] = cfRules[i].getCfRuleRecord();
+               }
+               CFRecordsAggregate cfra = new CFRecordsAggregate(regions, rules);
+               return _conditionalFormattingTable.add(cfra);
+       }
+
+       public int addConditionalFormatting(CellRangeAddress[] regions,
+                       HSSFConditionalFormattingRule rule1)
+       {
+               return addConditionalFormatting(regions,
+                               new HSSFConditionalFormattingRule[]
+                               {
+                                       rule1
+                               });
+       }
+
+       public int addConditionalFormatting(CellRangeAddress[] regions,
+                       HSSFConditionalFormattingRule rule1,
+                       HSSFConditionalFormattingRule rule2)
+       {
+               return addConditionalFormatting(regions,
+                               new HSSFConditionalFormattingRule[]
+                               {
+                                               rule1, rule2
+                               });
+       }
+
+       /**
+       * gets Conditional Formatting object at a particular index
+       *
+       * @param index
+       *                       of the Conditional Formatting object to fetch
+       * @return Conditional Formatting object
+       */
+       public HSSFConditionalFormatting getConditionalFormattingAt(int index) {
+               CFRecordsAggregate cf = _conditionalFormattingTable.get(index);
+               if (cf == null) {
+                       return null;
+               }
+               return new HSSFConditionalFormatting(_sheet.getWorkbook(), cf);
+       }
+
+       /**
+       * @return number of Conditional Formatting objects of the sheet
+       */
+       public int getNumConditionalFormattings() {
+               return _conditionalFormattingTable.size();
+       }
+
+       /**
+       * removes a Conditional Formatting object by index
+       * @param index of a Conditional Formatting object to remove
+       */
+       public void removeConditionalFormatting(int index) {
+               _conditionalFormattingTable.remove(index);
+       }
+}
index da8d56c0919da3b05f6d54594e887b8f8137774b..d2316fe88489ea790361e90a1c06c8d6d4cd087f 100644 (file)
@@ -1,38 +1,38 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.util;\r
-\r
-import org.apache.poi.hssf.record.RecordInputStream;\r
-import org.apache.poi.hssf.record.SelectionRecord;\r
-\r
-/**\r
- * See OOO documentation: excelfileformat.pdf sec 2.5.14 - 'Cell Range Address'<p/>\r
- * \r
- * Note - {@link SelectionRecord} uses the BIFF5 version of this structure\r
- * @deprecated use {@link org.apache.poi.ss.util.CellRangeAddress}\r
- * @author Dragos Buleandra (dragos.buleandra@trade2b.ro)\r
- */\r
-public class CellRangeAddress extends org.apache.poi.ss.util.CellRangeAddress {\r
-\r
-       public CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol) {\r
-               super(firstRow, lastRow, firstCol, lastCol);\r
-       }\r
-       public CellRangeAddress(RecordInputStream in) {\r
-               super(in);\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.util;
+
+import org.apache.poi.hssf.record.RecordInputStream;
+import org.apache.poi.hssf.record.SelectionRecord;
+
+/**
+ * See OOO documentation: excelfileformat.pdf sec 2.5.14 - 'Cell Range Address'<p/>
+ *
+ * Note - {@link SelectionRecord} uses the BIFF5 version of this structure
+ * @deprecated use {@link org.apache.poi.ss.util.CellRangeAddress}
+ * @author Dragos Buleandra (dragos.buleandra@trade2b.ro)
+ */
+public class CellRangeAddress extends org.apache.poi.ss.util.CellRangeAddress {
+
+       public CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol) {
+               super(firstRow, lastRow, firstCol, lastCol);
+       }
+       public CellRangeAddress(RecordInputStream in) {
+               super(in);
+       }
+}
index 43de0cf28a9542edf8a3b4b6b9ef5d004a823695..cada8bfe5b464dbb79a85d1b0e99123eaea731eb 100644 (file)
@@ -1,73 +1,73 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.hssf.util;\r
-\r
-import org.apache.poi.ss.util.CellRangeAddressBase;\r
-import org.apache.poi.util.LittleEndianByteArrayOutputStream;\r
-import org.apache.poi.util.LittleEndianInput;\r
-import org.apache.poi.util.LittleEndianOutput;\r
-\r
-/**\r
- * See OOO documentation: excelfileformat.pdf sec 2.5.14 - 'Cell Range Address'<p/>\r
- * \r
- * Like {@link CellRangeAddress} except column fields are 8-bit.\r
- * \r
- * @author Josh Micich\r
- */\r
-public final class CellRangeAddress8Bit extends CellRangeAddressBase {\r
-\r
-       public static final int ENCODED_SIZE = 6;\r
-\r
-       public CellRangeAddress8Bit(int firstRow, int lastRow, int firstCol, int lastCol) {\r
-               super(firstRow, lastRow, firstCol, lastCol);\r
-       }\r
-\r
-       public CellRangeAddress8Bit(LittleEndianInput in) {\r
-               super(readUShortAndCheck(in), in.readUShort(), in.readUByte(), in.readUByte());\r
-       }\r
-\r
-       private static int readUShortAndCheck(LittleEndianInput in) {\r
-               if (in.available() < ENCODED_SIZE) {\r
-                       // Ran out of data\r
-                       throw new RuntimeException("Ran out of data reading CellRangeAddress");\r
-               }\r
-               return in.readUShort();\r
-       }\r
-\r
-       /**\r
-        * @deprecated use {@link #serialize(LittleEndianOutput)}\r
-        */\r
-       public int serialize(int offset, byte[] data) {\r
-               serialize(new LittleEndianByteArrayOutputStream(data, offset, ENCODED_SIZE));\r
-               return ENCODED_SIZE;\r
-       }\r
-       public void serialize(LittleEndianOutput out) {\r
-               out.writeShort(getFirstRow());\r
-               out.writeShort(getLastRow());\r
-               out.writeByte(getFirstColumn());\r
-               out.writeByte(getLastColumn());\r
-       }\r
-       \r
-       public CellRangeAddress8Bit copy() {\r
-               return new CellRangeAddress8Bit(getFirstRow(), getLastRow(), getFirstColumn(), getLastColumn());\r
-       }\r
-\r
-       public static int getEncodedSize(int numberOfItems) {\r
-               return numberOfItems * ENCODED_SIZE;\r
-       }\r
-}\r
+/* ====================================================================
+   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.hssf.util;
+
+import org.apache.poi.ss.util.CellRangeAddressBase;
+import org.apache.poi.util.LittleEndianByteArrayOutputStream;
+import org.apache.poi.util.LittleEndianInput;
+import org.apache.poi.util.LittleEndianOutput;
+
+/**
+ * See OOO documentation: excelfileformat.pdf sec 2.5.14 - 'Cell Range Address'<p/>
+ *
+ * Like {@link CellRangeAddress} except column fields are 8-bit.
+ *
+ * @author Josh Micich
+ */
+public final class CellRangeAddress8Bit extends CellRangeAddressBase {
+
+       public static final int ENCODED_SIZE = 6;
+
+       public CellRangeAddress8Bit(int firstRow, int lastRow, int firstCol, int lastCol) {
+               super(firstRow, lastRow, firstCol, lastCol);
+       }
+
+       public CellRangeAddress8Bit(LittleEndianInput in) {
+               super(readUShortAndCheck(in), in.readUShort(), in.readUByte(), in.readUByte());
+       }
+
+       private static int readUShortAndCheck(LittleEndianInput in) {
+               if (in.available() < ENCODED_SIZE) {
+                       // Ran out of data
+                       throw new RuntimeException("Ran out of data reading CellRangeAddress");
+               }
+               return in.readUShort();
+       }
+
+       /**
+        * @deprecated use {@link #serialize(LittleEndianOutput)}
+        */
+       public int serialize(int offset, byte[] data) {
+               serialize(new LittleEndianByteArrayOutputStream(data, offset, ENCODED_SIZE));
+               return ENCODED_SIZE;
+       }
+       public void serialize(LittleEndianOutput out) {
+               out.writeShort(getFirstRow());
+               out.writeShort(getLastRow());
+               out.writeByte(getFirstColumn());
+               out.writeByte(getLastColumn());
+       }
+
+       public CellRangeAddress8Bit copy() {
+               return new CellRangeAddress8Bit(getFirstRow(), getLastRow(), getFirstColumn(), getLastColumn());
+       }
+
+       public static int getEncodedSize(int numberOfItems) {
+               return numberOfItems * ENCODED_SIZE;
+       }
+}
index 5028bab720b681250e8e5e50fecdce1b0bd91d1a..ace19d8d1820b38239d57b6fcdba841f7160ae56 100755 (executable)
@@ -1,74 +1,74 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.poifs.dev;\r
-\r
-import org.apache.poi.poifs.filesystem.*;\r
-\r
-import java.io.FileInputStream;\r
-import java.io.File;\r
-import java.io.IOException;\r
-import java.io.FileOutputStream;\r
-import java.util.Iterator;\r
-\r
-/**\r
- *\r
- * Dump internal structure of a OLE2 file into file system\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class POIFSDump {\r
-\r
-    public static void main(String[] args) throws Exception {\r
-        for (int i = 0; i < args.length; i++) {\r
-            System.out.println("Dumping " + args[i]);\r
-            FileInputStream is = new FileInputStream(args[i]);\r
-            POIFSFileSystem fs = new POIFSFileSystem(is);\r
-            is.close();\r
-\r
-            DirectoryEntry root = fs.getRoot();\r
-            File file = new File(root.getName());\r
-            file.mkdir();\r
-\r
-            dump(root, file);\r
-        }\r
-   }\r
-\r
-\r
-    public static void dump(DirectoryEntry root, File parent) throws IOException {\r
-        for(Iterator it = root.getEntries(); it.hasNext();){\r
-            Entry entry = (Entry)it.next();\r
-            if(entry instanceof DocumentNode){\r
-                DocumentNode node = (DocumentNode)entry;\r
-                DocumentInputStream is = new DocumentInputStream(node);\r
-                byte[] bytes = new byte[node.getSize()];\r
-                is.read(bytes);\r
-                is.close();\r
-\r
-                FileOutputStream out = new FileOutputStream(new File(parent, node.getName().trim()));\r
-                out.write(bytes);\r
-                out.close();\r
-            } else if (entry instanceof DirectoryEntry){\r
-                DirectoryEntry dir = (DirectoryEntry)entry;\r
-                File file = new File(parent, entry.getName());\r
-                file.mkdir();\r
-                dump(dir, file);\r
-            } else {\r
-                System.err.println("Skipping unsupported POIFS entry: " + entry);\r
-            }\r
-        }\r
-    }\r
-}\r
+/* ====================================================================
+   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.poifs.dev;
+
+import org.apache.poi.poifs.filesystem.*;
+
+import java.io.FileInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.FileOutputStream;
+import java.util.Iterator;
+
+/**
+ *
+ * Dump internal structure of a OLE2 file into file system
+ *
+ * @author Yegor Kozlov
+ */
+public class POIFSDump {
+
+    public static void main(String[] args) throws Exception {
+        for (int i = 0; i < args.length; i++) {
+            System.out.println("Dumping " + args[i]);
+            FileInputStream is = new FileInputStream(args[i]);
+            POIFSFileSystem fs = new POIFSFileSystem(is);
+            is.close();
+
+            DirectoryEntry root = fs.getRoot();
+            File file = new File(root.getName());
+            file.mkdir();
+
+            dump(root, file);
+        }
+   }
+
+
+    public static void dump(DirectoryEntry root, File parent) throws IOException {
+        for(Iterator it = root.getEntries(); it.hasNext();){
+            Entry entry = (Entry)it.next();
+            if(entry instanceof DocumentNode){
+                DocumentNode node = (DocumentNode)entry;
+                DocumentInputStream is = new DocumentInputStream(node);
+                byte[] bytes = new byte[node.getSize()];
+                is.read(bytes);
+                is.close();
+
+                FileOutputStream out = new FileOutputStream(new File(parent, node.getName().trim()));
+                out.write(bytes);
+                out.close();
+            } else if (entry instanceof DirectoryEntry){
+                DirectoryEntry dir = (DirectoryEntry)entry;
+                File file = new File(parent, entry.getName());
+                file.mkdir();
+                dump(dir, file);
+            } else {
+                System.err.println("Skipping unsupported POIFS entry: " + entry);
+            }
+        }
+    }
+}
index 4a7b2bbe4fad7bf508933a830ea8e3e1d8941211..316e5af06fff3099b7d3aea9dd849be1111bc101 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss;\r
-\r
-import org.apache.poi.ss.util.CellReference;\r
-\r
-/**\r
- * This enum allows spreadsheets from multiple Excel versions to be handled by the common code.\r
- * Properties of this enum correspond to attributes of the <i>spreadsheet</i> that are easily\r
- * discernable to the user.  It is not intended to deal with low-level issues like file formats.  \r
- * <p/>\r
- * \r
- * @author Josh Micich\r
- * @author Yegor Kozlov\r
- */\r
-public enum SpreadsheetVersion {\r
-    /**\r
-     * Excel97 format aka BIFF8\r
-     * <ul>\r
-     * <li>The total number of available columns is 256 (2^8)</li>\r
-     * <li>The total number of available rows is 64k (2^16)</li>\r
-     * <li>The maximum number of arguments to a function is 30</li>\r
-     * <li>Number of conditional format conditions on a cell is 3</li>\r
-     * </ul>\r
-     */\r
-       EXCEL97(0x10000, 0x0100, 30, 3),\r
-\r
-    /**\r
-     * Excel2007\r
-     *\r
-     * <ul>\r
-     * <li>The total number of available columns is 16K (2^14)</li>\r
-     * <li>The total number of available rows is 1M (2^20)</li>\r
-     * <li>The maximum number of arguments to a function is 255</li>\r
-     * <li>Number of conditional format conditions on a cell is unlimited\r
-     *  (actually limited by available memory in Excel)</li>\r
-     * <ul>\r
-     */\r
-    EXCEL2007(0x100000, 0x4000, 255, Integer.MAX_VALUE);\r
-\r
-       private final int _maxRows;\r
-       private final int _maxColumns;\r
-       private final int _maxFunctionArgs;\r
-    private final int _maxCondFormats;\r
-\r
-       private SpreadsheetVersion(int maxRows, int maxColumns, int maxFunctionArgs, int maxCondFormats) {\r
-               _maxRows = maxRows;\r
-               _maxColumns = maxColumns;\r
-               _maxFunctionArgs = maxFunctionArgs;\r
-        _maxCondFormats = maxCondFormats;\r
-       }\r
-\r
-       /**\r
-        * @return the maximum number of usable rows in each spreadsheet\r
-        */\r
-       public int getMaxRows() {\r
-               return _maxRows;\r
-       }\r
-\r
-    /**\r
-     * @return the last (maximum) valid row index, equals to <code> getMaxRows() - 1 </code>\r
-     */\r
-    public int getLastRowIndex() {\r
-        return _maxRows - 1;\r
-    }\r
-\r
-       /**\r
-        * @return the maximum number of usable columns in each spreadsheet\r
-        */\r
-       public int getMaxColumns() {\r
-               return _maxColumns;\r
-       }\r
-\r
-    /**\r
-     * @return the last (maximum) valid column index, equals to <code> getMaxColumns() - 1 </code>\r
-     */\r
-    public int getLastColumnIndex() {\r
-        return _maxColumns - 1;\r
-    }\r
-\r
-       /**\r
-        * @return the maximum number arguments that can be passed to a multi-arg\r
-        *         function (e.g. COUNTIF)\r
-        */\r
-       public int getMaxFunctionArgs() {\r
-               return _maxFunctionArgs;\r
-       }\r
-\r
-    /**\r
-     *\r
-     * @return the maximum number of conditional format conditions on a cell\r
-     */\r
-    public int getMaxConditionalFormats() {\r
-        return _maxCondFormats;\r
-    }\r
-\r
-    /**\r
-     * \r
-     * @return the last valid column index in a ALPHA-26 representation\r
-     *   ( <code>IV</code> or <code>XFD</code>).\r
-     */\r
-    public String getLastColumnName() {\r
-        return CellReference.convertNumToColString(getLastColumnIndex());\r
-    }\r
-}\r
+/* ====================================================================
+   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.ss;
+
+import org.apache.poi.ss.util.CellReference;
+
+/**
+ * This enum allows spreadsheets from multiple Excel versions to be handled by the common code.
+ * Properties of this enum correspond to attributes of the <i>spreadsheet</i> that are easily
+ * discernable to the user.  It is not intended to deal with low-level issues like file formats.
+ * <p/>
+ *
+ * @author Josh Micich
+ * @author Yegor Kozlov
+ */
+public enum SpreadsheetVersion {
+       /**
+        * Excel97 format aka BIFF8
+        * <ul>
+        * <li>The total number of available columns is 256 (2^8)</li>
+        * <li>The total number of available rows is 64k (2^16)</li>
+        * <li>The maximum number of arguments to a function is 30</li>
+        * <li>Number of conditional format conditions on a cell is 3</li>
+        * </ul>
+        */
+       EXCEL97(0x10000, 0x0100, 30, 3),
+
+       /**
+        * Excel2007
+        *
+        * <ul>
+        * <li>The total number of available columns is 16K (2^14)</li>
+        * <li>The total number of available rows is 1M (2^20)</li>
+        * <li>The maximum number of arguments to a function is 255</li>
+        * <li>Number of conditional format conditions on a cell is unlimited
+        * (actually limited by available memory in Excel)</li>
+        * <ul>
+        */
+       EXCEL2007(0x100000, 0x4000, 255, Integer.MAX_VALUE);
+
+       private final int _maxRows;
+       private final int _maxColumns;
+       private final int _maxFunctionArgs;
+       private final int _maxCondFormats;
+
+       private SpreadsheetVersion(int maxRows, int maxColumns, int maxFunctionArgs, int maxCondFormats) {
+               _maxRows = maxRows;
+               _maxColumns = maxColumns;
+               _maxFunctionArgs = maxFunctionArgs;
+               _maxCondFormats = maxCondFormats;
+       }
+
+       /**
+        * @return the maximum number of usable rows in each spreadsheet
+        */
+       public int getMaxRows() {
+               return _maxRows;
+       }
+
+       /**
+        * @return the last (maximum) valid row index, equals to <code> getMaxRows() - 1 </code>
+        */
+       public int getLastRowIndex() {
+               return _maxRows - 1;
+       }
+
+       /**
+        * @return the maximum number of usable columns in each spreadsheet
+        */
+       public int getMaxColumns() {
+               return _maxColumns;
+       }
+
+       /**
+        * @return the last (maximum) valid column index, equals to <code> getMaxColumns() - 1 </code>
+        */
+       public int getLastColumnIndex() {
+               return _maxColumns - 1;
+       }
+
+       /**
+        * @return the maximum number arguments that can be passed to a multi-arg function (e.g. COUNTIF)
+        */
+       public int getMaxFunctionArgs() {
+               return _maxFunctionArgs;
+       }
+
+       /**
+        *
+        * @return the maximum number of conditional format conditions on a cell
+        */
+       public int getMaxConditionalFormats() {
+               return _maxCondFormats;
+       }
+
+       /**
+        *
+        * @return the last valid column index in a ALPHA-26 representation
+        *  (<code>IV</code> or <code>XFD</code>).
+        */
+       public String getLastColumnName() {
+               return CellReference.convertNumToColString(getLastColumnIndex());
+       }
+}
index a9f79e9e642cc82b059d6bd8891bfb697f41d9dd..186fe6e1c8cdf35da9fbf996299a3b632c086b92 100644 (file)
@@ -1,77 +1,77 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula;\r
-\r
-import java.util.HashSet;\r
-import java.util.Set;\r
-\r
-import org.apache.poi.hssf.record.formula.eval.ValueEval;\r
-\r
-/**\r
- * Stores details about the current evaluation of a cell.<br/>\r
- */\r
-final class CellEvaluationFrame {\r
-\r
-       private final FormulaCellCacheEntry _cce;\r
-       private final Set<CellCacheEntry> _sensitiveInputCells;\r
-       private FormulaUsedBlankCellSet _usedBlankCellGroup;\r
-\r
-       public CellEvaluationFrame(FormulaCellCacheEntry cce) {\r
-               _cce = cce;\r
-               _sensitiveInputCells = new HashSet<CellCacheEntry>();\r
-       }\r
-       public CellCacheEntry getCCE() {\r
-               return _cce;\r
-       }\r
-\r
-       public String toString() {\r
-               StringBuffer sb = new StringBuffer(64);\r
-               sb.append(getClass().getName()).append(" [");\r
-               sb.append("]");\r
-               return sb.toString();\r
-       }\r
-       /**\r
-        * @param inputCell a cell directly used by the formula of this evaluation frame\r
-        */\r
-       public void addSensitiveInputCell(CellCacheEntry inputCell) {\r
-               _sensitiveInputCells.add(inputCell);\r
-       }\r
-       /**\r
-        * @return never <code>null</code>, (possibly empty) array of all cells directly used while \r
-        * evaluating the formula of this frame.\r
-        */\r
-       private CellCacheEntry[] getSensitiveInputCells() {\r
-               int nItems = _sensitiveInputCells.size();\r
-               if (nItems < 1) {\r
-                       return CellCacheEntry.EMPTY_ARRAY;\r
-               }\r
-               CellCacheEntry[] result = new CellCacheEntry[nItems];\r
-               _sensitiveInputCells.toArray(result);\r
-               return result;\r
-       }\r
-       public void addUsedBlankCell(int bookIndex, int sheetIndex, int rowIndex, int columnIndex) {\r
-               if (_usedBlankCellGroup == null) {\r
-                       _usedBlankCellGroup = new FormulaUsedBlankCellSet();\r
-               }\r
-               _usedBlankCellGroup.addCell(bookIndex, sheetIndex, rowIndex, columnIndex);\r
-       }\r
-       \r
-       public void updateFormulaResult(ValueEval result) {\r
-               _cce.updateFormulaResult(result, getSensitiveInputCells(), _usedBlankCellGroup);\r
-       }\r
-}
\ No newline at end of file
+/* ====================================================================
+   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.ss.formula;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.poi.hssf.record.formula.eval.ValueEval;
+
+/**
+ * Stores details about the current evaluation of a cell.<br/>
+ */
+final class CellEvaluationFrame {
+
+       private final FormulaCellCacheEntry _cce;
+       private final Set<CellCacheEntry> _sensitiveInputCells;
+       private FormulaUsedBlankCellSet _usedBlankCellGroup;
+
+       public CellEvaluationFrame(FormulaCellCacheEntry cce) {
+               _cce = cce;
+               _sensitiveInputCells = new HashSet<CellCacheEntry>();
+       }
+       public CellCacheEntry getCCE() {
+               return _cce;
+       }
+
+       public String toString() {
+               StringBuffer sb = new StringBuffer(64);
+               sb.append(getClass().getName()).append(" [");
+               sb.append("]");
+               return sb.toString();
+       }
+       /**
+        * @param inputCell a cell directly used by the formula of this evaluation frame
+        */
+       public void addSensitiveInputCell(CellCacheEntry inputCell) {
+               _sensitiveInputCells.add(inputCell);
+       }
+       /**
+        * @return never <code>null</code>, (possibly empty) array of all cells directly used while
+        * evaluating the formula of this frame.
+        */
+       private CellCacheEntry[] getSensitiveInputCells() {
+               int nItems = _sensitiveInputCells.size();
+               if (nItems < 1) {
+                       return CellCacheEntry.EMPTY_ARRAY;
+               }
+               CellCacheEntry[] result = new CellCacheEntry[nItems];
+               _sensitiveInputCells.toArray(result);
+               return result;
+       }
+       public void addUsedBlankCell(int bookIndex, int sheetIndex, int rowIndex, int columnIndex) {
+               if (_usedBlankCellGroup == null) {
+                       _usedBlankCellGroup = new FormulaUsedBlankCellSet();
+               }
+               _usedBlankCellGroup.addCell(bookIndex, sheetIndex, rowIndex, columnIndex);
+       }
+
+       public void updateFormulaResult(ValueEval result) {
+               _cce.updateFormulaResult(result, getSensitiveInputCells(), _usedBlankCellGroup);
+       }
+}
index ae8624c7b8b5c0cecec18ab3e0f8e80d6ddcd66a..7d6688bb82a24693076fcc2a04e8b66abf3928cd 100644 (file)
@@ -1,41 +1,41 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula;\r
-\r
-import org.apache.poi.hssf.record.formula.NamePtg;\r
-import org.apache.poi.hssf.record.formula.Ptg;\r
-/**\r
- * Abstracts a name record for formula evaluation.<br/>\r
- * \r
- * For POI internal use only\r
- * \r
- * @author Josh Micich\r
- */\r
-public interface EvaluationName {\r
-\r
-       String getNameText();\r
-\r
-       boolean isFunctionName();\r
-\r
-       boolean hasFormula();\r
-\r
-       Ptg[] getNameDefinition();\r
-\r
-       boolean isRange();\r
-       NamePtg createPtg();\r
-}\r
+/* ====================================================================
+   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.ss.formula;
+
+import org.apache.poi.hssf.record.formula.NamePtg;
+import org.apache.poi.hssf.record.formula.Ptg;
+/**
+ * Abstracts a name record for formula evaluation.<br/>
+ *
+ * For POI internal use only
+ *
+ * @author Josh Micich
+ */
+public interface EvaluationName {
+
+       String getNameText();
+
+       boolean isFunctionName();
+
+       boolean hasFormula();
+
+       Ptg[] getNameDefinition();
+
+       boolean isRange();
+       NamePtg createPtg();
+}
index 45b0c918f2f582ea60e520c71721286b4b0323d9..28f31eb497331888149fe82fe84c507a476185d1 100644 (file)
@@ -1,65 +1,65 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula;\r
-\r
-import org.apache.poi.hssf.record.formula.NamePtg;\r
-import org.apache.poi.hssf.record.formula.NameXPtg;\r
-import org.apache.poi.hssf.record.formula.Ptg;\r
-\r
-/**\r
- * Abstracts a workbook for the purpose of formula evaluation.<br/>\r
- * \r
- * For POI internal use only\r
- * \r
- * @author Josh Micich\r
- */\r
-public interface EvaluationWorkbook {\r
-       String getSheetName(int sheetIndex);\r
-       /**\r
-        * @return -1 if the specified sheet is from a different book\r
-        */\r
-       int getSheetIndex(EvaluationSheet sheet);\r
-       int getSheetIndex(String sheetName);\r
-\r
-       EvaluationSheet getSheet(int sheetIndex);\r
-\r
-       /**\r
-        * @return <code>null</code> if externSheetIndex refers to a sheet inside the current workbook\r
-        */\r
-       ExternalSheet getExternalSheet(int externSheetIndex);\r
-       int convertFromExternSheetIndex(int externSheetIndex);\r
-       EvaluationName getName(NamePtg namePtg);\r
-       String resolveNameXText(NameXPtg ptg);\r
-       Ptg[] getFormulaTokens(EvaluationCell cell);\r
-       \r
-       class ExternalSheet {\r
-               private final String _workbookName;\r
-               private final String _sheetName;\r
-\r
-               public ExternalSheet(String workbookName, String sheetName) {\r
-                       _workbookName = workbookName;\r
-                       _sheetName = sheetName;\r
-               }\r
-               public String getWorkbookName() {\r
-                       return _workbookName;\r
-               }\r
-               public String getSheetName() {\r
-                       return _sheetName;\r
-               }\r
-       }\r
-}\r
+/* ====================================================================
+   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.ss.formula;
+
+import org.apache.poi.hssf.record.formula.NamePtg;
+import org.apache.poi.hssf.record.formula.NameXPtg;
+import org.apache.poi.hssf.record.formula.Ptg;
+
+/**
+ * Abstracts a workbook for the purpose of formula evaluation.<br/>
+ *
+ * For POI internal use only
+ *
+ * @author Josh Micich
+ */
+public interface EvaluationWorkbook {
+       String getSheetName(int sheetIndex);
+       /**
+        * @return -1 if the specified sheet is from a different book
+        */
+       int getSheetIndex(EvaluationSheet sheet);
+       int getSheetIndex(String sheetName);
+
+       EvaluationSheet getSheet(int sheetIndex);
+
+       /**
+        * @return <code>null</code> if externSheetIndex refers to a sheet inside the current workbook
+        */
+       ExternalSheet getExternalSheet(int externSheetIndex);
+       int convertFromExternSheetIndex(int externSheetIndex);
+       EvaluationName getName(NamePtg namePtg);
+       String resolveNameXText(NameXPtg ptg);
+       Ptg[] getFormulaTokens(EvaluationCell cell);
+
+       class ExternalSheet {
+               private final String _workbookName;
+               private final String _sheetName;
+
+               public ExternalSheet(String workbookName, String sheetName) {
+                       _workbookName = workbookName;
+                       _sheetName = sheetName;
+               }
+               public String getWorkbookName() {
+                       return _workbookName;
+               }
+               public String getSheetName() {
+                       return _sheetName;
+               }
+       }
+}
index f2cef2cb42879425d611d40bfc3f99eeea31f49c..0eb8a7f6dcc2832f662bb435c2c2bd10f74d44ef 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula;\r
-\r
-import java.util.Arrays;\r
-\r
-import org.apache.poi.hssf.record.ArrayRecord;\r
-import org.apache.poi.hssf.record.SharedFormulaRecord;\r
-import org.apache.poi.hssf.record.TableRecord;\r
-import org.apache.poi.hssf.record.formula.ExpPtg;\r
-import org.apache.poi.hssf.record.formula.Ptg;\r
-import org.apache.poi.hssf.record.formula.TblPtg;\r
-import org.apache.poi.hssf.util.CellReference;\r
-import org.apache.poi.util.LittleEndian;\r
-import org.apache.poi.util.LittleEndianByteArrayInputStream;\r
-import org.apache.poi.util.LittleEndianInput;\r
-import org.apache.poi.util.LittleEndianOutput;\r
-\r
-/**\r
- * Encapsulates an encoded formula token array. \r
- * \r
- * @author Josh Micich\r
- */\r
-public class Formula {\r
-\r
-       private static final Formula EMPTY = new Formula(new byte[0], 0);\r
-\r
-       /** immutable */\r
-       private final byte[] _byteEncoding;\r
-       private final int _encodedTokenLen;\r
-       \r
-       private Formula(byte[] byteEncoding, int encodedTokenLen) {\r
-               _byteEncoding = byteEncoding;\r
-               _encodedTokenLen = encodedTokenLen;\r
-               if (false) { // set to true to eagerly check Ptg decoding \r
-                       LittleEndianByteArrayInputStream in = new LittleEndianByteArrayInputStream(byteEncoding);\r
-                       Ptg.readTokens(encodedTokenLen, in);\r
-                       int nUnusedBytes = _byteEncoding.length - in.getReadIndex();\r
-                       if (nUnusedBytes > 0) {\r
-                               // TODO - this seems to occur when IntersectionPtg is present\r
-                               // This example file "IntersectionPtg.xls"\r
-                               // used by test: TestIntersectionPtg.testReading()\r
-                               // has 10 bytes unused at the end of the formula\r
-                               // 10 extra bytes are just 0x01 and 0x00\r
-                               System.out.println(nUnusedBytes + " unused bytes at end of formula");\r
-                       }\r
-               }\r
-       }\r
-       /**\r
-        * Convenience method for {@link #read(int, LittleEndianInput, int)}\r
-        */\r
-       public static Formula read(int encodedTokenLen, LittleEndianInput in) {\r
-               return read(encodedTokenLen, in, encodedTokenLen);\r
-       }\r
-       /**\r
-        * When there are no array constants present, <tt>encodedTokenLen</tt>==<tt>totalEncodedLen</tt>\r
-        * @param encodedTokenLen number of bytes in the stream taken by the plain formula tokens\r
-        * @param totalEncodedLen the total number of bytes in the formula (includes trailing encoding\r
-        * for array constants, but does not include 2 bytes for initial <tt>ushort encodedTokenLen</tt> field.\r
-        * @return A new formula object as read from the stream.  Possibly empty, never <code>null</code>.\r
-        */\r
-       public static Formula read(int encodedTokenLen, LittleEndianInput in, int totalEncodedLen) {\r
-               byte[] byteEncoding = new byte[totalEncodedLen];\r
-               in.readFully(byteEncoding);\r
-               return new Formula(byteEncoding, encodedTokenLen);\r
-       }\r
-       \r
-       public Ptg[] getTokens() {\r
-               LittleEndianInput in = new LittleEndianByteArrayInputStream(_byteEncoding);\r
-               return Ptg.readTokens(_encodedTokenLen, in);\r
-       }\r
-       /**\r
-        * Writes  The formula encoding is includes:\r
-        * <ul>\r
-        * <li>ushort tokenDataLen</li>\r
-        * <li>tokenData</li>\r
-        * <li>arrayConstantData (if present)</li>\r
-        * </ul>\r
-        */\r
-       public void serialize(LittleEndianOutput out) {\r
-               out.writeShort(_encodedTokenLen);\r
-               out.write(_byteEncoding);\r
-       }\r
-\r
-       public void serializeTokens(LittleEndianOutput out) {\r
-               out.write(_byteEncoding, 0, _encodedTokenLen);\r
-       }\r
-       public void serializeArrayConstantData(LittleEndianOutput out) {\r
-               int len = _byteEncoding.length-_encodedTokenLen;\r
-               out.write(_byteEncoding, _encodedTokenLen, len);\r
-       }\r
-       \r
-       \r
-       /**\r
-        * @return total formula encoding length.  The formula encoding includes:\r
-        * <ul>\r
-        * <li>ushort tokenDataLen</li>\r
-        * <li>tokenData</li>\r
-        * <li>arrayConstantData (optional)</li>\r
-        * </ul>\r
-        * Note - this value is different to <tt>tokenDataLength</tt>\r
-        */\r
-       public int getEncodedSize() {\r
-               return 2 + _byteEncoding.length;\r
-       }\r
-       /**\r
-        * This method is often used when the formula length does not appear immediately before\r
-        * the encoded token data.\r
-        * \r
-        * @return the encoded length of the plain formula tokens.  This does <em>not</em> include\r
-        * the leading ushort field, nor any trailing array constant data.\r
-        */\r
-       public int getEncodedTokenSize() {\r
-               return _encodedTokenLen;\r
-       }\r
-       \r
-       /**\r
-        * Creates a {@link Formula} object from a supplied {@link Ptg} array. \r
-        * Handles <code>null</code>s OK.\r
-        * @param ptgs may be <code>null</code>\r
-        * @return Never <code>null</code> (Possibly empty if the supplied <tt>ptgs</tt> is <code>null</code>)\r
-        */\r
-       public static Formula create(Ptg[] ptgs) {\r
-               if (ptgs == null || ptgs.length < 1) {\r
-                       return EMPTY;\r
-               }\r
-               int totalSize = Ptg.getEncodedSize(ptgs);\r
-               byte[] encodedData = new byte[totalSize];\r
-               Ptg.serializePtgs(ptgs, encodedData, 0);\r
-               int encodedTokenLen = Ptg.getEncodedSizeWithoutArrayData(ptgs);\r
-               return new Formula(encodedData, encodedTokenLen);\r
-       }\r
-       /**\r
-        * Gets the {@link Ptg} array from the supplied {@link Formula}. \r
-        * Handles <code>null</code>s OK.\r
-        * \r
-        * @param formula may be <code>null</code>\r
-        * @return possibly <code>null</code> (if the supplied <tt>formula</tt> is <code>null</code>)\r
-        */\r
-       public static Ptg[] getTokens(Formula formula) {\r
-               if (formula == null) {\r
-                       return null;\r
-               }\r
-               return formula.getTokens();\r
-       }\r
-       \r
-       public Formula copy() {\r
-               // OK to return this because immutable\r
-               return this;\r
-       }\r
-       \r
-       /**\r
-        * Gets the locator for the corresponding {@link SharedFormulaRecord}, {@link ArrayRecord} or\r
-        * {@link TableRecord} if this formula belongs to such a grouping.  The {@link CellReference}\r
-        * returned by this method will  match the top left corner of the range of that grouping. \r
-        * The return value is usually not the same as the location of the cell containing this formula.\r
-        * \r
-        * @return the firstRow & firstColumn of an array formula or shared formula that this formula\r
-        * belongs to.  <code>null</code> if this formula is not part of an array or shared formula.\r
-        */\r
-       public CellReference getExpReference() {\r
-               byte[] data = _byteEncoding;\r
-               if (data.length != 5) {\r
-                       // tExp and tTbl are always 5 bytes long, and the only ptg in the formula\r
-                       return null;\r
-               }\r
-               switch (data[0]) {\r
-                       case ExpPtg.sid:\r
-                               break;\r
-                       case TblPtg.sid:\r
-                               break;\r
-                       default:\r
-                               return null;\r
-               }\r
-               int firstRow = LittleEndian.getUShort(data, 1);\r
-               int firstColumn = LittleEndian.getUShort(data, 3);\r
-               return new CellReference(firstRow, firstColumn);\r
-       }\r
-       public boolean isSame(Formula other) {\r
-               return Arrays.equals(_byteEncoding, other._byteEncoding);\r
-       }\r
-}\r
+/* ====================================================================
+   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.ss.formula;
+
+import java.util.Arrays;
+
+import org.apache.poi.hssf.record.ArrayRecord;
+import org.apache.poi.hssf.record.SharedFormulaRecord;
+import org.apache.poi.hssf.record.TableRecord;
+import org.apache.poi.hssf.record.formula.ExpPtg;
+import org.apache.poi.hssf.record.formula.Ptg;
+import org.apache.poi.hssf.record.formula.TblPtg;
+import org.apache.poi.hssf.util.CellReference;
+import org.apache.poi.util.LittleEndian;
+import org.apache.poi.util.LittleEndianByteArrayInputStream;
+import org.apache.poi.util.LittleEndianInput;
+import org.apache.poi.util.LittleEndianOutput;
+
+/**
+ * Encapsulates an encoded formula token array.
+ *
+ * @author Josh Micich
+ */
+public class Formula {
+
+       private static final Formula EMPTY = new Formula(new byte[0], 0);
+
+       /** immutable */
+       private final byte[] _byteEncoding;
+       private final int _encodedTokenLen;
+
+       private Formula(byte[] byteEncoding, int encodedTokenLen) {
+               _byteEncoding = byteEncoding;
+               _encodedTokenLen = encodedTokenLen;
+               if (false) { // set to true to eagerly check Ptg decoding
+                       LittleEndianByteArrayInputStream in = new LittleEndianByteArrayInputStream(byteEncoding);
+                       Ptg.readTokens(encodedTokenLen, in);
+                       int nUnusedBytes = _byteEncoding.length - in.getReadIndex();
+                       if (nUnusedBytes > 0) {
+                               // TODO - this seems to occur when IntersectionPtg is present
+                               // This example file "IntersectionPtg.xls"
+                               // used by test: TestIntersectionPtg.testReading()
+                               // has 10 bytes unused at the end of the formula
+                               // 10 extra bytes are just 0x01 and 0x00
+                               System.out.println(nUnusedBytes + " unused bytes at end of formula");
+                       }
+               }
+       }
+       /**
+        * Convenience method for {@link #read(int, LittleEndianInput, int)}
+        */
+       public static Formula read(int encodedTokenLen, LittleEndianInput in) {
+               return read(encodedTokenLen, in, encodedTokenLen);
+       }
+       /**
+        * When there are no array constants present, <tt>encodedTokenLen</tt>==<tt>totalEncodedLen</tt>
+        * @param encodedTokenLen number of bytes in the stream taken by the plain formula tokens
+        * @param totalEncodedLen the total number of bytes in the formula (includes trailing encoding
+        * for array constants, but does not include 2 bytes for initial <tt>ushort encodedTokenLen</tt> field.
+        * @return A new formula object as read from the stream.  Possibly empty, never <code>null</code>.
+        */
+       public static Formula read(int encodedTokenLen, LittleEndianInput in, int totalEncodedLen) {
+               byte[] byteEncoding = new byte[totalEncodedLen];
+               in.readFully(byteEncoding);
+               return new Formula(byteEncoding, encodedTokenLen);
+       }
+
+       public Ptg[] getTokens() {
+               LittleEndianInput in = new LittleEndianByteArrayInputStream(_byteEncoding);
+               return Ptg.readTokens(_encodedTokenLen, in);
+       }
+       /**
+        * Writes  The formula encoding is includes:
+        * <ul>
+        * <li>ushort tokenDataLen</li>
+        * <li>tokenData</li>
+        * <li>arrayConstantData (if present)</li>
+        * </ul>
+        */
+       public void serialize(LittleEndianOutput out) {
+               out.writeShort(_encodedTokenLen);
+               out.write(_byteEncoding);
+       }
+
+       public void serializeTokens(LittleEndianOutput out) {
+               out.write(_byteEncoding, 0, _encodedTokenLen);
+       }
+       public void serializeArrayConstantData(LittleEndianOutput out) {
+               int len = _byteEncoding.length-_encodedTokenLen;
+               out.write(_byteEncoding, _encodedTokenLen, len);
+       }
+
+
+       /**
+        * @return total formula encoding length.  The formula encoding includes:
+        * <ul>
+        * <li>ushort tokenDataLen</li>
+        * <li>tokenData</li>
+        * <li>arrayConstantData (optional)</li>
+        * </ul>
+        * Note - this value is different to <tt>tokenDataLength</tt>
+        */
+       public int getEncodedSize() {
+               return 2 + _byteEncoding.length;
+       }
+       /**
+        * This method is often used when the formula length does not appear immediately before
+        * the encoded token data.
+        *
+        * @return the encoded length of the plain formula tokens.  This does <em>not</em> include
+        * the leading ushort field, nor any trailing array constant data.
+        */
+       public int getEncodedTokenSize() {
+               return _encodedTokenLen;
+       }
+
+       /**
+        * Creates a {@link Formula} object from a supplied {@link Ptg} array.
+        * Handles <code>null</code>s OK.
+        * @param ptgs may be <code>null</code>
+        * @return Never <code>null</code> (Possibly empty if the supplied <tt>ptgs</tt> is <code>null</code>)
+        */
+       public static Formula create(Ptg[] ptgs) {
+               if (ptgs == null || ptgs.length < 1) {
+                       return EMPTY;
+               }
+               int totalSize = Ptg.getEncodedSize(ptgs);
+               byte[] encodedData = new byte[totalSize];
+               Ptg.serializePtgs(ptgs, encodedData, 0);
+               int encodedTokenLen = Ptg.getEncodedSizeWithoutArrayData(ptgs);
+               return new Formula(encodedData, encodedTokenLen);
+       }
+       /**
+        * Gets the {@link Ptg} array from the supplied {@link Formula}.
+        * Handles <code>null</code>s OK.
+        *
+        * @param formula may be <code>null</code>
+        * @return possibly <code>null</code> (if the supplied <tt>formula</tt> is <code>null</code>)
+        */
+       public static Ptg[] getTokens(Formula formula) {
+               if (formula == null) {
+                       return null;
+               }
+               return formula.getTokens();
+       }
+
+       public Formula copy() {
+               // OK to return this because immutable
+               return this;
+       }
+
+       /**
+        * Gets the locator for the corresponding {@link SharedFormulaRecord}, {@link ArrayRecord} or
+        * {@link TableRecord} if this formula belongs to such a grouping.  The {@link CellReference}
+        * returned by this method will  match the top left corner of the range of that grouping.
+        * The return value is usually not the same as the location of the cell containing this formula.
+        *
+        * @return the firstRow & firstColumn of an array formula or shared formula that this formula
+        * belongs to.  <code>null</code> if this formula is not part of an array or shared formula.
+        */
+       public CellReference getExpReference() {
+               byte[] data = _byteEncoding;
+               if (data.length != 5) {
+                       // tExp and tTbl are always 5 bytes long, and the only ptg in the formula
+                       return null;
+               }
+               switch (data[0]) {
+                       case ExpPtg.sid:
+                               break;
+                       case TblPtg.sid:
+                               break;
+                       default:
+                               return null;
+               }
+               int firstRow = LittleEndian.getUShort(data, 1);
+               int firstColumn = LittleEndian.getUShort(data, 3);
+               return new CellReference(firstRow, firstColumn);
+       }
+       public boolean isSame(Formula other) {
+               return Arrays.equals(_byteEncoding, other._byteEncoding);
+       }
+}
index 2ecd69be9a67d315061876bf8d55cda28463fa11..83f7c99a969c4b7eb2e890b8c6596c076f35ff11 100644 (file)
@@ -1,55 +1,55 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula;\r
-\r
-import org.apache.poi.hssf.record.formula.NameXPtg;\r
-import org.apache.poi.ss.SpreadsheetVersion;\r
-\r
-/**\r
- * Abstracts a workbook for the purpose of formula parsing.<br/>\r
- * \r
- * For POI internal use only\r
- * \r
- * @author Josh Micich\r
- */\r
-public interface FormulaParsingWorkbook {\r
-       /**\r
-        *  named range name matching is case insensitive\r
-        */\r
-    EvaluationName getName(String name, int sheetIndex);\r
-\r
-       NameXPtg getNameXPtg(String name);\r
-\r
-       /**\r
-        * gets the externSheet index for a sheet from this workbook\r
-        */\r
-       int getExternalSheetIndex(String sheetName);\r
-       /**\r
-        * gets the externSheet index for a sheet from an external workbook\r
-        * @param workbookName e.g. "Budget.xls"\r
-        * @param sheetName a name of a sheet in that workbook\r
-        */\r
-       int getExternalSheetIndex(String workbookName, String sheetName);\r
-\r
-    /**\r
-     * Returns an enum holding spreadhseet properties specific to an Excel version (\r
-     * max column and row numbers, max arguments to a function, etc.)\r
-     */\r
-    SpreadsheetVersion getSpreadsheetVersion();\r
-\r
-}\r
+/* ====================================================================
+   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.ss.formula;
+
+import org.apache.poi.hssf.record.formula.NameXPtg;
+import org.apache.poi.ss.SpreadsheetVersion;
+
+/**
+ * Abstracts a workbook for the purpose of formula parsing.<br/>
+ *
+ * For POI internal use only
+ *
+ * @author Josh Micich
+ */
+public interface FormulaParsingWorkbook {
+       /**
+        *  named range name matching is case insensitive
+        */
+       EvaluationName getName(String name, int sheetIndex);
+
+       NameXPtg getNameXPtg(String name);
+
+       /**
+        * gets the externSheet index for a sheet from this workbook
+        */
+       int getExternalSheetIndex(String sheetName);
+       /**
+        * gets the externSheet index for a sheet from an external workbook
+        * @param workbookName e.g. "Budget.xls"
+        * @param sheetName a name of a sheet in that workbook
+        */
+       int getExternalSheetIndex(String workbookName, String sheetName);
+
+       /**
+        * Returns an enum holding spreadhseet properties specific to an Excel version (
+        * max column and row numbers, max arguments to a function, etc.)
+        */
+       SpreadsheetVersion getSpreadsheetVersion();
+
+}
index df078809cf30af2e2c826c757242a8491ff4c311..76dce7f55e0adda626daea88187c21ae09b3be5c 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula;\r
-\r
-import java.util.Stack;\r
-\r
-import org.apache.poi.hssf.record.formula.AttrPtg;\r
-import org.apache.poi.hssf.record.formula.MemAreaPtg;\r
-import org.apache.poi.hssf.record.formula.MemErrPtg;\r
-import org.apache.poi.hssf.record.formula.MemFuncPtg;\r
-import org.apache.poi.hssf.record.formula.OperationPtg;\r
-import org.apache.poi.hssf.record.formula.ParenthesisPtg;\r
-import org.apache.poi.hssf.record.formula.Ptg;\r
-\r
-/**\r
- * Common logic for rendering formulas.<br/>\r
- * \r
- * For POI internal use only\r
- * \r
- * @author Josh Micich\r
- */\r
-public class FormulaRenderer {\r
-    \r
-    /**\r
-     * Static method to convert an array of {@link Ptg}s in RPN order\r
-     * to a human readable string format in infix mode.\r
-     * @param book  used for defined names and 3D references\r
-     * @param ptgs  must not be <code>null</code>\r
-     * @return a human readable String\r
-     */\r
-    public static String toFormulaString(FormulaRenderingWorkbook book, Ptg[] ptgs) {\r
-        if (ptgs == null || ptgs.length == 0) {\r
-            throw new IllegalArgumentException("ptgs must not be null");\r
-        }\r
-        Stack<String> stack = new Stack<String>();\r
-\r
-        for (int i=0 ; i < ptgs.length; i++) {\r
-            Ptg ptg = ptgs[i];\r
-            // TODO - what about MemNoMemPtg?\r
-            if(ptg instanceof MemAreaPtg || ptg instanceof MemFuncPtg || ptg instanceof MemErrPtg) {\r
-                // marks the start of a list of area expressions which will be naturally combined\r
-                // by their trailing operators (e.g. UnionPtg)\r
-                // TODO - put comment and throw exception in toFormulaString() of these classes\r
-                continue;\r
-            }\r
-            if (ptg instanceof ParenthesisPtg) {\r
-                String contents = stack.pop();\r
-                stack.push ("(" + contents + ")");\r
-                continue;\r
-            }\r
-            if (ptg instanceof AttrPtg) {\r
-                AttrPtg attrPtg = ((AttrPtg) ptg);\r
-                if (attrPtg.isOptimizedIf() || attrPtg.isOptimizedChoose() || attrPtg.isGoto()) {\r
-                    continue;\r
-                }\r
-                if (attrPtg.isSpace()) {\r
-                    // POI currently doesn't render spaces in formulas\r
-                    continue;\r
-                    // but if it ever did, care must be taken:\r
-                    // tAttrSpace comes *before* the operand it applies to, which may be consistent\r
-                    // with how the formula text appears but is against the RPN ordering assumed here\r
-                }\r
-                if (attrPtg.isSemiVolatile()) {\r
-                    // similar to tAttrSpace - RPN is violated\r
-                    continue;\r
-                }\r
-                if (attrPtg.isSum()) {\r
-                    String[] operands = getOperands(stack, attrPtg.getNumberOfOperands());\r
-                    stack.push(attrPtg.toFormulaString(operands));\r
-                    continue;\r
-                }\r
-                throw new RuntimeException("Unexpected tAttr: " + attrPtg.toString());\r
-            }\r
-\r
-            if (ptg instanceof WorkbookDependentFormula) {\r
-                WorkbookDependentFormula optg = (WorkbookDependentFormula) ptg;\r
-                               stack.push(optg.toFormulaString(book));\r
-                continue;\r
-            }\r
-            if (! (ptg instanceof OperationPtg)) {\r
-                stack.push(ptg.toFormulaString());\r
-                continue;\r
-            }\r
-\r
-            OperationPtg o = (OperationPtg) ptg;\r
-            String[] operands = getOperands(stack, o.getNumberOfOperands());\r
-            stack.push(o.toFormulaString(operands));\r
-        }\r
-        if(stack.isEmpty()) {\r
-            // inspection of the code above reveals that every stack.pop() is followed by a\r
-            // stack.push(). So this is either an internal error or impossible.\r
-            throw new IllegalStateException("Stack underflow");\r
-        }\r
-        String result = stack.pop();\r
-        if(!stack.isEmpty()) {\r
-            // Might be caused by some tokens like AttrPtg and Mem*Ptg, which really shouldn't\r
-            // put anything on the stack\r
-            throw new IllegalStateException("too much stuff left on the stack");\r
-        }\r
-        return result;\r
-    }\r
-\r
-    private static String[] getOperands(Stack<String> stack, int nOperands) {\r
-        String[] operands = new String[nOperands];\r
-\r
-        for (int j = nOperands-1; j >= 0; j--) { // reverse iteration because args were pushed in-order\r
-            if(stack.isEmpty()) {\r
-               String msg = "Too few arguments supplied to operation. Expected (" + nOperands\r
-                    + ") operands but got (" + (nOperands - j - 1) + ")";\r
-                throw new IllegalStateException(msg);\r
-            }\r
-            operands[j] = stack.pop();\r
-        }\r
-        return operands;\r
-    }\r
-}\r
+/* ====================================================================
+   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.ss.formula;
+
+import java.util.Stack;
+
+import org.apache.poi.hssf.record.formula.AttrPtg;
+import org.apache.poi.hssf.record.formula.MemAreaPtg;
+import org.apache.poi.hssf.record.formula.MemErrPtg;
+import org.apache.poi.hssf.record.formula.MemFuncPtg;
+import org.apache.poi.hssf.record.formula.OperationPtg;
+import org.apache.poi.hssf.record.formula.ParenthesisPtg;
+import org.apache.poi.hssf.record.formula.Ptg;
+
+/**
+ * Common logic for rendering formulas.<br/>
+ *
+ * For POI internal use only
+ *
+ * @author Josh Micich
+ */
+public class FormulaRenderer {
+
+    /**
+     * Static method to convert an array of {@link Ptg}s in RPN order
+     * to a human readable string format in infix mode.
+     * @param book  used for defined names and 3D references
+     * @param ptgs  must not be <code>null</code>
+     * @return a human readable String
+     */
+    public static String toFormulaString(FormulaRenderingWorkbook book, Ptg[] ptgs) {
+        if (ptgs == null || ptgs.length == 0) {
+            throw new IllegalArgumentException("ptgs must not be null");
+        }
+        Stack<String> stack = new Stack<String>();
+
+        for (int i=0 ; i < ptgs.length; i++) {
+            Ptg ptg = ptgs[i];
+            // TODO - what about MemNoMemPtg?
+            if(ptg instanceof MemAreaPtg || ptg instanceof MemFuncPtg || ptg instanceof MemErrPtg) {
+                // marks the start of a list of area expressions which will be naturally combined
+                // by their trailing operators (e.g. UnionPtg)
+                // TODO - put comment and throw exception in toFormulaString() of these classes
+                continue;
+            }
+            if (ptg instanceof ParenthesisPtg) {
+                String contents = stack.pop();
+                stack.push ("(" + contents + ")");
+                continue;
+            }
+            if (ptg instanceof AttrPtg) {
+                AttrPtg attrPtg = ((AttrPtg) ptg);
+                if (attrPtg.isOptimizedIf() || attrPtg.isOptimizedChoose() || attrPtg.isGoto()) {
+                    continue;
+                }
+                if (attrPtg.isSpace()) {
+                    // POI currently doesn't render spaces in formulas
+                    continue;
+                    // but if it ever did, care must be taken:
+                    // tAttrSpace comes *before* the operand it applies to, which may be consistent
+                    // with how the formula text appears but is against the RPN ordering assumed here
+                }
+                if (attrPtg.isSemiVolatile()) {
+                    // similar to tAttrSpace - RPN is violated
+                    continue;
+                }
+                if (attrPtg.isSum()) {
+                    String[] operands = getOperands(stack, attrPtg.getNumberOfOperands());
+                    stack.push(attrPtg.toFormulaString(operands));
+                    continue;
+                }
+                throw new RuntimeException("Unexpected tAttr: " + attrPtg.toString());
+            }
+
+            if (ptg instanceof WorkbookDependentFormula) {
+                WorkbookDependentFormula optg = (WorkbookDependentFormula) ptg;
+                stack.push(optg.toFormulaString(book));
+                continue;
+            }
+            if (! (ptg instanceof OperationPtg)) {
+                stack.push(ptg.toFormulaString());
+                continue;
+            }
+
+            OperationPtg o = (OperationPtg) ptg;
+            String[] operands = getOperands(stack, o.getNumberOfOperands());
+            stack.push(o.toFormulaString(operands));
+        }
+        if(stack.isEmpty()) {
+            // inspection of the code above reveals that every stack.pop() is followed by a
+            // stack.push(). So this is either an internal error or impossible.
+            throw new IllegalStateException("Stack underflow");
+        }
+        String result = stack.pop();
+        if(!stack.isEmpty()) {
+            // Might be caused by some tokens like AttrPtg and Mem*Ptg, which really shouldn't
+            // put anything on the stack
+            throw new IllegalStateException("too much stuff left on the stack");
+        }
+        return result;
+    }
+
+    private static String[] getOperands(Stack<String> stack, int nOperands) {
+        String[] operands = new String[nOperands];
+
+        for (int j = nOperands-1; j >= 0; j--) { // reverse iteration because args were pushed in-order
+            if(stack.isEmpty()) {
+               String msg = "Too few arguments supplied to operation. Expected (" + nOperands
+                    + ") operands but got (" + (nOperands - j - 1) + ")";
+                throw new IllegalStateException(msg);
+            }
+            operands[j] = stack.pop();
+        }
+        return operands;
+    }
+}
index c9b95f6b1c306ffd354a69da3f4a37c90089f779..b0dcb3851270f9060a93ffdc534802ba149f3d86 100644 (file)
@@ -1,40 +1,40 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula;\r
-\r
-import org.apache.poi.hssf.record.formula.NamePtg;\r
-import org.apache.poi.hssf.record.formula.NameXPtg;\r
-import org.apache.poi.ss.formula.EvaluationWorkbook.ExternalSheet;\r
-\r
-/**\r
- * Abstracts a workbook for the purpose of converting formula to text.<br/>\r
- * \r
- * For POI internal use only\r
- * \r
- * @author Josh Micich\r
- */\r
-public interface FormulaRenderingWorkbook {\r
-\r
-       /**\r
-        * @return <code>null</code> if externSheetIndex refers to a sheet inside the current workbook\r
-        */\r
-       ExternalSheet getExternalSheet(int externSheetIndex);\r
-       String getSheetNameByExternSheet(int externSheetIndex);\r
-       String resolveNameXText(NameXPtg nameXPtg);\r
-       String getNameText(NamePtg namePtg);\r
-}\r
+/* ====================================================================
+   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.ss.formula;
+
+import org.apache.poi.hssf.record.formula.NamePtg;
+import org.apache.poi.hssf.record.formula.NameXPtg;
+import org.apache.poi.ss.formula.EvaluationWorkbook.ExternalSheet;
+
+/**
+ * Abstracts a workbook for the purpose of converting formula to text.<br/>
+ *
+ * For POI internal use only
+ *
+ * @author Josh Micich
+ */
+public interface FormulaRenderingWorkbook {
+
+       /**
+        * @return <code>null</code> if externSheetIndex refers to a sheet inside the current workbook
+        */
+       ExternalSheet getExternalSheet(int externSheetIndex);
+       String getSheetNameByExternSheet(int externSheetIndex);
+       String resolveNameXText(NameXPtg nameXPtg);
+       String getNameText(NamePtg namePtg);
+}
index 3b47030d47e34c65a01e7647d45a168760827cc9..b77001990752101e7e312d5ce2dd456c657fb967 100644 (file)
@@ -1,40 +1,40 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula;\r
-\r
-/**\r
- * Enumeration of various formula types.<br/>\r
- * \r
- * For POI internal use only\r
- * \r
- * @author Josh Micich\r
- */\r
-public final class FormulaType {\r
-       private FormulaType() {\r
-               // no instances of this class\r
-       }\r
-    public static final int CELL = 0;\r
-    public static final int SHARED = 1;\r
-    public static final int ARRAY =2;\r
-    public static final int CONDFORMAT = 3;\r
-    public static final int NAMEDRANGE = 4;\r
-    // this constant is currently very specific.  The exact differences from general data\r
-    // validation formulas or conditional format formulas is not known yet\r
-    public static final int DATAVALIDATION_LIST = 5;\r
-\r
-}\r
+/* ====================================================================
+   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.ss.formula;
+
+/**
+ * Enumeration of various formula types.<br/>
+ *
+ * For POI internal use only
+ *
+ * @author Josh Micich
+ */
+public final class FormulaType {
+       private FormulaType() {
+               // no instances of this class
+       }
+       public static final int CELL = 0;
+       public static final int SHARED = 1;
+       public static final int ARRAY =2;
+       public static final int CONDFORMAT = 3;
+       public static final int NAMEDRANGE = 4;
+       // this constant is currently very specific.  The exact differences from general data
+       // validation formulas or conditional format formulas is not known yet
+       public static final int DATAVALIDATION_LIST = 5;
+
+}
index f25e86fc405e9b5279e5a6ab430737a6fecad3e7..69f0834f50e13469ebf74452538081f887cee890 100644 (file)
@@ -1,68 +1,68 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula;\r
-\r
-import org.apache.poi.hssf.record.formula.AreaI;\r
-import org.apache.poi.hssf.record.formula.Ref3DPtg;\r
-import org.apache.poi.hssf.record.formula.RefPtg;\r
-import org.apache.poi.hssf.record.formula.AreaI.OffsetArea;\r
-import org.apache.poi.hssf.record.formula.eval.AreaEval;\r
-import org.apache.poi.hssf.record.formula.eval.RefEvalBase;\r
-import org.apache.poi.hssf.record.formula.eval.ValueEval;\r
-import org.apache.poi.hssf.util.CellReference;\r
-\r
-/**\r
-*\r
-* @author Josh Micich \r
-*/\r
-final class LazyRefEval extends RefEvalBase {\r
-\r
-       private final SheetRefEvaluator _evaluator;\r
-\r
-       public LazyRefEval(RefPtg ptg, SheetRefEvaluator sre) {\r
-               super(ptg.getRow(), ptg.getColumn());\r
-               _evaluator = sre;\r
-       }\r
-       public LazyRefEval(Ref3DPtg ptg, SheetRefEvaluator sre) {\r
-               super(ptg.getRow(), ptg.getColumn());\r
-               _evaluator = sre;\r
-       }\r
-\r
-       public ValueEval getInnerValueEval() {\r
-               return _evaluator.getEvalForCell(getRow(), getColumn());\r
-       }\r
-       \r
-       public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) {\r
-               \r
-               AreaI area = new OffsetArea(getRow(), getColumn(),\r
-                               relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx);\r
-\r
-               return new LazyAreaEval(area, _evaluator);\r
-       }\r
-       \r
-       public String toString() {\r
-               CellReference cr = new CellReference(getRow(), getColumn());\r
-               StringBuffer sb = new StringBuffer();\r
-               sb.append(getClass().getName()).append("[");\r
-               sb.append(_evaluator.getSheetName());\r
-               sb.append('!');\r
-               sb.append(cr.formatAsString());\r
-               sb.append("]");\r
-               return sb.toString();\r
-       }\r
-}\r
+/* ====================================================================
+   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.ss.formula;
+
+import org.apache.poi.hssf.record.formula.AreaI;
+import org.apache.poi.hssf.record.formula.Ref3DPtg;
+import org.apache.poi.hssf.record.formula.RefPtg;
+import org.apache.poi.hssf.record.formula.AreaI.OffsetArea;
+import org.apache.poi.hssf.record.formula.eval.AreaEval;
+import org.apache.poi.hssf.record.formula.eval.RefEvalBase;
+import org.apache.poi.hssf.record.formula.eval.ValueEval;
+import org.apache.poi.hssf.util.CellReference;
+
+/**
+*
+* @author Josh Micich
+*/
+final class LazyRefEval extends RefEvalBase {
+
+       private final SheetRefEvaluator _evaluator;
+
+       public LazyRefEval(RefPtg ptg, SheetRefEvaluator sre) {
+               super(ptg.getRow(), ptg.getColumn());
+               _evaluator = sre;
+       }
+       public LazyRefEval(Ref3DPtg ptg, SheetRefEvaluator sre) {
+               super(ptg.getRow(), ptg.getColumn());
+               _evaluator = sre;
+       }
+
+       public ValueEval getInnerValueEval() {
+               return _evaluator.getEvalForCell(getRow(), getColumn());
+       }
+
+       public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) {
+
+               AreaI area = new OffsetArea(getRow(), getColumn(),
+                               relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx);
+
+               return new LazyAreaEval(area, _evaluator);
+       }
+
+       public String toString() {
+               CellReference cr = new CellReference(getRow(), getColumn());
+               StringBuffer sb = new StringBuffer();
+               sb.append(getClass().getName()).append("[");
+               sb.append(_evaluator.getSheetName());
+               sb.append('!');
+               sb.append(cr.formatAsString());
+               sb.append("]");
+               return sb.toString();
+       }
+}
index bf636a4da3e3f90e4c5ab0741a1d27f48447bae1..b2a6ed123db71eb0b8dd5959a56cd45511d8f285 100644 (file)
@@ -1,48 +1,48 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula;\r
-\r
-import org.apache.poi.hssf.record.formula.eval.ValueEval;\r
-/**\r
- * \r
- * \r
- * @author Josh Micich\r
- */\r
-final class SheetRefEvaluator {\r
-\r
-       private final WorkbookEvaluator _bookEvaluator;\r
-       private final EvaluationTracker _tracker;\r
-       private final EvaluationSheet _sheet;\r
-       private final int _sheetIndex;\r
-\r
-       public SheetRefEvaluator(WorkbookEvaluator bookEvaluator, EvaluationTracker tracker,\r
-                       EvaluationWorkbook _workbook, int sheetIndex) {\r
-               _bookEvaluator = bookEvaluator;\r
-               _tracker = tracker;\r
-               _sheet = _workbook.getSheet(sheetIndex);\r
-               _sheetIndex = sheetIndex;\r
-       }\r
-\r
-       public String getSheetName() {\r
-               return _bookEvaluator.getSheetName(_sheetIndex);\r
-       }\r
-\r
-       public ValueEval getEvalForCell(int rowIndex, int columnIndex) {\r
-               return _bookEvaluator.evaluateReference(_sheet, _sheetIndex, rowIndex, columnIndex, _tracker);\r
-       }\r
-}\r
+/* ====================================================================
+   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.ss.formula;
+
+import org.apache.poi.hssf.record.formula.eval.ValueEval;
+/**
+ *
+ *
+ * @author Josh Micich
+ */
+final class SheetRefEvaluator {
+
+       private final WorkbookEvaluator _bookEvaluator;
+       private final EvaluationTracker _tracker;
+       private final EvaluationSheet _sheet;
+       private final int _sheetIndex;
+
+       public SheetRefEvaluator(WorkbookEvaluator bookEvaluator, EvaluationTracker tracker,
+                       EvaluationWorkbook _workbook, int sheetIndex) {
+               _bookEvaluator = bookEvaluator;
+               _tracker = tracker;
+               _sheet = _workbook.getSheet(sheetIndex);
+               _sheetIndex = sheetIndex;
+       }
+
+       public String getSheetName() {
+               return _bookEvaluator.getSheetName(_sheetIndex);
+       }
+
+       public ValueEval getEvalForCell(int rowIndex, int columnIndex) {
+               return _bookEvaluator.evaluateReference(_sheet, _sheetIndex, rowIndex, columnIndex, _tracker);
+       }
+}
index 3dc2c525d518f07b5880d9db7134f4ac7048aad6..4beaaa3b08f49bf08ac44e4b9717cd7ea17a395b 100644 (file)
@@ -1,30 +1,30 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula;\r
-\r
-/**\r
- * Should be implemented by any {@link org.apache.poi.hssf.record.formula.Ptg} subclass that needs a workbook to render its formula.\r
- * <br/>\r
- * \r
- * For POI internal use only\r
- * \r
- * @author Josh Micich\r
- */\r
-public interface WorkbookDependentFormula {\r
-       String toFormulaString(FormulaRenderingWorkbook book);\r
-}\r
+/* ====================================================================
+   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.ss.formula;
+
+/**
+ * Should be implemented by any {@link org.apache.poi.hssf.record.formula.Ptg} subclass that needs a workbook to render its formula.
+ * <br/>
+ *
+ * For POI internal use only
+ *
+ * @author Josh Micich
+ */
+public interface WorkbookDependentFormula {
+       String toFormulaString(FormulaRenderingWorkbook book);
+}
index 84480758eca3b675b6cfc18649425b01ec96a5d9..cad7f885828bba149728898a757d68c0b17e1ae1 100644 (file)
@@ -1,36 +1,36 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula.eval;\r
-\r
-import org.apache.poi.ss.usermodel.FormulaEvaluator;\r
-\r
-/**\r
- * An exception thrown by implementors of {@link FormulaEvaluator} when attempting to evaluate\r
- * a formula which requires features that POI does not (yet) support.\r
- * \r
- * @author Josh Micich\r
- */\r
-public final class NotImplementedException extends RuntimeException {\r
-\r
-       public NotImplementedException(String message) {\r
-               super(message);\r
-       }\r
-       public NotImplementedException(String message, NotImplementedException cause) {\r
-               super(message, cause);\r
-       }\r
-}\r
+/* ====================================================================
+   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.ss.formula.eval;
+
+import org.apache.poi.ss.usermodel.FormulaEvaluator;
+
+/**
+ * An exception thrown by implementors of {@link FormulaEvaluator} when attempting to evaluate
+ * a formula which requires features that POI does not (yet) support.
+ *
+ * @author Josh Micich
+ */
+public final class NotImplementedException extends RuntimeException {
+
+       public NotImplementedException(String message) {
+               super(message);
+       }
+       public NotImplementedException(String message, NotImplementedException cause) {
+               super(message, cause);
+       }
+}
index 3563904b1a5bbd3138de3612beb1865a7c13c69b..73c6a7ddc66460b0abb508f04c812ee8caca9741 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula.eval.forked;\r
-\r
-import org.apache.poi.hssf.record.formula.eval.BlankEval;\r
-import org.apache.poi.hssf.record.formula.eval.BoolEval;\r
-import org.apache.poi.hssf.record.formula.eval.ErrorEval;\r
-import org.apache.poi.hssf.record.formula.eval.NumberEval;\r
-import org.apache.poi.hssf.record.formula.eval.StringEval;\r
-import org.apache.poi.hssf.record.formula.eval.ValueEval;\r
-import org.apache.poi.hssf.usermodel.HSSFCell;\r
-import org.apache.poi.ss.formula.EvaluationCell;\r
-import org.apache.poi.ss.formula.EvaluationSheet;\r
-import org.apache.poi.ss.usermodel.Cell;\r
-\r
-/**\r
- * Represents a cell being used for forked evaluation that has had a value set different from the\r
- * corresponding cell in the shared master workbook.\r
- *\r
- * @author Josh Micich\r
- */\r
-final class ForkedEvaluationCell implements EvaluationCell {\r
-\r
-       private final EvaluationSheet _sheet;\r
-       /** corresponding cell from master workbook */\r
-       private final EvaluationCell _masterCell;\r
-       private boolean _booleanValue;\r
-       private int _cellType;\r
-       private int _errorValue;\r
-       private double _numberValue;\r
-       private String _stringValue;\r
-\r
-       public ForkedEvaluationCell(ForkedEvaluationSheet sheet, EvaluationCell masterCell) {\r
-               _sheet = sheet;\r
-               _masterCell = masterCell;\r
-               // start with value blank, but expect construction to be immediately\r
-               setValue(BlankEval.INSTANCE); // followed by a proper call to setValue()\r
-       }\r
-\r
-       public Object getIdentityKey() {\r
-               return _masterCell.getIdentityKey();\r
-       }\r
-\r
-       public void setValue(ValueEval value) {\r
-               Class<? extends ValueEval> cls = value.getClass();\r
-\r
-               if (cls == NumberEval.class) {\r
-                       _cellType = HSSFCell.CELL_TYPE_NUMERIC;\r
-                       _numberValue = ((NumberEval)value).getNumberValue();\r
-                       return;\r
-               }\r
-               if (cls == StringEval.class) {\r
-                       _cellType = HSSFCell.CELL_TYPE_STRING;\r
-                       _stringValue = ((StringEval)value).getStringValue();\r
-                       return;\r
-               }\r
-               if (cls == BoolEval.class) {\r
-                       _cellType = HSSFCell.CELL_TYPE_BOOLEAN;\r
-                       _booleanValue = ((BoolEval)value).getBooleanValue();\r
-                       return;\r
-               }\r
-               if (cls == ErrorEval.class) {\r
-                       _cellType = HSSFCell.CELL_TYPE_ERROR;\r
-                       _errorValue = ((ErrorEval)value).getErrorCode();\r
-                       return;\r
-               }\r
-               if (cls == BlankEval.class) {\r
-                       _cellType = HSSFCell.CELL_TYPE_BLANK;\r
-                       return;\r
-               }\r
-               throw new IllegalArgumentException("Unexpected value class (" + cls.getName() + ")");\r
-       }\r
-       public void copyValue(Cell destCell) {\r
-               switch (_cellType) {\r
-                       case Cell.CELL_TYPE_BLANK:   destCell.setCellType(Cell.CELL_TYPE_BLANK);    return;\r
-                       case Cell.CELL_TYPE_NUMERIC: destCell.setCellValue(_numberValue);           return;\r
-                       case Cell.CELL_TYPE_BOOLEAN: destCell.setCellValue(_booleanValue);          return;\r
-                       case Cell.CELL_TYPE_STRING:  destCell.setCellValue(_stringValue);           return;\r
-                       case Cell.CELL_TYPE_ERROR:   destCell.setCellErrorValue((byte)_errorValue); return;\r
-               }\r
-               throw new IllegalStateException("Unexpected data type (" + _cellType + ")");\r
-       }\r
-\r
-       private void checkCellType(int expectedCellType) {\r
-               if (_cellType != expectedCellType) {\r
-                       throw new RuntimeException("Wrong data type (" + _cellType + ")");\r
-               }\r
-       }\r
-       public int getCellType() {\r
-               return _cellType;\r
-       }\r
-       public boolean getBooleanCellValue() {\r
-               checkCellType(HSSFCell.CELL_TYPE_BOOLEAN);\r
-               return _booleanValue;\r
-       }\r
-       public int getErrorCellValue() {\r
-               checkCellType(HSSFCell.CELL_TYPE_ERROR);\r
-               return _errorValue;\r
-       }\r
-       public double getNumericCellValue() {\r
-               checkCellType(HSSFCell.CELL_TYPE_NUMERIC);\r
-               return _numberValue;\r
-       }\r
-       public String getStringCellValue() {\r
-               checkCellType(HSSFCell.CELL_TYPE_STRING);\r
-               return _stringValue;\r
-       }\r
-       public EvaluationSheet getSheet() {\r
-               return _sheet;\r
-       }\r
-       public int getRowIndex() {\r
-               return _masterCell.getRowIndex();\r
-       }\r
-       public int getColumnIndex() {\r
-               return _masterCell.getColumnIndex();\r
-       }\r
-}\r
+/* ====================================================================
+   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.ss.formula.eval.forked;
+
+import org.apache.poi.hssf.record.formula.eval.BlankEval;
+import org.apache.poi.hssf.record.formula.eval.BoolEval;
+import org.apache.poi.hssf.record.formula.eval.ErrorEval;
+import org.apache.poi.hssf.record.formula.eval.NumberEval;
+import org.apache.poi.hssf.record.formula.eval.StringEval;
+import org.apache.poi.hssf.record.formula.eval.ValueEval;
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.ss.formula.EvaluationCell;
+import org.apache.poi.ss.formula.EvaluationSheet;
+import org.apache.poi.ss.usermodel.Cell;
+
+/**
+ * Represents a cell being used for forked evaluation that has had a value set different from the
+ * corresponding cell in the shared master workbook.
+ *
+ * @author Josh Micich
+ */
+final class ForkedEvaluationCell implements EvaluationCell {
+
+       private final EvaluationSheet _sheet;
+       /** corresponding cell from master workbook */
+       private final EvaluationCell _masterCell;
+       private boolean _booleanValue;
+       private int _cellType;
+       private int _errorValue;
+       private double _numberValue;
+       private String _stringValue;
+
+       public ForkedEvaluationCell(ForkedEvaluationSheet sheet, EvaluationCell masterCell) {
+               _sheet = sheet;
+               _masterCell = masterCell;
+               // start with value blank, but expect construction to be immediately
+               setValue(BlankEval.INSTANCE); // followed by a proper call to setValue()
+       }
+
+       public Object getIdentityKey() {
+               return _masterCell.getIdentityKey();
+       }
+
+       public void setValue(ValueEval value) {
+               Class<? extends ValueEval> cls = value.getClass();
+
+               if (cls == NumberEval.class) {
+                       _cellType = HSSFCell.CELL_TYPE_NUMERIC;
+                       _numberValue = ((NumberEval)value).getNumberValue();
+                       return;
+               }
+               if (cls == StringEval.class) {
+                       _cellType = HSSFCell.CELL_TYPE_STRING;
+                       _stringValue = ((StringEval)value).getStringValue();
+                       return;
+               }
+               if (cls == BoolEval.class) {
+                       _cellType = HSSFCell.CELL_TYPE_BOOLEAN;
+                       _booleanValue = ((BoolEval)value).getBooleanValue();
+                       return;
+               }
+               if (cls == ErrorEval.class) {
+                       _cellType = HSSFCell.CELL_TYPE_ERROR;
+                       _errorValue = ((ErrorEval)value).getErrorCode();
+                       return;
+               }
+               if (cls == BlankEval.class) {
+                       _cellType = HSSFCell.CELL_TYPE_BLANK;
+                       return;
+               }
+               throw new IllegalArgumentException("Unexpected value class (" + cls.getName() + ")");
+       }
+       public void copyValue(Cell destCell) {
+               switch (_cellType) {
+                       case Cell.CELL_TYPE_BLANK:   destCell.setCellType(Cell.CELL_TYPE_BLANK);    return;
+                       case Cell.CELL_TYPE_NUMERIC: destCell.setCellValue(_numberValue);           return;
+                       case Cell.CELL_TYPE_BOOLEAN: destCell.setCellValue(_booleanValue);          return;
+                       case Cell.CELL_TYPE_STRING:  destCell.setCellValue(_stringValue);           return;
+                       case Cell.CELL_TYPE_ERROR:   destCell.setCellErrorValue((byte)_errorValue); return;
+               }
+               throw new IllegalStateException("Unexpected data type (" + _cellType + ")");
+       }
+
+       private void checkCellType(int expectedCellType) {
+               if (_cellType != expectedCellType) {
+                       throw new RuntimeException("Wrong data type (" + _cellType + ")");
+               }
+       }
+       public int getCellType() {
+               return _cellType;
+       }
+       public boolean getBooleanCellValue() {
+               checkCellType(HSSFCell.CELL_TYPE_BOOLEAN);
+               return _booleanValue;
+       }
+       public int getErrorCellValue() {
+               checkCellType(HSSFCell.CELL_TYPE_ERROR);
+               return _errorValue;
+       }
+       public double getNumericCellValue() {
+               checkCellType(HSSFCell.CELL_TYPE_NUMERIC);
+               return _numberValue;
+       }
+       public String getStringCellValue() {
+               checkCellType(HSSFCell.CELL_TYPE_STRING);
+               return _stringValue;
+       }
+       public EvaluationSheet getSheet() {
+               return _sheet;
+       }
+       public int getRowIndex() {
+               return _masterCell.getRowIndex();
+       }
+       public int getColumnIndex() {
+               return _masterCell.getColumnIndex();
+       }
+}
index 837ba932e4afc0fc405adc0249d6d079990a4d0c..c36232a1d8585038da610027d3a169f8190bfad2 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula.eval.forked;\r
-\r
-import java.util.Arrays;\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-\r
-import org.apache.poi.ss.formula.EvaluationCell;\r
-import org.apache.poi.ss.formula.EvaluationSheet;\r
-import org.apache.poi.ss.formula.EvaluationWorkbook;\r
-import org.apache.poi.ss.usermodel.Cell;\r
-import org.apache.poi.ss.usermodel.Row;\r
-import org.apache.poi.ss.usermodel.Sheet;\r
-\r
-/**\r
- * Represents a sheet being used for forked evaluation.  Initially, objects of this class contain\r
- * only the cells from the master workbook. By calling {@link #getOrCreateUpdatableCell(int, int)},\r
- * the master cell object is logically replaced with a {@link ForkedEvaluationCell} instance, which\r
- * will be used in all subsequent evaluations.\r
- *\r
- * @author Josh Micich\r
- */\r
-final class ForkedEvaluationSheet implements EvaluationSheet {\r
-\r
-       private final EvaluationSheet _masterSheet;\r
-       /**\r
-        * Only cells which have been split are put in this map.  (This has been done to conserve memory).\r
-        */\r
-       private final Map<RowColKey, ForkedEvaluationCell> _sharedCellsByRowCol;\r
-\r
-       public ForkedEvaluationSheet(EvaluationSheet masterSheet) {\r
-               _masterSheet = masterSheet;\r
-               _sharedCellsByRowCol = new HashMap<RowColKey, ForkedEvaluationCell>();\r
-       }\r
-\r
-       public EvaluationCell getCell(int rowIndex, int columnIndex) {\r
-               RowColKey key = new RowColKey(rowIndex, columnIndex);\r
-\r
-               ForkedEvaluationCell result = _sharedCellsByRowCol.get(key);\r
-               if (result == null) {\r
-                       return _masterSheet.getCell(rowIndex, columnIndex);\r
-               }\r
-               return result;\r
-       }\r
-\r
-       public ForkedEvaluationCell getOrCreateUpdatableCell(int rowIndex, int columnIndex) {\r
-               RowColKey key = new RowColKey(rowIndex, columnIndex);\r
-\r
-               ForkedEvaluationCell result = _sharedCellsByRowCol.get(key);\r
-               if (result == null) {\r
-                       EvaluationCell mcell = _masterSheet.getCell(rowIndex, columnIndex);\r
-                       result = new ForkedEvaluationCell(this, mcell);\r
-                       _sharedCellsByRowCol.put(key, result);\r
-               }\r
-               return result;\r
-       }\r
-\r
-       public void copyUpdatedCells(Sheet sheet) {\r
-               RowColKey[] keys = new RowColKey[_sharedCellsByRowCol.size()];\r
-               _sharedCellsByRowCol.keySet().toArray(keys);\r
-               Arrays.sort(keys);\r
-               for (int i = 0; i < keys.length; i++) {\r
-                       RowColKey key = keys[i];\r
-                       Row row = sheet.getRow(key.getRowIndex());\r
-                       if (row == null) {\r
-                               row = sheet.createRow(key.getRowIndex());\r
-                       }\r
-                       Cell destCell = row.getCell(key.getColumnIndex());\r
-                       if (destCell == null) {\r
-                               destCell = row.createCell(key.getColumnIndex());\r
-                       }\r
-\r
-                       ForkedEvaluationCell srcCell = _sharedCellsByRowCol.get(key);\r
-                       srcCell.copyValue(destCell);\r
-               }\r
-       }\r
-\r
-       public int getSheetIndex(EvaluationWorkbook mewb) {\r
-               return mewb.getSheetIndex(_masterSheet);\r
-       }\r
-\r
-       private static final class RowColKey implements Comparable<RowColKey>{\r
-               private final int _rowIndex;\r
-               private final int _columnIndex;\r
-\r
-               public RowColKey(int rowIndex, int columnIndex) {\r
-                       _rowIndex = rowIndex;\r
-                       _columnIndex = columnIndex;\r
-               }\r
-               @Override\r
-               public boolean equals(Object obj) {\r
-                       RowColKey other = (RowColKey) obj;\r
-                       return _rowIndex == other._rowIndex && _columnIndex == other._columnIndex;\r
-               }\r
-               @Override\r
-               public int hashCode() {\r
-                       return _rowIndex ^ _columnIndex;\r
-               }\r
-               public int compareTo(RowColKey o) {\r
-                       int cmp = _rowIndex - o._rowIndex;\r
-                       if (cmp != 0) {\r
-                               return cmp;\r
-                       }\r
-                       return _columnIndex - o._columnIndex;\r
-               }\r
-               public int getRowIndex() {\r
-                       return _rowIndex;\r
-               }\r
-               public int getColumnIndex() {\r
-                       return _columnIndex;\r
-               }\r
-       }\r
-}\r
+/* ====================================================================
+   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.ss.formula.eval.forked;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.poi.ss.formula.EvaluationCell;
+import org.apache.poi.ss.formula.EvaluationSheet;
+import org.apache.poi.ss.formula.EvaluationWorkbook;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+
+/**
+ * Represents a sheet being used for forked evaluation.  Initially, objects of this class contain
+ * only the cells from the master workbook. By calling {@link #getOrCreateUpdatableCell(int, int)},
+ * the master cell object is logically replaced with a {@link ForkedEvaluationCell} instance, which
+ * will be used in all subsequent evaluations.
+ *
+ * @author Josh Micich
+ */
+final class ForkedEvaluationSheet implements EvaluationSheet {
+
+       private final EvaluationSheet _masterSheet;
+       /**
+        * Only cells which have been split are put in this map.  (This has been done to conserve memory).
+        */
+       private final Map<RowColKey, ForkedEvaluationCell> _sharedCellsByRowCol;
+
+       public ForkedEvaluationSheet(EvaluationSheet masterSheet) {
+               _masterSheet = masterSheet;
+               _sharedCellsByRowCol = new HashMap<RowColKey, ForkedEvaluationCell>();
+       }
+
+       public EvaluationCell getCell(int rowIndex, int columnIndex) {
+               RowColKey key = new RowColKey(rowIndex, columnIndex);
+
+               ForkedEvaluationCell result = _sharedCellsByRowCol.get(key);
+               if (result == null) {
+                       return _masterSheet.getCell(rowIndex, columnIndex);
+               }
+               return result;
+       }
+
+       public ForkedEvaluationCell getOrCreateUpdatableCell(int rowIndex, int columnIndex) {
+               RowColKey key = new RowColKey(rowIndex, columnIndex);
+
+               ForkedEvaluationCell result = _sharedCellsByRowCol.get(key);
+               if (result == null) {
+                       EvaluationCell mcell = _masterSheet.getCell(rowIndex, columnIndex);
+                       result = new ForkedEvaluationCell(this, mcell);
+                       _sharedCellsByRowCol.put(key, result);
+               }
+               return result;
+       }
+
+       public void copyUpdatedCells(Sheet sheet) {
+               RowColKey[] keys = new RowColKey[_sharedCellsByRowCol.size()];
+               _sharedCellsByRowCol.keySet().toArray(keys);
+               Arrays.sort(keys);
+               for (int i = 0; i < keys.length; i++) {
+                       RowColKey key = keys[i];
+                       Row row = sheet.getRow(key.getRowIndex());
+                       if (row == null) {
+                               row = sheet.createRow(key.getRowIndex());
+                       }
+                       Cell destCell = row.getCell(key.getColumnIndex());
+                       if (destCell == null) {
+                               destCell = row.createCell(key.getColumnIndex());
+                       }
+
+                       ForkedEvaluationCell srcCell = _sharedCellsByRowCol.get(key);
+                       srcCell.copyValue(destCell);
+               }
+       }
+
+       public int getSheetIndex(EvaluationWorkbook mewb) {
+               return mewb.getSheetIndex(_masterSheet);
+       }
+
+       private static final class RowColKey implements Comparable<RowColKey>{
+               private final int _rowIndex;
+               private final int _columnIndex;
+
+               public RowColKey(int rowIndex, int columnIndex) {
+                       _rowIndex = rowIndex;
+                       _columnIndex = columnIndex;
+               }
+               @Override
+               public boolean equals(Object obj) {
+                       RowColKey other = (RowColKey) obj;
+                       return _rowIndex == other._rowIndex && _columnIndex == other._columnIndex;
+               }
+               @Override
+               public int hashCode() {
+                       return _rowIndex ^ _columnIndex;
+               }
+               public int compareTo(RowColKey o) {
+                       int cmp = _rowIndex - o._rowIndex;
+                       if (cmp != 0) {
+                               return cmp;
+                       }
+                       return _columnIndex - o._columnIndex;
+               }
+               public int getRowIndex() {
+                       return _rowIndex;
+               }
+               public int getColumnIndex() {
+                       return _columnIndex;
+               }
+       }
+}
index d7e158f6ff17c5c64bf984ec00de92a50c488c74..08c7841197c3ef948e369746af298816d73dfab8 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula.eval.forked;\r
-\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-\r
-import org.apache.poi.hssf.record.formula.NamePtg;\r
-import org.apache.poi.hssf.record.formula.NameXPtg;\r
-import org.apache.poi.hssf.record.formula.Ptg;\r
-import org.apache.poi.ss.formula.EvaluationCell;\r
-import org.apache.poi.ss.formula.EvaluationName;\r
-import org.apache.poi.ss.formula.EvaluationSheet;\r
-import org.apache.poi.ss.formula.EvaluationWorkbook;\r
-import org.apache.poi.ss.usermodel.Workbook;\r
-\r
-/**\r
- * Represents a workbook being used for forked evaluation. Most operations are delegated to the\r
- * shared master workbook, except those that potentially involve cell values that may have been \r
- * updated after a call to {@link #getOrCreateUpdatableCell(String, int, int)}.\r
- *\r
- * @author Josh Micich\r
- */\r
-final class ForkedEvaluationWorkbook implements EvaluationWorkbook {\r
-\r
-       private final EvaluationWorkbook _masterBook;\r
-       private final Map<String, ForkedEvaluationSheet> _sharedSheetsByName;\r
-\r
-       public ForkedEvaluationWorkbook(EvaluationWorkbook master) {\r
-               _masterBook = master;\r
-               _sharedSheetsByName = new HashMap<String, ForkedEvaluationSheet>();\r
-       }\r
-\r
-       public ForkedEvaluationCell getOrCreateUpdatableCell(String sheetName, int rowIndex,\r
-                       int columnIndex) {\r
-               ForkedEvaluationSheet sheet = getSharedSheet(sheetName);\r
-               return sheet.getOrCreateUpdatableCell(rowIndex, columnIndex);\r
-       }\r
-\r
-       public EvaluationCell getEvaluationCell(String sheetName, int rowIndex, int columnIndex) {\r
-               ForkedEvaluationSheet sheet = getSharedSheet(sheetName);\r
-               return sheet.getCell(rowIndex, columnIndex);\r
-       }\r
-\r
-       private ForkedEvaluationSheet getSharedSheet(String sheetName) {\r
-               ForkedEvaluationSheet result = _sharedSheetsByName.get(sheetName);\r
-               if (result == null) {\r
-                       result = new ForkedEvaluationSheet(_masterBook.getSheet(_masterBook\r
-                                       .getSheetIndex(sheetName)));\r
-                       _sharedSheetsByName.put(sheetName, result);\r
-               }\r
-               return result;\r
-       }\r
-\r
-       public void copyUpdatedCells(Workbook workbook) {\r
-               String[] sheetNames = new String[_sharedSheetsByName.size()];\r
-               _sharedSheetsByName.keySet().toArray(sheetNames);\r
-               OrderedSheet[] oss = new OrderedSheet[sheetNames.length];\r
-               for (int i = 0; i < sheetNames.length; i++) {\r
-                       String sheetName = sheetNames[i];\r
-                       oss[i] = new OrderedSheet(sheetName, _masterBook.getSheetIndex(sheetName));\r
-               }\r
-               for (int i = 0; i < oss.length; i++) {\r
-                       String sheetName = oss[i].getSheetName();\r
-                       ForkedEvaluationSheet sheet = _sharedSheetsByName.get(sheetName);\r
-                       sheet.copyUpdatedCells(workbook.getSheet(sheetName));\r
-               }\r
-       }\r
-\r
-       public int convertFromExternSheetIndex(int externSheetIndex) {\r
-               return _masterBook.convertFromExternSheetIndex(externSheetIndex);\r
-       }\r
-\r
-       public ExternalSheet getExternalSheet(int externSheetIndex) {\r
-               return _masterBook.getExternalSheet(externSheetIndex);\r
-       }\r
-\r
-       public Ptg[] getFormulaTokens(EvaluationCell cell) {\r
-               if (cell instanceof ForkedEvaluationCell) {\r
-                   // doesn't happen yet because formulas cannot be modified from the master workbook\r
-                   throw new RuntimeException("Updated formulas not supported yet");\r
-               }\r
-               return _masterBook.getFormulaTokens(cell);\r
-       }\r
-\r
-       public EvaluationName getName(NamePtg namePtg) {\r
-               return _masterBook.getName(namePtg);\r
-       }\r
-\r
-       public EvaluationSheet getSheet(int sheetIndex) {\r
-               return getSharedSheet(getSheetName(sheetIndex));\r
-       }\r
-\r
-       public int getSheetIndex(EvaluationSheet sheet) {\r
-               if (sheet instanceof ForkedEvaluationSheet) {\r
-                       ForkedEvaluationSheet mes = (ForkedEvaluationSheet) sheet;\r
-                       return mes.getSheetIndex(_masterBook);\r
-               }\r
-               return _masterBook.getSheetIndex(sheet);\r
-       }\r
-\r
-       public int getSheetIndex(String sheetName) {\r
-               return _masterBook.getSheetIndex(sheetName);\r
-       }\r
-\r
-       public String getSheetName(int sheetIndex) {\r
-               return _masterBook.getSheetName(sheetIndex);\r
-       }\r
-\r
-       public String resolveNameXText(NameXPtg ptg) {\r
-               return _masterBook.resolveNameXText(ptg);\r
-       }\r
-\r
-       private static final class OrderedSheet implements Comparable<OrderedSheet> {\r
-               private final String _sheetName;\r
-               private final int _index;\r
-\r
-               public OrderedSheet(String sheetName, int index) {\r
-                       _sheetName = sheetName;\r
-                       _index = index;\r
-               }\r
-               public String getSheetName() {\r
-                       return _sheetName;\r
-               }\r
-               public int compareTo(OrderedSheet o) {\r
-                       return _index - o._index;\r
-               }\r
-       }\r
-}\r
+/* ====================================================================
+   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.ss.formula.eval.forked;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.poi.hssf.record.formula.NamePtg;
+import org.apache.poi.hssf.record.formula.NameXPtg;
+import org.apache.poi.hssf.record.formula.Ptg;
+import org.apache.poi.ss.formula.EvaluationCell;
+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.usermodel.Workbook;
+
+/**
+ * Represents a workbook being used for forked evaluation. Most operations are delegated to the
+ * shared master workbook, except those that potentially involve cell values that may have been
+ * updated after a call to {@link #getOrCreateUpdatableCell(String, int, int)}.
+ *
+ * @author Josh Micich
+ */
+final class ForkedEvaluationWorkbook implements EvaluationWorkbook {
+
+       private final EvaluationWorkbook _masterBook;
+       private final Map<String, ForkedEvaluationSheet> _sharedSheetsByName;
+
+       public ForkedEvaluationWorkbook(EvaluationWorkbook master) {
+               _masterBook = master;
+               _sharedSheetsByName = new HashMap<String, ForkedEvaluationSheet>();
+       }
+
+       public ForkedEvaluationCell getOrCreateUpdatableCell(String sheetName, int rowIndex,
+                       int columnIndex) {
+               ForkedEvaluationSheet sheet = getSharedSheet(sheetName);
+               return sheet.getOrCreateUpdatableCell(rowIndex, columnIndex);
+       }
+
+       public EvaluationCell getEvaluationCell(String sheetName, int rowIndex, int columnIndex) {
+               ForkedEvaluationSheet sheet = getSharedSheet(sheetName);
+               return sheet.getCell(rowIndex, columnIndex);
+       }
+
+       private ForkedEvaluationSheet getSharedSheet(String sheetName) {
+               ForkedEvaluationSheet result = _sharedSheetsByName.get(sheetName);
+               if (result == null) {
+                       result = new ForkedEvaluationSheet(_masterBook.getSheet(_masterBook
+                                       .getSheetIndex(sheetName)));
+                       _sharedSheetsByName.put(sheetName, result);
+               }
+               return result;
+       }
+
+       public void copyUpdatedCells(Workbook workbook) {
+               String[] sheetNames = new String[_sharedSheetsByName.size()];
+               _sharedSheetsByName.keySet().toArray(sheetNames);
+               OrderedSheet[] oss = new OrderedSheet[sheetNames.length];
+               for (int i = 0; i < sheetNames.length; i++) {
+                       String sheetName = sheetNames[i];
+                       oss[i] = new OrderedSheet(sheetName, _masterBook.getSheetIndex(sheetName));
+               }
+               for (int i = 0; i < oss.length; i++) {
+                       String sheetName = oss[i].getSheetName();
+                       ForkedEvaluationSheet sheet = _sharedSheetsByName.get(sheetName);
+                       sheet.copyUpdatedCells(workbook.getSheet(sheetName));
+               }
+       }
+
+       public int convertFromExternSheetIndex(int externSheetIndex) {
+               return _masterBook.convertFromExternSheetIndex(externSheetIndex);
+       }
+
+       public ExternalSheet getExternalSheet(int externSheetIndex) {
+               return _masterBook.getExternalSheet(externSheetIndex);
+       }
+
+       public Ptg[] getFormulaTokens(EvaluationCell cell) {
+               if (cell instanceof ForkedEvaluationCell) {
+                       // doesn't happen yet because formulas cannot be modified from the master workbook
+                       throw new RuntimeException("Updated formulas not supported yet");
+               }
+               return _masterBook.getFormulaTokens(cell);
+       }
+
+       public EvaluationName getName(NamePtg namePtg) {
+               return _masterBook.getName(namePtg);
+       }
+
+       public EvaluationSheet getSheet(int sheetIndex) {
+               return getSharedSheet(getSheetName(sheetIndex));
+       }
+
+       public int getSheetIndex(EvaluationSheet sheet) {
+               if (sheet instanceof ForkedEvaluationSheet) {
+                       ForkedEvaluationSheet mes = (ForkedEvaluationSheet) sheet;
+                       return mes.getSheetIndex(_masterBook);
+               }
+               return _masterBook.getSheetIndex(sheet);
+       }
+
+       public int getSheetIndex(String sheetName) {
+               return _masterBook.getSheetIndex(sheetName);
+       }
+
+       public String getSheetName(int sheetIndex) {
+               return _masterBook.getSheetName(sheetIndex);
+       }
+
+       public String resolveNameXText(NameXPtg ptg) {
+               return _masterBook.resolveNameXText(ptg);
+       }
+
+       private static final class OrderedSheet implements Comparable<OrderedSheet> {
+               private final String _sheetName;
+               private final int _index;
+
+               public OrderedSheet(String sheetName, int index) {
+                       _sheetName = sheetName;
+                       _index = index;
+               }
+               public String getSheetName() {
+                       return _sheetName;
+               }
+               public int compareTo(OrderedSheet o) {
+                       return _index - o._index;
+               }
+       }
+}
index 6a1e1b1505597b86a0d82c0e0c1c7043e01e12f4..e89d2a6104500dc4ec38a9a737817a4890e945ab 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.formula.eval.forked;\r
-\r
-import org.apache.poi.hssf.record.formula.eval.BoolEval;\r
-import org.apache.poi.hssf.record.formula.eval.ErrorEval;\r
-import org.apache.poi.hssf.record.formula.eval.NumberEval;\r
-import org.apache.poi.hssf.record.formula.eval.StringEval;\r
-import org.apache.poi.hssf.record.formula.eval.ValueEval;\r
-import org.apache.poi.hssf.usermodel.HSSFCell;\r
-import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;\r
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
-import org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment;\r
-import org.apache.poi.ss.formula.EvaluationCell;\r
-import org.apache.poi.ss.formula.EvaluationWorkbook;\r
-import org.apache.poi.ss.formula.IStabilityClassifier;\r
-import org.apache.poi.ss.formula.WorkbookEvaluator;\r
-import org.apache.poi.ss.usermodel.Workbook;\r
-\r
-/**\r
- * An alternative workbook evaluator that saves memory in situations where a single workbook is\r
- * concurrently and independently evaluated many times.  With standard formula evaluation, around \r
- * 90% of memory consumption is due to loading of the {@link HSSFWorkbook} or {@link org.apache.poi.xssf.usermodel.XSSFWorkbook}.\r
- * This class enables a 'master workbook' to be loaded just once and shared between many evaluation\r
- * clients.  Each evaluation client creates its own {@link ForkedEvaluator} and can set cell values\r
- * that will be used for local evaluations (and don't disturb evaluations on other evaluators).\r
- *\r
- * @author Josh Micich\r
- */\r
-public final class ForkedEvaluator {\r
-\r
-       private WorkbookEvaluator _evaluator;\r
-       private ForkedEvaluationWorkbook _sewb;\r
-\r
-       private ForkedEvaluator(EvaluationWorkbook masterWorkbook, IStabilityClassifier stabilityClassifier) {\r
-               _sewb = new ForkedEvaluationWorkbook(masterWorkbook);\r
-               _evaluator = new WorkbookEvaluator(_sewb, stabilityClassifier);\r
-       }\r
-       private static EvaluationWorkbook createEvaluationWorkbook(Workbook wb) {\r
-               if (wb instanceof HSSFWorkbook) {\r
-                       return HSSFEvaluationWorkbook.create((HSSFWorkbook) wb);\r
-               }\r
-// TODO rearrange POI build to allow this\r
-//             if (wb instanceof XSSFWorkbook) {\r
-//                     return XSSFEvaluationWorkbook.create((XSSFWorkbook) wb);\r
-//             }\r
-               throw new IllegalArgumentException("Unexpected workbook type (" + wb.getClass().getName() + ")");\r
-       }\r
-       public static ForkedEvaluator create(Workbook wb, IStabilityClassifier stabilityClassifier) {\r
-               return new ForkedEvaluator(createEvaluationWorkbook(wb), stabilityClassifier);\r
-       }\r
-\r
-       /**\r
-        * Sets the specified cell to the supplied <tt>value</tt>\r
-        * @param sheetName the name of the sheet containing the cell\r
-        * @param rowIndex zero based\r
-        * @param columnIndex zero based\r
-        */\r
-       public void updateCell(String sheetName, int rowIndex, int columnIndex, ValueEval value) {\r
-\r
-               ForkedEvaluationCell cell = _sewb.getOrCreateUpdatableCell(sheetName, rowIndex, columnIndex);\r
-               cell.setValue(value);\r
-               _evaluator.notifyUpdateCell(cell);\r
-       }\r
-       /**\r
-        * Copies the values of all updated cells (modified by calls to {@link \r
-        * #updateCell(String, int, int, ValueEval)}) to the supplied <tt>workbook</tt>.<br/>\r
-        * Typically, the supplied <tt>workbook</tt> is a writable copy of the 'master workbook', \r
-        * but at the very least it must contain sheets with the same names. \r
-        */\r
-       public void copyUpdatedCells(Workbook workbook) {\r
-               _sewb.copyUpdatedCells(workbook);\r
-       }\r
-\r
-       /**\r
-        * If cell contains a formula, the formula is evaluated and returned,\r
-        * else the CellValue simply copies the appropriate cell value from\r
-        * the cell and also its cell type. This method should be preferred over\r
-        * evaluateInCell() when the call should not modify the contents of the\r
-        * original cell.\r
-        *\r
-        * @param cell may be <code>null</code> signifying that the cell is not present (or blank)\r
-        * @return <code>null</code> if the supplied cell is <code>null</code> or blank\r
-        */\r
-       public ValueEval evaluate(String sheetName, int rowIndex, int columnIndex) {\r
-               EvaluationCell cell = _sewb.getEvaluationCell(sheetName, rowIndex, columnIndex);\r
-\r
-               switch (cell.getCellType()) {\r
-                       case HSSFCell.CELL_TYPE_BOOLEAN:\r
-                               return BoolEval.valueOf(cell.getBooleanCellValue());\r
-                       case HSSFCell.CELL_TYPE_ERROR:\r
-                               return ErrorEval.valueOf(cell.getErrorCellValue());\r
-                       case HSSFCell.CELL_TYPE_FORMULA:\r
-                               return _evaluator.evaluate(cell);\r
-                       case HSSFCell.CELL_TYPE_NUMERIC:\r
-                               return new NumberEval(cell.getNumericCellValue());\r
-                       case HSSFCell.CELL_TYPE_STRING:\r
-                               return new StringEval(cell.getStringCellValue());\r
-                       case HSSFCell.CELL_TYPE_BLANK:\r
-                               return null;\r
-               }\r
-               throw new IllegalStateException("Bad cell type (" + cell.getCellType() + ")");\r
-       }\r
-       /**\r
-        * Coordinates several formula evaluators together so that formulas that involve external\r
-        * references can be evaluated.\r
-        * @param workbookNames the simple file names used to identify the workbooks in formulas\r
-        * with external links (for example "MyData.xls" as used in a formula "[MyData.xls]Sheet1!A1")\r
-        * @param evaluators all evaluators for the full set of workbooks required by the formulas.\r
-        */\r
-       public static void setupEnvironment(String[] workbookNames, ForkedEvaluator[] evaluators) {\r
-               WorkbookEvaluator[] wbEvals = new WorkbookEvaluator[evaluators.length];\r
-               for (int i = 0; i < wbEvals.length; i++) {\r
-                       wbEvals[i] = evaluators[i]._evaluator;\r
-               }\r
-               CollaboratingWorkbooksEnvironment.setup(workbookNames, wbEvals);\r
-       }\r
-}\r
+/* ====================================================================
+   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.ss.formula.eval.forked;
+
+import org.apache.poi.hssf.record.formula.eval.BoolEval;
+import org.apache.poi.hssf.record.formula.eval.ErrorEval;
+import org.apache.poi.hssf.record.formula.eval.NumberEval;
+import org.apache.poi.hssf.record.formula.eval.StringEval;
+import org.apache.poi.hssf.record.formula.eval.ValueEval;
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment;
+import org.apache.poi.ss.formula.EvaluationCell;
+import org.apache.poi.ss.formula.EvaluationWorkbook;
+import org.apache.poi.ss.formula.IStabilityClassifier;
+import org.apache.poi.ss.formula.WorkbookEvaluator;
+import org.apache.poi.ss.usermodel.Workbook;
+
+/**
+ * An alternative workbook evaluator that saves memory in situations where a single workbook is
+ * concurrently and independently evaluated many times.  With standard formula evaluation, around
+ * 90% of memory consumption is due to loading of the {@link HSSFWorkbook} or {@link org.apache.poi.xssf.usermodel.XSSFWorkbook}.
+ * This class enables a 'master workbook' to be loaded just once and shared between many evaluation
+ * clients.  Each evaluation client creates its own {@link ForkedEvaluator} and can set cell values
+ * that will be used for local evaluations (and don't disturb evaluations on other evaluators).
+ *
+ * @author Josh Micich
+ */
+public final class ForkedEvaluator {
+
+       private WorkbookEvaluator _evaluator;
+       private ForkedEvaluationWorkbook _sewb;
+
+       private ForkedEvaluator(EvaluationWorkbook masterWorkbook, IStabilityClassifier stabilityClassifier) {
+               _sewb = new ForkedEvaluationWorkbook(masterWorkbook);
+               _evaluator = new WorkbookEvaluator(_sewb, stabilityClassifier);
+       }
+       private static EvaluationWorkbook createEvaluationWorkbook(Workbook wb) {
+               if (wb instanceof HSSFWorkbook) {
+                       return HSSFEvaluationWorkbook.create((HSSFWorkbook) wb);
+               }
+// TODO rearrange POI build to allow this
+//             if (wb instanceof XSSFWorkbook) {
+//                     return XSSFEvaluationWorkbook.create((XSSFWorkbook) wb);
+//             }
+               throw new IllegalArgumentException("Unexpected workbook type (" + wb.getClass().getName() + ")");
+       }
+       public static ForkedEvaluator create(Workbook wb, IStabilityClassifier stabilityClassifier) {
+               return new ForkedEvaluator(createEvaluationWorkbook(wb), stabilityClassifier);
+       }
+
+       /**
+        * Sets the specified cell to the supplied <tt>value</tt>
+        * @param sheetName the name of the sheet containing the cell
+        * @param rowIndex zero based
+        * @param columnIndex zero based
+        */
+       public void updateCell(String sheetName, int rowIndex, int columnIndex, ValueEval value) {
+
+               ForkedEvaluationCell cell = _sewb.getOrCreateUpdatableCell(sheetName, rowIndex, columnIndex);
+               cell.setValue(value);
+               _evaluator.notifyUpdateCell(cell);
+       }
+       /**
+        * Copies the values of all updated cells (modified by calls to {@link
+        * #updateCell(String, int, int, ValueEval)}) to the supplied <tt>workbook</tt>.<br/>
+        * Typically, the supplied <tt>workbook</tt> is a writable copy of the 'master workbook',
+        * but at the very least it must contain sheets with the same names.
+        */
+       public void copyUpdatedCells(Workbook workbook) {
+               _sewb.copyUpdatedCells(workbook);
+       }
+
+       /**
+        * If cell contains a formula, the formula is evaluated and returned,
+        * else the CellValue simply copies the appropriate cell value from
+        * the cell and also its cell type. This method should be preferred over
+        * evaluateInCell() when the call should not modify the contents of the
+        * original cell.
+        *
+        * @param cell may be <code>null</code> signifying that the cell is not present (or blank)
+        * @return <code>null</code> if the supplied cell is <code>null</code> or blank
+        */
+       public ValueEval evaluate(String sheetName, int rowIndex, int columnIndex) {
+               EvaluationCell cell = _sewb.getEvaluationCell(sheetName, rowIndex, columnIndex);
+
+               switch (cell.getCellType()) {
+                       case HSSFCell.CELL_TYPE_BOOLEAN:
+                               return BoolEval.valueOf(cell.getBooleanCellValue());
+                       case HSSFCell.CELL_TYPE_ERROR:
+                               return ErrorEval.valueOf(cell.getErrorCellValue());
+                       case HSSFCell.CELL_TYPE_FORMULA:
+                               return _evaluator.evaluate(cell);
+                       case HSSFCell.CELL_TYPE_NUMERIC:
+                               return new NumberEval(cell.getNumericCellValue());
+                       case HSSFCell.CELL_TYPE_STRING:
+                               return new StringEval(cell.getStringCellValue());
+                       case HSSFCell.CELL_TYPE_BLANK:
+                               return null;
+               }
+               throw new IllegalStateException("Bad cell type (" + cell.getCellType() + ")");
+       }
+       /**
+        * Coordinates several formula evaluators together so that formulas that involve external
+        * references can be evaluated.
+        * @param workbookNames the simple file names used to identify the workbooks in formulas
+        * with external links (for example "MyData.xls" as used in a formula "[MyData.xls]Sheet1!A1")
+        * @param evaluators all evaluators for the full set of workbooks required by the formulas.
+        */
+       public static void setupEnvironment(String[] workbookNames, ForkedEvaluator[] evaluators) {
+               WorkbookEvaluator[] wbEvals = new WorkbookEvaluator[evaluators.length];
+               for (int i = 0; i < wbEvals.length; i++) {
+                       wbEvals[i] = evaluators[i]._evaluator;
+               }
+               CollaboratingWorkbooksEnvironment.setup(workbookNames, wbEvals);
+       }
+}
index 705f55710105856799d95c8c943e78f8320050fd..664f100562e2d5ba2a7caf81b58b5b9a023ebb2d 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.usermodel;\r
-\r
-import org.apache.poi.hssf.record.formula.eval.ErrorEval;\r
-import org.apache.poi.ss.usermodel.Cell;\r
-\r
-/**\r
- * Mimics the 'data view' of a cell. This allows formula evaluator\r
- * to return a CellValue instead of precasting the value to String\r
- * or Number or boolean type.\r
- * @author Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt;\r
- */\r
-public final class CellValue {\r
-       public static final CellValue TRUE = new CellValue(Cell.CELL_TYPE_BOOLEAN, 0.0, true,  null, 0);\r
-       public static final CellValue FALSE= new CellValue(Cell.CELL_TYPE_BOOLEAN, 0.0, false, null, 0);\r
-\r
-       private final int _cellType;\r
-       private final double _numberValue;\r
-       private final boolean _booleanValue;\r
-       private final String _textValue;\r
-       private final int _errorCode;\r
-\r
-       private CellValue(int cellType, double numberValue, boolean booleanValue,\r
-                       String textValue, int errorCode) {\r
-               _cellType = cellType;\r
-               _numberValue = numberValue;\r
-               _booleanValue = booleanValue;\r
-               _textValue = textValue;\r
-               _errorCode = errorCode;\r
-       }\r
-\r
-\r
-       public CellValue(double numberValue) {\r
-               this(Cell.CELL_TYPE_NUMERIC, numberValue, false, null, 0);\r
-       }\r
-       public static CellValue valueOf(boolean booleanValue) {\r
-               return booleanValue ? TRUE : FALSE;\r
-       }\r
-       public CellValue(String stringValue) {\r
-               this(Cell.CELL_TYPE_STRING, 0.0, false, stringValue, 0);\r
-       }\r
-       public static CellValue getError(int errorCode) {\r
-               return new CellValue(Cell.CELL_TYPE_ERROR, 0.0, false, null, errorCode);\r
-       }\r
-\r
-\r
-       /**\r
-        * @return Returns the booleanValue.\r
-        */\r
-       public boolean getBooleanValue() {\r
-               return _booleanValue;\r
-       }\r
-       /**\r
-        * @return Returns the numberValue.\r
-        */\r
-       public double getNumberValue() {\r
-               return _numberValue;\r
-       }\r
-       /**\r
-        * @return Returns the stringValue.\r
-        */\r
-       public String getStringValue() {\r
-               return _textValue;\r
-       }\r
-       /**\r
-        * @return Returns the cellType.\r
-        */\r
-       public int getCellType() {\r
-               return _cellType;\r
-       }\r
-       /**\r
-        * @return Returns the errorValue.\r
-        */\r
-       public byte getErrorValue() {\r
-               return (byte) _errorCode;\r
-       }\r
-       public String toString() {\r
-               StringBuffer sb = new StringBuffer(64);\r
-               sb.append(getClass().getName()).append(" [");\r
-               sb.append(formatAsString());\r
-               sb.append("]");\r
-               return sb.toString();\r
-       }\r
-\r
-       public String formatAsString() {\r
-               switch (_cellType) {\r
-                       case Cell.CELL_TYPE_NUMERIC:\r
-                               return String.valueOf(_numberValue);\r
-                       case Cell.CELL_TYPE_STRING:\r
-                               return '"' + _textValue + '"';\r
-                       case Cell.CELL_TYPE_BOOLEAN:\r
-                               return _booleanValue ? "TRUE" : "FALSE";\r
-                       case Cell.CELL_TYPE_ERROR:\r
-                               return ErrorEval.getText(_errorCode);\r
-               }\r
-               return "<error unexpected cell type " + _cellType + ">";\r
-       }\r
-}\r
+/* ====================================================================
+   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.ss.usermodel;
+
+import org.apache.poi.hssf.record.formula.eval.ErrorEval;
+import org.apache.poi.ss.usermodel.Cell;
+
+/**
+ * Mimics the 'data view' of a cell. This allows formula evaluator
+ * to return a CellValue instead of precasting the value to String
+ * or Number or boolean type.
+ * @author Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt;
+ */
+public final class CellValue {
+       public static final CellValue TRUE = new CellValue(Cell.CELL_TYPE_BOOLEAN, 0.0, true,  null, 0);
+       public static final CellValue FALSE= new CellValue(Cell.CELL_TYPE_BOOLEAN, 0.0, false, null, 0);
+
+       private final int _cellType;
+       private final double _numberValue;
+       private final boolean _booleanValue;
+       private final String _textValue;
+       private final int _errorCode;
+
+       private CellValue(int cellType, double numberValue, boolean booleanValue,
+                       String textValue, int errorCode) {
+               _cellType = cellType;
+               _numberValue = numberValue;
+               _booleanValue = booleanValue;
+               _textValue = textValue;
+               _errorCode = errorCode;
+       }
+
+
+       public CellValue(double numberValue) {
+               this(Cell.CELL_TYPE_NUMERIC, numberValue, false, null, 0);
+       }
+       public static CellValue valueOf(boolean booleanValue) {
+               return booleanValue ? TRUE : FALSE;
+       }
+       public CellValue(String stringValue) {
+               this(Cell.CELL_TYPE_STRING, 0.0, false, stringValue, 0);
+       }
+       public static CellValue getError(int errorCode) {
+               return new CellValue(Cell.CELL_TYPE_ERROR, 0.0, false, null, errorCode);
+       }
+
+
+       /**
+        * @return Returns the booleanValue.
+        */
+       public boolean getBooleanValue() {
+               return _booleanValue;
+       }
+       /**
+        * @return Returns the numberValue.
+        */
+       public double getNumberValue() {
+               return _numberValue;
+       }
+       /**
+        * @return Returns the stringValue.
+        */
+       public String getStringValue() {
+               return _textValue;
+       }
+       /**
+        * @return Returns the cellType.
+        */
+       public int getCellType() {
+               return _cellType;
+       }
+       /**
+        * @return Returns the errorValue.
+        */
+       public byte getErrorValue() {
+               return (byte) _errorCode;
+       }
+       public String toString() {
+               StringBuffer sb = new StringBuffer(64);
+               sb.append(getClass().getName()).append(" [");
+               sb.append(formatAsString());
+               sb.append("]");
+               return sb.toString();
+       }
+
+       public String formatAsString() {
+               switch (_cellType) {
+                       case Cell.CELL_TYPE_NUMERIC:
+                               return String.valueOf(_numberValue);
+                       case Cell.CELL_TYPE_STRING:
+                               return '"' + _textValue + '"';
+                       case Cell.CELL_TYPE_BOOLEAN:
+                               return _booleanValue ? "TRUE" : "FALSE";
+                       case Cell.CELL_TYPE_ERROR:
+                               return ErrorEval.getText(_errorCode);
+               }
+               return "<error unexpected cell type " + _cellType + ">";
+       }
+}
index 6a51a7288ce35f076f09f408f616523769fa03aa..a4e66635cad59b8cb64941499cd72b037267bda1 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.ss.usermodel;\r
-\r
-/**\r
- * A client anchor is attached to an excel worksheet.  It anchors against a\r
- * top-left and bottom-right cell.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public interface ClientAnchor {\r
-    /**\r
-     * Move and Resize With Anchor Cells\r
-     * <p>\r
-     * Specifies that the current drawing shall move and\r
-     * resize to maintain its row and column anchors (i.e. the\r
-     * object is anchored to the actual from and to row and column)\r
-     * </p>\r
-     */\r
-    public static final int MOVE_AND_RESIZE = 0;\r
-\r
-    /**\r
-     * Move With Cells but Do Not Resize\r
-     * <p>\r
-     * Specifies that the current drawing shall move with its\r
-     * row and column (i.e. the object is anchored to the\r
-     * actual from row and column), but that the size shall remain absolute.\r
-     * </p>\r
-     * <p>\r
-     * If additional rows/columns are added between the from and to locations of the drawing,\r
-     * the drawing shall move its to anchors as needed to maintain this same absolute size.\r
-     * </p>\r
-     */\r
-    public static final int MOVE_DONT_RESIZE = 2;\r
-\r
-    /**\r
-     * Do Not Move or Resize With Underlying Rows/Columns\r
-     * <p>\r
-     * Specifies that the current start and end positions shall\r
-     * be maintained with respect to the distances from the\r
-     * absolute start point of the worksheet.\r
-     * </p>\r
-     * <p>\r
-     * If additional rows/columns are added before the\r
-     * drawing, the drawing shall move its anchors as needed\r
-     * to maintain this same absolute position.\r
-     * </p>\r
-     */\r
-    public static final int DONT_MOVE_AND_RESIZE = 3;\r
-\r
-    /**\r
-     * Returns the column (0 based) of the first cell.\r
-     *\r
-     * @return 0-based column of the first cell.\r
-     */\r
-    public short getCol1();\r
-\r
-    /**\r
-     * Sets the column (0 based) of the first cell.\r
-     *\r
-     * @param col1 0-based column of the first cell.\r
-     */\r
-    public void setCol1(int col1);\r
-\r
-    /**\r
-     * Returns the column (0 based) of the second cell.\r
-     *\r
-     * @return 0-based column of the second cell.\r
-     */\r
-    public short getCol2();\r
-\r
-    /**\r
-     * Returns the column (0 based) of the second cell.\r
-     *\r
-     * @param col2 0-based column of the second cell.\r
-     */\r
-    public void setCol2(int col2);\r
-\r
-    /**\r
-     * Returns the row (0 based) of the first cell.\r
-     *\r
-     * @return 0-based row of the first cell.\r
-     */\r
-    public int getRow1();\r
-\r
-    /**\r
-     * Returns the row (0 based) of the first cell.\r
-     *\r
-     * @param row1 0-based row of the first cell.\r
-     */\r
-    public void setRow1(int row1);\r
-\r
-    /**\r
-     * Returns the row (0 based) of the second cell.\r
-     *\r
-     * @return 0-based row of the second cell.\r
-     */\r
-    public int getRow2();\r
-\r
-    /**\r
-     * Returns the row (0 based) of the first cell.\r
-     *\r
-     * @param row2 0-based row of the first cell.\r
-     */\r
-    public void setRow2(int row2);\r
-\r
-    /**\r
-     * Returns the x coordinate within the first cell\r
-     *\r
-     * @return the x coordinate within the first cell\r
-     */\r
-    public int getDx1();\r
-\r
-    /**\r
-     * Sets the x coordinate within the first cell\r
-     *\r
-     * @param dx1 the x coordinate within the first cell\r
-     */\r
-    public void setDx1(int dx1);\r
-\r
-    /**\r
-     * Returns the y coordinate within the first cell\r
-     *\r
-     * @return the y coordinate within the first cell\r
-     */\r
-    public int getDy1();\r
-\r
-    /**\r
-     * Sets the y coordinate within the first cell\r
-     *\r
-     * @param dy1 the y coordinate within the first cell\r
-     */\r
-    public void setDy1(int dy1);\r
-\r
-    /**\r
-     * Sets the y coordinate within the second cell\r
-     *\r
-     * @return the y coordinate within the second cell\r
-     */\r
-    public int getDy2();\r
-\r
-    /**\r
-     * Sets the y coordinate within the second cell\r
-     *\r
-     * @param dy2 the y coordinate within the second cell\r
-     */\r
-    public void setDy2(int dy2);\r
-\r
-    /**\r
-     * Returns the x coordinate within the second cell\r
-     *\r
-     * @return the x coordinate within the second cell\r
-     */\r
-    public int getDx2();\r
-\r
-    /**\r
-     * Sets the x coordinate within the second cell\r
-     *\r
-     * @param dx2 the x coordinate within the second cell\r
-     */\r
-    public void setDx2(int dx2);\r
-\r
-\r
-    /**\r
-     * Sets the anchor type\r
-     * <p>\r
-     * 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.\r
-     * </p>\r
-     * @param anchorType the anchor type\r
-     * @see #MOVE_AND_RESIZE\r
-     * @see #MOVE_DONT_RESIZE\r
-     * @see #DONT_MOVE_AND_RESIZE\r
-     */\r
-    public void setAnchorType( int anchorType );\r
-\r
-    /**\r
-     * Gets the anchor type\r
-     * <p>\r
-     * 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.\r
-     * </p>\r
-     * @return the anchor type\r
-     * @see #MOVE_AND_RESIZE\r
-     * @see #MOVE_DONT_RESIZE\r
-     * @see #DONT_MOVE_AND_RESIZE\r
-     */\r
-    public int getAnchorType();\r
-\r
-}\r
+/* ====================================================================
+   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.ss.usermodel;
+
+/**
+ * A client anchor is attached to an excel worksheet.  It anchors against a
+ * top-left and bottom-right cell.
+ *
+ * @author Yegor Kozlov
+ */
+public interface ClientAnchor {
+    /**
+     * Move and Resize With Anchor Cells
+     * <p>
+     * Specifies that the current drawing shall move and
+     * resize to maintain its row and column anchors (i.e. the
+     * object is anchored to the actual from and to row and column)
+     * </p>
+     */
+    public static final int MOVE_AND_RESIZE = 0;
+
+    /**
+     * Move With Cells but Do Not Resize
+     * <p>
+     * Specifies that the current drawing shall move with its
+     * row and column (i.e. the object is anchored to the
+     * actual from row and column), but that the size shall remain absolute.
+     * </p>
+     * <p>
+     * If additional rows/columns are added between the from and to locations of the drawing,
+     * the drawing shall move its to anchors as needed to maintain this same absolute size.
+     * </p>
+     */
+    public static final int MOVE_DONT_RESIZE = 2;
+
+    /**
+     * Do Not Move or Resize With Underlying Rows/Columns
+     * <p>
+     * Specifies that the current start and end positions shall
+     * be maintained with respect to the distances from the
+     * absolute start point of the worksheet.
+     * </p>
+     * <p>
+     * If additional rows/columns are added before the
+     * drawing, the drawing shall move its anchors as needed
+     * to maintain this same absolute position.
+     * </p>
+     */
+    public static final int DONT_MOVE_AND_RESIZE = 3;
+
+    /**
+     * Returns the column (0 based) of the first cell.
+     *
+     * @return 0-based column of the first cell.
+     */
+    public short getCol1();
+
+    /**
+     * Sets the column (0 based) of the first cell.
+     *
+     * @param col1 0-based column of the first cell.
+     */
+    public void setCol1(int col1);
+
+    /**
+     * Returns the column (0 based) of the second cell.
+     *
+     * @return 0-based column of the second cell.
+     */
+    public short getCol2();
+
+    /**
+     * Returns the column (0 based) of the second cell.
+     *
+     * @param col2 0-based column of the second cell.
+     */
+    public void setCol2(int col2);
+
+    /**
+     * Returns the row (0 based) of the first cell.
+     *
+     * @return 0-based row of the first cell.
+     */
+    public int getRow1();
+
+    /**
+     * Returns the row (0 based) of the first cell.
+     *
+     * @param row1 0-based row of the first cell.
+     */
+    public void setRow1(int row1);
+
+    /**
+     * Returns the row (0 based) of the second cell.
+     *
+     * @return 0-based row of the second cell.
+     */
+    public int getRow2();
+
+    /**
+     * Returns the row (0 based) of the first cell.
+     *
+     * @param row2 0-based row of the first cell.
+     */
+    public void setRow2(int row2);
+
+    /**
+     * Returns the x coordinate within the first cell
+     *
+     * @return the x coordinate within the first cell
+     */
+    public int getDx1();
+
+    /**
+     * Sets the x coordinate within the first cell
+     *
+     * @param dx1 the x coordinate within the first cell
+     */
+    public void setDx1(int dx1);
+
+    /**
+     * Returns the y coordinate within the first cell
+     *
+     * @return the y coordinate within the first cell
+     */
+    public int getDy1();
+
+    /**
+     * Sets the y coordinate within the first cell
+     *
+     * @param dy1 the y coordinate within the first cell
+     */
+    public void setDy1(int dy1);
+
+    /**
+     * Sets the y coordinate within the second cell
+     *
+     * @return the y coordinate within the second cell
+     */
+    public int getDy2();
+
+    /**
+     * Sets the y coordinate within the second cell
+     *
+     * @param dy2 the y coordinate within the second cell
+     */
+    public void setDy2(int dy2);
+
+    /**
+     * Returns the x coordinate within the second cell
+     *
+     * @return the x coordinate within the second cell
+     */
+    public int getDx2();
+
+    /**
+     * Sets the x coordinate within the second cell
+     *
+     * @param dx2 the x coordinate within the second cell
+     */
+    public void setDx2(int dx2);
+
+
+    /**
+     * Sets the anchor type
+     * <p>
+     * 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.
+     * </p>
+     * @param anchorType the anchor type
+     * @see #MOVE_AND_RESIZE
+     * @see #MOVE_DONT_RESIZE
+     * @see #DONT_MOVE_AND_RESIZE
+     */
+    public void setAnchorType( int anchorType );
+
+    /**
+     * Gets the anchor type
+     * <p>
+     * 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.
+     * </p>
+     * @return the anchor type
+     * @see #MOVE_AND_RESIZE
+     * @see #MOVE_DONT_RESIZE
+     * @see #DONT_MOVE_AND_RESIZE
+     */
+    public int getAnchorType();
+
+}
index 50e3690f7c8cf4de1bc5d9107e67e49a27dbbfb3..f402a0cfabb7caa82932b48dd8045d097532899d 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.ss.usermodel;\r
-\r
-import java.util.regex.Pattern;\r
-import java.util.regex.Matcher;\r
-import java.util.*;\r
-import java.text.*;\r
-\r
-/**\r
- * DataFormatter contains methods for formatting the value stored in an\r
- * Cell. This can be useful for reports and GUI presentations when you\r
- * need to display data exactly as it appears in Excel. Supported formats\r
- * include currency, SSN, percentages, decimals, dates, phone numbers, zip\r
- * codes, etc.\r
- * <p>\r
- * Internally, formats will be implemented using subclasses of {@link Format}\r
- * such as {@link DecimalFormat} and {@link SimpleDateFormat}. Therefore the\r
- * formats used by this class must obey the same pattern rules as these Format\r
- * subclasses. This means that only legal number pattern characters ("0", "#",\r
- * ".", "," etc.) may appear in number formats. Other characters can be\r
- * inserted <em>before</em> or <em> after</em> the number pattern to form a\r
- * prefix or suffix.\r
- * </p>\r
- * <p>\r
- * For example the Excel pattern <code>"$#,##0.00 "USD"_);($#,##0.00 "USD")"\r
- * </code> will be correctly formatted as "$1,000.00 USD" or "($1,000.00 USD)".\r
- * However the pattern <code>"00-00-00"</code> is incorrectly formatted by\r
- * DecimalFormat as "000000--". For Excel formats that are not compatible with\r
- * DecimalFormat, you can provide your own custom {@link Format} implementation\r
- * via <code>DataFormatter.addFormat(String,Format)</code>. The following\r
- * custom formats are already provided by this class:\r
- * </p>\r
- * <pre>\r
- * <ul><li>SSN "000-00-0000"</li>\r
- *     <li>Phone Number "(###) ###-####"</li>\r
- *     <li>Zip plus 4 "00000-0000"</li>\r
- * </ul>\r
- * </pre>\r
- * <p>\r
- * If the Excel format pattern cannot be parsed successfully, then a default\r
- * format will be used. The default number format will mimic the Excel General\r
- * format: "#" for whole numbers and "#.##########" for decimal numbers. You\r
- * can override the default format pattern with <code>\r
- * DataFormatter.setDefaultNumberFormat(Format)</code>. <b>Note:</b> the\r
- * default format will only be used when a Format cannot be created from the\r
- * cell's data format string.\r
- *\r
- * @author James May (james dot may at fmr dot com)\r
- *\r
- */\r
-public class DataFormatter {\r
-\r
-    /** Pattern to find a number format: "0" or  "#" */\r
-    private static final Pattern numPattern = Pattern.compile("[0#]+");\r
-\r
-    /** Pattern to find days of week as text "ddd...." */\r
-    private static final Pattern daysAsText = Pattern.compile("([d]{3,})", Pattern.CASE_INSENSITIVE);\r
-\r
-    /** Pattern to find "AM/PM" marker */\r
-    private static final Pattern amPmPattern = Pattern.compile("((A|P)[M/P]*)", Pattern.CASE_INSENSITIVE);\r
-\r
-    /** A regex to find patterns like [$$-1009] and [$?-452]. */\r
-    private static final Pattern specialPatternGroup = Pattern.compile("(\\[\\$[^-\\]]*-[0-9A-Z]+\\])");\r
-\r
-    /** <em>General</em> format for whole numbers. */\r
-    private static final Format generalWholeNumFormat = new DecimalFormat("#");\r
-\r
-    /** <em>General</em> format for decimal numbers. */\r
-    private static final Format generalDecimalNumFormat = new DecimalFormat("#.##########");\r
-\r
-    /** A default format to use when a number pattern cannot be parsed. */\r
-    private Format defaultNumFormat;\r
-\r
-    /**\r
-     * A map to cache formats.\r
-     *  Map<String,Format> formats\r
-     */\r
-    private final Map formats;\r
-\r
-    /**\r
-     * Constructor\r
-     */\r
-    public DataFormatter() {\r
-        formats = new HashMap();\r
-\r
-        // init built-in formats\r
-\r
-        Format zipFormat = ZipPlusFourFormat.instance;\r
-        addFormat("00000\\-0000", zipFormat);\r
-        addFormat("00000-0000", zipFormat);\r
-\r
-        Format phoneFormat = PhoneFormat.instance;\r
-        // allow for format string variations\r
-        addFormat("[<=9999999]###\\-####;\\(###\\)\\ ###\\-####", phoneFormat);\r
-        addFormat("[<=9999999]###-####;(###) ###-####", phoneFormat);\r
-        addFormat("###\\-####;\\(###\\)\\ ###\\-####", phoneFormat);\r
-        addFormat("###-####;(###) ###-####", phoneFormat);\r
-\r
-        Format ssnFormat = SSNFormat.instance;\r
-        addFormat("000\\-00\\-0000", ssnFormat);\r
-        addFormat("000-00-0000", ssnFormat);\r
-    }\r
-\r
-    /**\r
-     * Return a Format for the given cell if one exists, otherwise try to\r
-     * create one. This method will return <code>null</code> if the any of the\r
-     * following is true:\r
-     * <ul>\r
-     * <li>the cell's style is null</li>\r
-     * <li>the style's data format string is null or empty</li>\r
-     * <li>the format string cannot be recognized as either a number or date</li>\r
-     * </ul>\r
-     *\r
-     * @param cell The cell to retrieve a Format for\r
-     * @return A Format for the format String\r
-     */\r
-    private Format getFormat(Cell cell) {\r
-        if ( cell.getCellStyle() == null) {\r
-            return null;\r
-        }\r
-\r
-        int formatIndex = cell.getCellStyle().getDataFormat();\r
-        String formatStr = cell.getCellStyle().getDataFormatString();\r
-        if(formatStr == null || formatStr.trim().length() == 0) {\r
-            return null;\r
-        }\r
-        return getFormat(cell.getNumericCellValue(), formatIndex, formatStr);\r
-    }\r
-\r
-    private Format getFormat(double cellValue, int formatIndex, String formatStr) {\r
-        Format format = (Format)formats.get(formatStr);\r
-        if (format != null) {\r
-            return format;\r
-        }\r
-        if (formatStr.equals("General") || formatStr.equals("@")) {\r
-            if (DataFormatter.isWholeNumber(cellValue)) {\r
-                return generalWholeNumFormat;\r
-            }\r
-            return generalDecimalNumFormat;\r
-        }\r
-        format = createFormat(cellValue, formatIndex, formatStr);\r
-        formats.put(formatStr, format);\r
-        return format;\r
-    }\r
-\r
-    /**\r
-     * Create and return a Format based on the format string from a  cell's\r
-     * style. If the pattern cannot be parsed, return a default pattern.\r
-     *\r
-     * @param cell The Excel cell\r
-     * @return A Format representing the excel format. May return null.\r
-     */\r
-    public Format createFormat(Cell cell) {\r
-\r
-        int formatIndex = cell.getCellStyle().getDataFormat();\r
-        String formatStr = cell.getCellStyle().getDataFormatString();\r
-        return createFormat(cell.getNumericCellValue(), formatIndex, formatStr);\r
-    }\r
-\r
-    private Format createFormat(double cellValue, int formatIndex, String sFormat) {\r
-        // remove color formatting if present\r
-        String formatStr = sFormat.replaceAll("\\[[a-zA-Z]*\\]", "");\r
-\r
-        // try to extract special characters like currency\r
-        Matcher m = specialPatternGroup.matcher(formatStr);\r
-        while(m.find()) {\r
-            String match = m.group();\r
-            String symbol = match.substring(match.indexOf('$') + 1, match.indexOf('-'));\r
-            if (symbol.indexOf('$') > -1) {\r
-                StringBuffer sb = new StringBuffer();\r
-                sb.append(symbol.substring(0, symbol.indexOf('$')));\r
-                sb.append('\\');\r
-                sb.append(symbol.substring(symbol.indexOf('$'), symbol.length()));\r
-                symbol = sb.toString();\r
-            }\r
-            formatStr = m.replaceAll(symbol);\r
-            m = specialPatternGroup.matcher(formatStr);\r
-        }\r
-\r
-        if(formatStr == null || formatStr.trim().length() == 0) {\r
-            return getDefaultFormat(cellValue);\r
-        }\r
-\r
-\r
-        if(DateUtil.isADateFormat(formatIndex,formatStr) &&\r
-                DateUtil.isValidExcelDate(cellValue)) {\r
-            return createDateFormat(formatStr, cellValue);\r
-        }\r
-        if (numPattern.matcher(formatStr).find()) {\r
-            return createNumberFormat(formatStr, cellValue);\r
-        }\r
-        // TODO - when does this occur?\r
-        return null;\r
-    }\r
-\r
-    private Format createDateFormat(String pFormatStr, double cellValue) {\r
-        String formatStr = pFormatStr;\r
-        formatStr = formatStr.replaceAll("\\\\-","-");\r
-        formatStr = formatStr.replaceAll("\\\\,",",");\r
-        formatStr = formatStr.replaceAll("\\\\ "," ");\r
-        formatStr = formatStr.replaceAll(";@", "");\r
-        boolean hasAmPm = false;\r
-        Matcher amPmMatcher = amPmPattern.matcher(formatStr);\r
-        while (amPmMatcher.find()) {\r
-            formatStr = amPmMatcher.replaceAll("@");\r
-            hasAmPm = true;\r
-            amPmMatcher = amPmPattern.matcher(formatStr);\r
-        }\r
-        formatStr = formatStr.replaceAll("@", "a");\r
-\r
-\r
-        Matcher dateMatcher = daysAsText.matcher(formatStr);\r
-        if (dateMatcher.find()) {\r
-            String match = dateMatcher.group(0);\r
-            formatStr = dateMatcher.replaceAll(match.toUpperCase().replaceAll("D", "E"));\r
-        }\r
-\r
-        // Convert excel date format to SimpleDateFormat.\r
-        // Excel uses lower case 'm' for both minutes and months.\r
-        // From Excel help:\r
-        /*\r
-            The "m" or "mm" code must appear immediately after the "h" or"hh"\r
-            code or immediately before the "ss" code; otherwise, Microsoft\r
-            Excel displays the month instead of minutes."\r
-          */\r
-\r
-        StringBuffer sb = new StringBuffer();\r
-        char[] chars = formatStr.toCharArray();\r
-        boolean mIsMonth = true;\r
-        List ms = new ArrayList();\r
-        for(int j=0; j<chars.length; j++) {\r
-            char c = chars[j];\r
-            if (c == 'h' || c == 'H') {\r
-                mIsMonth = false;\r
-                if (hasAmPm) {\r
-                    sb.append('h');\r
-                } else {\r
-                    sb.append('H');\r
-                }\r
-            }\r
-            else if (c == 'm') {\r
-                if(mIsMonth) {\r
-                    sb.append('M');\r
-                    ms.add(\r
-                            new Integer(sb.length() -1)\r
-                    );\r
-                } else {\r
-                    sb.append('m');\r
-                }\r
-            }\r
-            else if (c == 's' || c == 'S') {\r
-                sb.append('s');\r
-                // if 'M' precedes 's' it should be minutes ('m')\r
-                for (int i = 0; i < ms.size(); i++) {\r
-                    int index = ((Integer)ms.get(i)).intValue();\r
-                    if (sb.charAt(index) == 'M') {\r
-                        sb.replace(index, index+1, "m");\r
-                    }\r
-                }\r
-                mIsMonth = true;\r
-                ms.clear();\r
-            }\r
-            else if (Character.isLetter(c)) {\r
-                mIsMonth = true;\r
-                ms.clear();\r
-                if (c == 'y' || c == 'Y') {\r
-                    sb.append('y');\r
-                }\r
-                else if (c == 'd' || c == 'D') {\r
-                    sb.append('d');\r
-                }\r
-                else {\r
-                    sb.append(c);\r
-                }\r
-            }\r
-            else {\r
-                sb.append(c);\r
-            }\r
-        }\r
-        formatStr = sb.toString();\r
-\r
-        try {\r
-            return new SimpleDateFormat(formatStr);\r
-        } catch(IllegalArgumentException iae) {\r
-\r
-            // the pattern could not be parsed correctly,\r
-            // so fall back to the default number format\r
-            return getDefaultFormat(cellValue);\r
-        }\r
-\r
-    }\r
-\r
-    private Format createNumberFormat(String formatStr, double cellValue) {\r
-        StringBuffer sb = new StringBuffer(formatStr);\r
-        for (int i = 0; i < sb.length(); i++) {\r
-            char c = sb.charAt(i);\r
-            //handle (#,##0_);\r
-            if (c == '(') {\r
-                int idx = sb.indexOf(")", i);\r
-                if (idx > -1 && sb.charAt(idx -1) == '_') {\r
-                    sb.deleteCharAt(idx);\r
-                    sb.deleteCharAt(idx - 1);\r
-                    sb.deleteCharAt(i);\r
-                    i--;\r
-                }\r
-            } else if (c == ')' && i > 0 && sb.charAt(i - 1) == '_') {\r
-                sb.deleteCharAt(i);\r
-                sb.deleteCharAt(i - 1);\r
-                i--;\r
-            // remove quotes and back slashes\r
-            } else if (c == '\\' || c == '"') {\r
-                sb.deleteCharAt(i);\r
-                i--;\r
-\r
-            // for scientific/engineering notation\r
-            } else if (c == '+' && i > 0 && sb.charAt(i - 1) == 'E') {\r
-                sb.deleteCharAt(i);\r
-                i--;\r
-            }\r
-        }\r
-\r
-        try {\r
-            return new DecimalFormat(sb.toString());\r
-        } catch(IllegalArgumentException iae) {\r
-\r
-            // the pattern could not be parsed correctly,\r
-            // so fall back to the default number format\r
-            return getDefaultFormat(cellValue);\r
-        }\r
-    }\r
-\r
-    /**\r
-     * Return true if the double value represents a whole number\r
-     * @param d the double value to check\r
-     * @return <code>true</code> if d is a whole number\r
-     */\r
-    private static boolean isWholeNumber(double d) {\r
-        return d == Math.floor(d);\r
-    }\r
-\r
-    /**\r
-     * Returns a default format for a cell.\r
-     * @param cell The cell\r
-     * @return a default format\r
-     */\r
-    public Format getDefaultFormat(Cell cell) {\r
-        return getDefaultFormat(cell.getNumericCellValue());\r
-    }\r
-    private Format getDefaultFormat(double cellValue) {\r
-        // for numeric cells try user supplied default\r
-        if (defaultNumFormat != null) {\r
-            return defaultNumFormat;\r
-\r
-          // otherwise use general format\r
-        }\r
-        if (isWholeNumber(cellValue)){\r
-            return generalWholeNumFormat;\r
-        }\r
-        return generalDecimalNumFormat;\r
-    }\r
-\r
-    /**\r
-     * Returns the formatted value of an Excel date as a <tt>String</tt> based\r
-     * on the cell's <code>DataFormat</code>. i.e. "Thursday, January 02, 2003"\r
-     * , "01/02/2003" , "02-Jan" , etc.\r
-     *\r
-     * @param cell The cell\r
-     * @return a formatted date string\r
-     */\r
-    private String getFormattedDateString(Cell cell) {\r
-        Format dateFormat = getFormat(cell);\r
-        Date d = cell.getDateCellValue();\r
-        if (dateFormat != null) {\r
-            return dateFormat.format(d);\r
-        }\r
-        return d.toString();\r
-    }\r
-\r
-    /**\r
-     * Returns the formatted value of an Excel number as a <tt>String</tt>\r
-     * based on the cell's <code>DataFormat</code>. Supported formats include\r
-     * currency, percents, decimals, phone number, SSN, etc.:\r
-     * "61.54%", "$100.00", "(800) 555-1234".\r
-     *\r
-     * @param cell The cell\r
-     * @return a formatted number string\r
-     */\r
-    private String getFormattedNumberString(Cell cell) {\r
-\r
-        Format numberFormat = getFormat(cell);\r
-        double d = cell.getNumericCellValue();\r
-        if (numberFormat == null) {\r
-            return String.valueOf(d);\r
-        }\r
-        return numberFormat.format(new Double(d));\r
-    }\r
-\r
-    /**\r
-     * Formats the given raw cell value, based on the supplied\r
-     *  format index and string, according to excel style rules.\r
-     * @see #formatCellValue(Cell)\r
-     */\r
-    public String formatRawCellContents(double value, int formatIndex, String formatString) {\r
-        // Is it a date?\r
-        if(DateUtil.isADateFormat(formatIndex,formatString) &&\r
-                DateUtil.isValidExcelDate(value)) {\r
-\r
-            Format dateFormat = getFormat(value, formatIndex, formatString);\r
-            Date d = DateUtil.getJavaDate(value);\r
-            if (dateFormat == null) {\r
-                return d.toString();\r
-            }\r
-            return dateFormat.format(d);\r
-        }\r
-        // else Number\r
-        Format numberFormat = getFormat(value, formatIndex, formatString);\r
-        if (numberFormat == null) {\r
-            return String.valueOf(value);\r
-        }\r
-        return numberFormat.format(new Double(value));\r
-    }\r
-\r
-    /**\r
-     * <p>\r
-     * Returns the formatted value of a cell as a <tt>String</tt> regardless\r
-     * of the cell type. If the Excel format pattern cannot be parsed then the\r
-     * cell value will be formatted using a default format.\r
-     * </p>\r
-     * <p>When passed a null or blank cell, this method will return an empty\r
-     * String (""). Formulas in formula type cells will not be evaluated.\r
-     * </p>\r
-     *\r
-     * @param cell The cell\r
-     * @return the formatted cell value as a String\r
-     */\r
-    public String formatCellValue(Cell cell) {\r
-        return formatCellValue(cell, null);\r
-    }\r
-\r
-    /**\r
-     * <p>\r
-     * Returns the formatted value of a cell as a <tt>String</tt> regardless\r
-     * of the cell type. If the Excel format pattern cannot be parsed then the\r
-     * cell value will be formatted using a default format.\r
-     * </p>\r
-     * <p>When passed a null or blank cell, this method will return an empty\r
-     * String (""). Formula cells will be evaluated using the given\r
-     * {@link FormulaEvaluator} if the evaluator is non-null. If the\r
-     * evaluator is null, then the formula String will be returned. The caller\r
-     * is responsible for setting the currentRow on the evaluator\r
-     *</p>\r
-     *\r
-     * @param cell The cell (can be null)\r
-     * @param evaluator The FormulaEvaluator (can be null)\r
-     * @return a string value of the cell\r
-     */\r
-    public String formatCellValue(Cell cell, FormulaEvaluator evaluator) {\r
-\r
-        if (cell == null) {\r
-            return "";\r
-        }\r
-\r
-        int cellType = cell.getCellType();\r
-        if (cellType == Cell.CELL_TYPE_FORMULA) {\r
-            if (evaluator == null) {\r
-                return cell.getCellFormula();\r
-            }\r
-            cellType = evaluator.evaluateFormulaCell(cell);\r
-        }\r
-        switch (cellType) {\r
-            case Cell.CELL_TYPE_NUMERIC :\r
-\r
-                if (DateUtil.isCellDateFormatted(cell)) {\r
-                    return getFormattedDateString(cell);\r
-                }\r
-                return getFormattedNumberString(cell);\r
-\r
-            case Cell.CELL_TYPE_STRING :\r
-                return cell.getRichStringCellValue().getString();\r
-\r
-            case Cell.CELL_TYPE_BOOLEAN :\r
-                return String.valueOf(cell.getBooleanCellValue());\r
-            case Cell.CELL_TYPE_BLANK :\r
-                return "";\r
-        }\r
-        throw new RuntimeException("Unexpected celltype (" + cellType + ")");\r
-    }\r
-\r
-\r
-    /**\r
-     * <p>\r
-     * Sets a default number format to be used when the Excel format cannot be\r
-     * parsed successfully. <b>Note:</b> This is a fall back for when an error\r
-     * occurs while parsing an Excel number format pattern. This will not\r
-     * affect cells with the <em>General</em> format.\r
-     * </p>\r
-     * <p>\r
-     * The value that will be passed to the Format's format method (specified\r
-     * by <code>java.text.Format#format</code>) will be a double value from a\r
-     * numeric cell. Therefore the code in the format method should expect a\r
-     * <code>Number</code> value.\r
-     * </p>\r
-     *\r
-     * @param format A Format instance to be used as a default\r
-     * @see java.text.Format#format\r
-     */\r
-    public void setDefaultNumberFormat(Format format) {\r
-        Iterator itr = formats.entrySet().iterator();\r
-        while(itr.hasNext()) {\r
-            Map.Entry entry = (Map.Entry)itr.next();\r
-            if (entry.getValue() == generalDecimalNumFormat\r
-                    || entry.getValue() == generalWholeNumFormat) {\r
-                entry.setValue(format);\r
-            }\r
-        }\r
-        defaultNumFormat = format;\r
-    }\r
-\r
-    /**\r
-     * Adds a new format to the available formats.\r
-     * <p>\r
-     * The value that will be passed to the Format's format method (specified\r
-     * by <code>java.text.Format#format</code>) will be a double value from a\r
-     * numeric cell. Therefore the code in the format method should expect a\r
-     * <code>Number</code> value.\r
-     * </p>\r
-     * @param excelFormatStr The data format string\r
-     * @param format A Format instance\r
-     */\r
-    public void addFormat(String excelFormatStr, Format format) {\r
-        formats.put(excelFormatStr, format);\r
-    }\r
-\r
-    // Some custom formats\r
-\r
-    /**\r
-     * @return a <tt>DecimalFormat</tt> with parseIntegerOnly set <code>true</code>\r
-     */\r
-    /* package */ static DecimalFormat createIntegerOnlyFormat(String fmt) {\r
-        DecimalFormat result = new DecimalFormat(fmt);\r
-        result.setParseIntegerOnly(true);\r
-        return result;\r
-    }\r
-    /**\r
-     * Format class for Excel's SSN format. This class mimics Excel's built-in\r
-     * SSN formatting.\r
-     *\r
-     * @author James May\r
-     */\r
-    private static final class SSNFormat extends Format {\r
-        public static final Format instance = new SSNFormat();\r
-        private static final DecimalFormat df = createIntegerOnlyFormat("000000000");\r
-        private SSNFormat() {\r
-            // enforce singleton\r
-        }\r
-\r
-        /** Format a number as an SSN */\r
-        public static String format(Number num) {\r
-            String result = df.format(num);\r
-            StringBuffer sb = new StringBuffer();\r
-            sb.append(result.substring(0, 3)).append('-');\r
-            sb.append(result.substring(3, 5)).append('-');\r
-            sb.append(result.substring(5, 9));\r
-            return sb.toString();\r
-        }\r
-\r
-        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {\r
-            return toAppendTo.append(format((Number)obj));\r
-        }\r
-\r
-        public Object parseObject(String source, ParsePosition pos) {\r
-            return df.parseObject(source, pos);\r
-        }\r
-    }\r
-\r
-    /**\r
-     * Format class for Excel Zip + 4 format. This class mimics Excel's\r
-     * built-in formatting for Zip + 4.\r
-     * @author James May\r
-     */\r
-    private static final class ZipPlusFourFormat extends Format {\r
-        public static final Format instance = new ZipPlusFourFormat();\r
-        private static final DecimalFormat df = createIntegerOnlyFormat("000000000");\r
-        private ZipPlusFourFormat() {\r
-            // enforce singleton\r
-        }\r
-\r
-        /** Format a number as Zip + 4 */\r
-        public static String format(Number num) {\r
-            String result = df.format(num);\r
-            StringBuffer sb = new StringBuffer();\r
-            sb.append(result.substring(0, 5)).append('-');\r
-            sb.append(result.substring(5, 9));\r
-            return sb.toString();\r
-        }\r
-\r
-        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {\r
-            return toAppendTo.append(format((Number)obj));\r
-        }\r
-\r
-        public Object parseObject(String source, ParsePosition pos) {\r
-            return df.parseObject(source, pos);\r
-        }\r
-    }\r
-\r
-    /**\r
-     * Format class for Excel phone number format. This class mimics Excel's\r
-     * built-in phone number formatting.\r
-     * @author James May\r
-     */\r
-    private static final class PhoneFormat extends Format {\r
-        public static final Format instance = new PhoneFormat();\r
-        private static final DecimalFormat df = createIntegerOnlyFormat("##########");\r
-        private PhoneFormat() {\r
-            // enforce singleton\r
-        }\r
-\r
-        /** Format a number as a phone number */\r
-        public static String format(Number num) {\r
-            String result = df.format(num);\r
-            StringBuffer sb = new StringBuffer();\r
-            String seg1, seg2, seg3;\r
-            int len = result.length();\r
-            if (len <= 4) {\r
-                return result;\r
-            }\r
-\r
-            seg3 = result.substring(len - 4, len);\r
-            seg2 = result.substring(Math.max(0, len - 7), len - 4);\r
-            seg1 = result.substring(Math.max(0, len - 10), Math.max(0, len - 7));\r
-\r
-            if(seg1 != null && seg1.trim().length() > 0) {\r
-                sb.append('(').append(seg1).append(") ");\r
-            }\r
-            if(seg2 != null && seg2.trim().length() > 0) {\r
-                sb.append(seg2).append('-');\r
-            }\r
-            sb.append(seg3);\r
-            return sb.toString();\r
-        }\r
-\r
-        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {\r
-            return toAppendTo.append(format((Number)obj));\r
-        }\r
-\r
-        public Object parseObject(String source, ParsePosition pos) {\r
-            return df.parseObject(source, pos);\r
-        }\r
-    }\r
-}\r
+/* ====================================================================
+   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.ss.usermodel;
+
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
+import java.util.*;
+import java.text.*;
+
+/**
+ * DataFormatter contains methods for formatting the value stored in an
+ * Cell. This can be useful for reports and GUI presentations when you
+ * need to display data exactly as it appears in Excel. Supported formats
+ * include currency, SSN, percentages, decimals, dates, phone numbers, zip
+ * codes, etc.
+ * <p>
+ * Internally, formats will be implemented using subclasses of {@link Format}
+ * such as {@link DecimalFormat} and {@link SimpleDateFormat}. Therefore the
+ * formats used by this class must obey the same pattern rules as these Format
+ * subclasses. This means that only legal number pattern characters ("0", "#",
+ * ".", "," etc.) may appear in number formats. Other characters can be
+ * inserted <em>before</em> or <em> after</em> the number pattern to form a
+ * prefix or suffix.
+ * </p>
+ * <p>
+ * For example the Excel pattern <code>"$#,##0.00 "USD"_);($#,##0.00 "USD")"
+ * </code> will be correctly formatted as "$1,000.00 USD" or "($1,000.00 USD)".
+ * However the pattern <code>"00-00-00"</code> is incorrectly formatted by
+ * DecimalFormat as "000000--". For Excel formats that are not compatible with
+ * DecimalFormat, you can provide your own custom {@link Format} implementation
+ * via <code>DataFormatter.addFormat(String,Format)</code>. The following
+ * custom formats are already provided by this class:
+ * </p>
+ * <pre>
+ * <ul><li>SSN "000-00-0000"</li>
+ *     <li>Phone Number "(###) ###-####"</li>
+ *     <li>Zip plus 4 "00000-0000"</li>
+ * </ul>
+ * </pre>
+ * <p>
+ * If the Excel format pattern cannot be parsed successfully, then a default
+ * format will be used. The default number format will mimic the Excel General
+ * format: "#" for whole numbers and "#.##########" for decimal numbers. You
+ * can override the default format pattern with <code>
+ * DataFormatter.setDefaultNumberFormat(Format)</code>. <b>Note:</b> the
+ * default format will only be used when a Format cannot be created from the
+ * cell's data format string.
+ *
+ * @author James May (james dot may at fmr dot com)
+ *
+ */
+public class DataFormatter {
+
+    /** Pattern to find a number format: "0" or  "#" */
+    private static final Pattern numPattern = Pattern.compile("[0#]+");
+
+    /** Pattern to find days of week as text "ddd...." */
+    private static final Pattern daysAsText = Pattern.compile("([d]{3,})", Pattern.CASE_INSENSITIVE);
+
+    /** Pattern to find "AM/PM" marker */
+    private static final Pattern amPmPattern = Pattern.compile("((A|P)[M/P]*)", Pattern.CASE_INSENSITIVE);
+
+    /** A regex to find patterns like [$$-1009] and [$?-452]. */
+    private static final Pattern specialPatternGroup = Pattern.compile("(\\[\\$[^-\\]]*-[0-9A-Z]+\\])");
+
+    /** <em>General</em> format for whole numbers. */
+    private static final Format generalWholeNumFormat = new DecimalFormat("#");
+
+    /** <em>General</em> format for decimal numbers. */
+    private static final Format generalDecimalNumFormat = new DecimalFormat("#.##########");
+
+    /** A default format to use when a number pattern cannot be parsed. */
+    private Format defaultNumFormat;
+
+    /**
+     * A map to cache formats.
+     *  Map<String,Format> formats
+     */
+    private final Map formats;
+
+    /**
+     * Constructor
+     */
+    public DataFormatter() {
+        formats = new HashMap();
+
+        // init built-in formats
+
+        Format zipFormat = ZipPlusFourFormat.instance;
+        addFormat("00000\\-0000", zipFormat);
+        addFormat("00000-0000", zipFormat);
+
+        Format phoneFormat = PhoneFormat.instance;
+        // allow for format string variations
+        addFormat("[<=9999999]###\\-####;\\(###\\)\\ ###\\-####", phoneFormat);
+        addFormat("[<=9999999]###-####;(###) ###-####", phoneFormat);
+        addFormat("###\\-####;\\(###\\)\\ ###\\-####", phoneFormat);
+        addFormat("###-####;(###) ###-####", phoneFormat);
+
+        Format ssnFormat = SSNFormat.instance;
+        addFormat("000\\-00\\-0000", ssnFormat);
+        addFormat("000-00-0000", ssnFormat);
+    }
+
+    /**
+     * Return a Format for the given cell if one exists, otherwise try to
+     * create one. This method will return <code>null</code> if the any of the
+     * following is true:
+     * <ul>
+     * <li>the cell's style is null</li>
+     * <li>the style's data format string is null or empty</li>
+     * <li>the format string cannot be recognized as either a number or date</li>
+     * </ul>
+     *
+     * @param cell The cell to retrieve a Format for
+     * @return A Format for the format String
+     */
+    private Format getFormat(Cell cell) {
+        if ( cell.getCellStyle() == null) {
+            return null;
+        }
+
+        int formatIndex = cell.getCellStyle().getDataFormat();
+        String formatStr = cell.getCellStyle().getDataFormatString();
+        if(formatStr == null || formatStr.trim().length() == 0) {
+            return null;
+        }
+        return getFormat(cell.getNumericCellValue(), formatIndex, formatStr);
+    }
+
+    private Format getFormat(double cellValue, int formatIndex, String formatStr) {
+        Format format = (Format)formats.get(formatStr);
+        if (format != null) {
+            return format;
+        }
+        if (formatStr.equals("General") || formatStr.equals("@")) {
+            if (DataFormatter.isWholeNumber(cellValue)) {
+                return generalWholeNumFormat;
+            }
+            return generalDecimalNumFormat;
+        }
+        format = createFormat(cellValue, formatIndex, formatStr);
+        formats.put(formatStr, format);
+        return format;
+    }
+
+    /**
+     * Create and return a Format based on the format string from a  cell's
+     * style. If the pattern cannot be parsed, return a default pattern.
+     *
+     * @param cell The Excel cell
+     * @return A Format representing the excel format. May return null.
+     */
+    public Format createFormat(Cell cell) {
+
+        int formatIndex = cell.getCellStyle().getDataFormat();
+        String formatStr = cell.getCellStyle().getDataFormatString();
+        return createFormat(cell.getNumericCellValue(), formatIndex, formatStr);
+    }
+
+    private Format createFormat(double cellValue, int formatIndex, String sFormat) {
+        // remove color formatting if present
+        String formatStr = sFormat.replaceAll("\\[[a-zA-Z]*\\]", "");
+
+        // try to extract special characters like currency
+        Matcher m = specialPatternGroup.matcher(formatStr);
+        while(m.find()) {
+            String match = m.group();
+            String symbol = match.substring(match.indexOf('$') + 1, match.indexOf('-'));
+            if (symbol.indexOf('$') > -1) {
+                StringBuffer sb = new StringBuffer();
+                sb.append(symbol.substring(0, symbol.indexOf('$')));
+                sb.append('\\');
+                sb.append(symbol.substring(symbol.indexOf('$'), symbol.length()));
+                symbol = sb.toString();
+            }
+            formatStr = m.replaceAll(symbol);
+            m = specialPatternGroup.matcher(formatStr);
+        }
+
+        if(formatStr == null || formatStr.trim().length() == 0) {
+            return getDefaultFormat(cellValue);
+        }
+
+
+        if(DateUtil.isADateFormat(formatIndex,formatStr) &&
+                DateUtil.isValidExcelDate(cellValue)) {
+            return createDateFormat(formatStr, cellValue);
+        }
+        if (numPattern.matcher(formatStr).find()) {
+            return createNumberFormat(formatStr, cellValue);
+        }
+        // TODO - when does this occur?
+        return null;
+    }
+
+    private Format createDateFormat(String pFormatStr, double cellValue) {
+        String formatStr = pFormatStr;
+        formatStr = formatStr.replaceAll("\\\\-","-");
+        formatStr = formatStr.replaceAll("\\\\,",",");
+        formatStr = formatStr.replaceAll("\\\\ "," ");
+        formatStr = formatStr.replaceAll(";@", "");
+        boolean hasAmPm = false;
+        Matcher amPmMatcher = amPmPattern.matcher(formatStr);
+        while (amPmMatcher.find()) {
+            formatStr = amPmMatcher.replaceAll("@");
+            hasAmPm = true;
+            amPmMatcher = amPmPattern.matcher(formatStr);
+        }
+        formatStr = formatStr.replaceAll("@", "a");
+
+
+        Matcher dateMatcher = daysAsText.matcher(formatStr);
+        if (dateMatcher.find()) {
+            String match = dateMatcher.group(0);
+            formatStr = dateMatcher.replaceAll(match.toUpperCase().replaceAll("D", "E"));
+        }
+
+        // Convert excel date format to SimpleDateFormat.
+        // Excel uses lower case 'm' for both minutes and months.
+        // From Excel help:
+        /*
+            The "m" or "mm" code must appear immediately after the "h" or"hh"
+            code or immediately before the "ss" code; otherwise, Microsoft
+            Excel displays the month instead of minutes."
+          */
+
+        StringBuffer sb = new StringBuffer();
+        char[] chars = formatStr.toCharArray();
+        boolean mIsMonth = true;
+        List ms = new ArrayList();
+        for(int j=0; j<chars.length; j++) {
+            char c = chars[j];
+            if (c == 'h' || c == 'H') {
+                mIsMonth = false;
+                if (hasAmPm) {
+                    sb.append('h');
+                } else {
+                    sb.append('H');
+                }
+            }
+            else if (c == 'm') {
+                if(mIsMonth) {
+                    sb.append('M');
+                    ms.add(
+                            new Integer(sb.length() -1)
+                    );
+                } else {
+                    sb.append('m');
+                }
+            }
+            else if (c == 's' || c == 'S') {
+                sb.append('s');
+                // if 'M' precedes 's' it should be minutes ('m')
+                for (int i = 0; i < ms.size(); i++) {
+                    int index = ((Integer)ms.get(i)).intValue();
+                    if (sb.charAt(index) == 'M') {
+                        sb.replace(index, index+1, "m");
+                    }
+                }
+                mIsMonth = true;
+                ms.clear();
+            }
+            else if (Character.isLetter(c)) {
+                mIsMonth = true;
+                ms.clear();
+                if (c == 'y' || c == 'Y') {
+                    sb.append('y');
+                }
+                else if (c == 'd' || c == 'D') {
+                    sb.append('d');
+                }
+                else {
+                    sb.append(c);
+                }
+            }
+            else {
+                sb.append(c);
+            }
+        }
+        formatStr = sb.toString();
+
+        try {
+            return new SimpleDateFormat(formatStr);
+        } catch(IllegalArgumentException iae) {
+
+            // the pattern could not be parsed correctly,
+            // so fall back to the default number format
+            return getDefaultFormat(cellValue);
+        }
+
+    }
+
+    private Format createNumberFormat(String formatStr, double cellValue) {
+        StringBuffer sb = new StringBuffer(formatStr);
+        for (int i = 0; i < sb.length(); i++) {
+            char c = sb.charAt(i);
+            //handle (#,##0_);
+            if (c == '(') {
+                int idx = sb.indexOf(")", i);
+                if (idx > -1 && sb.charAt(idx -1) == '_') {
+                    sb.deleteCharAt(idx);
+                    sb.deleteCharAt(idx - 1);
+                    sb.deleteCharAt(i);
+                    i--;
+                }
+            } else if (c == ')' && i > 0 && sb.charAt(i - 1) == '_') {
+                sb.deleteCharAt(i);
+                sb.deleteCharAt(i - 1);
+                i--;
+            // remove quotes and back slashes
+            } else if (c == '\\' || c == '"') {
+                sb.deleteCharAt(i);
+                i--;
+
+            // for scientific/engineering notation
+            } else if (c == '+' && i > 0 && sb.charAt(i - 1) == 'E') {
+                sb.deleteCharAt(i);
+                i--;
+            }
+        }
+
+        try {
+            return new DecimalFormat(sb.toString());
+        } catch(IllegalArgumentException iae) {
+
+            // the pattern could not be parsed correctly,
+            // so fall back to the default number format
+            return getDefaultFormat(cellValue);
+        }
+    }
+
+    /**
+     * Return true if the double value represents a whole number
+     * @param d the double value to check
+     * @return <code>true</code> if d is a whole number
+     */
+    private static boolean isWholeNumber(double d) {
+        return d == Math.floor(d);
+    }
+
+    /**
+     * Returns a default format for a cell.
+     * @param cell The cell
+     * @return a default format
+     */
+    public Format getDefaultFormat(Cell cell) {
+        return getDefaultFormat(cell.getNumericCellValue());
+    }
+    private Format getDefaultFormat(double cellValue) {
+        // for numeric cells try user supplied default
+        if (defaultNumFormat != null) {
+            return defaultNumFormat;
+
+          // otherwise use general format
+        }
+        if (isWholeNumber(cellValue)){
+            return generalWholeNumFormat;
+        }
+        return generalDecimalNumFormat;
+    }
+
+    /**
+     * Returns the formatted value of an Excel date as a <tt>String</tt> based
+     * on the cell's <code>DataFormat</code>. i.e. "Thursday, January 02, 2003"
+     * , "01/02/2003" , "02-Jan" , etc.
+     *
+     * @param cell The cell
+     * @return a formatted date string
+     */
+    private String getFormattedDateString(Cell cell) {
+        Format dateFormat = getFormat(cell);
+        Date d = cell.getDateCellValue();
+        if (dateFormat != null) {
+            return dateFormat.format(d);
+        }
+        return d.toString();
+    }
+
+    /**
+     * Returns the formatted value of an Excel number as a <tt>String</tt>
+     * based on the cell's <code>DataFormat</code>. Supported formats include
+     * currency, percents, decimals, phone number, SSN, etc.:
+     * "61.54%", "$100.00", "(800) 555-1234".
+     *
+     * @param cell The cell
+     * @return a formatted number string
+     */
+    private String getFormattedNumberString(Cell cell) {
+
+        Format numberFormat = getFormat(cell);
+        double d = cell.getNumericCellValue();
+        if (numberFormat == null) {
+            return String.valueOf(d);
+        }
+        return numberFormat.format(new Double(d));
+    }
+
+    /**
+     * Formats the given raw cell value, based on the supplied
+     *  format index and string, according to excel style rules.
+     * @see #formatCellValue(Cell)
+     */
+    public String formatRawCellContents(double value, int formatIndex, String formatString) {
+        // Is it a date?
+        if(DateUtil.isADateFormat(formatIndex,formatString) &&
+                DateUtil.isValidExcelDate(value)) {
+
+            Format dateFormat = getFormat(value, formatIndex, formatString);
+            Date d = DateUtil.getJavaDate(value);
+            if (dateFormat == null) {
+                return d.toString();
+            }
+            return dateFormat.format(d);
+        }
+        // else Number
+        Format numberFormat = getFormat(value, formatIndex, formatString);
+        if (numberFormat == null) {
+            return String.valueOf(value);
+        }
+        return numberFormat.format(new Double(value));
+    }
+
+    /**
+     * <p>
+     * Returns the formatted value of a cell as a <tt>String</tt> regardless
+     * of the cell type. If the Excel format pattern cannot be parsed then the
+     * cell value will be formatted using a default format.
+     * </p>
+     * <p>When passed a null or blank cell, this method will return an empty
+     * String (""). Formulas in formula type cells will not be evaluated.
+     * </p>
+     *
+     * @param cell The cell
+     * @return the formatted cell value as a String
+     */
+    public String formatCellValue(Cell cell) {
+        return formatCellValue(cell, null);
+    }
+
+    /**
+     * <p>
+     * Returns the formatted value of a cell as a <tt>String</tt> regardless
+     * of the cell type. If the Excel format pattern cannot be parsed then the
+     * cell value will be formatted using a default format.
+     * </p>
+     * <p>When passed a null or blank cell, this method will return an empty
+     * String (""). Formula cells will be evaluated using the given
+     * {@link FormulaEvaluator} if the evaluator is non-null. If the
+     * evaluator is null, then the formula String will be returned. The caller
+     * is responsible for setting the currentRow on the evaluator
+     *</p>
+     *
+     * @param cell The cell (can be null)
+     * @param evaluator The FormulaEvaluator (can be null)
+     * @return a string value of the cell
+     */
+    public String formatCellValue(Cell cell, FormulaEvaluator evaluator) {
+
+        if (cell == null) {
+            return "";
+        }
+
+        int cellType = cell.getCellType();
+        if (cellType == Cell.CELL_TYPE_FORMULA) {
+            if (evaluator == null) {
+                return cell.getCellFormula();
+            }
+            cellType = evaluator.evaluateFormulaCell(cell);
+        }
+        switch (cellType) {
+            case Cell.CELL_TYPE_NUMERIC :
+
+                if (DateUtil.isCellDateFormatted(cell)) {
+                    return getFormattedDateString(cell);
+                }
+                return getFormattedNumberString(cell);
+
+            case Cell.CELL_TYPE_STRING :
+                return cell.getRichStringCellValue().getString();
+
+            case Cell.CELL_TYPE_BOOLEAN :
+                return String.valueOf(cell.getBooleanCellValue());
+            case Cell.CELL_TYPE_BLANK :
+                return "";
+        }
+        throw new RuntimeException("Unexpected celltype (" + cellType + ")");
+    }
+
+
+    /**
+     * <p>
+     * Sets a default number format to be used when the Excel format cannot be
+     * parsed successfully. <b>Note:</b> This is a fall back for when an error
+     * occurs while parsing an Excel number format pattern. This will not
+     * affect cells with the <em>General</em> format.
+     * </p>
+     * <p>
+     * The value that will be passed to the Format's format method (specified
+     * by <code>java.text.Format#format</code>) will be a double value from a
+     * numeric cell. Therefore the code in the format method should expect a
+     * <code>Number</code> value.
+     * </p>
+     *
+     * @param format A Format instance to be used as a default
+     * @see java.text.Format#format
+     */
+    public void setDefaultNumberFormat(Format format) {
+        Iterator itr = formats.entrySet().iterator();
+        while(itr.hasNext()) {
+            Map.Entry entry = (Map.Entry)itr.next();
+            if (entry.getValue() == generalDecimalNumFormat
+                    || entry.getValue() == generalWholeNumFormat) {
+                entry.setValue(format);
+            }
+        }
+        defaultNumFormat = format;
+    }
+
+    /**
+     * Adds a new format to the available formats.
+     * <p>
+     * The value that will be passed to the Format's format method (specified
+     * by <code>java.text.Format#format</code>) will be a double value from a
+     * numeric cell. Therefore the code in the format method should expect a
+     * <code>Number</code> value.
+     * </p>
+     * @param excelFormatStr The data format string
+     * @param format A Format instance
+     */
+    public void addFormat(String excelFormatStr, Format format) {
+        formats.put(excelFormatStr, format);
+    }
+
+    // Some custom formats
+
+    /**
+     * @return a <tt>DecimalFormat</tt> with parseIntegerOnly set <code>true</code>
+     */
+    /* package */ static DecimalFormat createIntegerOnlyFormat(String fmt) {
+        DecimalFormat result = new DecimalFormat(fmt);
+        result.setParseIntegerOnly(true);
+        return result;
+    }
+    /**
+     * Format class for Excel's SSN format. This class mimics Excel's built-in
+     * SSN formatting.
+     *
+     * @author James May
+     */
+    private static final class SSNFormat extends Format {
+        public static final Format instance = new SSNFormat();
+        private static final DecimalFormat df = createIntegerOnlyFormat("000000000");
+        private SSNFormat() {
+            // enforce singleton
+        }
+
+        /** Format a number as an SSN */
+        public static String format(Number num) {
+            String result = df.format(num);
+            StringBuffer sb = new StringBuffer();
+            sb.append(result.substring(0, 3)).append('-');
+            sb.append(result.substring(3, 5)).append('-');
+            sb.append(result.substring(5, 9));
+            return sb.toString();
+        }
+
+        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
+            return toAppendTo.append(format((Number)obj));
+        }
+
+        public Object parseObject(String source, ParsePosition pos) {
+            return df.parseObject(source, pos);
+        }
+    }
+
+    /**
+     * Format class for Excel Zip + 4 format. This class mimics Excel's
+     * built-in formatting for Zip + 4.
+     * @author James May
+     */
+    private static final class ZipPlusFourFormat extends Format {
+        public static final Format instance = new ZipPlusFourFormat();
+        private static final DecimalFormat df = createIntegerOnlyFormat("000000000");
+        private ZipPlusFourFormat() {
+            // enforce singleton
+        }
+
+        /** Format a number as Zip + 4 */
+        public static String format(Number num) {
+            String result = df.format(num);
+            StringBuffer sb = new StringBuffer();
+            sb.append(result.substring(0, 5)).append('-');
+            sb.append(result.substring(5, 9));
+            return sb.toString();
+        }
+
+        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
+            return toAppendTo.append(format((Number)obj));
+        }
+
+        public Object parseObject(String source, ParsePosition pos) {
+            return df.parseObject(source, pos);
+        }
+    }
+
+    /**
+     * Format class for Excel phone number format. This class mimics Excel's
+     * built-in phone number formatting.
+     * @author James May
+     */
+    private static final class PhoneFormat extends Format {
+        public static final Format instance = new PhoneFormat();
+        private static final DecimalFormat df = createIntegerOnlyFormat("##########");
+        private PhoneFormat() {
+            // enforce singleton
+        }
+
+        /** Format a number as a phone number */
+        public static String format(Number num) {
+            String result = df.format(num);
+            StringBuffer sb = new StringBuffer();
+            String seg1, seg2, seg3;
+            int len = result.length();
+            if (len <= 4) {
+                return result;
+            }
+
+            seg3 = result.substring(len - 4, len);
+            seg2 = result.substring(Math.max(0, len - 7), len - 4);
+            seg1 = result.substring(Math.max(0, len - 10), Math.max(0, len - 7));
+
+            if(seg1 != null && seg1.trim().length() > 0) {
+                sb.append('(').append(seg1).append(") ");
+            }
+            if(seg2 != null && seg2.trim().length() > 0) {
+                sb.append(seg2).append('-');
+            }
+            sb.append(seg3);
+            return sb.toString();
+        }
+
+        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
+            return toAppendTo.append(format((Number)obj));
+        }
+
+        public Object parseObject(String source, ParsePosition pos) {
+            return df.parseObject(source, pos);
+        }
+    }
+}
index c7b8dc0e84b5f6e518d4e3fe1ca8bb86898defab..b27c3098c0a3e3023a4afbce459e1c28b8a36fff 100755 (executable)
@@ -1,24 +1,24 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.ss.usermodel;\r
-\r
-/**\r
- * @author Yegor Kozlov\r
- */\r
-public interface Drawing {\r
-    Picture createPicture(ClientAnchor anchor, int pictureIndex);\r
-}\r
+/* ====================================================================
+   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.ss.usermodel;
+
+/**
+ * @author Yegor Kozlov
+ */
+public interface Drawing {
+    Picture createPicture(ClientAnchor anchor, int pictureIndex);
+}
index 4f631c6ee4a2afeaf74ee34556e3f26b274ddc5f..c3c43301e51d94d78d168ab2230bd620c1f7e304 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.ss.usermodel;\r
-\r
-import java.util.Map;\r
-import java.util.HashMap;\r
-\r
-/**\r
- * Enumerates error values in SpreadsheetML formula calculations.\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public enum FormulaError {\r
-    /**\r
-     * Intended to indicate when two areas are required to intersect, but do not.\r
-     * <p>Example:\r
-     * In the case of SUM(B1 C1), the space between B1 and C1 is treated as the binary\r
-     * intersection operator, when a comma was intended. end example]\r
-     * </p>\r
-     */\r
-    NULL(0x00, "#NULL!"),\r
-\r
-    /**\r
-     * Intended to indicate when any number, including zero, is divided by zero.\r
-     * Note: However, any error code divided by zero results in that error code.\r
-     */\r
-    DIV0(0x07, "#DIV/0!"),\r
-\r
-    /**\r
-     * Intended to indicate when an incompatible type argument is passed to a function, or\r
-     * an incompatible type operand is used with an operator.\r
-     * <p>Example:\r
-     * In the case of a function argument, text was expected, but a number was provided\r
-     * </p>\r
-     */\r
-    VALUE(0x0F, "#VALUE!"),\r
-\r
-    /**\r
-     * Intended to indicate when a cell reference is invalid.\r
-     * <p>Example:\r
-     * If a formula contains a reference to a cell, and then the row or column containing that cell is deleted,\r
-     * a #REF! error results. If a worksheet does not support 20,001 columns,\r
-     * OFFSET(A1,0,20000) will result in a #REF! error.\r
-     * </p>\r
-     */\r
-    REF(0x1D, "#REF!"),\r
-\r
-    /**\r
-     * Intended to indicate when what looks like a name is used, but no such name has been defined.\r
-     * <p>Example:\r
-     * XYZ/3, where XYZ is not a defined name. Total is & A10,\r
-     * where neither Total nor is is a defined name. Presumably, "Total is " & A10\r
-     * was intended. SUM(A1C10), where the range A1:C10 was intended.\r
-     * </p>\r
-     */\r
-    NAME(0x1D, "#NAME?"),\r
-\r
-    /**\r
-     * Intended to indicate when an argument to a function has a compatible type, but has a\r
-     * value that is outside the domain over which that function is defined. (This is known as\r
-     * a domain error.)\r
-     * <p>Example:\r
-     * Certain calls to ASIN, ATANH, FACT, and SQRT might result in domain errors.\r
-     * </p>\r
-     * Intended to indicate that the result of a function cannot be represented in a value of\r
-     * the specified type, typically due to extreme magnitude. (This is known as a range\r
-     * error.)\r
-     * <p>Example: FACT(1000) might result in a range error. </p>\r
-     */\r
-    NUM(0x24, "#NUM!"),\r
-\r
-    /**\r
-     * Intended to indicate when a designated value is not available.\r
-     * <p>Example:\r
-     * Some functions, such as SUMX2MY2, perform a series of operations on corresponding\r
-     * elements in two arrays. If those arrays do not have the same number of elements, then\r
-     * for some elements in the longer array, there are no corresponding elements in the\r
-     * shorter one; that is, one or more values in the shorter array are not available.\r
-     * </p>\r
-     * This error value can be produced by calling the function NA\r
-     */\r
-    NA(0x2A, "#N/A");\r
-\r
-    private byte type;\r
-    private String repr;\r
-\r
-    private FormulaError(int type, String repr) {\r
-        this.type = (byte) type;\r
-        this.repr = repr;\r
-    }\r
-\r
-    /**\r
-     * @return numeric code of the error\r
-     */\r
-    public byte getCode() {\r
-        return type;\r
-    }\r
-\r
-    /**\r
-     * @return string representation of the error\r
-     */\r
-    public String getString() {\r
-        return repr;\r
-    }\r
-\r
-    private static Map<String, FormulaError> smap = new HashMap<String, FormulaError>();\r
-    private static Map<Byte, FormulaError> imap = new HashMap<Byte, FormulaError>();\r
-    static{\r
-        for (FormulaError error : values()) {\r
-            imap.put(error.getCode(), error);\r
-            smap.put(error.getString(), error);\r
-        }\r
-    }\r
-\r
-    public static FormulaError forInt(byte type){\r
-        FormulaError err = imap.get(type);\r
-        if(err == null) throw new IllegalArgumentException("Unknown error type: " + type);\r
-        return err;\r
-    }\r
-\r
-    public static FormulaError forString(String code){\r
-        FormulaError err = smap.get(code);\r
-        if(err == null) throw new IllegalArgumentException("Unknown error code: " + code);\r
-        return err;\r
-    }\r
-}\r
+/* ====================================================================
+   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.ss.usermodel;
+
+import java.util.Map;
+import java.util.HashMap;
+
+/**
+ * Enumerates error values in SpreadsheetML formula calculations.
+ *
+ * @author Yegor Kozlov
+ */
+public enum FormulaError {
+    /**
+     * Intended to indicate when two areas are required to intersect, but do not.
+     * <p>Example:
+     * In the case of SUM(B1 C1), the space between B1 and C1 is treated as the binary
+     * intersection operator, when a comma was intended. end example]
+     * </p>
+     */
+    NULL(0x00, "#NULL!"),
+
+    /**
+     * Intended to indicate when any number, including zero, is divided by zero.
+     * Note: However, any error code divided by zero results in that error code.
+     */
+    DIV0(0x07, "#DIV/0!"),
+
+    /**
+     * Intended to indicate when an incompatible type argument is passed to a function, or
+     * an incompatible type operand is used with an operator.
+     * <p>Example:
+     * In the case of a function argument, text was expected, but a number was provided
+     * </p>
+     */
+    VALUE(0x0F, "#VALUE!"),
+
+    /**
+     * Intended to indicate when a cell reference is invalid.
+     * <p>Example:
+     * If a formula contains a reference to a cell, and then the row or column containing that cell is deleted,
+     * a #REF! error results. If a worksheet does not support 20,001 columns,
+     * OFFSET(A1,0,20000) will result in a #REF! error.
+     * </p>
+     */
+    REF(0x1D, "#REF!"),
+
+    /**
+     * Intended to indicate when what looks like a name is used, but no such name has been defined.
+     * <p>Example:
+     * XYZ/3, where XYZ is not a defined name. Total is & A10,
+     * where neither Total nor is is a defined name. Presumably, "Total is " & A10
+     * was intended. SUM(A1C10), where the range A1:C10 was intended.
+     * </p>
+     */
+    NAME(0x1D, "#NAME?"),
+
+    /**
+     * Intended to indicate when an argument to a function has a compatible type, but has a
+     * value that is outside the domain over which that function is defined. (This is known as
+     * a domain error.)
+     * <p>Example:
+     * Certain calls to ASIN, ATANH, FACT, and SQRT might result in domain errors.
+     * </p>
+     * Intended to indicate that the result of a function cannot be represented in a value of
+     * the specified type, typically due to extreme magnitude. (This is known as a range
+     * error.)
+     * <p>Example: FACT(1000) might result in a range error. </p>
+     */
+    NUM(0x24, "#NUM!"),
+
+    /**
+     * Intended to indicate when a designated value is not available.
+     * <p>Example:
+     * Some functions, such as SUMX2MY2, perform a series of operations on corresponding
+     * elements in two arrays. If those arrays do not have the same number of elements, then
+     * for some elements in the longer array, there are no corresponding elements in the
+     * shorter one; that is, one or more values in the shorter array are not available.
+     * </p>
+     * This error value can be produced by calling the function NA
+     */
+    NA(0x2A, "#N/A");
+
+    private byte type;
+    private String repr;
+
+    private FormulaError(int type, String repr) {
+        this.type = (byte) type;
+        this.repr = repr;
+    }
+
+    /**
+     * @return numeric code of the error
+     */
+    public byte getCode() {
+        return type;
+    }
+
+    /**
+     * @return string representation of the error
+     */
+    public String getString() {
+        return repr;
+    }
+
+    private static Map<String, FormulaError> smap = new HashMap<String, FormulaError>();
+    private static Map<Byte, FormulaError> imap = new HashMap<Byte, FormulaError>();
+    static{
+        for (FormulaError error : values()) {
+            imap.put(error.getCode(), error);
+            smap.put(error.getString(), error);
+        }
+    }
+
+    public static FormulaError forInt(byte type){
+        FormulaError err = imap.get(type);
+        if(err == null) throw new IllegalArgumentException("Unknown error type: " + type);
+        return err;
+    }
+
+    public static FormulaError forString(String code){
+        FormulaError err = smap.get(code);
+        if(err == null) throw new IllegalArgumentException("Unknown error code: " + code);
+        return err;
+    }
+}
index bcc05d8fbf32bcedf3913682c5cfe631e6cc01cb..9be6017ab09b94e1d6020cb416f547da616fb949 100755 (executable)
@@ -1,95 +1,95 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.usermodel;\r
-\r
-/**\r
- * The enumeration value indicating horizontal alignment of a cell,\r
- * i.e., whether it is aligned general, left, right, horizontally centered, filled (replicated),\r
- * justified, centered across multiple cells, or distributed.\r
- */\r
-public enum HorizontalAlignment {\r
-    /**\r
-     * The horizontal alignment is general-aligned. Text data is left-aligned.\r
-     * Numbers, dates, and times are rightaligned. Boolean types are centered.\r
-     * Changing the alignment does not change the type of data.\r
-     */\r
-    GENERAL,\r
-\r
-    /**\r
-     * The horizontal alignment is left-aligned, even in Rightto-Left mode.\r
-     * Aligns contents at the left edge of the cell. If an indent amount is specified, the contents of\r
-     * the cell is indented from the left by the specified number of character spaces. The character spaces are\r
-     * based on the default font and font size for the workbook.\r
-     */\r
-    LEFT,\r
-\r
-    /**\r
-     * The horizontal alignment is centered, meaning the text is centered across the cell.\r
-     */\r
-    CENTER,\r
-\r
-    /**\r
-     * The horizontal alignment is right-aligned, meaning that cell contents are aligned at the right edge of the cell,\r
-     * even in Right-to-Left mode.\r
-     */\r
-    RIGHT,\r
-\r
-    /**\r
-     * Indicates that the value of the cell should be filled\r
-     * across the entire width of the cell. If blank cells to the right also have the fill alignment,\r
-     * they are also filled with the value, using a convention similar to centerContinuous.\r
-     * <p>\r
-     * Additional rules:\r
-     * <ol>\r
-     * <li>Only whole values can be appended, not partial values.</li>\r
-     * <li>The column will not be widened to 'best fit' the filled value</li>\r
-     * <li>If appending an additional occurrence of the value exceeds the boundary of the cell\r
-     * left/right edge, don't append the additional occurrence of the value.</li>\r
-     * <li>The display value of the cell is filled, not the underlying raw number.</li>\r
-     * </ol>\r
-     * </p>\r
-     */\r
-    FILL,\r
-\r
-    /**\r
-     * The horizontal alignment is justified (flush left and right).\r
-     * For each line of text, aligns each line of the wrapped text in a cell to the right and left\r
-     * (except the last line). If no single line of text wraps in the cell, then the text is not justified.\r
-     */\r
-    JUSTIFY,\r
-\r
-    /**\r
-     * The horizontal alignment is centered across multiple cells.\r
-     * The information about how many cells to span is expressed in the Sheet Part,\r
-     * in the row of the cell in question. For each cell that is spanned in the alignment,\r
-     * a cell element needs to be written out, with the same style Id which references the centerContinuous alignment.\r
-     */\r
-    CENTER_SELECTION,\r
-\r
-    /**\r
-     * Indicates that each 'word' in each line of text inside the cell is evenly distributed\r
-     * across the width of the cell, with flush right and left margins.\r
-     * <p>\r
-     * When there is also an indent value to apply, both the left and right side of the cell\r
-     * are padded by the indent value.\r
-     * </p>\r
-     * <p> A 'word' is a set of characters with no space character in them. </p>\r
-     * <p> Two lines inside a cell are separated by a carriage return. </p>\r
-     */\r
-    DISTRIBUTED\r
-}\r
+/* ====================================================================
+   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.ss.usermodel;
+
+/**
+ * The enumeration value indicating horizontal alignment of a cell,
+ * i.e., whether it is aligned general, left, right, horizontally centered, filled (replicated),
+ * justified, centered across multiple cells, or distributed.
+ */
+public enum HorizontalAlignment {
+    /**
+     * The horizontal alignment is general-aligned. Text data is left-aligned.
+     * Numbers, dates, and times are rightaligned. Boolean types are centered.
+     * Changing the alignment does not change the type of data.
+     */
+    GENERAL,
+
+    /**
+     * The horizontal alignment is left-aligned, even in Rightto-Left mode.
+     * Aligns contents at the left edge of the cell. If an indent amount is specified, the contents of
+     * the cell is indented from the left by the specified number of character spaces. The character spaces are
+     * based on the default font and font size for the workbook.
+     */
+    LEFT,
+
+    /**
+     * The horizontal alignment is centered, meaning the text is centered across the cell.
+     */
+    CENTER,
+
+    /**
+     * The horizontal alignment is right-aligned, meaning that cell contents are aligned at the right edge of the cell,
+     * even in Right-to-Left mode.
+     */
+    RIGHT,
+
+    /**
+     * Indicates that the value of the cell should be filled
+     * across the entire width of the cell. If blank cells to the right also have the fill alignment,
+     * they are also filled with the value, using a convention similar to centerContinuous.
+     * <p>
+     * Additional rules:
+     * <ol>
+     * <li>Only whole values can be appended, not partial values.</li>
+     * <li>The column will not be widened to 'best fit' the filled value</li>
+     * <li>If appending an additional occurrence of the value exceeds the boundary of the cell
+     * left/right edge, don't append the additional occurrence of the value.</li>
+     * <li>The display value of the cell is filled, not the underlying raw number.</li>
+     * </ol>
+     * </p>
+     */
+    FILL,
+
+    /**
+     * The horizontal alignment is justified (flush left and right).
+     * For each line of text, aligns each line of the wrapped text in a cell to the right and left
+     * (except the last line). If no single line of text wraps in the cell, then the text is not justified.
+     */
+    JUSTIFY,
+
+    /**
+     * The horizontal alignment is centered across multiple cells.
+     * The information about how many cells to span is expressed in the Sheet Part,
+     * in the row of the cell in question. For each cell that is spanned in the alignment,
+     * a cell element needs to be written out, with the same style Id which references the centerContinuous alignment.
+     */
+    CENTER_SELECTION,
+
+    /**
+     * Indicates that each 'word' in each line of text inside the cell is evenly distributed
+     * across the width of the cell, with flush right and left margins.
+     * <p>
+     * When there is also an indent value to apply, both the left and right side of the cell
+     * are padded by the indent value.
+     * </p>
+     * <p> A 'word' is a set of characters with no space character in them. </p>
+     * <p> Two lines inside a cell are separated by a carriage return. </p>
+     */
+    DISTRIBUTED
+}
index dd6a8e7d31395270c6056e8b1beea15082b93098..e816c9ac1563773da95f06fb2218d8022beee3e9 100755 (executable)
@@ -1,42 +1,42 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.ss.usermodel;\r
-\r
-/**\r
- * Repersents a picture in a SpreadsheetML document\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public interface Picture {\r
-\r
-    /**\r
-     * Reset the image to the original size.\r
-     */\r
-    void resize();\r
-\r
-    /**\r
-     * Reset the image to the original size.\r
-     *\r
-     * @param scale the amount by which image dimensions are multiplied relative to the original size.\r
-     * <code>resize(1.0)</code> sets the original size, <code>resize(0.5)</code> resize to 50% of the original,\r
-     * <code>resize(2.0)</code> resizes to 200% of the original.\r
-     */\r
-    void resize(double scale);\r
-\r
-    ClientAnchor getPreferredSize();\r
-\r
-}\r
+/* ====================================================================
+   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.ss.usermodel;
+
+/**
+ * Repersents a picture in a SpreadsheetML document
+ *
+ * @author Yegor Kozlov
+ */
+public interface Picture {
+
+    /**
+     * Reset the image to the original size.
+     */
+    void resize();
+
+    /**
+     * Reset the image to the original size.
+     *
+     * @param scale the amount by which image dimensions are multiplied relative to the original size.
+     * <code>resize(1.0)</code> sets the original size, <code>resize(0.5)</code> resize to 50% of the original,
+     * <code>resize(2.0)</code> resizes to 200% of the original.
+     */
+    void resize(double scale);
+
+    ClientAnchor getPreferredSize();
+
+}
index ef8409340c0f9e183b6db3a2fc83c2cb33b26393..3c5747ee5a60ae945a341725fd1c16b5aee474a9 100755 (executable)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-package org.apache.poi.ss.usermodel;\r
-\r
-/**\r
- * All known types of automatic shapes in DrawingML\r
- *\r
- * @author Yegor Kozlov\r
- */\r
-public class ShapeTypes {\r
-    public static final int LINE = 1;\r
-    public static final int LINE_INV = 2;\r
-    public static final int TRIANGLE = 3;\r
-    public static final int RT_TRIANGLE = 4;\r
-    public static final int RECT = 5;\r
-    public static final int DIAMOND = 6;\r
-    public static final int PARALLELOGRAM = 7;\r
-    public static final int TRAPEZOID = 8;\r
-    public static final int NON_ISOSCELES_TRAPEZOID = 9;\r
-    public static final int PENTAGON = 10;\r
-    public static final int HEXAGON = 11;\r
-    public static final int HEPTAGON = 12;\r
-    public static final int OCTAGON = 13;\r
-    public static final int DECAGON = 14;\r
-    public static final int DODECAGON = 15;\r
-    public static final int STAR_4 = 16;\r
-    public static final int STAR_5 = 17;\r
-    public static final int STAR_6 = 18;\r
-    public static final int STAR_7 = 19;\r
-    public static final int STAR_8 = 20;\r
-    public static final int STAR_10 = 21;\r
-    public static final int STAR_12 = 22;\r
-    public static final int STAR_16 = 23;\r
-    public static final int STAR_24 = 24;\r
-    public static final int STAR_32 = 25;\r
-    public static final int ROUND_RECT = 26;\r
-    public static final int ROUND_1_RECT = 27;\r
-    public static final int ROUND_2_SAME_RECT = 28;\r
-    public static final int ROUND_2_DIAG_RECT = 29;\r
-    public static final int SNIP_ROUND_RECT = 30;\r
-    public static final int SNIP_1_RECT = 31;\r
-    public static final int SNIP_2_SAME_RECT = 32;\r
-    public static final int SNIP_2_DIAG_RECT = 33;\r
-    public static final int PLAQUE = 34;\r
-    public static final int ELLIPSE = 35;\r
-    public static final int TEARDROP = 36;\r
-    public static final int HOME_PLATE = 37;\r
-    public static final int CHEVRON = 38;\r
-    public static final int PIE_WEDGE = 39;\r
-    public static final int PIE = 40;\r
-    public static final int BLOCK_ARC = 41;\r
-    public static final int DONUT = 42;\r
-    public static final int NO_SMOKING = 43;\r
-    public static final int RIGHT_ARROW = 44;\r
-    public static final int LEFT_ARROW = 45;\r
-    public static final int UP_ARROW = 46;\r
-    public static final int DOWN_ARROW = 47;\r
-    public static final int STRIPED_RIGHT_ARROW = 48;\r
-    public static final int NOTCHED_RIGHT_ARROW = 49;\r
-    public static final int BENT_UP_ARROW = 50;\r
-    public static final int LEFT_RIGHT_ARROW = 51;\r
-    public static final int UP_DOWN_ARROW = 52;\r
-    public static final int LEFT_UP_ARROW = 53;\r
-    public static final int LEFT_RIGHT_UP_ARROW = 54;\r
-    public static final int QUAD_ARROW = 55;\r
-    public static final int LEFT_ARROW_CALLOUT = 56;\r
-    public static final int RIGHT_ARROW_CALLOUT = 57;\r
-    public static final int UP_ARROW_CALLOUT = 58;\r
-    public static final int DOWN_ARROW_CALLOUT = 59;\r
-    public static final int LEFT_RIGHT_ARROW_CALLOUT = 60;\r
-    public static final int UP_DOWN_ARROW_CALLOUT = 61;\r
-    public static final int QUAD_ARROW_CALLOUT = 62;\r
-    public static final int BENT_ARROW = 63;\r
-    public static final int UTURN_ARROW = 64;\r
-    public static final int CIRCULAR_ARROW = 65;\r
-    public static final int LEFT_CIRCULAR_ARROW = 66;\r
-    public static final int LEFT_RIGHT_CIRCULAR_ARROW = 67;\r
-    public static final int CURVED_RIGHT_ARROW = 68;\r
-    public static final int CURVED_LEFT_ARROW = 69;\r
-    public static final int CURVED_UP_ARROW = 70;\r
-    public static final int CURVED_DOWN_ARROW = 71;\r
-    public static final int SWOOSH_ARROW = 72;\r
-    public static final int CUBE = 73;\r
-    public static final int CAN = 74;\r
-    public static final int LIGHTNING_BOLT = 75;\r
-    public static final int HEART = 76;\r
-    public static final int SUN = 77;\r
-    public static final int MOON = 78;\r
-    public static final int SMILEY_FACE = 79;\r
-    public static final int IRREGULAR_SEAL_1 = 80;\r
-    public static final int IRREGULAR_SEAL_2 = 81;\r
-    public static final int FOLDED_CORNER = 82;\r
-    public static final int BEVEL = 83;\r
-    public static final int FRAME = 84;\r
-    public static final int HALF_FRAME = 85;\r
-    public static final int CORNER = 86;\r
-    public static final int DIAG_STRIPE = 87;\r
-    public static final int CHORD = 88;\r
-    public static final int ARC = 89;\r
-    public static final int LEFT_BRACKET = 90;\r
-    public static final int RIGHT_BRACKET = 91;\r
-    public static final int LEFT_BRACE = 92;\r
-    public static final int RIGHT_BRACE = 93;\r
-    public static final int BRACKET_PAIR = 94;\r
-    public static final int BRACE_PAIR = 95;\r
-    public static final int STRAIGHT_CONNECTOR_1 = 96;\r
-    public static final int BENT_CONNECTOR_2 = 97;\r
-    public static final int BENT_CONNECTOR_3 = 98;\r
-    public static final int BENT_CONNECTOR_4 = 99;\r
-    public static final int BENT_CONNECTOR_5 = 100;\r
-    public static final int CURVED_CONNECTOR_2 = 101;\r
-    public static final int CURVED_CONNECTOR_3 = 102;\r
-    public static final int CURVED_CONNECTOR_4 = 103;\r
-    public static final int CURVED_CONNECTOR_5 = 104;\r
-    public static final int CALLOUT_1 = 105;\r
-    public static final int CALLOUT_2 = 106;\r
-    public static final int CALLOUT_3 = 107;\r
-    public static final int ACCENT_CALLOUT_1 = 108;\r
-    public static final int ACCENT_CALLOUT_2 = 109;\r
-    public static final int ACCENT_CALLOUT_3 = 110;\r
-    public static final int BORDER_CALLOUT_1 = 111;\r
-    public static final int BORDER_CALLOUT_2 = 112;\r
-    public static final int BORDER_CALLOUT_3 = 113;\r
-    public static final int ACCENT_BORDER_CALLOUT_1 = 114;\r
-    public static final int ACCENT_BORDER_CALLOUT_2 = 115;\r
-    public static final int ACCENT_BORDER_CALLOUT_3 = 116;\r
-    public static final int WEDGE_RECT_CALLOUT = 117;\r
-    public static final int WEDGE_ROUND_RECT_CALLOUT = 118;\r
-    public static final int WEDGE_ELLIPSE_CALLOUT = 119;\r
-    public static final int CLOUD_CALLOUT = 120;\r
-    public static final int CLOUD = 121;\r
-    public static final int RIBBON = 122;\r
-    public static final int RIBBON_2 = 123;\r
-    public static final int ELLIPSE_RIBBON = 124;\r
-    public static final int ELLIPSE_RIBBON_2 = 125;\r
-    public static final int LEFT_RIGHT_RIBBON = 126;\r
-    public static final int VERTICAL_SCROLL = 127;\r
-    public static final int HORIZONTAL_SCROLL = 128;\r
-    public static final int WAVE = 129;\r
-    public static final int DOUBLE_WAVE = 130;\r
-    public static final int PLUS = 131;\r
-    public static final int FLOW_CHART_PROCESS = 132;\r
-    public static final int FLOW_CHART_DECISION = 133;\r
-    public static final int FLOW_CHART_INPUT_OUTPUT = 134;\r
-    public static final int FLOW_CHART_PREDEFINED_PROCESS = 135;\r
-    public static final int FLOW_CHART_INTERNAL_STORAGE = 136;\r
-    public static final int FLOW_CHART_DOCUMENT = 137;\r
-    public static final int FLOW_CHART_MULTIDOCUMENT = 138;\r
-    public static final int FLOW_CHART_TERMINATOR = 139;\r
-    public static final int FLOW_CHART_PREPARATION = 140;\r
-    public static final int FLOW_CHART_MANUAL_INPUT = 141;\r
-    public static final int FLOW_CHART_MANUAL_OPERATION = 142;\r
-    public static final int FLOW_CHART_CONNECTOR = 143;\r
-    public static final int FLOW_CHART_PUNCHED_CARD = 144;\r
-    public static final int FLOW_CHART_PUNCHED_TAPE = 145;\r
-    public static final int FLOW_CHART_SUMMING_JUNCTION = 146;\r
-    public static final int FLOW_CHART_OR = 147;\r
-    public static final int FLOW_CHART_COLLATE = 148;\r
-    public static final int FLOW_CHART_SORT = 149;\r
-    public static final int FLOW_CHART_EXTRACT = 150;\r
-    public static final int FLOW_CHART_MERGE = 151;\r
-    public static final int FLOW_CHART_OFFLINE_STORAGE = 152;\r
-    public static final int FLOW_CHART_ONLINE_STORAGE = 153;\r
-    public static final int FLOW_CHART_MAGNETIC_TAPE = 154;\r
-    public static final int FLOW_CHART_MAGNETIC_DISK = 155;\r
-    public static final int FLOW_CHART_MAGNETIC_DRUM = 156;\r
-    public static final int FLOW_CHART_DISPLAY = 157;\r
-    public static final int FLOW_CHART_DELAY = 158;\r
-    public static final int FLOW_CHART_ALTERNATE_PROCESS = 159;\r
-    public static final int FLOW_CHART_OFFPAGE_CONNECTOR = 160;\r
-    public static final int ACTION_BUTTON_BLANK = 161;\r
-    public static final int ACTION_BUTTON_HOME = 162;\r
-    public static final int ACTION_BUTTON_HELP = 163;\r
-    public static final int ACTION_BUTTON_INFORMATION = 164;\r
-    public static final int ACTION_BUTTON_FORWARD_NEXT = 165;\r
-    public static final int ACTION_BUTTON_BACK_PREVIOUS = 166;\r
-    public static final int ACTION_BUTTON_END = 167;\r
-    public static final int ACTION_BUTTON_BEGINNING = 168;\r
-    public static final int ACTION_BUTTON_RETURN = 169;\r
-    public static final int ACTION_BUTTON_DOCUMENT = 170;\r
-    public static final int ACTION_BUTTON_SOUND = 171;\r
-    public static final int ACTION_BUTTON_MOVIE = 172;\r
-    public static final int GEAR_6 = 173;\r
-    public static final int GEAR_9 = 174;\r
-    public static final int FUNNEL = 175;\r
-    public static final int MATH_PLUS = 176;\r
-    public static final int MATH_MINUS = 177;\r
-    public static final int MATH_MULTIPLY = 178;\r
-    public static final int MATH_DIVIDE = 179;\r
-    public static final int MATH_EQUAL = 180;\r
-    public static final int MATH_NOT_EQUAL = 181;\r
-    public static final int CORNER_TABS = 182;\r
-    public static final int SQUARE_TABS = 183;\r
-    public static final int PLAQUE_TABS = 184;\r
-    public static final int CHART_X = 185;\r
-    public static final int CHART_STAR = 186;\r
-    public static final int CHART_PLUS = 187;\r
-}\r
+/* ====================================================================
+   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.ss.usermodel;
+
+/**
+ * All known types of automatic shapes in DrawingML
+ *
+ * @author Yegor Kozlov
+ */
+public class ShapeTypes {
+    public static final int LINE = 1;
+    public static final int LINE_INV = 2;
+    public static final int TRIANGLE = 3;
+    public static final int RT_TRIANGLE = 4;
+    public static final int RECT = 5;
+    public static final int DIAMOND = 6;
+    public static final int PARALLELOGRAM = 7;
+    public static final int TRAPEZOID = 8;
+    public static final int NON_ISOSCELES_TRAPEZOID = 9;
+    public static final int PENTAGON = 10;
+    public static final int HEXAGON = 11;
+    public static final int HEPTAGON = 12;
+    public static final int OCTAGON = 13;
+    public static final int DECAGON = 14;
+    public static final int DODECAGON = 15;
+    public static final int STAR_4 = 16;
+    public static final int STAR_5 = 17;
+    public static final int STAR_6 = 18;
+    public static final int STAR_7 = 19;
+    public static final int STAR_8 = 20;
+    public static final int STAR_10 = 21;
+    public static final int STAR_12 = 22;
+    public static final int STAR_16 = 23;
+    public static final int STAR_24 = 24;
+    public static final int STAR_32 = 25;
+    public static final int ROUND_RECT = 26;
+    public static final int ROUND_1_RECT = 27;
+    public static final int ROUND_2_SAME_RECT = 28;
+    public static final int ROUND_2_DIAG_RECT = 29;
+    public static final int SNIP_ROUND_RECT = 30;
+    public static final int SNIP_1_RECT = 31;
+    public static final int SNIP_2_SAME_RECT = 32;
+    public static final int SNIP_2_DIAG_RECT = 33;
+    public static final int PLAQUE = 34;
+    public static final int ELLIPSE = 35;
+    public static final int TEARDROP = 36;
+    public static final int HOME_PLATE = 37;
+    public static final int CHEVRON = 38;
+    public static final int PIE_WEDGE = 39;
+    public static final int PIE = 40;
+    public static final int BLOCK_ARC = 41;
+    public static final int DONUT = 42;
+    public static final int NO_SMOKING = 43;
+    public static final int RIGHT_ARROW = 44;
+    public static final int LEFT_ARROW = 45;
+    public static final int UP_ARROW = 46;
+    public static final int DOWN_ARROW = 47;
+    public static final int STRIPED_RIGHT_ARROW = 48;
+    public static final int NOTCHED_RIGHT_ARROW = 49;
+    public static final int BENT_UP_ARROW = 50;
+    public static final int LEFT_RIGHT_ARROW = 51;
+    public static final int UP_DOWN_ARROW = 52;
+    public static final int LEFT_UP_ARROW = 53;
+    public static final int LEFT_RIGHT_UP_ARROW = 54;
+    public static final int QUAD_ARROW = 55;
+    public static final int LEFT_ARROW_CALLOUT = 56;
+    public static final int RIGHT_ARROW_CALLOUT = 57;
+    public static final int UP_ARROW_CALLOUT = 58;
+    public static final int DOWN_ARROW_CALLOUT = 59;
+    public static final int LEFT_RIGHT_ARROW_CALLOUT = 60;
+    public static final int UP_DOWN_ARROW_CALLOUT = 61;
+    public static final int QUAD_ARROW_CALLOUT = 62;
+    public static final int BENT_ARROW = 63;
+    public static final int UTURN_ARROW = 64;
+    public static final int CIRCULAR_ARROW = 65;
+    public static final int LEFT_CIRCULAR_ARROW = 66;
+    public static final int LEFT_RIGHT_CIRCULAR_ARROW = 67;
+    public static final int CURVED_RIGHT_ARROW = 68;
+    public static final int CURVED_LEFT_ARROW = 69;
+    public static final int CURVED_UP_ARROW = 70;
+    public static final int CURVED_DOWN_ARROW = 71;
+    public static final int SWOOSH_ARROW = 72;
+    public static final int CUBE = 73;
+    public static final int CAN = 74;
+    public static final int LIGHTNING_BOLT = 75;
+    public static final int HEART = 76;
+    public static final int SUN = 77;
+    public static final int MOON = 78;
+    public static final int SMILEY_FACE = 79;
+    public static final int IRREGULAR_SEAL_1 = 80;
+    public static final int IRREGULAR_SEAL_2 = 81;
+    public static final int FOLDED_CORNER = 82;
+    public static final int BEVEL = 83;
+    public static final int FRAME = 84;
+    public static final int HALF_FRAME = 85;
+    public static final int CORNER = 86;
+    public static final int DIAG_STRIPE = 87;
+    public static final int CHORD = 88;
+    public static final int ARC = 89;
+    public static final int LEFT_BRACKET = 90;
+    public static final int RIGHT_BRACKET = 91;
+    public static final int LEFT_BRACE = 92;
+    public static final int RIGHT_BRACE = 93;
+    public static final int BRACKET_PAIR = 94;
+    public static final int BRACE_PAIR = 95;
+    public static final int STRAIGHT_CONNECTOR_1 = 96;
+    public static final int BENT_CONNECTOR_2 = 97;
+    public static final int BENT_CONNECTOR_3 = 98;
+    public static final int BENT_CONNECTOR_4 = 99;
+    public static final int BENT_CONNECTOR_5 = 100;
+    public static final int CURVED_CONNECTOR_2 = 101;
+    public static final int CURVED_CONNECTOR_3 = 102;
+    public static final int CURVED_CONNECTOR_4 = 103;
+    public static final int CURVED_CONNECTOR_5 = 104;
+    public static final int CALLOUT_1 = 105;
+    public static final int CALLOUT_2 = 106;
+    public static final int CALLOUT_3 = 107;
+    public static final int ACCENT_CALLOUT_1 = 108;
+    public static final int ACCENT_CALLOUT_2 = 109;
+    public static final int ACCENT_CALLOUT_3 = 110;
+    public static final int BORDER_CALLOUT_1 = 111;
+    public static final int BORDER_CALLOUT_2 = 112;
+    public static final int BORDER_CALLOUT_3 = 113;
+    public static final int ACCENT_BORDER_CALLOUT_1 = 114;
+    public static final int ACCENT_BORDER_CALLOUT_2 = 115;
+    public static final int ACCENT_BORDER_CALLOUT_3 = 116;
+    public static final int WEDGE_RECT_CALLOUT = 117;
+    public static final int WEDGE_ROUND_RECT_CALLOUT = 118;
+    public static final int WEDGE_ELLIPSE_CALLOUT = 119;
+    public static final int CLOUD_CALLOUT = 120;
+    public static final int CLOUD = 121;
+    public static final int RIBBON = 122;
+    public static final int RIBBON_2 = 123;
+    public static final int ELLIPSE_RIBBON = 124;
+    public static final int ELLIPSE_RIBBON_2 = 125;
+    public static final int LEFT_RIGHT_RIBBON = 126;
+    public static final int VERTICAL_SCROLL = 127;
+    public static final int HORIZONTAL_SCROLL = 128;
+    public static final int WAVE = 129;
+    public static final int DOUBLE_WAVE = 130;
+    public static final int PLUS = 131;
+    public static final int FLOW_CHART_PROCESS = 132;
+    public static final int FLOW_CHART_DECISION = 133;
+    public static final int FLOW_CHART_INPUT_OUTPUT = 134;
+    public static final int FLOW_CHART_PREDEFINED_PROCESS = 135;
+    public static final int FLOW_CHART_INTERNAL_STORAGE = 136;
+    public static final int FLOW_CHART_DOCUMENT = 137;
+    public static final int FLOW_CHART_MULTIDOCUMENT = 138;
+    public static final int FLOW_CHART_TERMINATOR = 139;
+    public static final int FLOW_CHART_PREPARATION = 140;
+    public static final int FLOW_CHART_MANUAL_INPUT = 141;
+    public static final int FLOW_CHART_MANUAL_OPERATION = 142;
+    public static final int FLOW_CHART_CONNECTOR = 143;
+    public static final int FLOW_CHART_PUNCHED_CARD = 144;
+    public static final int FLOW_CHART_PUNCHED_TAPE = 145;
+    public static final int FLOW_CHART_SUMMING_JUNCTION = 146;
+    public static final int FLOW_CHART_OR = 147;
+    public static final int FLOW_CHART_COLLATE = 148;
+    public static final int FLOW_CHART_SORT = 149;
+    public static final int FLOW_CHART_EXTRACT = 150;
+    public static final int FLOW_CHART_MERGE = 151;
+    public static final int FLOW_CHART_OFFLINE_STORAGE = 152;
+    public static final int FLOW_CHART_ONLINE_STORAGE = 153;
+    public static final int FLOW_CHART_MAGNETIC_TAPE = 154;
+    public static final int FLOW_CHART_MAGNETIC_DISK = 155;
+    public static final int FLOW_CHART_MAGNETIC_DRUM = 156;
+    public static final int FLOW_CHART_DISPLAY = 157;
+    public static final int FLOW_CHART_DELAY = 158;
+    public static final int FLOW_CHART_ALTERNATE_PROCESS = 159;
+    public static final int FLOW_CHART_OFFPAGE_CONNECTOR = 160;
+    public static final int ACTION_BUTTON_BLANK = 161;
+    public static final int ACTION_BUTTON_HOME = 162;
+    public static final int ACTION_BUTTON_HELP = 163;
+    public static final int ACTION_BUTTON_INFORMATION = 164;
+    public static final int ACTION_BUTTON_FORWARD_NEXT = 165;
+    public static final int ACTION_BUTTON_BACK_PREVIOUS = 166;
+    public static final int ACTION_BUTTON_END = 167;
+    public static final int ACTION_BUTTON_BEGINNING = 168;
+    public static final int ACTION_BUTTON_RETURN = 169;
+    public static final int ACTION_BUTTON_DOCUMENT = 170;
+    public static final int ACTION_BUTTON_SOUND = 171;
+    public static final int ACTION_BUTTON_MOVIE = 172;
+    public static final int GEAR_6 = 173;
+    public static final int GEAR_9 = 174;
+    public static final int FUNNEL = 175;
+    public static final int MATH_PLUS = 176;
+    public static final int MATH_MINUS = 177;
+    public static final int MATH_MULTIPLY = 178;
+    public static final int MATH_DIVIDE = 179;
+    public static final int MATH_EQUAL = 180;
+    public static final int MATH_NOT_EQUAL = 181;
+    public static final int CORNER_TABS = 182;
+    public static final int SQUARE_TABS = 183;
+    public static final int PLAQUE_TABS = 184;
+    public static final int CHART_X = 185;
+    public static final int CHART_STAR = 186;
+    public static final int CHART_PLUS = 187;
+}
index 2f93273287c7df47a7cc1a7c6967dabe05529d73..398565d04352cc9a6297d5b647184fddb06f99f7 100755 (executable)
@@ -1,69 +1,69 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.ss.usermodel;\r
-\r
-/**\r
- * This enumeration value indicates the type of vertical alignment for a cell, i.e.,\r
- * whether it is aligned top, bottom, vertically centered, justified or distributed.\r
- */\r
-public enum VerticalAlignment {\r
-    /**\r
-     * The vertical alignment is aligned-to-top.\r
-     */\r
-    TOP,\r
-\r
-    /**\r
-     * The vertical alignment is centered across the height of the cell.\r
-     */\r
-    CENTER,\r
-\r
-    /**\r
-     * The vertical alignment is aligned-to-bottom.\r
-     */\r
-    BOTTOM,\r
-\r
-    /**\r
-     * <p>\r
-     * When text direction is horizontal: the vertical alignment of lines of text is distributed vertically,\r
-     * where each line of text inside the cell is evenly distributed across the height of the cell,\r
-     * with flush top and bottom margins.\r
-     * </p>\r
-     * <p>\r
-     * When text direction is vertical: similar behavior as horizontal justification.\r
-     * The alignment is justified (flush top and bottom in this case). For each line of text, each\r
-     * line of the wrapped text in a cell is aligned to the top and bottom (except the last line).\r
-     * If no single line of text wraps in the cell, then the text is not justified.\r
-     *  </p>\r
-     */\r
-    JUSTIFY,\r
-\r
-    /**\r
-     * <p>\r
-     * When text direction is horizontal: the vertical alignment of lines of text is distributed vertically,\r
-     * where each line of text inside the cell is evenly distributed across the height of the cell,\r
-     * with flush top\r
-     * </p>\r
-     * <p>\r
-     * When text direction is vertical: behaves exactly as distributed horizontal alignment.\r
-     * The first words in a line of text (appearing at the top of the cell) are flush\r
-     * with the top edge of the cell, and the last words of a line of text are flush with the bottom edge of the cell,\r
-     * and the line of text is distributed evenly from top to bottom.\r
-     * </p>\r
-     */\r
-    DISTRIBUTED\r
-}\r
+/* ====================================================================
+   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.ss.usermodel;
+
+/**
+ * This enumeration value indicates the type of vertical alignment for a cell, i.e.,
+ * whether it is aligned top, bottom, vertically centered, justified or distributed.
+ */
+public enum VerticalAlignment {
+    /**
+     * The vertical alignment is aligned-to-top.
+     */
+    TOP,
+
+    /**
+     * The vertical alignment is centered across the height of the cell.
+     */
+    CENTER,
+
+    /**
+     * The vertical alignment is aligned-to-bottom.
+     */
+    BOTTOM,
+
+    /**
+     * <p>
+     * When text direction is horizontal: the vertical alignment of lines of text is distributed vertically,
+     * where each line of text inside the cell is evenly distributed across the height of the cell,
+     * with flush top and bottom margins.
+     * </p>
+     * <p>
+     * When text direction is vertical: similar behavior as horizontal justification.
+     * The alignment is justified (flush top and bottom in this case). For each line of text, each
+     * line of the wrapped text in a cell is aligned to the top and bottom (except the last line).
+     * If no single line of text wraps in the cell, then the text is not justified.
+     *  </p>
+     */
+    JUSTIFY,
+
+    /**
+     * <p>
+     * When text direction is horizontal: the vertical alignment of lines of text is distributed vertically,
+     * where each line of text inside the cell is evenly distributed across the height of the cell,
+     * with flush top
+     * </p>
+     * <p>
+     * When text direction is vertical: behaves exactly as distributed horizontal alignment.
+     * The first words in a line of text (appearing at the top of the cell) are flush
+     * with the top edge of the cell, and the last words of a line of text are flush with the bottom edge of the cell,
+     * and the line of text is distributed evenly from top to bottom.
+     * </p>
+     */
+    DISTRIBUTED
+}
index d8e4395e6438a3607e5e417b2a17775509aa28d9..13282ac378a879acbe6450804379008a275790b5 100644 (file)
@@ -1,34 +1,34 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.util;\r
-/**\r
- * Implementors of this interface allow client code to 'delay' writing to a certain section of a \r
- * data output stream.<br/>\r
- * A typical application is for writing BIFF records when the size is not known until well after\r
- * the header has been written.  The client code can call {@link #createDelayedOutput(int)}\r
- * to reserve two bytes of the output for the 'ushort size' header field.  The delayed output can\r
- * be written at any stage. \r
- * \r
- * @author Josh Micich\r
- */\r
-public interface DelayableLittleEndianOutput extends LittleEndianOutput {\r
-       /**\r
-        * Creates an output stream intended for outputting a sequence of <tt>size</tt> bytes.\r
-        */\r
-       LittleEndianOutput createDelayedOutput(int size);\r
-}\r
+/* ====================================================================
+   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.util;
+/**
+ * Implementors of this interface allow client code to 'delay' writing to a certain section of a
+ * data output stream.<br/>
+ * A typical application is for writing BIFF records when the size is not known until well after
+ * the header has been written.  The client code can call {@link #createDelayedOutput(int)}
+ * to reserve two bytes of the output for the 'ushort size' header field.  The delayed output can
+ * be written at any stage.
+ *
+ * @author Josh Micich
+ */
+public interface DelayableLittleEndianOutput extends LittleEndianOutput {
+       /**
+        * Creates an output stream intended for outputting a sequence of <tt>size</tt> bytes.
+        */
+       LittleEndianOutput createDelayedOutput(int size);
+}
index dafa7eadacd8c734b4a01b25603871beaaa06cbf..d8db24797f085052b1d4d16c7a917ccdcf445502 100644 (file)
@@ -1,34 +1,34 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.util;\r
-/**\r
- * \r
- * @author Josh Micich\r
- */\r
-public interface LittleEndianInput {\r
-       int available();\r
-       byte readByte();\r
-       int readUByte();\r
-       short readShort();\r
-       int readUShort();\r
-       int readInt();\r
-       long readLong();\r
-       double readDouble();\r
-       void readFully(byte[] buf);\r
-       void readFully(byte[] buf, int off, int len);\r
-}\r
+/* ====================================================================
+   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.util;
+/**
+ *
+ * @author Josh Micich
+ */
+public interface LittleEndianInput {
+       int available();
+       byte readByte();
+       int readUByte();
+       short readShort();
+       int readUShort();
+       int readInt();
+       long readLong();
+       double readDouble();
+       void readFully(byte[] buf);
+       void readFully(byte[] buf, int off, int len);
+}
index 622ee23cd432d3bd5183c61b2a512150e867fb3c..1a37964a8f7a747a416a44c838e00b09273751c6 100644 (file)
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.util;\r
-\r
-import java.io.FilterInputStream;\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-\r
-/**\r
- * Wraps an {@link InputStream} providing {@link LittleEndianInput}<p/>\r
- * \r
- * This class does not buffer any input, so the stream read position maintained \r
- * by this class is consistent with that of the inner stream.\r
- * \r
- * @author Josh Micich\r
- */\r
-public class LittleEndianInputStream extends FilterInputStream implements LittleEndianInput {\r
-       public LittleEndianInputStream(InputStream is) {\r
-               super(is);\r
-       }\r
-       public int available() {\r
-               try {\r
-                       return super.available();\r
-               } catch (IOException e) {\r
-                       throw new RuntimeException(e);\r
-               }\r
-       }\r
-       public byte readByte() {\r
-               return (byte)readUByte();\r
-       }\r
-       public int readUByte() {\r
-               int ch;\r
-               try {\r
-                       ch = in.read();\r
-               } catch (IOException e) {\r
-                       throw new RuntimeException(e);\r
-               }\r
-               checkEOF(ch);\r
-               return ch;\r
-       }\r
-       public double readDouble() {\r
-               return Double.longBitsToDouble(readLong());\r
-       }\r
-       public int readInt() {\r
-               int ch1;\r
-               int ch2;\r
-               int ch3;\r
-               int ch4;\r
-               try {\r
-                       ch1 = in.read();\r
-                       ch2 = in.read();\r
-                       ch3 = in.read();\r
-                       ch4 = in.read();\r
-               } catch (IOException e) {\r
-                       throw new RuntimeException(e);\r
-               }\r
-               checkEOF(ch1 | ch2 | ch3 | ch4);\r
-               return (ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0);\r
-       }\r
-       public long readLong() {\r
-               int b0;\r
-               int b1;\r
-               int b2;\r
-               int b3;\r
-               int b4;\r
-               int b5;\r
-               int b6;\r
-               int b7;\r
-               try {\r
-                       b0 = in.read();\r
-                       b1 = in.read();\r
-                       b2 = in.read();\r
-                       b3 = in.read();\r
-                       b4 = in.read();\r
-                       b5 = in.read();\r
-                       b6 = in.read();\r
-                       b7 = in.read();\r
-               } catch (IOException e) {\r
-                       throw new RuntimeException(e);\r
-               }\r
-               checkEOF(b0 | b1 | b2 | b3 | b4 | b5 | b6 | b7);\r
-               return (((long)b7 << 56) +\r
-                               ((long)b6 << 48) +\r
-                               ((long)b5 << 40) +\r
-                               ((long)b4 << 32) +\r
-                               ((long)b3 << 24) +\r
-                               (b2 << 16) +\r
-                               (b1 <<  8) +\r
-                               (b0 <<  0));\r
-       }\r
-       public short readShort() {\r
-               return (short)readUShort();\r
-       }\r
-       public int readUShort() {\r
-               int ch1;\r
-               int ch2;\r
-               try {\r
-                       ch1 = in.read();\r
-                       ch2 = in.read();\r
-               } catch (IOException e) {\r
-                       throw new RuntimeException(e);\r
-               }\r
-               checkEOF(ch1 | ch2);\r
-               return (ch2 << 8) + (ch1 << 0);\r
-       }\r
-       private static void checkEOF(int value) {\r
-               if (value <0) {\r
-                       throw new RuntimeException("Unexpected end-of-file");\r
-               }\r
-       }\r
-\r
-       public void readFully(byte[] buf) {\r
-               readFully(buf, 0, buf.length);\r
-       }\r
-\r
-       public void readFully(byte[] buf, int off, int len) {\r
-               int max = off+len;\r
-               for(int i=off; i<max; i++) {\r
-                       int ch;\r
-                       try {\r
-                               ch = in.read();\r
-                       } catch (IOException e) {\r
-                               throw new RuntimeException(e);\r
-                       }\r
-                       checkEOF(ch);\r
-                       buf[i] = (byte) ch;\r
-               }\r
-       }\r
-}\r
+/* ====================================================================
+   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.util;
+
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Wraps an {@link InputStream} providing {@link LittleEndianInput}<p/>
+ *
+ * This class does not buffer any input, so the stream read position maintained
+ * by this class is consistent with that of the inner stream.
+ *
+ * @author Josh Micich
+ */
+public class LittleEndianInputStream extends FilterInputStream implements LittleEndianInput {
+       public LittleEndianInputStream(InputStream is) {
+               super(is);
+       }
+       public int available() {
+               try {
+                       return super.available();
+               } catch (IOException e) {
+                       throw new RuntimeException(e);
+               }
+       }
+       public byte readByte() {
+               return (byte)readUByte();
+       }
+       public int readUByte() {
+               int ch;
+               try {
+                       ch = in.read();
+               } catch (IOException e) {
+                       throw new RuntimeException(e);
+               }
+               checkEOF(ch);
+               return ch;
+       }
+       public double readDouble() {
+               return Double.longBitsToDouble(readLong());
+       }
+       public int readInt() {
+               int ch1;
+               int ch2;
+               int ch3;
+               int ch4;
+               try {
+                       ch1 = in.read();
+                       ch2 = in.read();
+                       ch3 = in.read();
+                       ch4 = in.read();
+               } catch (IOException e) {
+                       throw new RuntimeException(e);
+               }
+               checkEOF(ch1 | ch2 | ch3 | ch4);
+               return (ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0);
+       }
+       public long readLong() {
+               int b0;
+               int b1;
+               int b2;
+               int b3;
+               int b4;
+               int b5;
+               int b6;
+               int b7;
+               try {
+                       b0 = in.read();
+                       b1 = in.read();
+                       b2 = in.read();
+                       b3 = in.read();
+                       b4 = in.read();
+                       b5 = in.read();
+                       b6 = in.read();
+                       b7 = in.read();
+               } catch (IOException e) {
+                       throw new RuntimeException(e);
+               }
+               checkEOF(b0 | b1 | b2 | b3 | b4 | b5 | b6 | b7);
+               return (((long)b7 << 56) +
+                               ((long)b6 << 48) +
+                               ((long)b5 << 40) +
+                               ((long)b4 << 32) +
+                               ((long)b3 << 24) +
+                               (b2 << 16) +
+                               (b1 <<  8) +
+                               (b0 <<  0));
+       }
+       public short readShort() {
+               return (short)readUShort();
+       }
+       public int readUShort() {
+               int ch1;
+               int ch2;
+               try {
+                       ch1 = in.read();
+                       ch2 = in.read();
+               } catch (IOException e) {
+                       throw new RuntimeException(e);
+               }
+               checkEOF(ch1 | ch2);
+               return (ch2 << 8) + (ch1 << 0);
+       }
+       private static void checkEOF(int value) {
+               if (value <0) {
+                       throw new RuntimeException("Unexpected end-of-file");
+               }
+       }
+
+       public void readFully(byte[] buf) {
+               readFully(buf, 0, buf.length);
+       }
+
+       public void readFully(byte[] buf, int off, int len) {
+               int max = off+len;
+               for(int i=off; i<max; i++) {
+                       int ch;
+                       try {
+                               ch = in.read();
+                       } catch (IOException e) {
+                               throw new RuntimeException(e);
+                       }
+                       checkEOF(ch);
+                       buf[i] = (byte) ch;
+               }
+       }
+}
index 450b337bdbe5f182dbc67edc51a92254d4cf9d1a..708d97bf4a254ed30d216525d8a085b6fde12dc2 100644 (file)
@@ -1,31 +1,31 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.util;\r
-/**\r
- * \r
- * @author Josh Micich\r
- */\r
-public interface LittleEndianOutput {\r
-       void writeByte(int v);\r
-       void writeShort(int v);\r
-       void writeInt(int v);\r
-       void writeLong(long v);\r
-       void writeDouble(double v);\r
-       void write(byte[] b);\r
-       void write(byte[] b, int offset, int len);\r
-}\r
+/* ====================================================================
+   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.util;
+/**
+ *
+ * @author Josh Micich
+ */
+public interface LittleEndianOutput {
+       void writeByte(int v);
+       void writeShort(int v);
+       void writeInt(int v);
+       void writeLong(long v);
+       void writeDouble(double v);
+       void write(byte[] b);
+       void write(byte[] b, int offset, int len);
+}
index 249211d049086d5c492d086057ec9a11a92ed7e0..c8bb9d4b7822aea06d5ec1ecab6085b9277c0a38 100644 (file)
@@ -1,91 +1,91 @@
-/* ====================================================================\r
-   Licensed to the Apache Software Foundation (ASF) under one or more\r
-   contributor license agreements.  See the NOTICE file distributed with\r
-   this work for additional information regarding copyright ownership.\r
-   The ASF licenses this file to You under the Apache License, Version 2.0\r
-   (the "License"); you may not use this file except in compliance with\r
-   the License.  You may obtain a copy of the License at\r
-\r
-       http://www.apache.org/licenses/LICENSE-2.0\r
-\r
-   Unless required by applicable law or agreed to in writing, software\r
-   distributed under the License is distributed on an "AS IS" BASIS,\r
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-   See the License for the specific language governing permissions and\r
-   limitations under the License.\r
-==================================================================== */\r
-\r
-package org.apache.poi.util;\r
-\r
-import java.io.FilterOutputStream;\r
-import java.io.IOException;\r
-import java.io.OutputStream;\r
-\r
-/**\r
- * \r
- * @author Josh Micich\r
- */\r
-public final class LittleEndianOutputStream extends FilterOutputStream implements LittleEndianOutput {\r
-       public LittleEndianOutputStream(OutputStream out) {\r
-               super(out);\r
-       }\r
-\r
-       public void writeByte(int v) {\r
-               try {\r
-                       out.write(v);\r
-               } catch (IOException e) {\r
-                       throw new RuntimeException(e);\r
-               }\r
-       }\r
-\r
-       public void writeDouble(double v) {\r
-               writeLong(Double.doubleToLongBits(v));\r
-       }\r
-\r
-       public void writeInt(int v) {\r
-               int b3 = (v >>> 24) & 0xFF;\r
-               int b2 = (v >>> 16) & 0xFF;\r
-               int b1 = (v >>>  8) & 0xFF;\r
-               int b0 = (v >>>  0) & 0xFF;\r
-               try {\r
-                       out.write(b0);\r
-                       out.write(b1);\r
-                       out.write(b2);\r
-                       out.write(b3);\r
-               } catch (IOException e) {\r
-                       throw new RuntimeException(e);\r
-               }\r
-       }\r
-\r
-       public void writeLong(long v) {\r
-               writeInt((int)(v >>  0));\r
-               writeInt((int)(v >> 32));\r
-       }\r
-\r
-       public void writeShort(int v) {\r
-               int b1 = (v >>>  8) & 0xFF;\r
-               int b0 = (v >>>  0) & 0xFF;\r
-               try {\r
-                       out.write(b0);\r
-                       out.write(b1);\r
-               } catch (IOException e) {\r
-                       throw new RuntimeException(e);\r
-               }\r
-       }\r
-       public void write(byte[] b) {\r
-               // suppress IOException for interface method\r
-               try {\r
-                       super.write(b);\r
-               } catch (IOException e) {\r
-                       throw new RuntimeException(e);\r
-               }\r
-       }\r
-       public void write(byte[] b, int off, int len) {\r
-               // suppress IOException for interface method\r
-               try {\r
-                       super.write(b, off, len);\r
-               } catch (IOException e) {\r
-                       throw new RuntimeException(e);\r
-               }\r
-       }\r
-}\r
+/* ====================================================================
+   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.util;
+
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ *
+ * @author Josh Micich
+ */
+public final class LittleEndianOutputStream extends FilterOutputStream implements LittleEndianOutput {
+       public LittleEndianOutputStream(OutputStream out) {
+               super(out);
+       }
+
+       public void writeByte(int v) {
+               try {
+                       out.write(v);
+               } catch (IOException e) {
+                       throw new RuntimeException(e);
+               }
+       }
+
+       public void writeDouble(double v) {
+               writeLong(Double.doubleToLongBits(v));
+       }
+
+       public void writeInt(int v) {
+               int b3 = (v >>> 24) & 0xFF;
+               int b2 = (v >>> 16) & 0xFF;
+               int b1 = (v >>>  8) & 0xFF;
+               int b0 = (v >>>  0) & 0xFF;
+               try {
+                       out.write(b0);
+                       out.write(b1);
+                       out.write(b2);
+                       out.write(b3);
+               } catch (IOException e) {
+                       throw new RuntimeException(e);
+               }
+       }
+
+       public void writeLong(long v) {
+               writeInt((int)(v >>  0));
+               writeInt((int)(v >> 32));
+       }
+
+       public void writeShort(int v) {
+               int b1 = (v >>>  8) & 0xFF;
+               int b0 = (v >>>  0) & 0xFF;
+               try {
+                       out.write(b0);
+                       out.write(b1);
+               } catch (IOException e) {
+                       throw new RuntimeException(e);
+               }
+       }
+       public void write(byte[] b) {
+               // suppress IOException for interface method
+               try {
+                       super.write(b);
+               } catch (IOException e) {
+                       throw new RuntimeException(e);
+               }
+       }
+       public void write(byte[] b, int off, int len) {
+               // suppress IOException for interface method
+               try {
+                       super.write(b, off, len);
+               } catch (IOException e) {
+                       throw new RuntimeException(e);
+               }
+       }
+}