See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.hssf.contrib.view;
import java.awt.*;
* nearly completely consists of overridden methods.
*
* @author Jason Height
- * @since 16 July 2002
*/
public class SVTableCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
private static final Color black = getAWTColor(new HSSFColor.BLACK());
*
*/
private final Color getAWTColor(int index, Color deflt) {
- HSSFColor clr = (HSSFColor)colors.get(new Integer(index));
+ HSSFColor clr = (HSSFColor)colors.get(Integer.valueOf(index));
if (clr == null) return deflt;
return getAWTColor(clr);
}
short[] rgb = clr.getTriplet();
return new Color(rgb[0],rgb[1],rgb[2]);
}
-
}
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.hssf.contrib.view;
import java.util.*;
* SVTableCell Editor and Renderer helper functions.
*
* @author Jason Height
- * @since 16 July 2002
*/
public class SVTableUtils {
private final static Hashtable colors = HSSFColor.getIndexHash();
* @return The aWTColor value
*/
public final static Color getAWTColor(int index, Color deflt) {
- HSSFColor clr = (HSSFColor) colors.get(new Integer(index));
+ HSSFColor clr = (HSSFColor) colors.get(Integer.valueOf(index));
if (clr == null) {
return deflt;
}
short[] rgb = clr.getTriplet();
return new Color(rgb[0], rgb[1], rgb[2]);
}
-
}
* @see CellStyle for alignment options
*/
public static void setAlignment(Cell cell, Workbook workbook, short align) {
- setCellStyleProperty(cell, workbook, ALIGNMENT, new Short(align));
+ setCellStyleProperty(cell, workbook, ALIGNMENT, Short.valueOf(align));
}
/**
* @param value property value
*/
private static void putShort(Map<String, Object> properties, String name, short value) {
- properties.put(name, new Short(value));
+ properties.put(name, Short.valueOf(value));
}
/**
* @param value property value
*/
private static void putBoolean(Map<String, Object> properties, String name, boolean value) {
- properties.put(name, new Boolean(value));
+ properties.put(name, Boolean.valueOf(value));
}
/**
public CellPropertySetter(Workbook workbook, String propertyName, int value) {
_workbook = workbook;
_propertyName = propertyName;
- _propertyValue = new Short((short) value);
+ _propertyValue = Short.valueOf((short) value);
}
* the summary information and in the document summary information. The
* application reads the name of a POI filesystem from the command line and
* performs the following actions:</p>
- *
+ *
* <ul>
- *
+ *
* <li><p>Open the POI filesystem.</p></li>
- *
+ *
* <li><p>Read the summary information.</p></li>
- *
+ *
* <li><p>Read and print the "author" property.</p></li>
- *
+ *
* <li><p>Change the author to "Rainer Klute".</p></li>
- *
+ *
* <li><p>Read the document summary information.</p></li>
- *
+ *
* <li><p>Read and print the "category" property.</p></li>
- *
+ *
* <li><p>Change the category to "POI example".</p></li>
- *
+ *
* <li><p>Read the custom properties (if available).</p></li>
- *
+ *
* <li><p>Insert a new custom property.</p></li>
- *
+ *
* <li><p>Write the custom properties back to the document summary
* information.</p></li>
- *
+ *
* <li><p>Write the summary information to the POI filesystem.</p></li>
- *
+ *
* <li><p>Write the document summary information to the POI filesystem.</p></li>
- *
+ *
* <li><p>Write the POI filesystem back to the original file.</p></li>
- *
+ *
* </ol>
- *
+ *
* @author Rainer Klute <a
* href="mailto:klute@rainer-klute.de">klute@rainer-klute.de</a>
*/
-public class ModifyDocumentSummaryInformation
-{
+public class ModifyDocumentSummaryInformation {
/**
* <p>Main method - see class description.</p>
*
* @param args The command-line parameters.
- * @throws IOException
- * @throws MarkUnsupportedException
- * @throws NoPropertySetStreamException
- * @throws UnexpectedPropertySetTypeException
- * @throws WritingNotSupportedException
+ * @throws IOException
+ * @throws MarkUnsupportedException
+ * @throws NoPropertySetStreamException
+ * @throws UnexpectedPropertySetTypeException
+ * @throws WritingNotSupportedException
*/
public static void main(final String[] args) throws IOException,
NoPropertySetStreamException, MarkUnsupportedException,
CustomProperties customProperties = dsi.getCustomProperties();
if (customProperties == null)
customProperties = new CustomProperties();
-
+
/* Insert some custom properties into the container. */
customProperties.put("Key 1", "Value 1");
customProperties.put("Schl\u00fcssel 2", "Wert 2");
customProperties.put("Sample Number", new Integer(12345));
- customProperties.put("Sample Boolean", new Boolean(true));
+ customProperties.put("Sample Boolean", Boolean.TRUE);
customProperties.put("Sample Date", new Date());
/* Read a custom property. */
OutputStream out = new FileOutputStream(poiFilesystem);
poifs.writeFilesystem(out);
out.close();
- }
-
+ }
}
return r;
}
- Constructor<? extends EscherRecord> recordConstructor = recordsMap.get(new Short(header.getRecordId()));
+ Constructor<? extends EscherRecord> recordConstructor = recordsMap.get(Short.valueOf(header.getRecordId()));
EscherRecord escherRecord = null;
if (recordConstructor == null) {
return new UnknownEscherRecord();
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
- result.put(new Short(sid), constructor);
+ result.put(Short.valueOf(sid), constructor);
}
return result;
}
{
EscherProperty p1 = (EscherProperty) o1;
EscherProperty p2 = (EscherProperty) o2;
- return new Short( p1.getPropertyNumber() ).compareTo( new Short( p2.getPropertyNumber() ) );
+ return Short.valueOf( p1.getPropertyNumber() ).compareTo( Short.valueOf( p2.getPropertyNumber() ) );
}
} );
}
}
private static void addProp(Map<Short, EscherPropertyMetaData> m, int s, String propName) {
- m.put(new Short((short) s), new EscherPropertyMetaData(propName));
+ m.put(Short.valueOf((short) s), new EscherPropertyMetaData(propName));
}
private static void addProp(Map<Short, EscherPropertyMetaData> m, int s, String propName, byte type) {
- m.put(new Short((short) s), new EscherPropertyMetaData(propName, type));
+ m.put(Short.valueOf((short) s), new EscherPropertyMetaData(propName, type));
}
public static String getPropertyName(short propertyId) {
- EscherPropertyMetaData o = properties.get(new Short(propertyId));
+ EscherPropertyMetaData o = properties.get(Short.valueOf(propertyId));
return o == null ? "unknown" : o.getDescription();
}
public static byte getPropertyType(short propertyId) {
- EscherPropertyMetaData escherPropertyMetaData = properties.get(new Short(propertyId));
+ EscherPropertyMetaData escherPropertyMetaData = properties.get(Short.valueOf(propertyId));
return escherPropertyMetaData == null ? 0 : escherPropertyMetaData.getType();
}
}
* name is the key that maps to a typed value. This implementation hides
* property IDs from the developer and regards the property names as keys to
* typed values.</p>
- *
+ *
* <p>While this class provides a simple API to custom properties, it ignores
* the fact that not names, but IDs are the real keys to properties. Under the
* hood this class maintains a 1:1 relationship between IDs and names. Therefore
* mapping to the same name or with properties without a name: the result will
* contain only a subset of the original properties. If you really need to deal
* such property sets, use HPSF's low-level access methods.</p>
- *
+ *
* <p>An application can call the {@link #isPure} method to check whether a
* property set parsed by {@link CustomProperties} is still pure (i.e.
* unmodified) or whether one or more properties have been dropped.</p>
- *
+ *
* <p>This class is not thread-safe; concurrent access to instances of this
* class must be synchronized.</p>
- *
+ *
* @author Rainer Klute <a
* href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
*/
* <p>Maps property names to property IDs.</p>
*/
private Map dictionaryNameToID = new HashMap();
-
+
/**
* <p>Tells whether this object is pure or not.</p>
*/
") do not match.");
/* Register name and ID in the dictionary. Mapping in both directions is possible. If there is already a */
- final Long idKey = new Long(cp.getID());
+ final Long idKey = Long.valueOf(cp.getID());
final Object oldID = dictionaryNameToID.get(name);
dictionaryIDToName.remove(oldID);
dictionaryNameToID.put(name, idKey);
/**
* <p>Puts a {@link CustomProperty} that has not yet a valid ID into this
* map. The method will allocate a suitable ID for the custom property:</p>
- *
+ *
* <ul>
- *
+ *
* <li><p>If there is already a property with the same name, take the ID
* of that property.</p></li>
- *
+ *
* <li><p>Otherwise find the highest ID and use its value plus one.</p></li>
- *
+ *
* </ul>
- *
+ *
* @param customProperty
* @return If the was already a property with the same name, the
* @throws ClassCastException
/**
* <p>Removes a custom property.</p>
- * @param name The name of the custom property to remove
+ * @param name The name of the custom property to remove
* @return The removed property or <code>null</code> if the specified property was not found.
*
* @see java.util.HashSet#remove(java.lang.Object)
/**
* <p>Adds a named string property.</p>
- *
+ *
* @param name The property's name.
* @param value The property's value.
* @return the property that was stored under the specified name before, or
return put(cp);
}
-
+
/**
* <p>Gets a named value from the custom properties.</p>
- *
+ *
* @param name the name of the value to get
* @return the value or <code>null</code> if a value with the specified
* name is not found in the custom properties.
final CustomProperty cp = new CustomProperty(p, name);
return put(cp);
}
-
+
/**
* Returns a set of all the names of our
* custom properties
*/
public Set keySet() {
- return dictionaryNameToID.keySet();
- }
+ return dictionaryNameToID.keySet();
+ }
- /**
+ /**
* <p>Sets the codepage.</p>
*
* @param codepage the codepage
final MutableProperty p = new MutableProperty();
p.setID(PropertyIDMap.PID_CODEPAGE);
p.setType(Variant.VT_I2);
- p.setValue(new Integer(codepage));
+ p.setValue(Integer.valueOf(codepage));
put(new CustomProperty(p));
}
/**
* <p>Gets the dictionary which contains IDs and names of the named custom
* properties.
- *
+ *
* @return the dictionary.
*/
Map getDictionary()
* <p>Tells whether this {@link CustomProperties} instance is pure or one or
* more properties of the underlying low-level property set has been
* dropped.</p>
- *
+ *
* @return <code>true</code> if the {@link CustomProperties} is pure, else
* <code>false</code>.
*/
{
this.isPure = isPure;
}
-
}
/**
* <p>Gets the custom properties.</p>
- *
+ *
* @return The custom properties.
- * @since 2006-02-09
*/
public CustomProperties getCustomProperties()
{
{
propertyCount++;
final CustomProperty cp = new CustomProperty(p,
- (String) dictionary.get(new Long(id)));
+ (String) dictionary.get(Long.valueOf(id)));
cps.put(cp.getName(), cp);
}
}
/**
* <p>Sets the custom properties.</p>
- *
+ *
* @param customProperties The custom properties
- * @since 2006-02-07
*/
public void setCustomProperties(final CustomProperties customProperties)
{
/**
* <p>Removes the custom properties.</p>
- *
- * @since 2006-02-08
*/
public void removeCustomProperties()
{
{
throw new UnsupportedOperationException(msg + " is not yet implemented.");
}
-
}
/**
- * <p>Constructs a <code>MutableSection</code> by doing a deep copy of an
- * existing <code>Section</code>. All nested <code>Property</code>
+ * <p>Constructs a <code>MutableSection</code> by doing a deep copy of an
+ * existing <code>Section</code>. All nested <code>Property</code>
* instances, will be their mutable counterparts in the new
* <code>MutableSection</code>.</p>
- *
+ *
* @param s The section set to copy
*/
public MutableSection(final Section s)
*/
public void setProperty(final int id, final int value)
{
- setProperty(id, Variant.VT_I4, new Integer(value));
+ setProperty(id, Variant.VT_I4, Integer.valueOf(value));
dirty = true;
}
*/
public void setProperty(final int id, final long value)
{
- setProperty(id, Variant.VT_I8, new Long(value));
+ setProperty(id, Variant.VT_I8, Long.valueOf(value));
dirty = true;
}
*/
public void setProperty(final int id, final boolean value)
{
- setProperty(id, Variant.VT_BOOL, new Boolean(value));
+ setProperty(id, Variant.VT_BOOL, Boolean.valueOf(value));
dirty = true;
}
*/
protected void setPropertyBooleanValue(final int id, final boolean value)
{
- setProperty(id, Variant.VT_BOOL, new Boolean(value));
+ setProperty(id, Variant.VT_BOOL, Boolean.valueOf(value));
}
* properties) and the properties themselves.</p>
*
* @return the section's length in bytes.
- * @throws WritingNotSupportedException
- * @throws IOException
+ * @throws WritingNotSupportedException
+ * @throws IOException
*/
- private int calcSize() throws WritingNotSupportedException, IOException
+ private int calcSize() throws WritingNotSupportedException, IOException
{
final ByteArrayOutputStream out = new ByteArrayOutputStream();
write(out);
/**
* <p>Writes this section into an output stream.</p>
- *
+ *
* <p>Internally this is done by writing into three byte array output
* streams: one for the properties, one for the property list and one for
* the section as such. The two former are appended to the latter when they
* "propertyListStream". */
final ByteArrayOutputStream propertyListStream =
new ByteArrayOutputStream();
-
+
/* Maintain the current position in the list. */
int position = 0;
* dictionary is present. In order to cope with this problem we
* add the codepage property and set it to Unicode. */
setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
- new Integer(Constants.CP_UNICODE));
+ Integer.valueOf(Constants.CP_UNICODE));
codepage = getCodepage();
}
{
final MutableProperty p = (MutableProperty) i.next();
final long id = p.getID();
-
+
/* Write the property list entry. */
TypeWriter.writeUIntToStream(propertyListStream, p.getID());
TypeWriter.writeUIntToStream(propertyListStream, position);
/* Write the section: */
byte[] pb1 = propertyListStream.toByteArray();
byte[] pb2 = propertyStream.toByteArray();
-
+
/* Write the section's length: */
TypeWriter.writeToStream(out, LittleEndian.INT_SIZE * 2 +
pb1.length + pb2.length);
-
+
/* Write the section's number of properties: */
TypeWriter.writeToStream(out, getPropertyCount());
-
+
/* Write the property list: */
out.write(pb1);
-
+
/* Write the properties: */
out.write(pb2);
* <p>Overwrites the super class' method to cope with a redundancy:
* the property count is maintained in a separate member variable, but
* shouldn't.</p>
- *
+ *
* @return The number of properties in this section
*/
public int getPropertyCount()
/**
* <p>Gets this section's properties.</p>
- *
+ *
* @return this section's properties.
*/
public Property[] getProperties()
/**
* <p>Gets a property.</p>
- *
+ *
* @param id The ID of the property to get
* @return The property or <code>null</code> if there is no such property
*/
* method.</p>
*
* @param dictionary The dictionary
- *
+ *
* @exception IllegalPropertySetDataException if the dictionary's key and
* value types are not correct.
- *
+ *
* @see Section#getDictionary()
*/
public void setDictionary(final Map dictionary)
(Integer) getProperty(PropertyIDMap.PID_CODEPAGE);
if (codepage == null)
setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
- new Integer(Constants.CP_UNICODE));
+ Integer.valueOf(Constants.CP_UNICODE));
}
else
/* Setting the dictionary to null means to remove property 0.
/**
* <p>Sets a property.</p>
- *
+ *
* @param id The property ID.
* @param value The property's value. The value's class must be one of those
* supported by HPSF.
public void setCodepage(final int codepage)
{
setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
- new Integer(codepage));
+ Integer.valueOf(codepage));
}
-
}
for (int i = 0; i < nrEntries; i++)
{
/* The key. */
- final Long id = new Long(LittleEndian.getUInt(src, o));
+ final Long id = Long.valueOf(LittleEndian.getUInt(src, o));
o += LittleEndian.INT_SIZE;
/* The value (a string). The length is the either the
this.offset + ple.offset,
ple.length, codepage);
if (p.getID() == PropertyIDMap.PID_CODEPAGE)
- p = new Property(p.getID(), p.getType(), new Integer(codepage));
+ p = new Property(p.getID(), p.getType(), Integer.valueOf(codepage));
properties[i1++] = p;
}
{
String s = null;
if (dictionary != null)
- s = (String) dictionary.get(new Long(pid));
+ s = (String) dictionary.get(Long.valueOf(pid));
if (s == null)
s = SectionIDMap.getPIDString(getFormatID().getBytes(), pid);
if (s == null)
/**
* <p>Denotes a variant type with a length that is unknown to HPSF yet.</p>
*/
- public static final Integer LENGTH_UNKNOWN = new Integer(-2);
+ public static final Integer LENGTH_UNKNOWN = Integer.valueOf(-2);
/**
* <p>Denotes a variant type with a variable length.</p>
*/
- public static final Integer LENGTH_VARIABLE = new Integer(-1);
+ public static final Integer LENGTH_VARIABLE = Integer.valueOf(-1);
/**
* <p>Denotes a variant type with a length of 0 bytes.</p>
*/
- public static final Integer LENGTH_0 = new Integer(0);
+ public static final Integer LENGTH_0 = Integer.valueOf(0);
/**
* <p>Denotes a variant type with a length of 2 bytes.</p>
*/
- public static final Integer LENGTH_2 = new Integer(2);
+ public static final Integer LENGTH_2 = Integer.valueOf(2);
/**
* <p>Denotes a variant type with a length of 4 bytes.</p>
*/
- public static final Integer LENGTH_4 = new Integer(4);
+ public static final Integer LENGTH_4 = Integer.valueOf(4);
/**
* <p>Denotes a variant type with a length of 8 bytes.</p>
*/
- public static final Integer LENGTH_8 = new Integer(8);
+ public static final Integer LENGTH_8 = Integer.valueOf(8);
{
/* Initialize the number-to-name map: */
Map tm1 = new HashMap();
- tm1.put(new Long(0), "VT_EMPTY");
- tm1.put(new Long(1), "VT_NULL");
- tm1.put(new Long(2), "VT_I2");
- tm1.put(new Long(3), "VT_I4");
- tm1.put(new Long(4), "VT_R4");
- tm1.put(new Long(5), "VT_R8");
- tm1.put(new Long(6), "VT_CY");
- tm1.put(new Long(7), "VT_DATE");
- tm1.put(new Long(8), "VT_BSTR");
- tm1.put(new Long(9), "VT_DISPATCH");
- tm1.put(new Long(10), "VT_ERROR");
- tm1.put(new Long(11), "VT_BOOL");
- tm1.put(new Long(12), "VT_VARIANT");
- tm1.put(new Long(13), "VT_UNKNOWN");
- tm1.put(new Long(14), "VT_DECIMAL");
- tm1.put(new Long(16), "VT_I1");
- tm1.put(new Long(17), "VT_UI1");
- tm1.put(new Long(18), "VT_UI2");
- tm1.put(new Long(19), "VT_UI4");
- tm1.put(new Long(20), "VT_I8");
- tm1.put(new Long(21), "VT_UI8");
- tm1.put(new Long(22), "VT_INT");
- tm1.put(new Long(23), "VT_UINT");
- tm1.put(new Long(24), "VT_VOID");
- tm1.put(new Long(25), "VT_HRESULT");
- tm1.put(new Long(26), "VT_PTR");
- tm1.put(new Long(27), "VT_SAFEARRAY");
- tm1.put(new Long(28), "VT_CARRAY");
- tm1.put(new Long(29), "VT_USERDEFINED");
- tm1.put(new Long(30), "VT_LPSTR");
- tm1.put(new Long(31), "VT_LPWSTR");
- tm1.put(new Long(64), "VT_FILETIME");
- tm1.put(new Long(65), "VT_BLOB");
- tm1.put(new Long(66), "VT_STREAM");
- tm1.put(new Long(67), "VT_STORAGE");
- tm1.put(new Long(68), "VT_STREAMED_OBJECT");
- tm1.put(new Long(69), "VT_STORED_OBJECT");
- tm1.put(new Long(70), "VT_BLOB_OBJECT");
- tm1.put(new Long(71), "VT_CF");
- tm1.put(new Long(72), "VT_CLSID");
+ tm1.put(Long.valueOf(0), "VT_EMPTY");
+ tm1.put(Long.valueOf(1), "VT_NULL");
+ tm1.put(Long.valueOf(2), "VT_I2");
+ tm1.put(Long.valueOf(3), "VT_I4");
+ tm1.put(Long.valueOf(4), "VT_R4");
+ tm1.put(Long.valueOf(5), "VT_R8");
+ tm1.put(Long.valueOf(6), "VT_CY");
+ tm1.put(Long.valueOf(7), "VT_DATE");
+ tm1.put(Long.valueOf(8), "VT_BSTR");
+ tm1.put(Long.valueOf(9), "VT_DISPATCH");
+ tm1.put(Long.valueOf(10), "VT_ERROR");
+ tm1.put(Long.valueOf(11), "VT_BOOL");
+ tm1.put(Long.valueOf(12), "VT_VARIANT");
+ tm1.put(Long.valueOf(13), "VT_UNKNOWN");
+ tm1.put(Long.valueOf(14), "VT_DECIMAL");
+ tm1.put(Long.valueOf(16), "VT_I1");
+ tm1.put(Long.valueOf(17), "VT_UI1");
+ tm1.put(Long.valueOf(18), "VT_UI2");
+ tm1.put(Long.valueOf(19), "VT_UI4");
+ tm1.put(Long.valueOf(20), "VT_I8");
+ tm1.put(Long.valueOf(21), "VT_UI8");
+ tm1.put(Long.valueOf(22), "VT_INT");
+ tm1.put(Long.valueOf(23), "VT_UINT");
+ tm1.put(Long.valueOf(24), "VT_VOID");
+ tm1.put(Long.valueOf(25), "VT_HRESULT");
+ tm1.put(Long.valueOf(26), "VT_PTR");
+ tm1.put(Long.valueOf(27), "VT_SAFEARRAY");
+ tm1.put(Long.valueOf(28), "VT_CARRAY");
+ tm1.put(Long.valueOf(29), "VT_USERDEFINED");
+ tm1.put(Long.valueOf(30), "VT_LPSTR");
+ tm1.put(Long.valueOf(31), "VT_LPWSTR");
+ tm1.put(Long.valueOf(64), "VT_FILETIME");
+ tm1.put(Long.valueOf(65), "VT_BLOB");
+ tm1.put(Long.valueOf(66), "VT_STREAM");
+ tm1.put(Long.valueOf(67), "VT_STORAGE");
+ tm1.put(Long.valueOf(68), "VT_STREAMED_OBJECT");
+ tm1.put(Long.valueOf(69), "VT_STORED_OBJECT");
+ tm1.put(Long.valueOf(70), "VT_BLOB_OBJECT");
+ tm1.put(Long.valueOf(71), "VT_CF");
+ tm1.put(Long.valueOf(72), "VT_CLSID");
Map tm2 = new HashMap(tm1.size(), 1.0F);
tm2.putAll(tm1);
numberToName = Collections.unmodifiableMap(tm2);
/* Initialize the number-to-length map: */
tm1.clear();
- tm1.put(new Long(0), LENGTH_0);
- tm1.put(new Long(1), LENGTH_UNKNOWN);
- tm1.put(new Long(2), LENGTH_2);
- tm1.put(new Long(3), LENGTH_4);
- tm1.put(new Long(4), LENGTH_4);
- tm1.put(new Long(5), LENGTH_8);
- tm1.put(new Long(6), LENGTH_UNKNOWN);
- tm1.put(new Long(7), LENGTH_UNKNOWN);
- tm1.put(new Long(8), LENGTH_UNKNOWN);
- tm1.put(new Long(9), LENGTH_UNKNOWN);
- tm1.put(new Long(10), LENGTH_UNKNOWN);
- tm1.put(new Long(11), LENGTH_UNKNOWN);
- tm1.put(new Long(12), LENGTH_UNKNOWN);
- tm1.put(new Long(13), LENGTH_UNKNOWN);
- tm1.put(new Long(14), LENGTH_UNKNOWN);
- tm1.put(new Long(16), LENGTH_UNKNOWN);
- tm1.put(new Long(17), LENGTH_UNKNOWN);
- tm1.put(new Long(18), LENGTH_UNKNOWN);
- tm1.put(new Long(19), LENGTH_UNKNOWN);
- tm1.put(new Long(20), LENGTH_UNKNOWN);
- tm1.put(new Long(21), LENGTH_UNKNOWN);
- tm1.put(new Long(22), LENGTH_UNKNOWN);
- tm1.put(new Long(23), LENGTH_UNKNOWN);
- tm1.put(new Long(24), LENGTH_UNKNOWN);
- tm1.put(new Long(25), LENGTH_UNKNOWN);
- tm1.put(new Long(26), LENGTH_UNKNOWN);
- tm1.put(new Long(27), LENGTH_UNKNOWN);
- tm1.put(new Long(28), LENGTH_UNKNOWN);
- tm1.put(new Long(29), LENGTH_UNKNOWN);
- tm1.put(new Long(30), LENGTH_VARIABLE);
- tm1.put(new Long(31), LENGTH_UNKNOWN);
- tm1.put(new Long(64), LENGTH_8);
- tm1.put(new Long(65), LENGTH_UNKNOWN);
- tm1.put(new Long(66), LENGTH_UNKNOWN);
- tm1.put(new Long(67), LENGTH_UNKNOWN);
- tm1.put(new Long(68), LENGTH_UNKNOWN);
- tm1.put(new Long(69), LENGTH_UNKNOWN);
- tm1.put(new Long(70), LENGTH_UNKNOWN);
- tm1.put(new Long(71), LENGTH_UNKNOWN);
- tm1.put(new Long(72), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(0), LENGTH_0);
+ tm1.put(Long.valueOf(1), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(2), LENGTH_2);
+ tm1.put(Long.valueOf(3), LENGTH_4);
+ tm1.put(Long.valueOf(4), LENGTH_4);
+ tm1.put(Long.valueOf(5), LENGTH_8);
+ tm1.put(Long.valueOf(6), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(7), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(8), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(9), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(10), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(11), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(12), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(13), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(14), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(16), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(17), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(18), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(19), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(20), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(21), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(22), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(23), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(24), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(25), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(26), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(27), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(28), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(29), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(30), LENGTH_VARIABLE);
+ tm1.put(Long.valueOf(31), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(64), LENGTH_8);
+ tm1.put(Long.valueOf(65), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(66), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(67), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(68), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(69), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(70), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(71), LENGTH_UNKNOWN);
+ tm1.put(Long.valueOf(72), LENGTH_UNKNOWN);
tm2 = new HashMap(tm1.size(), 1.0F);
tm2.putAll(tm1);
numberToLength = Collections.unmodifiableMap(tm2);
*/
public static String getVariantName(final long variantType)
{
- final String name = (String) numberToName.get(new Long(variantType));
+ final String name = (String) numberToName.get(Long.valueOf(variantType));
return name != null ? name : "unknown variant type";
}
*/
public static int getVariantLength(final long variantType)
{
- final Long key = new Long((int) variantType);
+ final Long key = Long.valueOf((int) variantType);
final Long length = (Long) numberToLength.get(key);
if (length == null)
return -2;
/**
* <p>Supports reading and writing of variant data.</p>
- *
+ *
* <p><strong>FIXME (3):</strong> Reading and writing should be made more
* uniform than it is now. The following items should be resolved:
- *
+ *
* <ul>
*
* <li><p>Reading requires a length parameter that is 4 byte greater than the
* on or off.</p>
*
* @return <code>true</code> if logging is turned on, else
- * <code>false</code>.
+ * <code>false</code>.
*/
public static boolean isLogUnsupportedTypes()
{
{
if (unsupportedMessage == null)
unsupportedMessage = new LinkedList();
- Long vt = new Long(ex.getVariantType());
+ Long vt = Long.valueOf(ex.getVariantType());
if (!unsupportedMessage.contains(vt))
{
System.err.println(ex.getMessage());
* <p>Checks whether HPSF supports the specified variant type. Unsupported
* types should be implemented included in the {@link #SUPPORTED_TYPES}
* array.</p>
- *
+ *
* @see Variant
* @param variantType the variant type to check
* @return <code>true</code> if HPFS supports this type, else
/**
* <p>Reads a variant type from a byte array.</p>
- *
+ *
* @param src The byte array
* @param offset The offset in the byte array where the variant starts
* @param length The length of the variant including the variant type field
* Read a short. In Java it is represented as an
* Integer object.
*/
- value = new Integer(LittleEndian.getShort(src, o1));
+ value = Integer.valueOf(LittleEndian.getShort(src, o1));
break;
}
case Variant.VT_I4:
* Read a word. In Java it is represented as an
* Integer object.
*/
- value = new Integer(LittleEndian.getInt(src, o1));
+ value = Integer.valueOf(LittleEndian.getInt(src, o1));
break;
}
case Variant.VT_I8:
* Read a double word. In Java it is represented as a
* Long object.
*/
- value = new Long(LittleEndian.getLong(src, o1));
+ value = Long.valueOf(LittleEndian.getLong(src, o1));
break;
}
case Variant.VT_R8:
* while the current implementation calculates it in the Section constructor.
* Test files in Bugzilla 42726 and 45583 clearly show that this approach does not always work.
* The workaround below attempts to gracefully handle such cases instead of throwing exceptions.
- *
+ *
* August 20, 2009
*/
l1 = LittleEndian.getInt(src, o1); o1 += LittleEndian.INT_SIZE;
/**
- * <p>Turns a codepage number into the equivalent character encoding's
+ * <p>Turns a codepage number into the equivalent character encoding's
* name.</p>
*
* @param codepage The codepage number
- *
- * @return The character encoding's name. If the codepage number is 65001,
+ *
+ * @return The character encoding's name. If the codepage number is 65001,
* the encoding name is "UTF-8". All other positive numbers are mapped to
- * "cp" followed by the number, e.g. if the codepage number is 1252 the
+ * "cp" followed by the number, e.g. if the codepage number is 1252 the
* returned character encoding name will be "cp1252".
- *
+ *
* @exception UnsupportedEncodingException if the specified codepage is
* less than zero.
*/
}
case Variant.VT_LPWSTR:
{
- final int nrOfChars = ((String) value).length() + 1;
+ final int nrOfChars = ((String) value).length() + 1;
length += TypeWriter.writeUIntToStream(out, nrOfChars);
char[] s = Util.pad4((String) value);
for (int i = 0; i < s.length; i++)
+ value.getClass().toString() + ", "
+ value.toString());
}
- length += TypeWriter.writeToStream(out,
+ length += TypeWriter.writeToStream(out,
((Integer) value).intValue());
break;
}
}
case Variant.VT_R8:
{
- length += TypeWriter.writeToStream(out,
+ length += TypeWriter.writeToStream(out,
((Double) value).doubleValue());
break;
}
* is a byte array we can write it nevertheless. */
if (value instanceof byte[])
{
- final byte[] b = (byte[]) value;
+ final byte[] b = (byte[]) value;
out.write(b);
length = b.length;
writeUnsupportedTypeMessage
return length;
}
-
}
/** <p>ID of the property that denotes whether read/write access to the
* document is allowed or whether is should be opened as read-only. It can
* have the following values:</p>
- *
+ *
* <table>
* <tbody>
* <tr>
* section of the Document Summary Information property set.
*/
- /**
+ /**
* <p>The entry is a dictionary.</p>
*/
public static final int PID_DICTIONARY = 0;
*/
public static final int PID_CODEPAGE = 1;
- /**
+ /**
* <p>The entry is a string denoting the category the file belongs
* to, e.g. review, memo, etc. This is useful to find documents of
* same type.</p>
*/
public static final int PID_CATEGORY = 2;
- /**
+ /**
* <p>Target format for power point presentation, e.g. 35mm,
* printer, video etc.</p>
*/
public static final int PID_PRESFORMAT = 3;
- /**
+ /**
* <p>Number of bytes.</p>
*/
public static final int PID_BYTECOUNT = 4;
- /**
+ /**
* <p>Number of lines.</p>
*/
public static final int PID_LINECOUNT = 5;
- /**
+ /**
* <p>Number of paragraphs.</p>
*/
public static final int PID_PARCOUNT = 6;
- /**
+ /**
* <p>Number of slides in a power point presentation.</p>
*/
public static final int PID_SLIDECOUNT = 7;
- /**
+ /**
* <p>Number of slides with notes.</p>
*/
public static final int PID_NOTECOUNT = 8;
- /**
+ /**
* <p>Number of hidden slides.</p>
*/
public static final int PID_HIDDENCOUNT = 9;
- /**
+ /**
* <p>Number of multimedia clips, e.g. sound or video.</p>
*/
public static final int PID_MMCLIPCOUNT = 10;
- /**
+ /**
* <p>This entry is set to -1 when scaling of the thumbnail is
* desired. Otherwise the thumbnail should be cropped.</p>
*/
public static final int PID_SCALE = 11;
- /**
+ /**
* <p>This entry denotes an internally used property. It is a
* vector of variants consisting of pairs of a string (VT_LPSTR)
* and a number (VT_I4). The string is a heading name, and the
*/
public static final int PID_HEADINGPAIR = 12;
- /**
+ /**
* <p>This entry contains the names of document parts (word: names
* of the documents in the master document, excel: sheet names,
* power point: slide titles, binder: document names).</p>
*/
public static final int PID_DOCPARTS = 13;
- /**
+ /**
* <p>This entry contains the name of the project manager.</p>
*/
public static final int PID_MANAGER = 14;
- /**
+ /**
* <p>This entry contains the company name.</p>
*/
public static final int PID_COMPANY = 15;
- /**
+ /**
* <p>If this entry is -1 the links are dirty and should be
* re-evaluated.</p>
*/
public static final int PID_LINKSDIRTY = 16;
-
+
/**
* <p>The highest well-known property ID. Applications are free to use higher values for custom purposes.</p>
*/
/**
* <p>Creates a {@link PropertyIDMap}.</p>
- *
+ *
* @param initialCapacity The initial capacity as defined for
* {@link HashMap}
* @param loadFactor The load factor as defined for {@link HashMap}
/**
* <p>Creates a {@link PropertyIDMap} backed by another map.</p>
- *
+ *
* @param map The instance to be created is backed by this map.
*/
public PropertyIDMap(final Map map)
*/
public Object put(final long id, final String idString)
{
- return put(new Long(id), idString);
+ return put(Long.valueOf(id), idString);
}
*/
public Object get(final long id)
{
- return get(new Long(id));
+ return get(Long.valueOf(id));
}
System.out.println("s1: " + s1);
System.out.println("s2: " + s2);
}
-
}
public void processRecordInternally(Record record) {
if (record instanceof FormatRecord) {
FormatRecord fr = (FormatRecord) record;
- _customFormatRecords.put(new Integer(fr.getIndexCode()), fr);
+ _customFormatRecords.put(Integer.valueOf(fr.getIndexCode()), fr);
}
if (record instanceof ExtendedFormatRecord) {
ExtendedFormatRecord xr = (ExtendedFormatRecord) record;
public String getFormatString(int formatIndex) {
String format = null;
if (formatIndex >= HSSFDataFormat.getNumberOfBuiltinBuiltinFormats()) {
- FormatRecord tfr = _customFormatRecords.get(new Integer(formatIndex));
+ FormatRecord tfr = _customFormatRecords.get(Integer.valueOf(formatIndex));
if (tfr == null) {
System.err.println("Requested format at index " + formatIndex
+ ", but it wasn't found");
-
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
limitations under the License.
==================================================================== */
-
package org.apache.poi.hssf.eventusermodel;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
+import java.util.Map;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.RecordFactory;
* @author Andrew C. Oliver (acoliver at apache dot org)
* @author Carey Sublette (careysub@earthling.net)
*/
+public class HSSFRequest {
+ private final Map<Short, List<HSSFListener>> _records;
-public class HSSFRequest
-{
- private HashMap records;
-
- /** Creates a new instance of HSSFRequest */
-
- public HSSFRequest()
- {
- records =
- new HashMap(50); // most folks won't listen for too many of these
- }
-
- /**
- * add an event listener for a particular record type. The trick is you have to know
- * what the records are for or just start with our examples and build on them. Alternatively,
- * you CAN call addListenerForAllRecords and you'll recieve ALL record events in one listener,
- * but if you like to squeeze every last byte of efficiency out of life you my not like this.
- * (its sure as heck what I plan to do)
- *
- * @see #addListenerForAllRecords(HSSFListener)
- *
- * @param lsnr for the event
- * @param sid identifier for the record type this is the .sid static member on the individual records
- * for example req.addListener(myListener, BOFRecord.sid)
- */
+ /** Creates a new instance of HSSFRequest */
+ public HSSFRequest() {
+ _records = new HashMap<Short, List<HSSFListener>>(50); // most folks won't listen for too many of these
+ }
- public void addListener(HSSFListener lsnr, short sid)
- {
- List list = null;
- Object obj = records.get(new Short(sid));
-
- if (obj != null)
- {
- list = ( List ) obj;
- }
- else
- {
- list = new ArrayList(
- 1); // probably most people will use one listener
- list.add(lsnr);
- records.put(new Short(sid), list);
- }
- }
+ /**
+ * add an event listener for a particular record type. The trick is you have to know
+ * what the records are for or just start with our examples and build on them. Alternatively,
+ * you CAN call addListenerForAllRecords and you'll receive ALL record events in one listener,
+ * but if you like to squeeze every last byte of efficiency out of life you my not like this.
+ * (its sure as heck what I plan to do)
+ *
+ * @see #addListenerForAllRecords(HSSFListener)
+ *
+ * @param lsnr for the event
+ * @param sid identifier for the record type this is the .sid static member on the individual records
+ * for example req.addListener(myListener, BOFRecord.sid)
+ */
+ public void addListener(HSSFListener lsnr, short sid) {
+ List<HSSFListener> list = _records.get(Short.valueOf(sid));
- /**
- * This is the equivilent of calling addListener(myListener, sid) for EVERY
- * record in the org.apache.poi.hssf.record package. This is for lazy
- * people like me. You can call this more than once with more than one listener, but
- * that seems like a bad thing to do from a practice-perspective unless you have a
- * compelling reason to do so (like maybe you send the event two places or log it or
- * something?).
- *
- * @param lsnr a single listener to associate with ALL records
- */
+ if (list == null) {
+ list = new ArrayList<HSSFListener>(1); // probably most people will use one listener
+ _records.put(Short.valueOf(sid), list);
+ }
+ list.add(lsnr);
+ }
- public void addListenerForAllRecords(HSSFListener lsnr)
- {
- short[] rectypes = RecordFactory.getAllKnownRecordSIDs();
+ /**
+ * This is the equivalent of calling addListener(myListener, sid) for EVERY
+ * record in the org.apache.poi.hssf.record package. This is for lazy
+ * people like me. You can call this more than once with more than one listener, but
+ * that seems like a bad thing to do from a practice-perspective unless you have a
+ * compelling reason to do so (like maybe you send the event two places or log it or
+ * something?).
+ *
+ * @param lsnr a single listener to associate with ALL records
+ */
+ public void addListenerForAllRecords(HSSFListener lsnr) {
+ short[] rectypes = RecordFactory.getAllKnownRecordSIDs();
- for (int k = 0; k < rectypes.length; k++)
- {
- addListener(lsnr, rectypes[ k ]);
- }
- }
+ for (int k = 0; k < rectypes.length; k++) {
+ addListener(lsnr, rectypes[k]);
+ }
+ }
/**
* Called by HSSFEventFactory, passes the Record to each listener associated with
* @return numeric user-specified result code. If zero continue processing.
* @throws HSSFUserException User exception condition
*/
-
- protected short processRecord(Record rec) throws HSSFUserException
- {
- Object obj = records.get(new Short(rec.getSid()));
- short userCode = 0;
-
- if (obj != null)
- {
- List listeners = ( List ) obj;
-
- for (int k = 0; k < listeners.size(); k++)
- {
- Object listenObj = listeners.get(k);
- if (listenObj instanceof AbortableHSSFListener)
- {
- AbortableHSSFListener listener = ( AbortableHSSFListener ) listenObj;
- userCode = listener.abortableProcessRecord(rec);
- if (userCode!=0) break;
- }
- else
- {
- HSSFListener listener = ( HSSFListener ) listenObj;
+ protected short processRecord(Record rec) throws HSSFUserException {
+ Object obj = _records.get(Short.valueOf(rec.getSid()));
+ short userCode = 0;
+
+ if (obj != null) {
+ List listeners = (List) obj;
+
+ for (int k = 0; k < listeners.size(); k++) {
+ Object listenObj = listeners.get(k);
+ if (listenObj instanceof AbortableHSSFListener) {
+ AbortableHSSFListener listener = (AbortableHSSFListener) listenObj;
+ userCode = listener.abortableProcessRecord(rec);
+ if (userCode != 0)
+ break;
+ } else {
+ HSSFListener listener = (HSSFListener) listenObj;
listener.processRecord(rec);
}
- }
- }
- return userCode;
- }
+ }
+ }
+ return userCode;
+ }
}
dg.setLastMSOSPID( -1 );
dgg.addCluster( dgId, 0 );
dgg.setDrawingsSaved( dgg.getDrawingsSaved() + 1 );
- dgMap.put( new Short( dgId ), dg );
+ dgMap.put( Short.valueOf( dgId ), dg );
return dg;
}
public int allocateShapeId(short drawingGroupId)
{
// Get the last shape id for this drawing group.
- EscherDgRecord dg = (EscherDgRecord) dgMap.get(new Short(drawingGroupId));
+ EscherDgRecord dg = (EscherDgRecord) dgMap.get(Short.valueOf(drawingGroupId));
int lastShapeId = dg.getLastMSOSPID();
public void setColumnWidth(int column, int width) {
if(width > 255*256) throw new IllegalArgumentException("The maximum column width for an individual cell is 255 characters.");
- setColumn(column, null, new Integer(width), null, null, null);
+ setColumn(column, null, Integer.valueOf(width), null, null, null);
}
/**
setColumn( column, null, null, null, Boolean.valueOf(hidden), null);
}
public void setDefaultColumnStyle(int column, int styleIndex) {
- setColumn(column, new Short((short)styleIndex), null, null, null, null);
+ setColumn(column, Short.valueOf((short)styleIndex), null, null, null, null);
}
private void setColumn(int column, Short xfStyle, Integer width, Integer level, Boolean hidden, Boolean collapsed) {
public static Workbook createWorkbook(List<Record> recs) {
if (log.check( POILogger.DEBUG ))
log.log(DEBUG, "Workbook (readfile) created with reclen=",
- new Integer(recs.size()));
+ Integer.valueOf(recs.size()));
Workbook retval = new Workbook();
List<Record> records = new ArrayList<Record>(recs.size() / 3);
retval.records.setRecords(records);
public void setSheetBof(int sheetIndex, int pos) {
if (log.check( POILogger.DEBUG ))
- log.log(DEBUG, "setting bof for sheetnum =", new Integer(sheetIndex),
- " at pos=", new Integer(pos));
+ log.log(DEBUG, "setting bof for sheetnum =", Integer.valueOf(sheetIndex),
+ " at pos=", Integer.valueOf(pos));
checkSheets(sheetIndex);
getBoundSheetRec(sheetIndex)
.setPositionOfBof(pos);
public int getNumSheets() {
if (log.check( POILogger.DEBUG ))
- log.log(DEBUG, "getNumSheets=", new Integer(boundsheets.size()));
+ log.log(DEBUG, "getNumSheets=", Integer.valueOf(boundsheets.size()));
return boundsheets.size();
}
public int getNumExFormats() {
if (log.check( POILogger.DEBUG ))
- log.log(DEBUG, "getXF=", new Integer(numxfs));
+ log.log(DEBUG, "getXF=", Integer.valueOf(numxfs));
return numxfs;
}
UnicodeString retval = sst.getString(str);
if (log.check( POILogger.DEBUG ))
- log.log(DEBUG, "Returning SST for index=", new Integer(str),
+ log.log(DEBUG, "Returning SST for index=", Integer.valueOf(str),
" String= ", retval);
return retval;
}
(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
+ 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,
private Ptg field_2_refPtg;
/** for when the 'formula' doesn't parse properly */
private byte[] field_2_unknownFormulaData;
- /** note- this byte is not present in the encoding if the string length is zero */
+ /** note- this byte is not present in the encoding if the string length is zero */
private boolean field_3_unicode_flag; // Flags whether the string is Unicode.
private String field_4_ole_classname; // Classname of the embedded OLE document (e.g. Word.Document.8)
/** Formulas often have a single non-zero trailing byte.
* This is in a similar position to he pre-streamId padding
- * It is unknown if the value is important (it seems to mirror a value a few bytes earlier)
+ * It is unknown if the value is important (it seems to mirror a value a few bytes earlier)
* */
private Byte field_4_unknownByte;
- private Integer field_5_stream_id; // ID of the OLE stream containing the actual data.
+ private Integer field_5_stream_id; // ID of the OLE stream containing the actual data.
private byte[] field_6_unknown;
int b = in.readByte();
remaining -= LittleEndian.BYTE_SIZE;
if (field_2_refPtg != null && field_4_ole_classname == null) {
- field_4_unknownByte = new Byte((byte)b);
+ field_4_unknownByte = Byte.valueOf((byte)b);
}
}
int nUnexpectedPadding = remaining - dataLenAfterFormula;
// Fetch the stream ID
if (dataLenAfterFormula >= 4) {
- field_5_stream_id = new Integer(in.readInt());
+ field_5_stream_id = Integer.valueOf(in.readInt());
remaining -= LittleEndian.INT_SIZE;
} else {
field_5_stream_id = null;
switch(ptgSid) {
case AreaPtg.sid: return new AreaPtg(in);
case Area3DPtg.sid: return new Area3DPtg(in);
- case RefPtg.sid: return new RefPtg(in);
+ case RefPtg.sid: return new RefPtg(in);
case Ref3DPtg.sid: return new Ref3DPtg(in);
}
return null;
in.readFully(result);
return result;
}
-
+
private int getStreamIDOffset(int formulaSize) {
int result = 2 + 4; // formulaSize + f2unknown_int
result += formulaSize;
-
+
int stringLen;
if (field_4_ole_classname == null) {
// don't write 0x03, stringLen, flag, text
}
// pad to next 2 byte boundary
if ((result % 2) != 0) {
- result ++;
+ result ++;
}
return result;
}
-
+
private int getDataSize(int idOffset) {
int result = 2 + idOffset; // 2 for idOffset short field itself
if (field_5_stream_id != null) {
- result += 4;
+ result += 4;
}
return result + field_6_unknown.length;
}
int formulaSize = field_2_refPtg == null ? field_2_unknownFormulaData.length : field_2_refPtg.getSize();
int idOffset = getStreamIDOffset(formulaSize);
int dataSize = getDataSize(idOffset);
-
+
out.writeShort(sid);
out.writeShort(dataSize);
} else {
field_2_refPtg.write(out);
}
- pos += formulaSize;
+ pos += formulaSize;
int stringLen;
if (field_4_ole_classname == null) {
out.writeShort(stringLen);
pos+=2;
if (stringLen > 0) {
- out.writeByte(field_3_unicode_flag ? 0x01 : 0x00);
- pos+=1;
-
- if (field_3_unicode_flag) {
- StringUtil.putUnicodeLE(field_4_ole_classname, out);
- pos += stringLen * 2;
- } else {
- StringUtil.putCompressedUnicode(field_4_ole_classname, out);
- pos += stringLen;
- }
+ out.writeByte(field_3_unicode_flag ? 0x01 : 0x00);
+ pos+=1;
+
+ if (field_3_unicode_flag) {
+ StringUtil.putUnicodeLE(field_4_ole_classname, out);
+ pos += stringLen * 2;
+ } else {
+ StringUtil.putCompressedUnicode(field_4_ole_classname, out);
+ pos += stringLen;
+ }
}
}
case 0:
break;
default:
- throw new IllegalStateException("Bad padding calculation (" + idOffset + ", " + pos + ")");
+ throw new IllegalStateException("Bad padding calculation (" + idOffset + ", " + pos + ")");
}
if (field_5_stream_id != null) {
out.writeInt(field_5_stream_id.intValue());
- pos += 4;
+ pos += 4;
}
out.write(field_6_unknown);
}
{
if ( recordId == EscherClientDataRecord.RECORD_ID || recordId == EscherTextboxRecord.RECORD_ID )
{
- spEndingOffsets.add( new Integer( offset ) );
+ spEndingOffsets.add( Integer.valueOf( offset ) );
shapes.add( record );
}
}
*/
public final static short NOTE_VISIBLE = 0x2;
- private static final Byte DEFAULT_PADDING = new Byte((byte)0);
+ private static final Byte DEFAULT_PADDING = Byte.valueOf((byte)0);
private int field_1_row;
private int field_2_col;
private String field_6_author;
/**
* Saves padding byte value to reduce delta during round-trip serialization.<br/>
- *
+ *
* The documentation is not clear about how padding should work. In any case
- * Excel(2007) does something different.
+ * Excel(2007) does something different.
*/
private Byte field_7_padding;
field_6_author = StringUtil.readCompressedUnicode(in, length);
}
if (in.available() == 1) {
- field_7_padding = new Byte(in.readByte());
+ field_7_padding = Byte.valueOf(in.readByte());
}
}
for(int k = 0; k < nBreaks; k++) {
Break br = new Break(in);
_breaks.add(br);
- _breakMap.put(new Integer(br.main), br);
+ _breakMap.put(Integer.valueOf(br.main), br);
}
}
*/
public void addBreak(int main, int subFrom, int subTo) {
- Integer key = new Integer(main);
+ Integer key = Integer.valueOf(main);
Break region = _breakMap.get(key);
if(region == null) {
region = new Break(main, subFrom, subTo);
* @param main (zero-based)
*/
public final void removeBreak(int main) {
- Integer rowKey = new Integer(main);
+ Integer rowKey = Integer.valueOf(main);
Break region = _breakMap.get(rowKey);
_breaks.remove(region);
_breakMap.remove(rowKey);
* @return The Break or null if no break exists at the row/col specified.
*/
public final Break getBreak(int main) {
- Integer rowKey = new Integer(main);
+ Integer rowKey = Integer.valueOf(main);
return _breakMap.get(rowKey);
}
* <code>null</code> if the specified record is not interpreted by POI.
*/
public static Class<? extends Record> getRecordClass(int sid) {
- I_RecordCreator rc = _recordCreatorsById.get(new Integer(sid));
+ I_RecordCreator rc = _recordCreatorsById.get(Integer.valueOf(sid));
if (rc == null) {
return null;
}
}
public static Record createSingleRecord(RecordInputStream in) {
- I_RecordCreator constructor = _recordCreatorsById.get(new Integer(in.getSid()));
+ I_RecordCreator constructor = _recordCreatorsById.get(Integer.valueOf(in.getSid()));
if (constructor == null) {
return new UnknownRecord(in);
throw new RecordFormatException(
"Unable to determine record types");
}
- Integer key = new Integer(sid);
+ Integer key = Integer.valueOf(sid);
if (result.containsKey(key)) {
Class<?> prevClass = result.get(key).getRecordClass();
throw new RuntimeException("duplicate record sid 0x" + Integer.toHexString(sid).toUpperCase()
}
result.put(key, new ReflectionRecordCreator(constructor));
}
-// result.put(new Integer(0x0406), result.get(new Integer(0x06)));
+// result.put(Integer.valueOf(0x0406), result.get(Integer.valueOf(0x06)));
return result;
}
_linkPtg = readRefPtg(buf);
switch (linkSize - formulaSize - 6) {
case 1:
- _unknownByte6 = new Byte(in.readByte());
+ _unknownByte6 = Byte.valueOf(in.readByte());
break;
case 0:
_unknownByte6 = null;
* followed by two or more continue records unless there is no actual text. The
* first continue records contain the text data and the last continue record
* contains the formatting runs.<p/>
- *
+ *
* @author Glen Stampoultzis (glens at apache.org)
*/
public final class TextObjectRecord extends ContinuableRecord {
/*
* Note - the next three fields are very similar to those on
* EmbededObjectRefSubRecord(ftPictFmla 0x0009)
- *
+ *
* some observed values for the 4 bytes preceding the formula: C0 5E 86 03
* C0 11 AC 02 80 F1 8A 03 D4 F0 8A 03
*/
/** expect tRef, tRef3D, tArea, tArea3D or tName */
private Ptg _linkRefPtg;
/**
- * Not clear if needed . Excel seems to be OK if this byte is not present.
+ * Not clear if needed . Excel seems to be OK if this byte is not present.
* Value is often the same as the earlier firstColumn byte. */
private Byte _unknownPostFormulaByte;
}
_linkRefPtg = ptgs[0];
if (in.remaining() > 0) {
- _unknownPostFormulaByte = new Byte(in.readByte());
+ _unknownPostFormulaByte = Byte.valueOf(in.readByte());
} else {
_unknownPostFormulaByte = null;
}
}
private void serializeTXORecord(ContinuableRecordOutput out) {
-
+
out.writeShort(field_1_options);
out.writeShort(field_2_textOrientation);
out.writeShort(field_3_reserved4);
out.writeShort(_text.length());
out.writeShort(getFormattingDataLength());
out.writeInt(field_8_reserved7);
-
+
if (_linkRefPtg != null) {
int formulaSize = _linkRefPtg.getSize();
out.writeShort(formulaSize);
serializeTXORecord(out);
if (_text.getString().length() > 0) {
serializeTrailingRecords(out);
- }
+ }
}
private int getFormattingDataLength() {
if (_text.length() < 1) {
- // important - no formatting data if text is empty
+ // important - no formatting data if text is empty
return 0;
}
return (_text.numFormattingRuns() + 1) * FORMAT_RUN_ENCODED_SIZE;
/**
* Get the text orientation field for the TextObjectBase record.
- *
+ *
* @return One of TEXT_ORIENTATION_NONE TEXT_ORIENTATION_TOP_TO_BOTTOM
* TEXT_ORIENTATION_ROT_RIGHT TEXT_ORIENTATION_ROT_LEFT
*/
/**
* Set the text orientation field for the TextObjectBase record.
- *
+ *
* @param textOrientation
* One of TEXT_ORIENTATION_NONE TEXT_ORIENTATION_TOP_TO_BOTTOM
* TEXT_ORIENTATION_ROT_RIGHT TEXT_ORIENTATION_ROT_LEFT
public void setStr(HSSFRichTextString str) {
_text = str;
}
-
+
public Ptg getLinkRefPtg() {
return _linkRefPtg;
}
*/
public final class ColumnInfoRecordsAggregate extends RecordAggregate {
/**
- * List of {@link ColumnInfoRecord}s assumed to be in order
+ * List of {@link ColumnInfoRecord}s assumed to be in order
*/
private final List records;
-
-
+
+
private static final class CIRComparator implements Comparator {
public static final Comparator instance = new CIRComparator();
private CIRComparator() {
}
- public void setColumn(int targetColumnIx, Short xfIndex, Integer width,
+ public void setColumn(int targetColumnIx, Short xfIndex, Integer width,
Integer level, Boolean hidden, Boolean collapsed) {
ColumnInfoRecord ci = null;
int k = 0;
ColumnInfoRecord ciMid = copyColInfo(ci);
ColumnInfoRecord ciEnd = copyColInfo(ci);
int lastcolumn = ci.getLastColumn();
-
+
ciStart.setLastColumn(targetColumnIx - 1);
ciMid.setFirstColumn(targetColumnIx);
ciMid.setLastColumn(targetColumnIx);
setColumnInfoFields(ciMid, xfIndex, width, level, hidden, collapsed);
insertColumn(++k, ciMid);
-
+
ciEnd.setFirstColumn(targetColumnIx+1);
ciEnd.setLastColumn(lastcolumn);
insertColumn(++k, ciEnd);
- // no need to attemptMergeColInfoRecords because we
+ // no need to attemptMergeColInfoRecords because we
// know both on each side are different
}
}
/**
* Sets all non null fields into the <code>ci</code> parameter.
*/
- private static void setColumnInfoFields(ColumnInfoRecord ci, Short xfStyle, Integer width,
+ private static void setColumnInfoFields(ColumnInfoRecord ci, Short xfStyle, Integer width,
Integer level, Boolean hidden, Boolean collapsed) {
if (xfStyle != null) {
ci.setXFIndex(xfStyle.shortValue());
}
/**
- * Attempts to merge the col info record at the specified index
+ * Attempts to merge the col info record at the specified index
* with either or both of its neighbours
*/
private void attemptMergeColInfoRecords(int colInfoIx) {
int nRecords = records.size();
if (colInfoIx < 0 || colInfoIx >= nRecords) {
- throw new IllegalArgumentException("colInfoIx " + colInfoIx
+ throw new IllegalArgumentException("colInfoIx " + colInfoIx
+ " is out of range (0.." + (nRecords-1) + ")");
}
ColumnInfoRecord currentCol = getColInfo(colInfoIx);
* Creates an outline group for the specified columns, by setting the level
* field for each col info record in the range. {@link ColumnInfoRecord}s
* may be created, split or merged as a result of this operation.
- *
+ *
* @param fromColumnIx
* group from this column (inclusive)
* @param toColumnIx
level = Math.min(7, level);
colInfoSearchStartIdx = Math.max(0, colInfoIdx - 1); // -1 just in case this column is collapsed later.
}
- setColumn(i, null, null, new Integer(level), null, null);
+ setColumn(i, null, null, Integer.valueOf(level), null, null);
}
}
/**
_unknownRecords.add(rec);
}
public void insertRow(RowRecord row) {
- // Integer integer = new Integer(row.getRowNumber());
- _rowRecords.put(new Integer(row.getRowNumber()), row);
+ // Integer integer = Integer.valueOf(row.getRowNumber());
+ _rowRecords.put(Integer.valueOf(row.getRowNumber()), row);
if ((row.getRowNumber() < _firstrow) || (_firstrow == -1)) {
_firstrow = row.getRowNumber();
}
public void removeRow(RowRecord row) {
int rowIndex = row.getRowNumber();
_valuesAgg.removeAllCellsValuesForRow(rowIndex);
- Integer key = new Integer(rowIndex);
+ Integer key = Integer.valueOf(rowIndex);
RowRecord rr = _rowRecords.remove(key);
if (rr == null) {
throw new RuntimeException("Invalid row index (" + key.intValue() + ")");
if (rowIndex < 0 || rowIndex > maxrow) {
throw new IllegalArgumentException("The row number must be between 0 and " + maxrow);
}
- return _rowRecords.get(new Integer(rowIndex));
+ return _rowRecords.get(Integer.valueOf(rowIndex));
}
public int getPhysicalNumberOfRows()
/**
* Temporarily collects <tt>FunctionMetadata</tt> instances for creation of a
* <tt>FunctionMetadataRegistry</tt>.
- *
+ *
* @author Josh Micich
*/
final class FunctionDataBuilder {
byte returnClassCode, byte[] parameterClassCodes, boolean hasFootnote) {
FunctionMetadata fm = new FunctionMetadata(functionIndex, functionName, minParams, maxParams,
returnClassCode, parameterClassCodes);
-
- Integer indexKey = new Integer(functionIndex);
-
-
+
+ Integer indexKey = Integer.valueOf(functionIndex);
+
+
if(functionIndex > _maxFunctionIndex) {
_maxFunctionIndex = functionIndex;
}
if(!hasFootnote || !_mutatingFunctionIndexes.contains(indexKey)) {
throw new RuntimeException("Multiple entries for function name '" + functionName + "'");
}
- _functionDataByIndex.remove(new Integer(prevFM.getIndex()));
+ _functionDataByIndex.remove(Integer.valueOf(prevFM.getIndex()));
}
prevFM = (FunctionMetadata) _functionDataByIndex.get(indexKey);
if(prevFM != null) {
FunctionMetadata fd = jumbledArray[i];
fdIndexArray[fd.getIndex()] = fd;
}
-
+
return new FunctionMetadataRegistry(fdIndexArray, _functionDataByName);
}
-}
\ No newline at end of file
+}
public void addChar( char c, int width )
{
- charWidths.put(new Character(c), new Integer(width));
+ charWidths.put(new Character(c), Integer.valueOf(width));
}
/**
{
for ( int i = 0; i < characters.length; i++ )
{
- charWidths.put( new Character(characters[i]), new Integer(widths[i]));
+ charWidths.put( new Character(characters[i]), Integer.valueOf(widths[i]));
}
}
/**
* @see #getFormat
+ * @return 'wmf', 'jpeg' etc depending on the format. never <code>null</code>
*/
public String suggestFileExtension()
{
if (log.check( POILogger.DEBUG ))
log.log(DEBUG, "Time at start of cell creating in HSSF sheet = ",
- new Long(timestart));
+ Long.valueOf(timestart));
HSSFRow lastrow = null;
// Add every cell to its row
hrow.createCellFromRecord( cval );
if (log.check( POILogger.DEBUG ))
log.log( DEBUG, "record took ",
- new Long( System.currentTimeMillis() - cellstart ) );
+ Long.valueOf( System.currentTimeMillis() - cellstart ) );
}
if (log.check( POILogger.DEBUG ))
log.log(DEBUG, "total sheet cell creation took ",
- new Long(System.currentTimeMillis() - timestart));
+ Long.valueOf(System.currentTimeMillis() - timestart));
}
/**
}
if (_rows.size() > 0) {
- Integer key = new Integer(row.getRowNum());
+ Integer key = Integer.valueOf(row.getRowNum());
HSSFRow removedRow = _rows.remove(key);
if (removedRow != row) {
//should not happen if the input argument is valid
private void addRow(HSSFRow row, boolean addLow)
{
- _rows.put(new Integer(row.getRowNum()), row);
+ _rows.put(Integer.valueOf(row.getRowNum()), row);
if (addLow)
{
_sheet.addRow(row.getRowRecord());
* @return HSSFRow representing the row number or null if its not defined on the sheet
*/
public HSSFRow getRow(int rowIndex) {
- return _rows.get(new Integer(rowIndex));
+ return _rows.get(Integer.valueOf(rowIndex));
}
/**
// So we don't confuse users, give them back
// the same object every time, but create
// them lazily
- Short sIdx = new Short(idx);
+ Short sIdx = Short.valueOf(idx);
if(fonts.containsKey(sIdx)) {
return (HSSFFont)fonts.get(sIdx);
}
for (int i = 0; i < colors.length; i++) {
HSSFColor color = colors[i];
- Integer index1 = new Integer(color.getIndex());
+ Integer index1 = Integer.valueOf(color.getIndex());
if (result.containsKey(index1)) {
HSSFColor prevColor = (HSSFColor)result.get(index1);
throw new RuntimeException("Dup color index (" + index1
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
- return new Integer(s.intValue());
+ return Integer.valueOf(s.intValue());
}
private static HSSFColor[] getAllColors() {
if (sheetIndex < 0) {
throw new RuntimeException("Specified sheet from a different book");
}
- result = new Integer(sheetIndex);
+ result = Integer.valueOf(sheetIndex);
_sheetIndexesBySheet.put(sheet, result);
}
return result.intValue();
if (sheetIndex < 0) {
return -1;
}
- result = new Integer(sheetIndex);
+ result = Integer.valueOf(sheetIndex);
_sheetIndexesByName.put(sheetName, result);
}
return result.intValue();
* <p/>
*
* @author Yegor Kozlov
- *
- * Modified 6/17/09 by Stanislav Shor - positive formats don't need starting '('
- *
+ *
+ * Modified 6/17/09 by Stanislav Shor - positive formats don't need starting '('
+ *
*/
public final class BuiltinFormats {
/**
public static Map<Integer, String> getBuiltinFormats() {
Map<Integer, String> result = new LinkedHashMap<Integer, String>();
for (int i=0; i<_formats.length; i++) {
- result.put(new Integer(i), _formats[i]);
+ result.put(Integer.valueOf(i), _formats[i]);
}
return result;
}
if (format != null) {
return format;
}
- if (formatStr.equals("General") || formatStr.equals("@")) {
+ if ("General".equals(formatStr) || "@".equals(formatStr)) {
if (DataFormatter.isWholeNumber(cellValue)) {
return generalWholeNumFormat;
}
if(mIsMonth) {
sb.append('M');
ms.add(
- new Integer(sb.length() -1)
+ Integer.valueOf(sb.length() -1)
);
} else {
sb.append('m');
{
map = new HashMap(5);
}
-
+
public void addSheetReference(String sheetName, int number) {
- map.put(new Integer(number), sheetName);
- }
+ map.put(Integer.valueOf(number), sheetName);
+ }
public String getSheetName(int number) {
- return (String)map.get(new Integer(number));
+ return (String)map.get(Integer.valueOf(number));
}
-
}
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
package org.apache.poi.util;
* @author Jason Height (jheight at apache dot org)
*/
-public class BitFieldFactory
-{
+public class BitFieldFactory {
private static Map instances = new HashMap();
-
- public static BitField getInstance(final int mask) {
- BitField f = (BitField)instances.get(new Integer(mask));
+
+ public static BitField getInstance(int mask) {
+ BitField f = (BitField)instances.get(Integer.valueOf(mask));
if (f == null) {
f = new BitField(mask);
- instances.put(new Integer(mask), f);
+ instances.put(Integer.valueOf(mask), f);
}
return f;
}
-
-} // end public class BitFieldFactory
-
+}
* @see #readData(String)
*/
public static byte[] readData(InputStream stream, String section ) throws IOException {
-
+
try
{
StringBuffer sectionText = new StringBuffer();
characterCount++;
if ( characterCount == 2 )
{
- bytes.add( new Byte( b ) );
+ bytes.add( Byte.valueOf( b ) );
characterCount = 0;
b = (byte) 0;
}
characterCount++;
if ( characterCount == 2 )
{
- bytes.add( new Byte( b ) );
+ bytes.add( Byte.valueOf( b ) );
characterCount = 0;
b = (byte) 0;
}
{
int index = elements.size();
elements.add(value);
- valueKeyMap.put(value, new Integer(index));
+ valueKeyMap.put(value, Integer.valueOf(index));
return true;
}
for (int j = 0; j < array.length; j++)
{
- results.add(new Byte(array[ j ]));
+ results.add(Byte.valueOf(array[ j ]));
}
}
if (object instanceof char [])
for (int j = 0; j < array.length; j++)
{
- results.add(new Short(array[ j ]));
+ results.add(Short.valueOf(array[ j ]));
}
}
else if (object instanceof int [])
for (int j = 0; j < array.length; j++)
{
- results.add(new Integer(array[ j ]));
+ results.add(Integer.valueOf(array[ j ]));
}
}
else if (object instanceof long [])
for (int j = 0; j < array.length; j++)
{
- results.add(new Long(array[ j ]));
+ results.add(Long.valueOf(array[ j ]));
}
}
else if (object instanceof float [])
import org.apache.poi.hssf.record.RecordInputStream;
/**
* Title: String Utility Description: Collection of string handling utilities<p/>
- *
+ *
* Note - none of the methods in this class deals with {@link org.apache.poi.hssf.record.ContinueRecord}s. For such
* functionality, consider using {@link RecordInputStream
} *
* byte array. it is assumed that string[ offset ] and string[ offset +
* 1 ] contain the first 16-bit unicode character
* @param len the length of the final string
- * @return the converted string
+ * @return the converted string, never <code>null</code>.
* @exception ArrayIndexOutOfBoundsException if offset is out of bounds for
* the byte array (i.e., is negative or is greater than or equal to
* string.length)
* { 0x16, 0x00 } -0x16
*
* @param string the byte array to be converted
- * @return the converted string
+ * @return the converted string, never <code>null</code>
*/
public static String getFromUnicodeLE(byte[] string) {
if(string.length == 0) { return ""; }
* For this encoding, the is16BitFlag is always present even if nChars==0.
*/
public static String readUnicodeString(LittleEndianInput in) {
-
+
int nChars = in.readUShort();
byte flag = in.readByte();
if ((flag & 0x01) == 0) {
* </ol>
* For this encoding, the is16BitFlag is always present even if nChars==0.
* <br/>
- * This method should be used when the nChars field is <em>not</em> stored
- * as a ushort immediately before the is16BitFlag. Otherwise, {@link
- * #readUnicodeString(LittleEndianInput)} can be used.
+ * This method should be used when the nChars field is <em>not</em> stored
+ * as a ushort immediately before the is16BitFlag. Otherwise, {@link
+ * #readUnicodeString(LittleEndianInput)} can be used.
*/
public static String readUnicodeString(LittleEndianInput in, int nChars) {
byte is16Bit = in.readByte();
if ((is16Bit & 0x01) == 0) {
return readCompressedUnicode(in, nChars);
}
- return readUnicodeLE(in, nChars);
- }
+ return readUnicodeLE(in, nChars);
+ }
/**
* OutputStream <tt>out</tt> will get:
* <ol>
* For this encoding, the is16BitFlag is always present even if nChars==0.
*/
public static void writeUnicodeString(LittleEndianOutput out, String value) {
-
+
int nChars = value.length();
out.writeShort(nChars);
boolean is16Bit = hasMultibyte(value);
* </ol>
* For this encoding, the is16BitFlag is always present even if nChars==0.
* <br/>
- * This method should be used when the nChars field is <em>not</em> stored
- * as a ushort immediately before the is16BitFlag. Otherwise, {@link
- * #writeUnicodeString(LittleEndianOutput, String)} can be used.
+ * This method should be used when the nChars field is <em>not</em> stored
+ * as a ushort immediately before the is16BitFlag. Otherwise, {@link
+ * #writeUnicodeString(LittleEndianOutput, String)} can be used.
*/
- public static void writeUnicodeStringFlagAndData(LittleEndianOutput out, String value) {
+ public static void writeUnicodeStringFlagAndData(LittleEndianOutput out, String value) {
boolean is16Bit = hasMultibyte(value);
out.writeByte(is16Bit ? 0x01 : 0x00);
if (is16Bit) {
putCompressedUnicode(value, out);
}
}
-
+
/**
* @return the number of bytes that would be written by {@link #writeUnicodeString(LittleEndianOutput, String)}
*/
}
out.write(bytes);
}
-
+
public static String readUnicodeLE(LittleEndianInput in, int nChars) {
char[] buf = new char[nChars];
for (int i = 0; i < buf.length; i++) {
/**
* check the parameter has multibyte character
- *
+ *
* @param value string to check
* @return boolean result true:string has at least one multibyte character
*/
/**
* Checks to see if a given String needs to be represented as Unicode
- *
+ *
* @param value
* @return true if string needs Unicode to be represented.
*/
import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty;
/**
- * Wrapper around the two different kinds of OOXML properties
+ * Wrapper around the two different kinds of OOXML properties
* a document can have
*/
public class POIXMLProperties {
private ExtendedProperties ext;
private CustomProperties cust;
- private PackagePart extPart;
- private PackagePart custPart;
+ private PackagePart extPart;
+ private PackagePart custPart;
- private static final org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument NEW_EXT_INSTANCE;
- private static final org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument NEW_CUST_INSTANCE;
- static {
- NEW_EXT_INSTANCE = org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument.Factory.newInstance();
- NEW_EXT_INSTANCE.addNewProperties();
+ private static final org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument NEW_EXT_INSTANCE;
+ private static final org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument NEW_CUST_INSTANCE;
+ static {
+ NEW_EXT_INSTANCE = org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument.Factory.newInstance();
+ NEW_EXT_INSTANCE.addNewProperties();
- NEW_CUST_INSTANCE = org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument.Factory.newInstance();
- NEW_CUST_INSTANCE.addNewProperties();
- }
+ NEW_CUST_INSTANCE = org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument.Factory.newInstance();
+ NEW_CUST_INSTANCE.addNewProperties();
+ }
- public POIXMLProperties(OPCPackage docPackage) throws IOException, OpenXML4JException, XmlException {
+ public POIXMLProperties(OPCPackage docPackage) throws IOException, OpenXML4JException, XmlException {
this.pkg = docPackage;
-
+
// Core properties
- core = new CoreProperties((PackagePropertiesPart)pkg.getPackageProperties() );
-
+ core = new CoreProperties((PackagePropertiesPart)pkg.getPackageProperties() );
+
// Extended properties
PackageRelationshipCollection extRel =
pkg.getRelationshipsByType(POIXMLDocument.EXTENDED_PROPERTIES_REL_TYPE);
if(extRel.size() == 1) {
- extPart = pkg.getPart( extRel.getRelationship(0));
- org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument props = org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument.Factory.parse(
- extPart.getInputStream()
+ extPart = pkg.getPart( extRel.getRelationship(0));
+ org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument props = org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument.Factory.parse(
+ extPart.getInputStream()
);
ext = new ExtendedProperties(props);
} else {
- extPart = null;
- ext = new ExtendedProperties((org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument)NEW_EXT_INSTANCE.copy());
- }
-
+ extPart = null;
+ ext = new ExtendedProperties((org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument)NEW_EXT_INSTANCE.copy());
+ }
+
// Custom properties
PackageRelationshipCollection custRel =
pkg.getRelationshipsByType(POIXMLDocument.CUSTOM_PROPERTIES_REL_TYPE);
if(custRel.size() == 1) {
- custPart = pkg.getPart( custRel.getRelationship(0));
- org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument props = org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument.Factory.parse(
+ custPart = pkg.getPart( custRel.getRelationship(0));
+ org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument props = org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument.Factory.parse(
custPart.getInputStream()
);
cust = new CustomProperties(props);
} else {
- custPart = null;
- cust = new CustomProperties((org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument)NEW_CUST_INSTANCE.copy());
+ custPart = null;
+ cust = new CustomProperties((org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument)NEW_CUST_INSTANCE.copy());
}
}
-
+
/**
* Returns the core document properties
*/
public CoreProperties getCoreProperties() {
return core;
}
-
+
/**
* Returns the extended document properties
*/
public ExtendedProperties getExtendedProperties() {
return ext;
}
-
+
/**
* Returns the custom document properties
*/
public CustomProperties getCustomProperties() {
return cust;
}
-
+
/**
* Commit changes to the underlying OPC package
*/
public void commit() throws IOException{
- if(extPart == null && !NEW_EXT_INSTANCE.toString().equals(ext.props.toString())){
- try {
- PackagePartName prtname = PackagingURIHelper.createPartName("/docProps/app.xml");
- pkg.addRelationship(prtname, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties");
- extPart = pkg.createPart(prtname, "application/vnd.openxmlformats-officedocument.extended-properties+xml");
- } catch (InvalidFormatException e){
- throw new POIXMLException(e);
- }
- }
- if(custPart == null && !NEW_CUST_INSTANCE.toString().equals(cust.props.toString())){
- try {
- PackagePartName prtname = PackagingURIHelper.createPartName("/docProps/custom.xml");
- pkg.addRelationship(prtname, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties");
- custPart = pkg.createPart(prtname, "application/vnd.openxmlformats-officedocument.custom-properties+xml");
- } catch (InvalidFormatException e){
- throw new POIXMLException(e);
- }
- }
- if(extPart != null){
- XmlOptions xmlOptions = new XmlOptions(POIXMLDocumentPart.DEFAULT_XML_OPTIONS);
-
- Map<String, String> map = new HashMap<String, String>();
- map.put("http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes", "vt");
- xmlOptions.setSaveSuggestedPrefixes(map);
-
- OutputStream out = extPart.getOutputStream();
- ext.props.save(out, xmlOptions);
- out.close();
- }
- if(custPart != null){
- XmlOptions xmlOptions = new XmlOptions(POIXMLDocumentPart.DEFAULT_XML_OPTIONS);
-
- Map<String, String> map = new HashMap<String, String>();
- map.put("http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes", "vt");
- xmlOptions.setSaveSuggestedPrefixes(map);
-
- OutputStream out = custPart.getOutputStream();
- cust.props.save(out, xmlOptions);
- out.close();
- }
+ if(extPart == null && !NEW_EXT_INSTANCE.toString().equals(ext.props.toString())){
+ try {
+ PackagePartName prtname = PackagingURIHelper.createPartName("/docProps/app.xml");
+ pkg.addRelationship(prtname, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties");
+ extPart = pkg.createPart(prtname, "application/vnd.openxmlformats-officedocument.extended-properties+xml");
+ } catch (InvalidFormatException e){
+ throw new POIXMLException(e);
+ }
+ }
+ if(custPart == null && !NEW_CUST_INSTANCE.toString().equals(cust.props.toString())){
+ try {
+ PackagePartName prtname = PackagingURIHelper.createPartName("/docProps/custom.xml");
+ pkg.addRelationship(prtname, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties");
+ custPart = pkg.createPart(prtname, "application/vnd.openxmlformats-officedocument.custom-properties+xml");
+ } catch (InvalidFormatException e){
+ throw new POIXMLException(e);
+ }
+ }
+ if(extPart != null){
+ XmlOptions xmlOptions = new XmlOptions(POIXMLDocumentPart.DEFAULT_XML_OPTIONS);
+
+ Map<String, String> map = new HashMap<String, String>();
+ map.put("http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes", "vt");
+ xmlOptions.setSaveSuggestedPrefixes(map);
+
+ OutputStream out = extPart.getOutputStream();
+ ext.props.save(out, xmlOptions);
+ out.close();
+ }
+ if(custPart != null){
+ XmlOptions xmlOptions = new XmlOptions(POIXMLDocumentPart.DEFAULT_XML_OPTIONS);
+
+ Map<String, String> map = new HashMap<String, String>();
+ map.put("http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes", "vt");
+ xmlOptions.setSaveSuggestedPrefixes(map);
+
+ OutputStream out = custPart.getOutputStream();
+ cust.props.save(out, xmlOptions);
+ out.close();
+ }
}
-
+
/**
* The core document properties
*/
private CoreProperties(PackagePropertiesPart part) {
this.part = part;
}
-
+
public String getCategory() {
return part.getCategoryProperty().getValue();
}
}
public void setRevision(String revision) {
try {
- new Long(revision);
+ Long.valueOf(revision);
part.setRevisionProperty(revision);
}
catch (NumberFormatException e) {}
}
-
+
public PackagePropertiesPart getUnderlyingProperties() {
return part;
}
}
-
+
/**
* Extended document properties
*/
private ExtendedProperties(org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument props) {
this.props = props;
}
-
+
public org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties getUnderlyingProperties() {
return props.getProperties();
}
}
-
+
/**
* Custom document properties
*/
public class CustomProperties {
- /**
- * Each custom property element contains an fmtid attribute
- * with the same GUID value ({D5CDD505-2E9C-101B-9397-08002B2CF9AE}).
- */
- public static final String FORMAT_ID = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";
+ /**
+ * Each custom property element contains an fmtid attribute
+ * with the same GUID value ({D5CDD505-2E9C-101B-9397-08002B2CF9AE}).
+ */
+ public static final String FORMAT_ID = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";
- private org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument props;
+ private org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument props;
private CustomProperties(org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument props) {
this.props = props;
}
-
+
public org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperties getUnderlyingProperties() {
return props.getProperties();
}
- /**
- * Add a new property
- *
- * @param name the property name
- * @throws IllegalArgumentException if a property with this name already exists
- */
- private CTProperty add(String name) {
- if(contains(name)) {
- throw new IllegalArgumentException("A property with this name " +
- "already exists in the custom properties");
- }
-
- CTProperty p = props.getProperties().addNewProperty();
- int pid = nextPid();
- p.setPid(pid);
- p.setFmtid(FORMAT_ID);
- p.setName(name);
- return p;
- }
-
- /**
- * Add a new string property
- *
- * @throws IllegalArgumentException if a property with this name already exists
- */
- public void addProperty(String name, String value){
- CTProperty p = add(name);
- p.setLpwstr(value);
- }
-
- /**
- * Add a new double property
- *
- * @throws IllegalArgumentException if a property with this name already exists
- */
- public void addProperty(String name, double value){
- CTProperty p = add(name);
- p.setR8(value);
- }
-
- /**
- * Add a new integer property
- *
- * @throws IllegalArgumentException if a property with this name already exists
- */
- public void addProperty(String name, int value){
- CTProperty p = add(name);
- p.setI4(value);
- }
-
- /**
- * Add a new boolean property
- *
- * @throws IllegalArgumentException if a property with this name already exists
- */
- public void addProperty(String name, boolean value){
- CTProperty p = add(name);
- p.setBool(value);
- }
-
- /**
- * Generate next id that uniquely relates a custom property
- *
- * @return next property id starting with 2
- */
- protected int nextPid(){
- int propid = 1;
- for(CTProperty p : props.getProperties().getPropertyArray()){
- if(p.getPid() > propid) propid = p.getPid();
- }
- return propid + 1;
- }
-
- /**
- * Check if a property with this name already exists in the collection of custom properties
- *
- * @param name the name to check
- * @return whether a property with the given name exists in the custom properties
- */
- public boolean contains(String name){
- for(CTProperty p : props.getProperties().getPropertyArray()){
- if(p.getName().equals(name)) return true;
- }
- return false;
- }
- }
+ /**
+ * Add a new property
+ *
+ * @param name the property name
+ * @throws IllegalArgumentException if a property with this name already exists
+ */
+ private CTProperty add(String name) {
+ if(contains(name)) {
+ throw new IllegalArgumentException("A property with this name " +
+ "already exists in the custom properties");
+ }
+
+ CTProperty p = props.getProperties().addNewProperty();
+ int pid = nextPid();
+ p.setPid(pid);
+ p.setFmtid(FORMAT_ID);
+ p.setName(name);
+ return p;
+ }
+
+ /**
+ * Add a new string property
+ *
+ * @throws IllegalArgumentException if a property with this name already exists
+ */
+ public void addProperty(String name, String value){
+ CTProperty p = add(name);
+ p.setLpwstr(value);
+ }
+
+ /**
+ * Add a new double property
+ *
+ * @throws IllegalArgumentException if a property with this name already exists
+ */
+ public void addProperty(String name, double value){
+ CTProperty p = add(name);
+ p.setR8(value);
+ }
+
+ /**
+ * Add a new integer property
+ *
+ * @throws IllegalArgumentException if a property with this name already exists
+ */
+ public void addProperty(String name, int value){
+ CTProperty p = add(name);
+ p.setI4(value);
+ }
+
+ /**
+ * Add a new boolean property
+ *
+ * @throws IllegalArgumentException if a property with this name already exists
+ */
+ public void addProperty(String name, boolean value){
+ CTProperty p = add(name);
+ p.setBool(value);
+ }
+
+ /**
+ * Generate next id that uniquely relates a custom property
+ *
+ * @return next property id starting with 2
+ */
+ protected int nextPid(){
+ int propid = 1;
+ for(CTProperty p : props.getProperties().getPropertyArray()){
+ if(p.getPid() > propid) propid = p.getPid();
+ }
+ return propid + 1;
+ }
+
+ /**
+ * Check if a property with this name already exists in the collection of custom properties
+ *
+ * @param name the name to check
+ * @return whether a property with the given name exists in the custom properties
+ */
+ public boolean contains(String name){
+ for(CTProperty p : props.getProperties().getPropertyArray()){
+ if(p.getName().equals(name)) return true;
+ }
+ return false;
+ }
+ }
}
import org.xml.sax.SAXException;
/**
- *
+ *
* Maps an XLSX to an XML according to one of the mapping defined.
- *
- *
+ *
+ *
* The output XML Schema must respect this limitations:
- *
+ *
* <ul>
* <li> all mandatory elements and attributes must be mapped (enable validation to check this)</li>
- *
+ *
* <li> no <any> in complex type/element declaration </li>
* <li> no <anyAttribute> attributes declaration </li>
* <li> no recursive structures: recursive structures can't be nested more than one level </li>
* <li> no mixed content: an element can't contain simple text and child element(s) together </li>
* <li> no <substitutionGroup> in complex type/element declaration </li>
* </ul>
- *
- * @author Roberto Manicardi
- *
- *
*
+ * @author Roberto Manicardi
*/
-
-
public class XSSFExportToXml implements Comparator<String>{
-
+
private XSSFMap map;
-
+
/**
* Creates a new exporter and sets the mapping to be used when generating the XML output document
- *
+ *
* @param map the mapping rule to be used
*/
- public XSSFExportToXml(XSSFMap map){
+ public XSSFExportToXml(XSSFMap map) {
this.map = map;
}
-
+
/**
- *
- * Exports the data in an XML stream
- *
+ *
+ * Exports the data in an XML stream
+ *
* @param os OutputStream in which will contain the output XML
* @param validate if true, validates the XML againts the XML Schema
* @throws SAXException
public void exportToXML(OutputStream os, boolean validate) throws SAXException{
exportToXML(os,"UTF-8", validate);
}
-
+
private Document getEmptyDocument() throws ParserConfigurationException{
-
-
+
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
- Document doc = docBuilder.newDocument();
+ DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
+ Document doc = docBuilder.newDocument();
-
-
- return doc;
+ return doc;
}
-
+
/**
* Exports the data in an XML stream
- *
+ *
* @param os OutputStream in which will contain the output XML
- * @param encoding the output charset encoding
+ * @param encoding the output charset encoding
* @param validate if true, validates the XML againts the XML Schema
* @throws SAXException
* @throws InvalidFormatException
*/
-
public void exportToXML(OutputStream os, String encoding, boolean validate) throws SAXException{
List<XSSFSingleXmlCell> singleXMLCells = map.getRelatedSingleXMLCell();
List<Table> tables = map.getRelatedTables();
-
+
String rootElement = map.getCtMap().getRootElement();
-
+
try{
-
+
Document doc = getEmptyDocument();
-
- Element root = null;
-
- if(isNamespaceDeclared()){
- root=doc.createElementNS(getNamespace(),rootElement);
- }else{
- root=doc.createElement(rootElement);
- }
- doc.appendChild(root);
-
-
- List<String> xpaths = new Vector<String>();
- Map<String,XSSFSingleXmlCell> singleXmlCellsMappings = new HashMap<String,XSSFSingleXmlCell>();
- Map<String,Table> tableMappings = new HashMap<String,Table>();
-
- for(XSSFSingleXmlCell simpleXmlCell : singleXMLCells){
- xpaths.add(simpleXmlCell.getXpath());
- singleXmlCellsMappings.put(simpleXmlCell.getXpath(), simpleXmlCell);
- }
- for(Table table : tables){
- String commonXPath = table.getCommonXpath();
- xpaths.add(commonXPath);
- tableMappings.put(commonXPath, table);
- }
-
-
- Collections.sort(xpaths,this);
-
- for(String xpath : xpaths){
-
- XSSFSingleXmlCell simpleXmlCell = singleXmlCellsMappings.get(xpath);
- Table table = tableMappings.get(xpath);
-
- if(!xpath.matches(".*\\[.*")){
-
- // Exports elements and attributes mapped with simpleXmlCell
- if(simpleXmlCell!=null){
- XSSFCell cell = simpleXmlCell.getReferencedCell();
- if(cell!=null){
- Node currentNode = getNodeByXPath(xpath,doc.getFirstChild(),doc,false);
- STXmlDataType.Enum dataType = simpleXmlCell.getXmlDataType();
- mapCellOnNode(cell,currentNode,dataType);
- }
- }
-
- // Exports elements and attributes mapped with tables
- if(table!=null){
-
- List<XSSFXmlColumnPr> tableColumns = table.getXmlColumnPrs();
-
- XSSFSheet sheet = table.getXSSFSheet();
-
- int startRow = table.getStartCellReference().getRow();
- // In mappings created with Microsoft Excel the first row contains the table header and must be skipped
- startRow +=1;
-
- int endRow = table.getEndCellReference().getRow();
-
- for(int i = startRow; i<= endRow; i++){
- XSSFRow row = sheet.getRow(i);
-
- Node tableRootNode = getNodeByXPath(table.getCommonXpath(),doc.getFirstChild(),doc,true);
-
- short startColumnIndex = table.getStartCellReference().getCol();
- for(int j = startColumnIndex; j<= table.getEndCellReference().getCol();j++){
- XSSFCell cell = row.getCell(j);
- if(cell!=null){
- XSSFXmlColumnPr pointer = tableColumns.get(j-startColumnIndex);
- String localXPath = pointer.getLocalXPath();
- Node currentNode = getNodeByXPath(localXPath,tableRootNode,doc,false);
- STXmlDataType.Enum dataType = pointer.getXmlDataType();
-
-
- mapCellOnNode(cell,currentNode,dataType);
- }
-
- }
-
- }
-
-
-
- }
- }else{
- // TODO: implement filtering management in xpath
- }
- }
-
- boolean isValid = true;
- if(validate){
- isValid =isValid(doc);
- }
-
-
-
- if(isValid){
-
+
+ Element root = null;
+
+ if (isNamespaceDeclared()) {
+ root=doc.createElementNS(getNamespace(),rootElement);
+ } else {
+ root=doc.createElement(rootElement);
+ }
+ doc.appendChild(root);
+
+
+ List<String> xpaths = new Vector<String>();
+ Map<String,XSSFSingleXmlCell> singleXmlCellsMappings = new HashMap<String,XSSFSingleXmlCell>();
+ Map<String,Table> tableMappings = new HashMap<String,Table>();
+
+ for(XSSFSingleXmlCell simpleXmlCell : singleXMLCells) {
+ xpaths.add(simpleXmlCell.getXpath());
+ singleXmlCellsMappings.put(simpleXmlCell.getXpath(), simpleXmlCell);
+ }
+ for(Table table : tables) {
+ String commonXPath = table.getCommonXpath();
+ xpaths.add(commonXPath);
+ tableMappings.put(commonXPath, table);
+ }
+
+
+ Collections.sort(xpaths,this);
+
+ for(String xpath : xpaths) {
+
+ XSSFSingleXmlCell simpleXmlCell = singleXmlCellsMappings.get(xpath);
+ Table table = tableMappings.get(xpath);
+
+ if (!xpath.matches(".*\\[.*")) {
+
+ // Exports elements and attributes mapped with simpleXmlCell
+ if (simpleXmlCell!=null) {
+ XSSFCell cell = simpleXmlCell.getReferencedCell();
+ if (cell!=null) {
+ Node currentNode = getNodeByXPath(xpath,doc.getFirstChild(),doc,false);
+ STXmlDataType.Enum dataType = simpleXmlCell.getXmlDataType();
+ mapCellOnNode(cell,currentNode,dataType);
+ }
+ }
+
+ // Exports elements and attributes mapped with tables
+ if (table!=null) {
+
+ List<XSSFXmlColumnPr> tableColumns = table.getXmlColumnPrs();
+
+ XSSFSheet sheet = table.getXSSFSheet();
+
+ int startRow = table.getStartCellReference().getRow();
+ // In mappings created with Microsoft Excel the first row contains the table header and must be skipped
+ startRow +=1;
+
+ int endRow = table.getEndCellReference().getRow();
+
+ for(int i = startRow; i<= endRow; i++) {
+ XSSFRow row = sheet.getRow(i);
+
+ Node tableRootNode = getNodeByXPath(table.getCommonXpath(),doc.getFirstChild(),doc,true);
+
+ short startColumnIndex = table.getStartCellReference().getCol();
+ for(int j = startColumnIndex; j<= table.getEndCellReference().getCol();j++) {
+ XSSFCell cell = row.getCell(j);
+ if (cell!=null) {
+ XSSFXmlColumnPr pointer = tableColumns.get(j-startColumnIndex);
+ String localXPath = pointer.getLocalXPath();
+ Node currentNode = getNodeByXPath(localXPath,tableRootNode,doc,false);
+ STXmlDataType.Enum dataType = pointer.getXmlDataType();
+
+
+ mapCellOnNode(cell,currentNode,dataType);
+ }
+
+ }
+
+ }
+
+
+
+ }
+ } else {
+ // TODO: implement filtering management in xpath
+ }
+ }
+
+ boolean isValid = true;
+ if (validate) {
+ isValid =isValid(doc);
+ }
+
+
+
+ if (isValid) {
+
/////////////////
- //Output the XML
-
- //set up a transformer
- TransformerFactory transfac = TransformerFactory.newInstance();
- Transformer trans = transfac.newTransformer();
- trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
- trans.setOutputProperty(OutputKeys.INDENT, "yes");
- trans.setOutputProperty(OutputKeys.ENCODING, encoding);
-
- //create string from xml tree
-
- StreamResult result = new StreamResult(os);
- DOMSource source = new DOMSource(doc);
- trans.transform(source, result);
-
- }
- }catch(ParserConfigurationException e){
+ //Output the XML
+
+ //set up a transformer
+ TransformerFactory transfac = TransformerFactory.newInstance();
+ Transformer trans = transfac.newTransformer();
+ trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+ trans.setOutputProperty(OutputKeys.INDENT, "yes");
+ trans.setOutputProperty(OutputKeys.ENCODING, encoding);
+
+ //create string from xml tree
+
+ StreamResult result = new StreamResult(os);
+ DOMSource source = new DOMSource(doc);
+ trans.transform(source, result);
+
+ }
+ }catch(ParserConfigurationException e) {
e.printStackTrace();
- }catch(TransformerException e){
+ }catch(TransformerException e) {
e.printStackTrace();
}
-
+
}
-
+
/**
* Validate the generated XML against the XML Schema associated with the XSSFMap
- *
+ *
* @param xml the XML to validate
* @return
*/
-
private boolean isValid(Document xml) throws SAXException{
boolean isValid = false;
try{
- String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
- SchemaFactory factory = SchemaFactory.newInstance(language);
-
- Source source = new DOMSource(map.getSchema());
- Schema schema = factory.newSchema(source);
- Validator validator = schema.newValidator();
- validator.validate(new DOMSource(xml));
- //if no exceptions where raised, the document is valid
- isValid=true;
-
-
- }catch(IOException e){
+ String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
+ SchemaFactory factory = SchemaFactory.newInstance(language);
+
+ Source source = new DOMSource(map.getSchema());
+ Schema schema = factory.newSchema(source);
+ Validator validator = schema.newValidator();
+ validator.validate(new DOMSource(xml));
+ //if no exceptions where raised, the document is valid
+ isValid=true;
+
+
+ } catch(IOException e) {
e.printStackTrace();
}
- return isValid;
+ return isValid;
}
-
-
- private void mapCellOnNode(XSSFCell cell, Node node, STXmlDataType.Enum outputDataType){
-
-
+
+
+ private void mapCellOnNode(XSSFCell cell, Node node, STXmlDataType.Enum outputDataType) {
+
String value ="";
- switch (cell.getCellType()){
-
+ switch (cell.getCellType()) {
+
case XSSFCell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break;
case XSSFCell.CELL_TYPE_BOOLEAN: value += cell.getBooleanCellValue(); break;
case XSSFCell.CELL_TYPE_ERROR: value = cell.getErrorCellString(); break;
case XSSFCell.CELL_TYPE_FORMULA: value = cell.getStringCellValue(); break;
case XSSFCell.CELL_TYPE_NUMERIC: value += cell.getRawValue(); break;
default: ;
-
+
}
- if(node instanceof Element){
+ if (node instanceof Element) {
Element currentElement = (Element) node;
currentElement.setTextContent(value);
- }else{
+ } else {
node.setNodeValue(value);
- }
-
-
+ }
}
-
- private String removeNamespace(String elementName){
+
+ private String removeNamespace(String elementName) {
return elementName.matches(".*:.*")?elementName.split(":")[1]:elementName;
}
-
-
-
- private Node getNodeByXPath(String xpath,Node rootNode,Document doc,boolean createMultipleInstances){
+
+
+
+ private Node getNodeByXPath(String xpath,Node rootNode,Document doc,boolean createMultipleInstances) {
String[] xpathTokens = xpath.split("/");
-
-
+
+
Node currentNode =rootNode;
// The first token is empty, the second is the root node
- for(int i =2; i<xpathTokens.length;i++){
-
+ for(int i =2; i<xpathTokens.length;i++) {
+
String axisName = removeNamespace(xpathTokens[i]);
-
- if(!axisName.startsWith("@")){
-
- NodeList list =currentNode.getChildNodes();
-
- Node selectedNode = null;
- if(!(createMultipleInstances && i==xpathTokens.length-1) ){
- // select the last child node only if we need to map to a single cell
- selectedNode = selectNode(axisName, list);
+
+ if (!axisName.startsWith("@")) {
+
+ NodeList list =currentNode.getChildNodes();
+
+ Node selectedNode = null;
+ if (!(createMultipleInstances && i==xpathTokens.length-1) ) {
+ // select the last child node only if we need to map to a single cell
+ selectedNode = selectNode(axisName, list);
}
- if(selectedNode==null){
- selectedNode = createElement(doc, currentNode, axisName);
- }
- currentNode = selectedNode;
- }else{
-
-
+ if (selectedNode==null) {
+ selectedNode = createElement(doc, currentNode, axisName);
+ }
+ currentNode = selectedNode;
+ } else {
+
+
Node attribute = createAttribute(doc, currentNode, axisName);
-
- currentNode = attribute;
-
+
+ currentNode = attribute;
}
-
}
return currentNode;
}
String attributeName = axisName.substring(1);
NamedNodeMap attributesMap = currentNode.getAttributes();
Node attribute = attributesMap.getNamedItem(attributeName);
- if(attribute==null){
+ if (attribute==null) {
attribute = doc.createAttribute(attributeName);
attributesMap.setNamedItem(attribute);
}
private Node createElement(Document doc, Node currentNode, String axisName) {
Node selectedNode;
- if(isNamespaceDeclared()){
+ if (isNamespaceDeclared()) {
selectedNode =doc.createElementNS(getNamespace(),axisName);
- }else{
+ } else {
selectedNode =doc.createElement(axisName);
}
currentNode.appendChild(selectedNode);
private Node selectNode(String axisName, NodeList list) {
Node selectedNode = null;
- for(int j=0;j<list.getLength();j++){
+ for(int j=0;j<list.getLength();j++) {
Node node = list.item(j);
- if(node.getNodeName().equals(axisName)){
+ if (node.getNodeName().equals(axisName)) {
selectedNode=node;
break;
}
}
return selectedNode;
}
-
-
- private boolean isNamespaceDeclared(){
+
+
+ private boolean isNamespaceDeclared() {
String schemaNamespace = getNamespace();
return schemaNamespace!=null && !schemaNamespace.equals("");
}
-
- private String getNamespace(){
+
+ private String getNamespace() {
return map.getCTSchema().getNamespace();
}
-
+
/**
* Compares two xpaths to define an ordering according to the XML Schema
- *
+ *
*/
public int compare(String leftXpath, String rightXpath) {
-
- int result = 0;
+
+ int result = 0;
Node xmlSchema = map.getSchema();
-
-
-
-
+
+
String[] leftTokens = leftXpath.split("/");
String[] rightTokens = rightXpath.split("/");
-
+
int minLenght = leftTokens.length< rightTokens.length? leftTokens.length : rightTokens.length;
-
+
Node localComplexTypeRootNode = xmlSchema;
-
-
- for(int i =1;i <minLenght; i++){
-
+
+
+ for(int i =1;i <minLenght; i++) {
+
String leftElementName =leftTokens[i];
String rightElementName = rightTokens[i];
-
- if(leftElementName.equals(rightElementName)){
-
-
+
+ if (leftElementName.equals(rightElementName)) {
+
+
Node complexType = getComplexTypeForElement(leftElementName, xmlSchema,localComplexTypeRootNode);
- localComplexTypeRootNode = complexType;
- }else{
+ localComplexTypeRootNode = complexType;
+ } else {
int leftIndex = indexOfElementInComplexType(leftElementName,localComplexTypeRootNode);
int rightIndex = indexOfElementInComplexType(rightElementName,localComplexTypeRootNode);
- if(leftIndex!=-1 && rightIndex!=-1){
- if( leftIndex < rightIndex){
+ if (leftIndex!=-1 && rightIndex!=-1) {
+ if ( leftIndex < rightIndex) {
result = -1;
- }if( leftIndex > rightIndex){
- result = 1;
+ }if ( leftIndex > rightIndex) {
+ result = 1;
}
- }else{
+ } else {
// NOTE: the xpath doesn't match correctly in the schema
}
-
-
}
-
}
-
-
-
-
+
return result;
}
-
- private int indexOfElementInComplexType(String elementName,Node complexType){
-
+
+ private int indexOfElementInComplexType(String elementName,Node complexType) {
+
NodeList list = complexType.getChildNodes();
int indexOf = -1;
-
- for(int i=0; i< list.getLength();i++){
+
+ for(int i=0; i< list.getLength();i++) {
Node node = list.item(i);
- if(node instanceof Element){
- if(node.getLocalName().equals("element")){
+ if (node instanceof Element) {
+ if (node.getLocalName().equals("element")) {
Node nameAttribute = node.getAttributes().getNamedItem("name");
- if(nameAttribute.getNodeValue().equals(removeNamespace(elementName))){
+ if (nameAttribute.getNodeValue().equals(removeNamespace(elementName))) {
indexOf = i;
break;
}
-
+
}
}
}
-
return indexOf;
-
}
-
- private Node getComplexTypeForElement(String elementName,Node xmlSchema,Node localComplexTypeRootNode){
+
+ private Node getComplexTypeForElement(String elementName,Node xmlSchema,Node localComplexTypeRootNode) {
Node complexTypeNode = null;
-
+
String elementNameWithoutNamespace = removeNamespace(elementName);
-
+
NodeList list = localComplexTypeRootNode.getChildNodes();
String complexTypeName = "";
-
-
- for(int i=0; i< list.getLength();i++){
+
+
+ for(int i=0; i< list.getLength();i++) {
Node node = list.item(i);
- if( node instanceof Element){
- if(node.getLocalName().equals("element")){
+ if ( node instanceof Element) {
+ if (node.getLocalName().equals("element")) {
Node nameAttribute = node.getAttributes().getNamedItem("name");
- if(nameAttribute.getNodeValue().equals(elementNameWithoutNamespace)){
+ if (nameAttribute.getNodeValue().equals(elementNameWithoutNamespace)) {
Node complexTypeAttribute = node.getAttributes().getNamedItem("type");
- if(complexTypeAttribute!=null){
+ if (complexTypeAttribute!=null) {
complexTypeName = complexTypeAttribute.getNodeValue();
break;
}
}
}
// Note: we expect that all the complex types are defined at root level
- if(!complexTypeName.equals("")){
+ if (!"".equals(complexTypeName)) {
NodeList complexTypeList = xmlSchema.getChildNodes();
- for(int i=0; i< complexTypeList.getLength();i++){
+ for(int i=0; i< complexTypeList.getLength();i++) {
Node node = list.item(i);
- if( node instanceof Element){
- if(node.getLocalName().equals("complexType")){
+ if ( node instanceof Element) {
+ if (node.getLocalName().equals("complexType")) {
Node nameAttribute = node.getAttributes().getNamedItem("name");
- if(nameAttribute.getNodeValue().equals(complexTypeName)){
-
+ if (nameAttribute.getNodeValue().equals(complexTypeName)) {
+
NodeList complexTypeChildList =node.getChildNodes();
- for(int j=0; j<complexTypeChildList.getLength();j++){
+ for(int j=0; j<complexTypeChildList.getLength();j++) {
Node sequence = complexTypeChildList.item(j);
-
- if( sequence instanceof Element){
- if(sequence.getLocalName().equals("sequence")){
+
+ if ( sequence instanceof Element) {
+ if (sequence.getLocalName().equals("sequence")) {
complexTypeNode = sequence;
break;
}
}
}
- if(complexTypeNode!=null){
+ if (complexTypeNode!=null) {
break;
}
-
+
}
}
}
}
}
-
return complexTypeNode;
-
-
}
-
-
}
private static Map<Integer, Borders> imap = new HashMap<Integer, Borders>();
static {
for (Borders p : values()) {
- imap.put(new Integer(p.getValue()), p);
+ imap.put(Integer.valueOf(p.getValue()), p);
}
}
public static Borders valueOf(int type) {
- Borders pBorder = imap.get(new Integer(type));
+ Borders pBorder = imap.get(Integer.valueOf(type));
if (pBorder == null) {
throw new IllegalArgumentException("Unknown paragraph border: " + type);
}
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTheme;
public class TOC {
-
+
CTSdtBlock block;
-
+
public TOC() {
this(CTSdtBlock.Factory.newInstance());
}
-
+
public TOC(CTSdtBlock block) {
this.block = block;
CTSdtPr sdtPr = block.addNewSdtPr();
p.addNewPPr().addNewPStyle().setVal("TOCHeading");
p.addNewR().addNewT().set("Table of Contents");
}
-
+
public CTSdtBlock getBlock() {
return this.block;
}
-
+
public void addRow(int level, String title, int page, String bookmarkRef) {
CTSdtContentBlock contentBlock = this.block.getSdtContent();
CTP p = contentBlock.addNewP();
// page number run
run = p.addNewR();
run.addNewRPr().addNewNoProof();
- run.addNewT().set(new Integer(page).toString());
+ run.addNewT().set(Integer.valueOf(page).toString());
run = p.addNewR();
run.addNewRPr().addNewNoProof();
run.addNewFldChar().setFldCharType(STFldCharType.END);
-
}
-
}
//build a tree of POIXMLDocumentParts, this document being the root
load(XWPFFactory.getInstance());
}
-
+
public XWPFDocument(InputStream is) throws IOException {
super(PackageHelper.open(is));
initFootnotes();
// filling paragraph list
- for (CTP p : body.getPArray()) {
+ for (CTP p : body.getPArray()) {
paragraphs.add(new XWPFParagraph(p, this));
}
private void initHyperlinks(){
// Get the hyperlinks
// TODO: make me optional/separated in private function
- try {
+ try {
Iterator <PackageRelationship> relIter =
getPackagePart().getRelationshipsByType(XWPFRelation.HYPERLINK.getRelation()).iterator();
while(relIter.hasNext()) {
*/
protected static OPCPackage newPackage() {
try {
- OPCPackage pkg = OPCPackage.create(PackageHelper.createTempFile());
+ OPCPackage pkg = OPCPackage.create(PackageHelper.createTempFile());
// Main part
PackagePartName corePartName = PackagingURIHelper.createPartName(XWPFRelation.DOCUMENT.getDefaultFileName());
// Create main part relationship
/**
* Create an empty table with one row and one column as default.
- *
+ *
* @return a new table
*/
public XWPFTable createTable(){
return new XWPFTable(this, ctDocument.getBody().addNewTbl());
}
-
+
/**
* Create an empty table with a number of rows and cols specified
* @param rows
* @return table
*/
public XWPFTable createTable(int rows, int cols) {
- return new XWPFTable(this, ctDocument.getBody().addNewTbl(), rows, cols);
+ return new XWPFTable(this, ctDocument.getBody().addNewTbl(), rows, cols);
}
-
+
public void createTOC() {
- CTSdtBlock block = this.getDocument().getBody().addNewSdt();
- TOC toc = new TOC(block);
- int i = 1;
- for (Iterator<XWPFParagraph> iterator = getParagraphsIterator() ; iterator.hasNext() ; ) {
- XWPFParagraph par = iterator.next();
- String parStyle = par.getStyle();
- if (parStyle != null && parStyle.substring(0, 7).equals("Heading")) {
- try {
- int level = new Integer(parStyle.substring("Heading".length()));
- toc.addRow(level, par.getText(), 1, "112723803");
- }
- catch (NumberFormatException e) {
- e.printStackTrace();
- }
- }
- }
+ CTSdtBlock block = this.getDocument().getBody().addNewSdt();
+ TOC toc = new TOC(block);
+ int i = 1;
+ for (Iterator<XWPFParagraph> iterator = getParagraphsIterator() ; iterator.hasNext() ; ) {
+ XWPFParagraph par = iterator.next();
+ String parStyle = par.getStyle();
+ if (parStyle != null && parStyle.substring(0, 7).equals("Heading")) {
+ try {
+ int level = Integer.valueOf(parStyle.substring("Heading".length()));
+ toc.addRow(level, par.getText(), 1, "112723803");
+ }
+ catch (NumberFormatException e) {
+ e.printStackTrace();
+ }
+ }
+ }
}
}
-
byte[] chpx = new byte[size];
System.arraycopy(fkp, ++chpxOffset, chpx, 0, size);
- //_papTable.put(new Integer(fcStart), papx);
+ //_papTable.put(Integer.valueOf(fcStart), papx);
_characterTable.add(new ChpxNode(fcStart, fcEnd, chpx));
}
lineWidth += 10 * tempString.length();//metrics.stringWidth(tempString);
if(lineWidth > pageWidth)
{
- lineHeights.add(new Integer(maxHeight));
+ lineHeights.add(Integer.valueOf(maxHeight));
maxHeight = 0;
lineWidth = 0;
}
}
- lineHeights.add(new Integer(maxHeight));
+ lineHeights.add(Integer.valueOf(maxHeight));
}
int sum = 0;
size = lineHeights.size();
LFOLVL lfolvl = override._levels[x];
if(lfolvl._fFormatting)
{
- LST lst = (LST)_lists.get(new Integer(override._lsid));
+ LST lst = (LST)_lists.get(Integer.valueOf(override._lsid));
LVL lvl = lfolvl._override;
lvl._istd = Utils.convertBytesToShort(lst._rgistd, level * 2);
return lvl;
}
else if(lfolvl._fStartAt)
{
- LST lst = (LST)_lists.get(new Integer(override._lsid));
+ LST lst = (LST)_lists.get(Integer.valueOf(override._lsid));
LVL lvl = lst._levels[level];
LVL newLvl = (LVL)lvl.clone();
newLvl._istd = Utils.convertBytesToShort(lst._rgistd, level * 2);
}
}
- LST lst = (LST)_lists.get(new Integer(override._lsid));
+ LST lst = (LST)_lists.get(Integer.valueOf(override._lsid));
LVL lvl = lst._levels[level];
lvl._istd = Utils.convertBytesToShort(lst._rgistd, level * 2);
return lvl;
byte code = plcflst[2 + 26 + (x * 28)];
lst._fSimpleList = StyleSheet.getFlag(code & 0x01);
//lstArray[x] = lst;
- _lists.put(new Integer(lst._lsid), lst);
+ _lists.put(Integer.valueOf(lst._lsid), lst);
if(lst._fSimpleList)
{
while (temp._entries[0].child != null) {
temp = temp._entries[0].child;
- parentIndex.push(new Integer(0));
+ parentIndex.push(Integer.valueOf(0));
}
return temp;
// else - You're not a leaf so simply find and return the successor of lastReturned
currentNode = currentNode._entries[index].child;
- parentIndex.push(new Integer(index));
+ parentIndex.push(Integer.valueOf(index));
while (currentNode._entries[0].child != null) {
currentNode = currentNode._entries[0].child;
- parentIndex.push(new Integer(0));
+ parentIndex.push(Integer.valueOf(0));
}
index = 1;
byte[] chpx = new byte[size];
System.arraycopy(fkp, ++chpxOffset, chpx, 0, size);
- //_papTable.put(new Integer(fcStart), papx);
+ //_papTable.put(Integer.valueOf(fcStart), papx);
_characterRuns.add(new ChpxNode(fcStart, fcEnd, chpx));
}
LFOLVL lfolvl = override._levels[x];
if(lfolvl._fFormatting)
{
- LST lst = (LST)_lists.get(new Integer(override._lsid));
+ LST lst = (LST)_lists.get(Integer.valueOf(override._lsid));
LVL lvl = lfolvl._override;
lvl._istd = Utils.convertBytesToShort(lst._rgistd, level * 2);
return lvl;
}
else if(lfolvl._fStartAt)
{
- LST lst = (LST)_lists.get(new Integer(override._lsid));
+ LST lst = (LST)_lists.get(Integer.valueOf(override._lsid));
LVL lvl = lst._levels[level];
LVL newLvl = (LVL)lvl.clone();
newLvl._istd = Utils.convertBytesToShort(lst._rgistd, level * 2);
}
}
- LST lst = (LST)_lists.get(new Integer(override._lsid));
+ LST lst = (LST)_lists.get(Integer.valueOf(override._lsid));
LVL lvl = lst._levels[level];
lvl._istd = Utils.convertBytesToShort(lst._rgistd, level * 2);
return lvl;
byte code = plcflst[2 + 26 + (x * 28)];
lst._fSimpleList = StyleSheet.getFlag(code & 0x01);
//lstArray[x] = lst;
- _lists.put(new Integer(lst._lsid), lst);
+ _lists.put(Integer.valueOf(lst._lsid), lst);
if(lst._fSimpleList)
{
while (temp.entries[0].child != null)
{
temp = temp.entries[0].child;
- parentIndex.push(new Integer(0));
+ parentIndex.push(Integer.valueOf(0));
}
return temp;
// else - You're not a leaf so simply find and return the successor of lastReturned
currentNode = currentNode.entries[index].child;
- parentIndex.push(new Integer(index));
+ parentIndex.push(Integer.valueOf(index));
while (currentNode.entries[0].child != null)
{
currentNode = currentNode.entries[0].child;
- parentIndex.push(new Integer(0));
+ parentIndex.push(Integer.valueOf(0));
}
index = 1;
// Types 0->7 = a flat at bit 0->7
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
int val = contents[offset] & (1<<type);
- command.value = new Boolean( (val > 0) );
+ command.value = Boolean.valueOf(val > 0);
break;
case 8:
- command.value = new Byte( contents[offset] );
+ command.value = Byte.valueOf(contents[offset]);
break;
case 9:
command.value = new Double(
command.value = StringUtil.getFromUnicodeLE(contents, startsAt, strLen);
break;
case 25:
- command.value = new Short(
+ command.value = Short.valueOf(
LittleEndian.getShort(contents, offset)
);
break;
case 26:
- command.value = new Integer(
+ command.value = Integer.valueOf(
LittleEndian.getInt(contents, offset)
);
break;
}
private void setOffset(int offset) {
this.offset = offset;
- value = new Integer(offset);
+ value = Integer.valueOf(offset);
}
}
}
defsL.toArray(new CommandDefinition[defsL.size()]);
// Add to the hashtable
- chunkCommandDefinitions.put(new Integer(chunkType), defs);
+ chunkCommandDefinitions.put(Integer.valueOf(chunkType), defs);
}
inp.close();
cpd.close();
// Feed in the stuff from chunks_parse_cmds.tbl
CommandDefinition[] defs = (CommandDefinition[])
- chunkCommandDefinitions.get(new Integer(header.getType()));
+ chunkCommandDefinitions.get(Integer.valueOf(header.getType()));
if(defs == null) defs = new CommandDefinition[0];
chunk.commandDefinitions = defs;
int offset = (
(Integer)pph.getSlideLocationsLookup().get(
- new Integer(maxSlideId)
+ Integer.valueOf(maxSlideId)
) ).intValue();
Record r3 = Record.buildRecordAtOffset(
hss.getUnderlyingBytes(),
HashMap offset2id = new HashMap();
while (usrOffset != 0){
UserEditAtom usr = (UserEditAtom) Record.buildRecordAtOffset(docstream, usrOffset);
- lst.add(new Integer(usrOffset));
+ lst.add(Integer.valueOf(usrOffset));
int psrOffset = usr.getPersistPointersOffset();
PersistPtrHolder ptr = (PersistPtrHolder)Record.buildRecordAtOffset(docstream, psrOffset);
- lst.add(new Integer(psrOffset));
+ lst.add(Integer.valueOf(psrOffset));
Hashtable entries = ptr.getSlideLocationsLookup();
for (Iterator it = entries.keySet().iterator(); it.hasNext(); ) {
Integer id = (Integer)it.next();
int oldPos = pdr.getLastOnDiskOffset();
int newPos = baos.size();
pdr.setLastOnDiskOffset(newPos);
- oldToNewPositions.put(new Integer(oldPos),new Integer(newPos));
+ oldToNewPositions.put(Integer.valueOf(oldPos),Integer.valueOf(newPos));
//System.out.println(oldPos + " -> " + newPos);
}
// Update and write out the Current User atom
int oldLastUserEditAtomPos = (int)currentUser.getCurrentEditOffset();
- Integer newLastUserEditAtomPos = (Integer)oldToNewPositions.get(new Integer(oldLastUserEditAtomPos));
+ Integer newLastUserEditAtomPos = (Integer)oldToNewPositions.get(Integer.valueOf(oldLastUserEditAtomPos));
if(newLastUserEditAtomPos == null) {
throw new HSLFException("Couldn't find the new location of the UserEditAtom that used to be at " + oldLastUserEditAtomPos);
}
int[] sheetIDs = pph.getKnownSlideIDs();
Hashtable sheetOffsets = pph.getSlideLocationsLookup();
for(int j=0; j<sheetIDs.length; j++) {
- Integer id = new Integer(sheetIDs[j]);
+ Integer id = Integer.valueOf(sheetIDs[j]);
Integer offset = (Integer)sheetOffsets.get(id);
System.out.println(" Knows about sheet " + id);
int[] sheetIDs = pph.getKnownSlideIDs();
Hashtable sheetOffsets = pph.getSlideLocationsLookup();
for(int j=0; j<sheetIDs.length; j++) {
- Integer id = new Integer(sheetIDs[j]);
+ Integer id = Integer.valueOf(sheetIDs[j]);
Integer offset = (Integer)sheetOffsets.get(id);
System.out.println(" Knows about sheet " + id);
if (notes == null) {
continue;
}
- Integer id = new Integer(notes._getSheetNumber());
+ Integer id = Integer.valueOf(notes._getSheetNumber());
if (seenNotes.contains(id)) {
continue;
}
* @return the name of the shape
*/
public static String typeName(int type) {
- String name = (String)types.get(new Integer(type));
+ String name = (String)types.get(Integer.valueOf(type));
return name;
}
/** The bytes that make up the text */
private byte[] _text;
- /** Grabs the text. */
+ /** Grabs the text. Never <code>null</code> */
public String getText() {
return StringUtil.getFromUnicodeLE(_text);
}
System.arraycopy(_ptrData,0,newPtrData,0,_ptrData.length);
// Add to the slide location lookup hash
- _slideLocations.put(new Integer(slideID), new Integer(posOnDisk));
+ _slideLocations.put(Integer.valueOf(slideID), Integer.valueOf(posOnDisk));
// Add to the ptrData offset lookup hash
- _slideOffsetDataLocation.put(new Integer(slideID),
- new Integer(_ptrData.length + 4));
+ _slideOffsetDataLocation.put(Integer.valueOf(slideID),
+ Integer.valueOf(_ptrData.length + 4));
// Build the info block
// First 20 bits = offset number = slide ID
for(int i=0; i<offset_count; i++) {
int sheet_no = offset_no + i;
long sheet_offset = LittleEndian.getUInt(_ptrData,pos);
- _slideLocations.put(new Integer(sheet_no), new Integer((int)sheet_offset));
- _slideOffsetDataLocation.put(new Integer(sheet_no), new Integer(pos));
+ _slideLocations.put(Integer.valueOf(sheet_no), Integer.valueOf((int)sheet_offset));
+ _slideOffsetDataLocation.put(Integer.valueOf(sheet_no), Integer.valueOf(pos));
// Wind on by 4 bytes per sheet found
pos += 4;
// Find where they used to live, and where they now live
// Then, update the right bit of _ptrData with their new location
for(int i=0; i<slideIDs.length; i++) {
- Integer id = new Integer(slideIDs[i]);
+ Integer id = Integer.valueOf(slideIDs[i]);
Integer oldPos = (Integer)_slideLocations.get(id);
Integer newPos = (Integer)oldToNewReferencesLookup.get(oldPos);
// Grab the right constructor
java.lang.reflect.Constructor con = c.getDeclaredConstructor(new Class[] { byte[].class, Integer.TYPE, Integer.TYPE });
// Instantiate
- toReturn = (Record)(con.newInstance(new Object[] { b, new Integer(start), new Integer(len) }));
+ toReturn = (Record)(con.newInstance(new Object[] { b, Integer.valueOf(start), Integer.valueOf(len) }));
} catch(InstantiationException ie) {
throw new RuntimeException("Couldn't instantiate the class for type with id " + type + " on class " + c + " : " + ie, ie);
} catch(java.lang.reflect.InvocationTargetException ite) {
public abstract class RecordContainer extends Record
{
protected Record[] _children;
- private Boolean changingChildRecordsLock = new Boolean(true);
+ private Boolean changingChildRecordsLock = Boolean.TRUE;
/**
* Return any children
* @return name of the record
*/
public static String recordName(int type) {
- String name = (String)typeToName.get(new Integer(type));
+ String name = (String)typeToName.get(Integer.valueOf(type));
if (name == null) name = "Unknown" + type;
return name;
}
* @return class to handle the record, or null if an unknown (eg Escher) record
*/
public static Class recordHandlingClass(int type) {
- Class c = (Class)typeToClass.get(new Integer(type));
+ Class c = (Class)typeToClass.get(Integer.valueOf(type));
return c;
}
if (val instanceof Type) {
Type t = (Type)val;
Class c = t.handlingClass;
- Integer id = new Integer(t.typeID);
+ Integer id = Integer.valueOf(t.typeID);
if(c == null) { c = UnknownRecordPlaceholder.class; }
typeToName.put(id, f[i].getName());
public void updateOtherRecordReferences(Hashtable oldToNewReferencesLookup) {
// Look up the new positions of our preceding UserEditAtomOffset
if(lastUserEditAtomOffset != 0) {
- Integer newLocation = (Integer)oldToNewReferencesLookup.get(new Integer(lastUserEditAtomOffset));
+ Integer newLocation = (Integer)oldToNewReferencesLookup.get(Integer.valueOf(lastUserEditAtomOffset));
if(newLocation == null) {
throw new RuntimeException("Couldn't find the new location of the UserEditAtom that used to be at " + lastUserEditAtomOffset);
}
}
// Ditto for our PersistPtr
- Integer newLocation = (Integer)oldToNewReferencesLookup.get(new Integer(persistPointersOffset));
+ Integer newLocation = (Integer)oldToNewReferencesLookup.get(Integer.valueOf(persistPointersOffset));
if(newLocation == null) {
throw new RuntimeException("Couldn't find the new location of the PersistPtr that used to be at " + persistPointersOffset);
}
// PersistPtr, remove their old positions
int[] ids = pph.getKnownSlideIDs();
for (int j = 0; j < ids.length; j++) {
- Integer id = new Integer(ids[j]);
+ Integer id = Integer.valueOf(ids[j]);
if (mostRecentByBytes.containsKey(id)) {
mostRecentByBytes.remove(id);
}
// Now, update the byte level locations with their latest values
Hashtable thisSetOfLocations = pph.getSlideLocationsLookup();
for (int j = 0; j < ids.length; j++) {
- Integer id = new Integer(ids[j]);
+ Integer id = Integer.valueOf(ids[j]);
mostRecentByBytes.put(id, thisSetOfLocations.get(id));
}
}
}
Arrays.sort(allIDs);
for (int i = 0; i < allIDs.length; i++) {
- _sheetIdToCoreRecordsLookup.put(new Integer(allIDs[i]), new Integer(i));
+ _sheetIdToCoreRecordsLookup.put(Integer.valueOf(allIDs[i]), Integer.valueOf(i));
}
// Now convert the byte offsets back into record offsets
for (int i = 0; i < _records.length; i++) {
if (_records[i] instanceof PositionDependentRecord) {
PositionDependentRecord pdr = (PositionDependentRecord) _records[i];
- Integer recordAt = new Integer(pdr.getLastOnDiskOffset());
+ Integer recordAt = Integer.valueOf(pdr.getLastOnDiskOffset());
// Is it one we care about?
for (int j = 0; j < allIDs.length; j++) {
- Integer thisID = new Integer(allIDs[j]);
+ Integer thisID = Integer.valueOf(allIDs[j]);
Integer thatRecordAt = (Integer) mostRecentByBytes.get(thisID);
if (thatRecordAt.equals(recordAt)) {
* the refID
*/
private Record getCoreRecordForRefID(int refID) {
- Integer coreRecordId = (Integer) _sheetIdToCoreRecordsLookup.get(new Integer(refID));
+ Integer coreRecordId = (Integer) _sheetIdToCoreRecordsLookup.get(Integer.valueOf(refID));
if (coreRecordId != null) {
Record r = _mostRecentCoreRecords[coreRecordId.intValue()];
return r;
// Record the match between slide id and these notes
SlidePersistAtom spa = notesSets[i].getSlidePersistAtom();
- Integer slideId = new Integer(spa.getSlideIdentifier());
- slideIdToNotes.put(slideId, new Integer(i));
+ Integer slideId = Integer.valueOf(spa.getSlideIdentifier());
+ slideIdToNotes.put(slideId, Integer.valueOf(i));
} else {
logger.log(POILogger.ERROR, "A Notes SlideAtomSet at " + i
+ " said its record was at refID "
// 0 if slide has no notes.
int noteId = slidesRecords[i].getSlideAtom().getNotesID();
if (noteId != 0) {
- Integer notesPos = (Integer) slideIdToNotes.get(new Integer(noteId));
+ Integer notesPos = (Integer) slideIdToNotes.get(Integer.valueOf(noteId));
if (notesPos != null)
notes = _notes[notesPos.intValue()];
else
fieldOffset += LittleEndian.INT_SIZE;
int dsSize = LittleEndian.getInt(mainStream, fieldOffset);
- if (offsetList.contains(new Integer(x)) ^ areKnown)
+ if (offsetList.contains(Integer.valueOf(x)) ^ areKnown)
{
if (dsSize > 0)
{
{
UnhandledDataStructure unhandled = new UnhandledDataStructure(
tableStream, dsOffset, dsSize);
- _unknownMap.put(new Integer(x), unhandled);
+ _unknownMap.put(Integer.valueOf(x), unhandled);
}
}
}
for (int x = 0; x < length; x++)
{
- UnhandledDataStructure ds = (UnhandledDataStructure)_unknownMap.get(new Integer(x));
+ UnhandledDataStructure ds = (UnhandledDataStructure)_unknownMap.get(Integer.valueOf(x));
if (ds != null)
{
LittleEndian.putInt(mainStream, offset, tableStream.getOffset());
FSPA fspa = new FSPA(property.getBytes(), 0);
_shapes.add(fspa);
- _shapeIndexesByPropertyStart.put(new Integer(property.getStart()), new Integer(i));
+ _shapeIndexesByPropertyStart.put(Integer.valueOf(property.getStart()), Integer.valueOf(i));
}
}
public FSPA getFspaFromCp(int cp)
{
- Integer idx = (Integer)_shapeIndexesByPropertyStart.get(new Integer(cp));
+ Integer idx = (Integer)_shapeIndexesByPropertyStart.get(Integer.valueOf(cp));
if (idx == null) {
return null;
}
public void fillVariableFields(byte[] mainDocument, byte[] tableStream)
{
HashSet fieldSet = new HashSet();
- fieldSet.add(new Integer(FIBFieldHandler.STSHF));
- fieldSet.add(new Integer(FIBFieldHandler.CLX));
- fieldSet.add(new Integer(FIBFieldHandler.DOP));
- fieldSet.add(new Integer(FIBFieldHandler.PLCFBTECHPX));
- fieldSet.add(new Integer(FIBFieldHandler.PLCFBTEPAPX));
- fieldSet.add(new Integer(FIBFieldHandler.PLCFSED));
- fieldSet.add(new Integer(FIBFieldHandler.PLCFLST));
- fieldSet.add(new Integer(FIBFieldHandler.PLFLFO));
- fieldSet.add(new Integer(FIBFieldHandler.PLCFFLDMOM));
- fieldSet.add(new Integer(FIBFieldHandler.STTBFFFN));
- fieldSet.add(new Integer(FIBFieldHandler.STTBSAVEDBY));
- fieldSet.add(new Integer(FIBFieldHandler.MODIFIED));
+ fieldSet.add(Integer.valueOf(FIBFieldHandler.STSHF));
+ fieldSet.add(Integer.valueOf(FIBFieldHandler.CLX));
+ fieldSet.add(Integer.valueOf(FIBFieldHandler.DOP));
+ fieldSet.add(Integer.valueOf(FIBFieldHandler.PLCFBTECHPX));
+ fieldSet.add(Integer.valueOf(FIBFieldHandler.PLCFBTEPAPX));
+ fieldSet.add(Integer.valueOf(FIBFieldHandler.PLCFSED));
+ fieldSet.add(Integer.valueOf(FIBFieldHandler.PLCFLST));
+ fieldSet.add(Integer.valueOf(FIBFieldHandler.PLFLFO));
+ fieldSet.add(Integer.valueOf(FIBFieldHandler.PLCFFLDMOM));
+ fieldSet.add(Integer.valueOf(FIBFieldHandler.STTBFFFN));
+ fieldSet.add(Integer.valueOf(FIBFieldHandler.STTBSAVEDBY));
+ fieldSet.add(Integer.valueOf(FIBFieldHandler.MODIFIED));
_shortHandler = new FIBShortHandler(mainDocument);
for (int x = 0; x < length; x++)
{
ListData lst = new ListData(tableStream, lstOffset);
- _listMap.put(new Integer(lst.getLsid()), lst);
+ _listMap.put(Integer.valueOf(lst.getLsid()), lst);
lstOffset += LIST_DATA_SIZE;
int num = lst.numLevels();
public int addList(ListData lst, ListFormatOverride override)
{
int lsid = lst.getLsid();
- while (_listMap.get(new Integer(lsid)) != null)
+ while (_listMap.get(Integer.valueOf(lsid)) != null)
{
lsid = lst.resetListID();
override.setLsid(lsid);
}
- _listMap.put(new Integer(lsid), lst);
+ _listMap.put(Integer.valueOf(lsid), lst);
_overrideList.add(override);
return lsid;
}
public ListLevel getLevel(int listID, int level)
{
- ListData lst = (ListData)_listMap.get(new Integer(listID));
+ ListData lst = (ListData)_listMap.get(Integer.valueOf(listID));
if(level < lst.numLevels()) {
ListLevel lvl = lst.getLevels()[level];
return lvl;
public ListData getListData(int listID)
{
- return (ListData) _listMap.get(new Integer(listID));
+ return (ListData) _listMap.get(Integer.valueOf(listID));
}
public boolean equals(Object obj)
HashMap tabMap = new HashMap();
for (int x = 0; x < tabPositions.length; x++)
{
- tabMap.put(new Integer(tabPositions[x]), new Byte(tabDescriptors[x]));
+ tabMap.put(Integer.valueOf(tabPositions[x]), Byte.valueOf(tabDescriptors[x]));
}
for (int x = 0; x < delSize; x++)
{
- tabMap.remove(new Integer(LittleEndian.getShort(grpprl, offset)));
+ tabMap.remove(Integer.valueOf(LittleEndian.getShort(grpprl, offset)));
offset += LittleEndian.SHORT_SIZE;
}
int start = offset;
for (int x = 0; x < addSize; x++)
{
- Integer key = new Integer(LittleEndian.getShort(grpprl, offset));
- Byte val = new Byte(grpprl[start + ((LittleEndian.SHORT_SIZE * addSize) + x)]);
+ Integer key = Integer.valueOf(LittleEndian.getShort(grpprl, offset));
+ Byte val = Byte.valueOf(grpprl[start + ((LittleEndian.SHORT_SIZE * addSize) + x)]);
tabMap.put(key, val);
offset += LittleEndian.SHORT_SIZE;
}
// HashMap tabMap = new HashMap();
// for (int x = 0; x < tabPositions.length; x++)
// {
-// tabMap.put(new Integer(tabPositions[x]), new Byte(tabDescriptors[x]));
+// tabMap.put(Integer.valueOf(tabPositions[x]), Byte.valueOf(tabDescriptors[x]));
// }
//
// for (int x = 0; x < delSize; x++)
// {
-// tabMap.remove(new Integer(LittleEndian.getInt(grpprl, offset)));
+// tabMap.remove(Integer.valueOf(LittleEndian.getInt(grpprl, offset)));
// offset += LittleEndian.INT_SIZE;;
// }
//
// int addSize = grpprl[offset++];
// for (int x = 0; x < addSize; x++)
// {
-// Integer key = new Integer(LittleEndian.getInt(grpprl, offset));
-// Byte val = new Byte(grpprl[(LittleEndian.INT_SIZE * (addSize - x)) + x]);
+// Integer key = Integer.valueOf(LittleEndian.getInt(grpprl, offset));
+// Byte val = Byte.valueOf(grpprl[(LittleEndian.INT_SIZE * (addSize - x)) + x]);
// tabMap.put(key, val);
// offset += LittleEndian.INT_SIZE;
// }
Record[] r = wss.getRecords();
Hashtable pp = new Hashtable();
Hashtable ue = new Hashtable();
- ue.put(new Integer(0),new Integer(0)); // Will show 0 if first
+ ue.put(Integer.valueOf(0),Integer.valueOf(0)); // Will show 0 if first
int pos = 0;
int lastUEPos = -1;
for(int i=0; i<r.length; i++) {
if(r[i] instanceof PersistPtrHolder) {
- pp.put(new Integer(pos), r[i]);
+ pp.put(Integer.valueOf(pos), r[i]);
}
if(r[i] instanceof UserEditAtom) {
- ue.put(new Integer(pos), r[i]);
+ ue.put(Integer.valueOf(pos), r[i]);
lastUEPos = pos;
}
int luPos = uea.getLastUserEditAtomOffset();
int ppPos = uea.getPersistPointersOffset();
- assertTrue(pp.containsKey(new Integer(ppPos)));
- assertTrue(ue.containsKey(new Integer(luPos)));
+ assertTrue(pp.containsKey(Integer.valueOf(ppPos)));
+ assertTrue(ue.containsKey(Integer.valueOf(luPos)));
}
}
//map slide number and starting phrase of its notes
Map<Integer, String> notesMap = new HashMap<Integer, String>();
- notesMap.put(new Integer(4), "For decades before calculators");
- notesMap.put(new Integer(5), "Several commercial applications");
- notesMap.put(new Integer(6), "There are three variations of LNS that are discussed here");
- notesMap.put(new Integer(7), "Although multiply and square root are easier");
- notesMap.put(new Integer(8), "The bus Z is split into Z_H and Z_L");
+ notesMap.put(Integer.valueOf(4), "For decades before calculators");
+ notesMap.put(Integer.valueOf(5), "Several commercial applications");
+ notesMap.put(Integer.valueOf(6), "There are three variations of LNS that are discussed here");
+ notesMap.put(Integer.valueOf(7), "Although multiply and square root are easier");
+ notesMap.put(Integer.valueOf(8), "The bus Z is split into Z_H and Z_L");
Slide[] slide = ppt.getSlides();
for (int i = 0; i < slide.length; i++) {
- Integer slideNumber = new Integer(slide[i].getSlideNumber());
+ Integer slideNumber = Integer.valueOf(slide[i].getSlideNumber());
Notes notes = slide[i].getNotesSheet();
if (notesMap.containsKey(slideNumber)){
assertNotNull(notes);
/**
* Basing on: src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java
* This class tests reading and writing of meta data. No actual document is created. All information
- * is stored in a virtal document in a ByteArrayOutputStream
+ * is stored in a virtual document in a ByteArrayOutputStream
* @author Matthias G\u00fcnter
*/
-public class TestMetaDataIPI extends TestCase{
-
- private ByteArrayOutputStream bout= null; //our store
- private POIFSFileSystem poifs=null;
- DirectoryEntry dir = null;
- DocumentSummaryInformation dsi=null;
- SummaryInformation si=null;
-
-
-
- /**
- * Setup is used to get the document ready. Gets the DocumentSummaryInformation and the
- * SummaryInformation to reasonable values
- */
- public void setUp(){
- bout=new ByteArrayOutputStream();
- poifs= new POIFSFileSystem();
- dir = poifs.getRoot();
- dsi=null;
- try
- {
- DocumentEntry dsiEntry = (DocumentEntry)
- dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
- DocumentInputStream dis = new DocumentInputStream(dsiEntry);
- PropertySet ps = new PropertySet(dis);
- dis.close();
- dsi = new DocumentSummaryInformation(ps);
-
-
- }
- catch (FileNotFoundException ex)
- {
- /* There is no document summary information yet. We have to create a
- * new one. */
- dsi = PropertySetFactory.newDocumentSummaryInformation();
- assertNotNull(dsi);
- } catch (IOException e) {
- e.printStackTrace();
- fail();
- } catch (NoPropertySetStreamException e) {
- e.printStackTrace();
- fail();
- } catch (MarkUnsupportedException e) {
- e.printStackTrace();
- fail();
- } catch (UnexpectedPropertySetTypeException e) {
- e.printStackTrace();
- fail();
- }
- assertNotNull(dsi);
- try
- {
- DocumentEntry dsiEntry = (DocumentEntry)
- dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
- DocumentInputStream dis = new DocumentInputStream(dsiEntry);
- PropertySet ps = new PropertySet(dis);
- dis.close();
- si = new SummaryInformation(ps);
-
-
- }
- catch (FileNotFoundException ex)
- {
- /* There is no document summary information yet. We have to create a
- * new one. */
- si = PropertySetFactory.newSummaryInformation();
- assertNotNull(si);
- } catch (IOException e) {
- e.printStackTrace();
- fail();
- } catch (NoPropertySetStreamException e) {
- e.printStackTrace();
- fail();
- } catch (MarkUnsupportedException e) {
- e.printStackTrace();
- fail();
- } catch (UnexpectedPropertySetTypeException e) {
- e.printStackTrace();
- fail();
+public final class TestMetaDataIPI extends TestCase{
+
+ private ByteArrayOutputStream bout; //our store
+ private POIFSFileSystem poifs;
+ private DirectoryEntry dir;
+ private DocumentSummaryInformation dsi;
+ private SummaryInformation si;
+
+
+
+ /**
+ * Setup is used to get the document ready. Gets the DocumentSummaryInformation and the
+ * SummaryInformation to reasonable values
+ */
+ public void setUp() {
+ bout = new ByteArrayOutputStream();
+ poifs = new POIFSFileSystem();
+ dir = poifs.getRoot();
+ dsi = null;
+ try {
+ DocumentEntry dsiEntry = (DocumentEntry) dir
+ .getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
+ DocumentInputStream dis = new DocumentInputStream(dsiEntry);
+ PropertySet ps = new PropertySet(dis);
+ dis.close();
+ dsi = new DocumentSummaryInformation(ps);
+
+ } catch (FileNotFoundException ex) {
+ /*
+ * There is no document summary information yet. We have to create a
+ * new one.
+ */
+ dsi = PropertySetFactory.newDocumentSummaryInformation();
+ assertNotNull(dsi);
+ } catch (Exception e) {
+ e.printStackTrace();
+ fail();
+ }
+ assertNotNull(dsi);
+ try {
+ DocumentEntry dsiEntry = (DocumentEntry) dir
+ .getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
+ DocumentInputStream dis = new DocumentInputStream(dsiEntry);
+ PropertySet ps = new PropertySet(dis);
+ dis.close();
+ si = new SummaryInformation(ps);
+
+ } catch (FileNotFoundException ex) {
+ /*
+ * There is no document summary information yet. We have to create a
+ * new one.
+ */
+ si = PropertySetFactory.newSummaryInformation();
+ assertNotNull(si);
+ } catch (Exception e) {
+ e.printStackTrace();
+ fail();
+ }
+ assertNotNull(dsi);
}
- assertNotNull(dsi);
-
-
- }
-
- /**
- * Setting a lot of things to null.
- */
- public void tearDown(){
- bout=null;
- poifs=null;
- dir=null;
- dsi=null;
-
- }
-
-
- /**
- * Closes the ByteArrayOutputStream and reads it into a ByteArrayInputStream.
- * When finished writing information this method is used in the tests to
- * start reading from the created document and then the see if the results match.
- *
- */
- public void closeAndReOpen(){
-
- try {
+
+ /**
+ * Closes the ByteArrayOutputStream and reads it into a ByteArrayInputStream.
+ * When finished writing information this method is used in the tests to
+ * start reading from the created document and then the see if the results match.
+ */
+ public void closeAndReOpen() {
+
+ try {
dsi.write(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);
- si.write(dir,SummaryInformation.DEFAULT_STREAM_NAME);
+ si.write(dir, SummaryInformation.DEFAULT_STREAM_NAME);
} catch (WritingNotSupportedException e) {
e.printStackTrace();
fail();
fail();
}
- si=null;
- dsi=null;
+ si = null;
+ dsi = null;
try {
-
poifs.writeFilesystem(bout);
bout.flush();
-
} catch (IOException e) {
-
e.printStackTrace();
fail();
}
-
- InputStream is=new ByteArrayInputStream(bout.toByteArray());
- assertNotNull(is);
- POIFSFileSystem poifs=null;
+
+ InputStream is = new ByteArrayInputStream(bout.toByteArray());
+ assertNotNull(is);
+ POIFSFileSystem poifs = null;
try {
poifs = new POIFSFileSystem(is);
} catch (IOException e) {
-
e.printStackTrace();
fail();
}
- try {
+ try {
is.close();
} catch (IOException e) {
e.printStackTrace();
fail();
}
- assertNotNull(poifs);
- /* Read the document summary information. */
- DirectoryEntry dir = poifs.getRoot();
-
- try
- {
- DocumentEntry dsiEntry = (DocumentEntry)
- dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
- DocumentInputStream dis = new DocumentInputStream(dsiEntry);
- PropertySet ps = new PropertySet(dis);
- dis.close();
- dsi = new DocumentSummaryInformation(ps);
- }
- catch (FileNotFoundException ex)
- {
- fail();
- } catch (IOException e) {
- e.printStackTrace();
+ assertNotNull(poifs);
+ /* Read the document summary information. */
+ DirectoryEntry dir = poifs.getRoot();
+
+ try {
+ DocumentEntry dsiEntry = (DocumentEntry) dir
+ .getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
+ DocumentInputStream dis = new DocumentInputStream(dsiEntry);
+ PropertySet ps = new PropertySet(dis);
+ dis.close();
+ dsi = new DocumentSummaryInformation(ps);
+ } catch (FileNotFoundException ex) {
fail();
- } catch (NoPropertySetStreamException e) {
+ } catch (Exception e) {
e.printStackTrace();
fail();
- } catch (MarkUnsupportedException e) {
+ }
+ try {
+ DocumentEntry dsiEntry = (DocumentEntry) dir
+ .getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
+ DocumentInputStream dis = new DocumentInputStream(dsiEntry);
+ PropertySet ps = new PropertySet(dis);
+ dis.close();
+ si = new SummaryInformation(ps);
+
+ } catch (FileNotFoundException ex) {
+ /*
+ * There is no document summary information yet. We have to create a
+ * new one.
+ */
+ si = PropertySetFactory.newSummaryInformation();
+ assertNotNull(si);
+ } catch (Exception e) {
e.printStackTrace();
fail();
- } catch (UnexpectedPropertySetTypeException e) {
- e.printStackTrace();
+ }
+ }
+
+ /**
+ * Sets the most important information in DocumentSummaryInformation and Summary Information and rereads it
+ */
+ public void testOne() {
+
+ // DocumentSummaryInformation
+ dsi.setCompany("xxxCompanyxxx");
+ dsi.setManager("xxxManagerxxx");
+ dsi.setCategory("xxxCategoryxxx");
+
+ // SummaryInformation
+ si.setTitle("xxxTitlexxx");
+ si.setAuthor("xxxAuthorxxx");
+ si.setComments("xxxCommentsxxx");
+ si.setKeywords("xxxKeyWordsxxx");
+ si.setSubject("xxxSubjectxxx");
+
+ // Custom Properties (in DocumentSummaryInformation
+ CustomProperties customProperties = dsi.getCustomProperties();
+ if (customProperties == null) {
+ customProperties = new CustomProperties();
+ }
+
+ /* Insert some custom properties into the container. */
+ customProperties.put("Key1", "Value1");
+ customProperties.put("Schl\u00fcssel2", "Wert2");
+ customProperties.put("Sample Integer", new Integer(12345));
+ customProperties.put("Sample Boolean", Boolean.TRUE);
+ Date date = new Date();
+ customProperties.put("Sample Date", date);
+ customProperties.put("Sample Double", new Double(-1.0001));
+ customProperties.put("Sample Negative Integer", new Integer(-100000));
+
+ dsi.setCustomProperties(customProperties);
+
+ // start reading
+ closeAndReOpen();
+
+ // testing
+ assertNotNull(dsi);
+ assertNotNull(si);
+
+ assertEquals("Category", "xxxCategoryxxx", dsi.getCategory());
+ assertEquals("Company", "xxxCompanyxxx", dsi.getCompany());
+ assertEquals("Manager", "xxxManagerxxx", dsi.getManager());
+
+ assertEquals("", "xxxAuthorxxx", si.getAuthor());
+ assertEquals("", "xxxTitlexxx", si.getTitle());
+ assertEquals("", "xxxCommentsxxx", si.getComments());
+ assertEquals("", "xxxKeyWordsxxx", si.getKeywords());
+ assertEquals("", "xxxSubjectxxx", si.getSubject());
+
+ /*
+ * Read the custom properties. If there are no custom properties yet,
+ * the application has to create a new CustomProperties object. It will
+ * serve as a container for custom properties.
+ */
+ customProperties = dsi.getCustomProperties();
+ if (customProperties == null) {
fail();
}
- try
- {
- DocumentEntry dsiEntry = (DocumentEntry)
- dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
- DocumentInputStream dis = new DocumentInputStream(dsiEntry);
- PropertySet ps = new PropertySet(dis);
- dis.close();
- si = new SummaryInformation(ps);
-
-
- }
- catch (FileNotFoundException ex)
- {
- /* There is no document summary information yet. We have to create a
- * new one. */
- si = PropertySetFactory.newSummaryInformation();
- assertNotNull(si);
- } catch (IOException e) {
- e.printStackTrace();
- fail();
- } catch (NoPropertySetStreamException e) {
- e.printStackTrace();
- fail();
- } catch (MarkUnsupportedException e) {
- e.printStackTrace();
- fail();
- } catch (UnexpectedPropertySetTypeException e) {
- e.printStackTrace();
- fail();
- }
- }
-
- /**
- * Sets the most important information in DocumentSummaryInformation and Summary Information and rereads it
- *
- */
- public void testOne(){
-
- //DocumentSummaryInformation
- dsi.setCompany("xxxCompanyxxx");
- dsi.setManager("xxxManagerxxx");
- dsi.setCategory("xxxCategoryxxx");
-
- //SummaryInformation
- si.setTitle("xxxTitlexxx");
- si.setAuthor("xxxAuthorxxx");
- si.setComments("xxxCommentsxxx");
- si.setKeywords("xxxKeyWordsxxx");
- si.setSubject("xxxSubjectxxx");
-
- //Custom Properties (in DocumentSummaryInformation
- CustomProperties customProperties = dsi.getCustomProperties();
- if (customProperties == null){
- customProperties = new CustomProperties();
- }
-
- /* Insert some custom properties into the container. */
- customProperties.put("Key1", "Value1");
- customProperties.put("Schl\u00fcssel2", "Wert2");
- customProperties.put("Sample Integer", new Integer(12345));
- customProperties.put("Sample Boolean", new Boolean(true));
- Date date=new Date();
- customProperties.put("Sample Date", date);
- customProperties.put("Sample Double", new Double(-1.0001));
- customProperties.put("Sample Negative Integer", new Integer(-100000));
-
- dsi.setCustomProperties(customProperties);
-
- //start reading
- closeAndReOpen();
-
- //testing
- assertNotNull(dsi);
- assertNotNull(si);
-
- assertEquals("Category","xxxCategoryxxx",dsi.getCategory());
- assertEquals("Company","xxxCompanyxxx",dsi.getCompany());
- assertEquals("Manager","xxxManagerxxx",dsi.getManager());
-
- assertEquals("","xxxAuthorxxx",si.getAuthor());
- assertEquals("","xxxTitlexxx",si.getTitle());
- assertEquals("","xxxCommentsxxx",si.getComments());
- assertEquals("","xxxKeyWordsxxx",si.getKeywords());
- assertEquals("","xxxSubjectxxx",si.getSubject());
-
-
- /* Read the custom properties. If there are no custom properties yet,
- * the application has to create a new CustomProperties object. It will
- * serve as a container for custom properties. */
- customProperties = dsi.getCustomProperties();
- if (customProperties == null){
- fail();
- }
-
- /* Insert some custom properties into the container. */
- String a1=(String) customProperties.get("Key1");
- assertEquals("Key1","Value1",a1);
- String a2=(String) customProperties.get("Schl\u00fcssel2");
- assertEquals("Schl\u00fcssel2","Wert2",a2);
- Integer a3=(Integer) customProperties.get("Sample Integer");
- assertEquals("Sample Number",new Integer(12345),a3);
- Boolean a4=(Boolean) customProperties.get("Sample Boolean");
- assertEquals("Sample Boolean",new Boolean(true),a4);
- Date a5=(Date) customProperties.get("Sample Date");
- assertEquals("Custom Date:",date,a5);
-
- Double a6=(Double) customProperties.get("Sample Double");
- assertEquals("Custom Float",new Double(-1.0001),a6);
-
- Integer a7=(Integer) customProperties.get("Sample Negative Integer");
- assertEquals("Neg", new Integer(-100000),a7);
- }
-
-
- /**
- * multiplies a string
- * @param s Input String
- * @return the multiplied String
- */
- public String elongate(String s){
- StringBuffer sb=new StringBuffer();
- for (int i=0;i<10000;i++){
- sb.append(s);
- sb.append(" ");
- }
- return sb.toString();
- }
-
-
-
- /**
- * Test very long input in each of the fields (approx 30-60KB each)
- *
- */
-public void testTwo(){
-
- String company=elongate("company");
- String manager=elongate("manager");
- String category=elongate("category");
- String title=elongate("title");
- String author=elongate("author");
- String comments=elongate("comments");
- String keywords=elongate("keywords");
- String subject=elongate("subject");
- String p1=elongate("p1");
- String p2=elongate("p2");
- String k1=elongate("k1");
- String k2=elongate("k2");
-
- dsi.setCompany(company);
- dsi.setManager(manager);
- dsi.setCategory(category);
-
- si.setTitle(title);
- si.setAuthor(author);
- si.setComments(comments);
- si.setKeywords(keywords);
- si.setSubject(subject);
- CustomProperties customProperties = dsi.getCustomProperties();
- if (customProperties == null){
- customProperties = new CustomProperties();
- }
-
- /* Insert some custom properties into the container. */
- customProperties.put(k1, p1);
- customProperties.put(k2, p2);
- customProperties.put("Sample Number", new Integer(12345));
- customProperties.put("Sample Boolean", new Boolean(true));
- Date date=new Date();
- customProperties.put("Sample Date", date);
-
- dsi.setCustomProperties(customProperties);
-
-
- closeAndReOpen();
-
- assertNotNull(dsi);
- assertNotNull(si);
- /* Change the category to "POI example". Any former category value will
- * be lost. If there has been no category yet, it will be created. */
- assertEquals("Category",category,dsi.getCategory());
- assertEquals("Company",company,dsi.getCompany());
- assertEquals("Manager",manager,dsi.getManager());
-
- assertEquals("",author,si.getAuthor());
- assertEquals("",title,si.getTitle());
- assertEquals("",comments,si.getComments());
- assertEquals("",keywords,si.getKeywords());
- assertEquals("",subject,si.getSubject());
-
-
- /* Read the custom properties. If there are no custom properties
- * yet, the application has to create a new CustomProperties object.
- * It will serve as a container for custom properties. */
- customProperties = dsi.getCustomProperties();
- if (customProperties == null){
- fail();
- }
-
- /* Insert some custom properties into the container. */
- String a1=(String) customProperties.get(k1);
- assertEquals("Key1",p1,a1);
- String a2=(String) customProperties.get(k2);
- assertEquals("Schl\u00fcssel2",p2,a2);
- Integer a3=(Integer) customProperties.get("Sample Number");
- assertEquals("Sample Number",new Integer(12345),a3);
- Boolean a4=(Boolean) customProperties.get("Sample Boolean");
- assertEquals("Sample Boolean",new Boolean(true),a4);
- Date a5=(Date) customProperties.get("Sample Date");
- assertEquals("Custom Date:",date,a5);
+ /* Insert some custom properties into the container. */
+ String a1 = (String) customProperties.get("Key1");
+ assertEquals("Key1", "Value1", a1);
+ String a2 = (String) customProperties.get("Schl\u00fcssel2");
+ assertEquals("Schl\u00fcssel2", "Wert2", a2);
+ Integer a3 = (Integer) customProperties.get("Sample Integer");
+ assertEquals("Sample Number", new Integer(12345), a3);
+ Boolean a4 = (Boolean) customProperties.get("Sample Boolean");
+ assertEquals("Sample Boolean", Boolean.TRUE, a4);
+ Date a5 = (Date) customProperties.get("Sample Date");
+ assertEquals("Custom Date:", date, a5);
+
+ Double a6 = (Double) customProperties.get("Sample Double");
+ assertEquals("Custom Float", new Double(-1.0001), a6);
+
+ Integer a7 = (Integer) customProperties.get("Sample Negative Integer");
+ assertEquals("Neg", new Integer(-100000), a7);
+ }
+ /**
+ * multiplies a string
+ * @param s Input String
+ * @return the multiplied String
+ */
+ private static String elongate(String s) {
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < 10000; i++) {
+ sb.append(s);
+ sb.append(" ");
+ }
+ return sb.toString();
}
-
-/**
- * adds strange characters to the string
- * @param s Input String
- * @return the multiplied String
- */
-public String strangize(String s){
- StringBuffer sb=new StringBuffer();
- String[] umlaute= {"\u00e4","\u00fc","\u00f6","\u00dc","$","\u00d6","\u00dc","\u00c9","\u00d6","@","\u00e7","&"};
- char j=0;
- Random rand=new Random();
- for (int i=0;i<5;i++){
- sb.append(s);
- sb.append(" ");
- j=(char) rand.nextInt(220);
- j+=33;
- // System.out.println(j);
- sb.append(">");
- sb.append(new Character(j));
- sb.append("=");
- sb.append(umlaute[rand.nextInt(umlaute.length)]);
- sb.append("<");
- }
-
- return sb.toString();
-}
+ /**
+ * Test very long input in each of the fields (approx 30-60KB each)
+ */
+ public void testTwo() {
+
+ String company = elongate("company");
+ String manager = elongate("manager");
+ String category = elongate("category");
+ String title = elongate("title");
+ String author = elongate("author");
+ String comments = elongate("comments");
+ String keywords = elongate("keywords");
+ String subject = elongate("subject");
+ String p1 = elongate("p1");
+ String p2 = elongate("p2");
+ String k1 = elongate("k1");
+ String k2 = elongate("k2");
+
+ dsi.setCompany(company);
+ dsi.setManager(manager);
+ dsi.setCategory(category);
+
+ si.setTitle(title);
+ si.setAuthor(author);
+ si.setComments(comments);
+ si.setKeywords(keywords);
+ si.setSubject(subject);
+ CustomProperties customProperties = dsi.getCustomProperties();
+ if (customProperties == null) {
+ customProperties = new CustomProperties();
+ }
+ /* Insert some custom properties into the container. */
+ customProperties.put(k1, p1);
+ customProperties.put(k2, p2);
+ customProperties.put("Sample Number", new Integer(12345));
+ customProperties.put("Sample Boolean", Boolean.TRUE);
+ Date date = new Date();
+ customProperties.put("Sample Date", date);
+
+ dsi.setCustomProperties(customProperties);
+
+ closeAndReOpen();
+
+ assertNotNull(dsi);
+ assertNotNull(si);
+ /*
+ * Change the category to "POI example". Any former category value will
+ * be lost. If there has been no category yet, it will be created.
+ */
+ assertEquals("Category", category, dsi.getCategory());
+ assertEquals("Company", company, dsi.getCompany());
+ assertEquals("Manager", manager, dsi.getManager());
+
+ assertEquals("", author, si.getAuthor());
+ assertEquals("", title, si.getTitle());
+ assertEquals("", comments, si.getComments());
+ assertEquals("", keywords, si.getKeywords());
+ assertEquals("", subject, si.getSubject());
+
+ /*
+ * Read the custom properties. If there are no custom properties yet,
+ * the application has to create a new CustomProperties object. It will
+ * serve as a container for custom properties.
+ */
+ customProperties = dsi.getCustomProperties();
+ if (customProperties == null) {
+ fail();
+ }
-/**
- * Tests with strange characters in keys and data (Umlaute etc.)
- *
- */
-public void testThree(){
-
- String company=strangize("company");
- String manager=strangize("manager");
- String category=strangize("category");
- String title=strangize("title");
- String author=strangize("author");
- String comments=strangize("comments");
- String keywords=strangize("keywords");
- String subject=strangize("subject");
- String p1=strangize("p1");
- String p2=strangize("p2");
- String k1=strangize("k1");
- String k2=strangize("k2");
-
- dsi.setCompany(company);
- dsi.setManager(manager);
- dsi.setCategory(category);
-
- si.setTitle(title);
- si.setAuthor(author);
- si.setComments(comments);
- si.setKeywords(keywords);
- si.setSubject(subject);
- CustomProperties customProperties = dsi.getCustomProperties();
- if (customProperties == null){
- customProperties = new CustomProperties();
- }
-
- /* Insert some custom properties into the container. */
- customProperties.put(k1, p1);
- customProperties.put(k2, p2);
- customProperties.put("Sample Number", new Integer(12345));
- customProperties.put("Sample Boolean", new Boolean(false));
- Date date=new Date(0);
- customProperties.put("Sample Date", date);
-
- dsi.setCustomProperties(customProperties);
-
-
- closeAndReOpen();
-
- assertNotNull(dsi);
- assertNotNull(si);
- /* Change the category to "POI example". Any former category value will
- * be lost. If there has been no category yet, it will be created. */
- assertEquals("Category",category,dsi.getCategory());
- assertEquals("Company",company,dsi.getCompany());
- assertEquals("Manager",manager,dsi.getManager());
-
- assertEquals("",author,si.getAuthor());
- assertEquals("",title,si.getTitle());
- assertEquals("",comments,si.getComments());
- assertEquals("",keywords,si.getKeywords());
- assertEquals("",subject,si.getSubject());
-
-
- /* Read the custom properties. If there are no custom properties yet,
- * the application has to create a new CustomProperties object. It will
- * serve as a container for custom properties. */
- customProperties = dsi.getCustomProperties();
- if (customProperties == null){
- fail();
- }
-
- /* Insert some custom properties into the container. */
- // System.out.println(k1);
- String a1=(String) customProperties.get(k1);
- assertEquals("Key1",p1,a1);
- String a2=(String) customProperties.get(k2);
- assertEquals("Schl\u00fcssel2",p2,a2);
- Integer a3=(Integer) customProperties.get("Sample Number");
- assertEquals("Sample Number",new Integer(12345),a3);
- Boolean a4=(Boolean) customProperties.get("Sample Boolean");
- assertEquals("Sample Boolean",new Boolean(false),a4);
- Date a5=(Date) customProperties.get("Sample Date");
- assertEquals("Custom Date:",date,a5);
-
+ /* Insert some custom properties into the container. */
+ String a1 = (String) customProperties.get(k1);
+ assertEquals("Key1", p1, a1);
+ String a2 = (String) customProperties.get(k2);
+ assertEquals("Schl\u00fcssel2", p2, a2);
+ Integer a3 = (Integer) customProperties.get("Sample Number");
+ assertEquals("Sample Number", new Integer(12345), a3);
+ Boolean a4 = (Boolean) customProperties.get("Sample Boolean");
+ assertEquals("Sample Boolean", Boolean.TRUE, a4);
+ Date a5 = (Date) customProperties.get("Sample Date");
+ assertEquals("Custom Date:", date, a5);
}
-
- /**
- * Iterative testing: writing, reading etc.
- *
- */
- public void testFour(){
- for (int i=1;i<100;i++){
- setUp();
- testThree();
- tearDown();
- }
- }
-
-
- /**
- * adds strange characters to the string with the adding of unicode characters
- * @param s Input String
- * @return the multiplied String
- */
- public String strangizeU(String s){
-
- StringBuffer sb=new StringBuffer();
- String[] umlaute= {"\u00e4","\u00fc","\u00f6","\u00dc","$","\u00d6","\u00dc","\u00c9","\u00d6","@","\u00e7","&"};
- char j=0;
- Random rand=new Random();
- for (int i=0;i<5;i++){
- sb.append(s);
- sb.append(" ");
- j=(char) rand.nextInt(220);
- j+=33;
- // System.out.println(j);
- sb.append(">");
- sb.append(new Character(j));
- sb.append("=");
- sb.append(umlaute[rand.nextInt(umlaute.length)]);
- sb.append("<");
- }
- sb.append("\u00e4\u00f6\u00fc\uD840\uDC00");
- return sb.toString();
- }
- /**
- * Unicode test
- *
- */
- public void testUnicode(){
- String company=strangizeU("company");
- String manager=strangizeU("manager");
- String category=strangizeU("category");
- String title=strangizeU("title");
- String author=strangizeU("author");
- String comments=strangizeU("comments");
- String keywords=strangizeU("keywords");
- String subject=strangizeU("subject");
- String p1=strangizeU("p1");
- String p2=strangizeU("p2");
- String k1=strangizeU("k1");
- String k2=strangizeU("k2");
-
- dsi.setCompany(company);
- dsi.setManager(manager);
- dsi.setCategory(category);
-
- si.setTitle(title);
- si.setAuthor(author);
- si.setComments(comments);
- si.setKeywords(keywords);
- si.setSubject(subject);
- CustomProperties customProperties = dsi.getCustomProperties();
- if (customProperties == null){
- customProperties = new CustomProperties();
- }
-
- /* Insert some custom properties into the container. */
- customProperties.put(k1, p1);
- customProperties.put(k2, p2);
- customProperties.put("Sample Number", new Integer(12345));
- customProperties.put("Sample Boolean", new Boolean(true));
- Date date=new Date();
- customProperties.put("Sample Date", date);
-
- dsi.setCustomProperties(customProperties);
-
-
- closeAndReOpen();
-
- assertNotNull(dsi);
- assertNotNull(si);
- /* Change the category to "POI example". Any former category value will
- * be lost. If there has been no category yet, it will be created. */
- assertEquals("Category",category,dsi.getCategory());
- assertEquals("Company",company,dsi.getCompany());
- assertEquals("Manager",manager,dsi.getManager());
-
- assertEquals("",author,si.getAuthor());
- assertEquals("",title,si.getTitle());
- assertEquals("",comments,si.getComments());
- assertEquals("",keywords,si.getKeywords());
- assertEquals("",subject,si.getSubject());
-
-
- /* Read the custom properties. If there are no custom properties yet,
- * the application has to create a new CustomProperties object. It will
- * serve as a container for custom properties. */
- customProperties = dsi.getCustomProperties();
- if (customProperties == null){
- fail();
- }
-
- /* Insert some custom properties into the container. */
- // System.out.println(k1);
- String a1=(String) customProperties.get(k1);
- assertEquals("Key1",p1,a1);
- String a2=(String) customProperties.get(k2);
- assertEquals("Schl\u00fcssel2",p2,a2);
- Integer a3=(Integer) customProperties.get("Sample Number");
- assertEquals("Sample Number",new Integer(12345),a3);
- Boolean a4=(Boolean) customProperties.get("Sample Boolean");
- assertEquals("Sample Boolean",new Boolean(true),a4);
- Date a5=(Date) customProperties.get("Sample Date");
- assertEquals("Custom Date:",date,a5);
-
-
-
- }
-
-
- /**
- * Iterative testing of the unicode test
- *
+
+ /**
+ * adds strange characters to the string
+ * @param s Input String
+ * @return the multiplied String
+ */
+ private static String strangize(String s) {
+ StringBuffer sb = new StringBuffer();
+ String[] umlaute = { "\u00e4", "\u00fc", "\u00f6", "\u00dc", "$", "\u00d6", "\u00dc",
+ "\u00c9", "\u00d6", "@", "\u00e7", "&" };
+ char j = 0;
+ Random rand = new Random(0); // TODO - no Random - tests should be completely deterministic
+ for (int i = 0; i < 5; i++) {
+ sb.append(s);
+ sb.append(" ");
+ j = (char) rand.nextInt(220);
+ j += 33;
+ // System.out.println(j);
+ sb.append(">");
+ sb.append(new Character(j));
+ sb.append("=");
+ sb.append(umlaute[rand.nextInt(umlaute.length)]);
+ sb.append("<");
+ }
+
+ return sb.toString();
+ }
+
+
+ /**
+ * Tests with strange characters in keys and data (Umlaute etc.)
+ */
+ public void testThree() {
+
+ String company = strangize("company");
+ String manager = strangize("manager");
+ String category = strangize("category");
+ String title = strangize("title");
+ String author = strangize("author");
+ String comments = strangize("comments");
+ String keywords = strangize("keywords");
+ String subject = strangize("subject");
+ String p1 = strangize("p1");
+ String p2 = strangize("p2");
+ String k1 = strangize("k1");
+ String k2 = strangize("k2");
+
+ dsi.setCompany(company);
+ dsi.setManager(manager);
+ dsi.setCategory(category);
+
+ si.setTitle(title);
+ si.setAuthor(author);
+ si.setComments(comments);
+ si.setKeywords(keywords);
+ si.setSubject(subject);
+ CustomProperties customProperties = dsi.getCustomProperties();
+ if (customProperties == null) {
+ customProperties = new CustomProperties();
+ }
+
+ /* Insert some custom properties into the container. */
+ customProperties.put(k1, p1);
+ customProperties.put(k2, p2);
+ customProperties.put("Sample Number", new Integer(12345));
+ customProperties.put("Sample Boolean", Boolean.FALSE);
+ Date date = new Date(0);
+ customProperties.put("Sample Date", date);
+
+ dsi.setCustomProperties(customProperties);
+
+ closeAndReOpen();
+
+ assertNotNull(dsi);
+ assertNotNull(si);
+ /*
+ * Change the category to "POI example". Any former category value will
+ * be lost. If there has been no category yet, it will be created.
+ */
+ assertEquals("Category", category, dsi.getCategory());
+ assertEquals("Company", company, dsi.getCompany());
+ assertEquals("Manager", manager, dsi.getManager());
+
+ assertEquals("", author, si.getAuthor());
+ assertEquals("", title, si.getTitle());
+ assertEquals("", comments, si.getComments());
+ assertEquals("", keywords, si.getKeywords());
+ assertEquals("", subject, si.getSubject());
+
+ /*
+ * Read the custom properties. If there are no custom properties yet,
+ * the application has to create a new CustomProperties object. It will
+ * serve as a container for custom properties.
+ */
+ customProperties = dsi.getCustomProperties();
+ if (customProperties == null) {
+ fail();
+ }
+
+ /* Insert some custom properties into the container. */
+ // System.out.println(k1);
+ String a1 = (String) customProperties.get(k1);
+ assertEquals("Key1", p1, a1);
+ String a2 = (String) customProperties.get(k2);
+ assertEquals("Schl\u00fcssel2", p2, a2);
+ Integer a3 = (Integer) customProperties.get("Sample Number");
+ assertEquals("Sample Number", new Integer(12345), a3);
+ Boolean a4 = (Boolean) customProperties.get("Sample Boolean");
+ assertEquals("Sample Boolean", Boolean.FALSE, a4);
+ Date a5 = (Date) customProperties.get("Sample Date");
+ assertEquals("Custom Date:", date, a5);
+
+ }
+
+ /**
+ * Iterative testing: writing, reading etc.
+ */
+ public void testFour() {
+ for (int i = 1; i < 100; i++) {
+ setUp();
+ testThree();
+ }
+ }
+
+
+
+ /**
+ * adds strange characters to the string with the adding of unicode characters
+ * @param s Input String
+ * @return the multiplied String
*/
- public void testSix(){
- for (int i=1;i<100;i++){
- setUp();
- testUnicode();
- tearDown();
- }
- }
-
+ private static String strangizeU(String s) {
+
+ StringBuffer sb = new StringBuffer();
+ String[] umlaute = { "\u00e4", "\u00fc", "\u00f6", "\u00dc", "$", "\u00d6", "\u00dc",
+ "\u00c9", "\u00d6", "@", "\u00e7", "&" };
+ char j = 0;
+ Random rand = new Random(0); // TODO - no Random - tests should be completely deterministic
+ for (int i = 0; i < 5; i++) {
+ sb.append(s);
+ sb.append(" ");
+ j = (char) rand.nextInt(220);
+ j += 33;
+ // System.out.println(j);
+ sb.append(">");
+ sb.append(new Character(j));
+ sb.append("=");
+ sb.append(umlaute[rand.nextInt(umlaute.length)]);
+ sb.append("<");
+ }
+ sb.append("\u00e4\u00f6\u00fc\uD840\uDC00");
+ return sb.toString();
+ }
+
+ /**
+ * Unicode test
+ */
+ public void testUnicode() {
+ String company = strangizeU("company");
+ String manager = strangizeU("manager");
+ String category = strangizeU("category");
+ String title = strangizeU("title");
+ String author = strangizeU("author");
+ String comments = strangizeU("comments");
+ String keywords = strangizeU("keywords");
+ String subject = strangizeU("subject");
+ String p1 = strangizeU("p1");
+ String p2 = strangizeU("p2");
+ String k1 = strangizeU("k1");
+ String k2 = strangizeU("k2");
+
+ dsi.setCompany(company);
+ dsi.setManager(manager);
+ dsi.setCategory(category);
+
+ si.setTitle(title);
+ si.setAuthor(author);
+ si.setComments(comments);
+ si.setKeywords(keywords);
+ si.setSubject(subject);
+ CustomProperties customProperties = dsi.getCustomProperties();
+ if (customProperties == null) {
+ customProperties = new CustomProperties();
+ }
+
+ /* Insert some custom properties into the container. */
+ customProperties.put(k1, p1);
+ customProperties.put(k2, p2);
+ customProperties.put("Sample Number", new Integer(12345));
+ customProperties.put("Sample Boolean", Boolean.TRUE);
+ Date date = new Date();
+ customProperties.put("Sample Date", date);
+
+ dsi.setCustomProperties(customProperties);
+
+ closeAndReOpen();
+
+ assertNotNull(dsi);
+ assertNotNull(si);
+ /*
+ * Change the category to "POI example". Any former category value will
+ * be lost. If there has been no category yet, it will be created.
+ */
+ assertEquals("Category", category, dsi.getCategory());
+ assertEquals("Company", company, dsi.getCompany());
+ assertEquals("Manager", manager, dsi.getManager());
+
+ assertEquals("", author, si.getAuthor());
+ assertEquals("", title, si.getTitle());
+ assertEquals("", comments, si.getComments());
+ assertEquals("", keywords, si.getKeywords());
+ assertEquals("", subject, si.getSubject());
+
+ /*
+ * Read the custom properties. If there are no custom properties yet,
+ * the application has to create a new CustomProperties object. It will
+ * serve as a container for custom properties.
+ */
+ customProperties = dsi.getCustomProperties();
+ if (customProperties == null) {
+ fail();
+ }
+
+ /* Insert some custom properties into the container. */
+ // System.out.println(k1);
+ String a1 = (String) customProperties.get(k1);
+ assertEquals("Key1", p1, a1);
+ String a2 = (String) customProperties.get(k2);
+ assertEquals("Schl\u00fcssel2", p2, a2);
+ Integer a3 = (Integer) customProperties.get("Sample Number");
+ assertEquals("Sample Number", new Integer(12345), a3);
+ Boolean a4 = (Boolean) customProperties.get("Sample Boolean");
+ assertEquals("Sample Boolean", Boolean.TRUE, a4);
+ Date a5 = (Date) customProperties.get("Sample Date");
+ assertEquals("Custom Date:", date, a5);
+ }
+
/**
- * Tests conversion in custom fields and errors
- *
- */
- public void testConvAndExistance(){
-
-
- CustomProperties customProperties = dsi.getCustomProperties();
- if (customProperties == null){
- customProperties = new CustomProperties();
- }
-
- /* Insert some custom properties into the container. */
- customProperties.put("int", new Integer(12345));
- customProperties.put("negint", new Integer(-12345));
- customProperties.put("long", new Long(12345));
- customProperties.put("neglong", new Long(-12345));
- customProperties.put("boolean", new Boolean(true));
- customProperties.put("string", "a String");
- //customProperties.put("float", new Float(12345.0)); is not valid
- //customProperties.put("negfloat", new Float(-12345.1)); is not valid
- customProperties.put("double", new Double(12345.2));
- customProperties.put("negdouble", new Double(-12345.3));
- //customProperties.put("char", new Character('a')); is not valid
-
- Date date=new Date();
- customProperties.put("date", date);
-
- dsi.setCustomProperties(customProperties);
-
-
- closeAndReOpen();
-
- assertNotNull(dsi);
- assertNotNull(si);
- /* Change the category to "POI example". Any former category value will
- * be lost. If there has been no category yet, it will be created. */
- assertNull(dsi.getCategory());
- assertNull(dsi.getCompany());
- assertNull(dsi.getManager());
-
- assertNull(si.getAuthor());
- assertNull(si.getTitle());
- assertNull(si.getComments());
- assertNull(si.getKeywords());
- assertNull(si.getSubject());
-
-
- /* Read the custom properties. If there are no custom properties
- * yet, the application has to create a new CustomProperties object.
- * It will serve as a container for custom properties. */
- customProperties = dsi.getCustomProperties();
- if (customProperties == null){
- fail();
- }
-
- /* Insert some custom properties into the container. */
-
- Integer a3=(Integer) customProperties.get("int");
- assertEquals("int",new Integer(12345),a3);
-
- a3=(Integer) customProperties.get("negint");
- assertEquals("negint",new Integer(-12345),a3);
-
- Long al=(Long) customProperties.get("neglong");
- assertEquals("neglong",new Long(-12345),al);
-
- al=(Long) customProperties.get("long");
- assertEquals("long",new Long(12345),al);
-
- Boolean a4=(Boolean) customProperties.get("boolean");
- assertEquals("boolean",new Boolean(true),a4);
-
- Date a5=(Date) customProperties.get("date");
- assertEquals("Custom Date:",date,a5);
-
- Double d=(Double) customProperties.get("double");
- assertEquals("int",new Double(12345.2),d);
-
- d=(Double) customProperties.get("negdouble");
- assertEquals("string",new Double(-12345.3),d);
-
- String s=(String) customProperties.get("string");
- assertEquals("sring","a String",s);
-
- Object o=null;
-
- o=customProperties.get("string");
- if (!(o instanceof String)){
- fail();
- }
- o=customProperties.get("boolean");
- if (!(o instanceof Boolean)){
- fail();
- }
-
- o=customProperties.get("int");
- if (!(o instanceof Integer)){
- fail();
- }
- o=customProperties.get("negint");
- if (!(o instanceof Integer)){
- fail();
- }
-
- o=customProperties.get("long");
- if (!(o instanceof Long)){
- fail();
- }
- o=customProperties.get("neglong");
- if (!(o instanceof Long)){
- fail();
- }
-
- o=customProperties.get("double");
- if (!(o instanceof Double)){
- fail();
- }
- o=customProperties.get("negdouble");
- if (!(o instanceof Double)){
- fail();
- }
-
- o=customProperties.get("date");
- if (!(o instanceof Date)){
- fail();
- }
- }
-
-
-
-}
\ No newline at end of file
+ * Iterative testing of the unicode test
+ *
+ */
+ public void testSix() {
+ for (int i = 1; i < 100; i++) {
+ setUp();
+ testUnicode();
+ }
+ }
+
+
+ /**
+ * Tests conversion in custom fields and errors
+ */
+ public void testConvAndExistence() {
+
+ CustomProperties customProperties = dsi.getCustomProperties();
+ if (customProperties == null) {
+ customProperties = new CustomProperties();
+ }
+
+ /* Insert some custom properties into the container. */
+ customProperties.put("int", new Integer(12345));
+ customProperties.put("negint", new Integer(-12345));
+ customProperties.put("long", new Long(12345));
+ customProperties.put("neglong", new Long(-12345));
+ customProperties.put("boolean", Boolean.TRUE);
+ customProperties.put("string", "a String");
+ // customProperties.put("float", new Float(12345.0)); is not valid
+ // customProperties.put("negfloat", new Float(-12345.1)); is not valid
+ customProperties.put("double", new Double(12345.2));
+ customProperties.put("negdouble", new Double(-12345.3));
+ // customProperties.put("char", new Character('a')); is not valid
+
+ Date date = new Date();
+ customProperties.put("date", date);
+
+ dsi.setCustomProperties(customProperties);
+
+ closeAndReOpen();
+
+ assertNotNull(dsi);
+ assertNotNull(si);
+ /*
+ * Change the category to "POI example". Any former category value will
+ * be lost. If there has been no category yet, it will be created.
+ */
+ assertNull(dsi.getCategory());
+ assertNull(dsi.getCompany());
+ assertNull(dsi.getManager());
+
+ assertNull(si.getAuthor());
+ assertNull(si.getTitle());
+ assertNull(si.getComments());
+ assertNull(si.getKeywords());
+ assertNull(si.getSubject());
+
+ /*
+ * Read the custom properties. If there are no custom properties yet,
+ * the application has to create a new CustomProperties object. It will
+ * serve as a container for custom properties.
+ */
+ customProperties = dsi.getCustomProperties();
+ if (customProperties == null) {
+ fail();
+ }
+
+ /* Insert some custom properties into the container. */
+
+ Integer a3 = (Integer) customProperties.get("int");
+ assertEquals("int", new Integer(12345), a3);
+
+ a3 = (Integer) customProperties.get("negint");
+ assertEquals("negint", new Integer(-12345), a3);
+
+ Long al = (Long) customProperties.get("neglong");
+ assertEquals("neglong", new Long(-12345), al);
+
+ al = (Long) customProperties.get("long");
+ assertEquals("long", new Long(12345), al);
+
+ Boolean a4 = (Boolean) customProperties.get("boolean");
+ assertEquals("boolean", Boolean.TRUE, a4);
+
+ Date a5 = (Date) customProperties.get("date");
+ assertEquals("Custom Date:", date, a5);
+
+ Double d = (Double) customProperties.get("double");
+ assertEquals("int", new Double(12345.2), d);
+
+ d = (Double) customProperties.get("negdouble");
+ assertEquals("string", new Double(-12345.3), d);
+
+ String s = (String) customProperties.get("string");
+ assertEquals("sring", "a String", s);
+
+
+ assertTrue(customProperties.get("string") instanceof String);
+ assertTrue(customProperties.get("boolean") instanceof Boolean);
+ assertTrue(customProperties.get("int") instanceof Integer);
+ assertTrue(customProperties.get("negint") instanceof Integer);
+ assertTrue(customProperties.get("long") instanceof Long);
+ assertTrue(customProperties.get("neglong") instanceof Long);
+ assertTrue(customProperties.get("double") instanceof Double);
+ assertTrue(customProperties.get("negdouble") instanceof Double);
+ assertTrue(customProperties.get("date") instanceof Date);
+ }
+}
/**
* <p>Read a the test file from the "data" directory.</p>
- *
+ *
* @exception FileNotFoundException if the file to be read does not exist.
* @exception IOException if any other I/O exception occurs
*/
* <p>Tests the {@link PropertySet} methods. The test file has two
* property set: the first one is a {@link SummaryInformation},
* the second one is a {@link DocumentSummaryInformation}.</p>
- *
+ *
* @exception IOException if an I/O exception occurs
* @exception HPSFException if an HPSF exception occurs
*/
Assert.assertEquals(ps.getSectionCount(), 2);
Section s = (Section) ps.getSections().get(1);
Assert.assertEquals(s.getProperty(1),
- new Integer(Constants.CP_UTF16));
+ Integer.valueOf(Constants.CP_UTF16));
Assert.assertEquals(s.getProperty(2),
- new Integer(-96070278));
+ Integer.valueOf(-96070278));
Assert.assertEquals(s.getProperty(3),
"MCon_Info zu Office bei Schreiner");
Assert.assertEquals(s.getProperty(4),
/**
* <p>Writes an empty property set to a POIFS and reads it back
* in.</p>
- *
+ *
* @exception IOException if an I/O exception occurs
*/
public void testNoFormatID() throws IOException
/**
* <p>Writes an empty property set to a POIFS and reads it back
* in.</p>
- *
+ *
* @exception IOException if an I/O exception occurs
* @exception UnsupportedVariantTypeException if HPSF does not yet support
* a variant type to be written
/**
* <p>Writes a simple property set with a SummaryInformation section to a
* POIFS and reads it back in.</p>
- *
+ *
* @exception IOException if an I/O exception occurs
* @exception UnsupportedVariantTypeException if HPSF does not yet support
* a variant type to be written
throws IOException, UnsupportedVariantTypeException
{
final String AUTHOR = "Rainer Klute";
- final String TITLE = "Test Document";
+ final String TITLE = "Test Document";
final File dataDir = _samples.getFile("");
final File filename = new File(dataDir, POI_FS);
filename.deleteOnExit();
final OutputStream out = new FileOutputStream(filename);
final POIFSFileSystem poiFs = new POIFSFileSystem();
-
+
final MutablePropertySet ps = new MutablePropertySet();
final MutableSection si = new MutableSection();
si.setFormatID(SectionIDMap.SUMMARY_INFORMATION_ID);
ps.getSections().set(0, si);
-
+
final MutableProperty p = new MutableProperty();
p.setID(PropertyIDMap.PID_AUTHOR);
p.setType(Variant.VT_LPWSTR);
p.setValue(AUTHOR);
si.setProperty(p);
si.setProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPSTR, TITLE);
-
+
poiFs.createDocument(ps.toInputStream(),
SummaryInformation.DEFAULT_STREAM_NAME);
poiFs.writeFilesystem(out);
out.close();
-
+
/* Read the POIFS: */
final PropertySet[] psa = new PropertySet[1];
final POIFSReader r = new POIFSReader();
fail(org.apache.poi.hpsf.Util.toString(ex));
}
}
-
+
},
SummaryInformation.DEFAULT_STREAM_NAME);
r.read(new FileInputStream(filename));
/**
* <p>Writes a simple property set with two sections to a POIFS and reads it
* back in.</p>
- *
+ *
* @exception IOException if an I/O exception occurs
* @exception WritingNotSupportedException if HPSF does not yet support
* a variant type to be written
{
Throwable t = null;
final int codepage = CODEPAGE_DEFAULT;
- if (!hasProperDefaultCharset())
+ if (!hasProperDefaultCharset())
{
System.err.println(IMPROPER_DEFAULT_CHARSET_MESSAGE +
" This testcase is skipped.");
try
{
check(Variant.VT_EMPTY, null, codepage);
- check(Variant.VT_BOOL, new Boolean(true), codepage);
- check(Variant.VT_BOOL, new Boolean(false), codepage);
+ check(Variant.VT_BOOL, Boolean.TRUE, codepage);
+ check(Variant.VT_BOOL, Boolean.FALSE, codepage);
check(Variant.VT_CF, new byte[]{0}, codepage);
check(Variant.VT_CF, new byte[]{0, 1}, codepage);
check(Variant.VT_CF, new byte[]{0, 1, 2}, codepage);
check(Variant.VT_CF, new byte[]{0, 1, 2, 3, 4, 5}, codepage);
check(Variant.VT_CF, new byte[]{0, 1, 2, 3, 4, 5, 6}, codepage);
check(Variant.VT_CF, new byte[]{0, 1, 2, 3, 4, 5, 6, 7}, codepage);
- check(Variant.VT_I4, new Integer(27), codepage);
- check(Variant.VT_I8, new Long(28), codepage);
+ check(Variant.VT_I4, Integer.valueOf(27), codepage);
+ check(Variant.VT_I8, Long.valueOf(28), codepage);
check(Variant.VT_R8, new Double(29.0), codepage);
- check(Variant.VT_I4, new Integer(-27), codepage);
- check(Variant.VT_I8, new Long(-28), codepage);
+ check(Variant.VT_I4, Integer.valueOf(-27), codepage);
+ check(Variant.VT_I8, Long.valueOf(-28), codepage);
check(Variant.VT_R8, new Double(-29.0), codepage);
check(Variant.VT_FILETIME, new Date(), codepage);
check(Variant.VT_I4, new Integer(Integer.MAX_VALUE), codepage);
for (int i = 0; i < validCodepages.length; i++)
{
final int cp = validCodepages[i];
- if (cp == -1 && !hasProperDefaultCharset())
+ if (cp == -1 && !hasProperDefaultCharset())
{
System.err.println(IMPROPER_DEFAULT_CHARSET_MESSAGE +
" This testcase is skipped for the default codepage.");
* @param codepage The codepage to use for writing and reading.
* @throws UnsupportedVariantTypeException if the variant is not supported.
* @throws IOException if an I/O exception occurs.
- * @throws ReadingNotSupportedException
- * @throws UnsupportedEncodingException
+ * @throws ReadingNotSupportedException
+ * @throws UnsupportedEncodingException
*/
- private void check(final long variantType, final Object value,
+ private void check(final long variantType, final Object value,
final int codepage)
throws UnsupportedVariantTypeException, IOException,
ReadingNotSupportedException, UnsupportedEncodingException
* <p>This test method does a write and read back test with all POI
* filesystems in the "data" directory by performing the following
* actions for each file:</p>
- *
+ *
* <ul>
- *
+ *
* <li><p>Read its property set streams.</p></li>
- *
+ *
* <li><p>Create a new POI filesystem containing the origin file's
* property set streams.</p></li>
- *
+ *
* <li><p>Read the property set streams from the POI filesystem just
* created.</p></li>
- *
+ *
* <li><p>Compare each property set stream with the corresponding one from
* the origin file and check whether they are equal.</p></li>
*
final InputStream in2 = new ByteArrayInputStream(bytes2);
final PropertySet ps1 = PropertySetFactory.create(in1);
final PropertySet ps2 = PropertySetFactory.create(in2);
-
+
/* Compare the property set stream with the corresponding one
* from the origin file and check whether they are equal. */
assertEquals("Equality for file " + f.getName(), ps1, ps2);
final MutablePropertySet ps1 = new MutablePropertySet();
final MutableSection s = (MutableSection) ps1.getSections().get(0);
final Map m = new HashMap(3, 1.0f);
- m.put(new Long(1), "String 1");
- m.put(new Long(2), "String 2");
- m.put(new Long(3), "String 3");
+ m.put(Long.valueOf(1), "String 1");
+ m.put(Long.valueOf(2), "String 2");
+ m.put(Long.valueOf(3), "String 3");
s.setDictionary(m);
s.setFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID[0]);
int codepage = Constants.CP_UNICODE;
s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
- new Integer(codepage));
+ Integer.valueOf(codepage));
poiFs.createDocument(ps1.toInputStream(), "Test");
poiFs.writeFilesystem(out);
out.close();
final MutablePropertySet ps1 = new MutablePropertySet();
final MutableSection s = (MutableSection) ps1.getSections().get(0);
final Map m = new HashMap(3, 1.0f);
- m.put(new Long(1), "String 1");
- m.put(new Long(2), "String 2");
- m.put(new Long(3), "String 3");
+ m.put(Long.valueOf(1), "String 1");
+ m.put(Long.valueOf(2), "String 2");
+ m.put(Long.valueOf(3), "String 3");
s.setDictionary(m);
s.setFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID[0]);
int codepage = 12345;
s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
- new Integer(codepage));
+ Integer.valueOf(codepage));
poiFs.createDocument(ps1.toInputStream(), "Test");
poiFs.writeFilesystem(out);
out.close();
/**
* <p>Tests HPSF's high-level writing functionality for the well-known property
* set "SummaryInformation" and "DocumentSummaryInformation".</p>
- *
+ *
* @author Rainer Klute
* <a href="mailto:klute@rainer-klute.de">klute@rainer-klute.de</a>
*/
* pointed to by the "POI.testdata.path" system property, trying to extract
* the document summary information stream in the root directory and calling
* its get... methods.</p>
- * @throws IOException
- * @throws FileNotFoundException
- * @throws MarkUnsupportedException
- * @throws NoPropertySetStreamException
- * @throws UnexpectedPropertySetTypeException
*/
public void testReadDocumentSummaryInformation()
throws FileNotFoundException, IOException,
final DocumentInputStream dis = new DocumentInputStream(dsiEntry);
final PropertySet ps = new PropertySet(dis);
final DocumentSummaryInformation dsi = new DocumentSummaryInformation(ps);
-
+
/* Execute the get... methods. */
dsi.getByteCount();
dsi.getByteOrder();
* <p>This test method test the writing of properties in the well-known
* property set streams "SummaryInformation" and
* "DocumentSummaryInformation" by performing the following steps:</p>
- *
+ *
* <ol>
- *
+ *
* <li><p>Read a test document <em>doc1</em> into a POI filesystem.</p></li>
- *
+ *
* <li><p>Read the summary information stream and the document summary
* information stream from the POI filesystem.</p></li>
- *
+ *
* <li><p>Write all properties supported by HPSF to the summary
* information (e.g. author, edit date, application name) and to the
* document summary information (e.g. company, manager).</p></li>
- *
+ *
* <li><p>Write the summary information stream and the document summary
* information stream to the POI filesystem.</p></li>
- *
+ *
* <li><p>Write the POI filesystem to a (temporary) file <em>doc2</em>
* and close the latter.</p></li>
- *
+ *
* <li><p>Open <em>doc2</em> for reading and check summary information
* and document summary information. All properties written before must be
* found in the property streams of <em>doc2</em> and have the correct
* values.</p></li>
- *
+ *
* <li><p>Remove all properties supported by HPSF from the summary
* information (e.g. author, edit date, application name) and from the
* document summary information (e.g. company, manager).</p></li>
- *
+ *
* <li><p>Write the summary information stream and the document summary
* information stream to the POI filesystem.</p></li>
- *
+ *
* <li><p>Write the POI filesystem to a (temporary) file <em>doc3</em>
* and close the latter.</p></li>
- *
+ *
* <li><p>Open <em>doc3</em> for reading and check summary information
* and document summary information. All properties removed before must not
* be found in the property streams of <em>doc3</em>.</p></li> </ol>
- *
+ *
* @throws IOException if some I/O error occurred.
* @throws MarkUnsupportedException
* @throws NoPropertySetStreamException
POIDataSamples _samples = POIDataSamples.getHPSFInstance();
final File dataDir = _samples.getFile("");
final File doc1 = new File(dataDir, POI_FS);
-
+
/* Read a test document <em>doc1</em> into a POI filesystem. */
POIFSFileSystem poifs = new POIFSFileSystem(new FileInputStream(doc1));
DirectoryEntry dir = poifs.getRoot();
DocumentEntry siEntry = (DocumentEntry) dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
DocumentEntry dsiEntry = (DocumentEntry) dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
-
+
/*
* Read the summary information stream and the document summary
* information stream from the POI filesystem.
- *
+ *
* Please note that the result consists of SummaryInformation and
* DocumentSummaryInformation instances which are in memory only. To
* make them permanent they have to be written to a POI filesystem
dis = new DocumentInputStream(dsiEntry);
ps = new PropertySet(dis);
DocumentSummaryInformation dsi = new DocumentSummaryInformation(ps);
-
+
/*
* Write all properties supported by HPSF to the summary information
* (e.g. author, edit date, application name) and to the document
final long time2 = cal.getTimeInMillis();
cal.set(2002, 8, 8, 8, 8, 8);
final long time3 = cal.getTimeInMillis();
-
+
int nr = 4711;
final String P_APPLICATION_NAME = "ApplicationName";
final String P_AUTHOR = "Author";
// FIXME (byte array properties not yet implemented): final byte[] P_THUMBNAIL = new byte[123];
final String P_TITLE = "Title";
final int P_WORD_COUNT = ++nr;
-
+
final int P_BYTE_COUNT = ++nr;
final String P_CATEGORY = "Category";
final String P_COMPANY = "Company";
final Long MIN_LONG = new Long(Long.MIN_VALUE);
final Double MAX_DOUBLE = new Double(Double.MAX_VALUE);
final Double MIN_DOUBLE = new Double(Double.MIN_VALUE);
-
+
si.setApplicationName(P_APPLICATION_NAME);
si.setAuthor(P_AUTHOR);
si.setCharCount(P_CHAR_COUNT);
// FIXME (byte array properties not yet implemented): si.setThumbnail(P_THUMBNAIL);
si.setTitle(P_TITLE);
si.setWordCount(P_WORD_COUNT);
-
+
dsi.setByteCount(P_BYTE_COUNT);
dsi.setCategory(P_CATEGORY);
dsi.setCompany(P_COMPANY);
customProperties.put("negative_Integer", NEGATIVE_INTEGER);
customProperties.put("negative_Long", NEGATIVE_LONG);
customProperties.put("negative_Double", NEGATIVE_DOUBLE);
- customProperties.put("Boolean", new Boolean(true));
+ customProperties.put("Boolean", Boolean.TRUE);
customProperties.put("Date", now);
customProperties.put("max_Integer", MAX_INTEGER);
customProperties.put("min_Integer", MIN_INTEGER);
dir = poifs.getRoot();
siEntry = (DocumentEntry) dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
dsiEntry = (DocumentEntry) dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
-
+
dis = new DocumentInputStream(siEntry);
ps = new PropertySet(dis);
si = new SummaryInformation(ps);
dis = new DocumentInputStream(dsiEntry);
ps = new PropertySet(dis);
dsi = new DocumentSummaryInformation(ps);
-
+
assertEquals(P_APPLICATION_NAME, si.getApplicationName());
assertEquals(P_AUTHOR, si.getAuthor());
assertEquals(P_CHAR_COUNT, si.getCharCount());
// FIXME (byte array properties not yet implemented): assertEquals(P_THUMBNAIL, si.getThumbnail());
assertEquals(P_TITLE, si.getTitle());
assertEquals(P_WORD_COUNT, si.getWordCount());
-
+
assertEquals(P_BYTE_COUNT, dsi.getByteCount());
assertEquals(P_CATEGORY, dsi.getCategory());
assertEquals(P_COMPANY, dsi.getCompany());
assertEquals(NEGATIVE_INTEGER, cps.get("negative_Integer"));
assertEquals(NEGATIVE_LONG, cps.get("negative_Long"));
assertEquals(NEGATIVE_DOUBLE, cps.get("negative_Double"));
- assertEquals(new Boolean(true), cps.get("Boolean"));
+ assertEquals(Boolean.TRUE, cps.get("Boolean"));
assertEquals(now, cps.get("Date"));
assertEquals(MAX_INTEGER, cps.get("max_Integer"));
assertEquals(MIN_INTEGER, cps.get("min_Integer"));
si.removeThumbnail();
si.removeTitle();
si.removeWordCount();
-
+
dsi.removeByteCount();
dsi.removeCategory();
dsi.removeCompany();
dsi.removePresentationFormat();
dsi.removeScale();
dsi.removeSlideCount();
-
- /*
+
+ /*
* <li><p>Write the summary information stream and the document summary
* information stream to the POI filesystem. */
si.write(dir, siEntry.getName());
dsi.write(dir, dsiEntry.getName());
-
- /*
+
+ /*
* <li><p>Write the POI filesystem to a (temporary) file <em>doc3</em>
* and close the latter. */
final File doc3 = File.createTempFile("POI_HPSF_Test.", ".tmp");
out = new FileOutputStream(doc3);
poifs.writeFilesystem(out);
out.close();
-
- /*
+
+ /*
* Open <em>doc3</em> for reading and check summary information
* and document summary information. All properties removed before must not
* be found in the property streams of <em>doc3</em>.
dir = poifs.getRoot();
siEntry = (DocumentEntry) dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
dsiEntry = (DocumentEntry) dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
-
+
dis = new DocumentInputStream(siEntry);
ps = new PropertySet(dis);
si = new SummaryInformation(ps);
dis = new DocumentInputStream(dsiEntry);
ps = new PropertySet(dis);
dsi = new DocumentSummaryInformation(ps);
-
+
assertEquals(null, si.getApplicationName());
assertEquals(null, si.getAuthor());
assertEquals(0, si.getCharCount());
assertEquals(null, si.getTitle());
assertEquals(0, si.getWordCount());
assertTrue(si.wasNull());
-
+
assertEquals(0, dsi.getByteCount());
assertTrue(dsi.wasNull());
assertEquals(null, dsi.getCategory());
else
dsi = PropertySetFactory.newDocumentSummaryInformation();
final CustomProperties cps = dsi.getCustomProperties();
-
+
if (cps == null)
/* The document does not have custom properties. */
return;
assertEquals(1, cps.size());
Object v1 = cps.get(KEY);
assertEquals(VALUE_1, v1);
-
+
/* After adding a custom property with the same name the size must still
* be one. */
cps.put(KEY, VALUE_2);
assertEquals(1, cps.size());
Object v2 = cps.get(KEY);
assertEquals(VALUE_2, v2);
-
+
/* Removing the custom property must return the remove property and
* reduce the size to 0. */
cp = (CustomProperty) cps.remove(KEY);
p.setType(Variant.VT_LPWSTR);
p.setValue(VALUE_1);
s.setProperty(p);
- dictionary.put(new Long(ID_1), NAME_1);
+ dictionary.put(Long.valueOf(ID_1), NAME_1);
s.setDictionary(dictionary);
cps = dsi.getCustomProperties();
assertEquals(1, cps.size());
/* Add another custom property. */
s.setProperty(ID_2, Variant.VT_LPWSTR, VALUE_1);
- dictionary.put(new Long(ID_2), NAME_1);
+ dictionary.put(Long.valueOf(ID_2), NAME_1);
s.setDictionary(dictionary);
cps = dsi.getCustomProperties();
assertEquals(1, cps.size());
* the file 'functionMetadata.txt'. There are more than 300 built-in functions in Excel and the
* intention of this class is to make it easier to maintain the metadata, by extracting it from
* a reliable source.
- *
+ *
* @author Josh Micich
*/
public final class ExcelFileFormatDocFunctionExtractor {
/**
* For simplicity, the output file is strictly simple ASCII.
- * This method detects any unexpected characters.
+ * This method detects any unexpected characters.
*/
/* package */ static boolean isSimpleAscii(char c) {
-
+
if (c>=0x21 && c<=0x7E) {
// everything from '!' to '~' (includes letters, digits, punctuation
return true;
}
return false;
}
-
-
+
+
private static final class FunctionData {
// special characters from the ooo document
private static final int CHAR_ELLIPSIS_8230 = 8230;
return b ? "x" : "";
}
}
-
+
private static final class FunctionDataCollector {
private final Map _allFunctionsByIndex;
private final Set _groupFunctionIndexes;
private final Set _groupFunctionNames;
private final PrintStream _ps;
-
+
public FunctionDataCollector(PrintStream ps) {
_ps = ps;
_allFunctionsByIndex = new HashMap();
public void addFuntion(int funcIx, boolean hasFootnote, String funcName, int minParams, int maxParams,
String returnClass, String paramClasses, String volatileFlagStr) {
boolean isVolatile = volatileFlagStr.length() > 0;
-
- Integer funcIxKey = new Integer(funcIx);
+
+ Integer funcIxKey = Integer.valueOf(funcIx);
if(!_groupFunctionIndexes.add(funcIxKey)) {
throw new RuntimeException("Duplicate function index (" + funcIx + ")");
}
if(!_groupFunctionNames.add(funcName)) {
throw new RuntimeException("Duplicate function name '" + funcName + "'");
}
-
+
checkRedefinedFunction(hasFootnote, funcName, funcIxKey);
- FunctionData fd = new FunctionData(funcIx, hasFootnote, funcName,
+ FunctionData fd = new FunctionData(funcIx, hasFootnote, funcName,
minParams, maxParams, returnClass, paramClasses, isVolatile);
-
+
_allFunctionsByIndex.put(funcIxKey, fd);
_allFunctionsByName.put(funcName, fd);
}
fdPrev = (FunctionData) _allFunctionsByIndex.get(funcIxKey);
if(fdPrev != null) {
if(!fdPrev.hasFootnote() || !hasNote) {
- throw new RuntimeException("changing function ["
+ throw new RuntimeException("changing function ["
+ funcIxKey + "] definition without foot-note");
}
_allFunctionsByName.remove(fdPrev.getName());
fdPrev = (FunctionData) _allFunctionsByName.get(funcName);
if(fdPrev != null) {
if(!fdPrev.hasFootnote() || !hasNote) {
- throw new RuntimeException("changing function '"
+ throw new RuntimeException("changing function '"
+ funcName + "' definition without foot-note");
}
- _allFunctionsByIndex.remove(new Integer(fdPrev.getIndex()));
+ _allFunctionsByIndex.remove(Integer.valueOf(fdPrev.getIndex()));
}
}
_groupFunctionIndexes.clear();
_groupFunctionNames.clear();
Arrays.sort(keys);
-
+
_ps.println("# " + headingText);
for (int i = 0; i < keys.length; i++) {
FunctionData fd = (FunctionData) _allFunctionsByIndex.get(keys[i]);
}
}
}
-
+
/**
- * To avoid drag-in - parse XML using only JDK.
+ * To avoid drag-in - parse XML using only JDK.
*/
private static class EFFDocHandler implements ContentHandler {
private static final String[] HEADING_PATH_NAMES = {
- "office:document-content", "office:body", "office:text", "text:h",
+ "office:document-content", "office:body", "office:text", "text:h",
};
private static final String[] TABLE_BASE_PATH_NAMES = {
- "office:document-content", "office:body", "office:text", "table:table",
+ "office:document-content", "office:body", "office:text", "table:table",
};
private static final String[] TABLE_ROW_RELPATH_NAMES = {
- "table:table-row",
+ "table:table-row",
};
private static final String[] TABLE_CELL_RELPATH_NAMES = {
- "table:table-row", "table:table-cell", "text:p",
+ "table:table-row", "table:table-cell", "text:p",
};
// after May 2008 there was one more style applied to the footnotes
- private static final String[] NOTE_REF_RELPATH_NAMES_OLD = {
+ private static final String[] NOTE_REF_RELPATH_NAMES_OLD = {
"table:table-row", "table:table-cell", "text:p", "text:span", "text:note-ref",
};
private static final String[] NOTE_REF_RELPATH_NAMES = {
/** <code>true</code> only when parsing the target tables */
private boolean _isInsideTable;
- private final List _rowData;
+ private final List _rowData;
private final StringBuffer _textNodeBuffer;
private final List _rowNoteFlags;
private boolean _cellHasNote;
if(matchesPath(0, HEADING_PATH_NAMES)) {
_lastHeadingText = _textNodeBuffer.toString().trim();
_textNodeBuffer.setLength(0);
- }
+ }
if(_isInsideTable) {
if(matchesTargetPath()) {
_fdc.endTableGroup(_lastHeadingText);
String returnClass = cellData[i + 4];
String paramClasses = cellData[i + 5];
String volatileFlagStr = cellData[i + 6];
-
+
_fdc.addFuntion(funcIx, hasFootnote, funcName, minParams, maxParams, returnClass, paramClasses, volatileFlagStr);
}
private static int parseInt(String valStr) {
private static void extractFunctionData(FunctionDataCollector fdc, InputStream is) {
XMLReader xr;
-
+
try {
// First up, try the default one
xr = XMLReaderFactory.createXMLReader();
public void write(byte[] b, int off, int len) throws IOException {
for (int i = 0; i < len; i++) {
checkByte(b[i + off]);
-
+
}
_os.write(b, off, len);
}
} catch(UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
-
+
outputLicenseHeader(ps);
Class genClass = ExcelFileFormatDocFunctionExtractor.class;
ps.println("# Created by (" + genClass.getName() + ")");
throw new RuntimeException(e);
}
ps.close();
-
+
String canonicalOutputFileName;
try {
canonicalOutputFileName = outFile.getCanonicalPath();
InputStream is = new FileInputStream(f);
while(true) {
int bytesRead = is.read(buf);
- if(bytesRead<1) {
+ if(bytesRead<1) {
break;
}
m.update(buf, 0, bytesRead);
} catch (IOException e) {
throw new RuntimeException(e);
}
-
+
return "0x" + new BigInteger(1, m.digest()).toString(16);
}
OutputStream os = new FileOutputStream(result);
while(true) {
int bytesRead = is.read(buf);
- if(bytesRead<1) {
+ if(bytesRead<1) {
break;
}
os.write(buf, 0, bytesRead);
processFile(effDocFile, outFile);
return;
}
-
+
File tempEFFDocFile = downloadSourceFile();
processFile(tempEFFDocFile, outFile);
tempEFFDocFile.delete();
(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
+ 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,
import java.util.List;
/**
- * Utility class to help test code verify that generated files do not differ from proof copies in
+ * Utility class to help test code verify that generated files do not differ from proof copies in
* any significant detail. Normally this task would be simple except for the presence of artifacts
- * in the file that change every time it is generated. Usually these volatile artifacts are
+ * in the file that change every time it is generated. Usually these volatile artifacts are
* time-stamps, user names, or other machine dependent parameters.
- *
+ *
* @author Josh Micich
*/
public final class StreamUtility {
/**
* Compares two streams with expected differences in specified regions. The streams are
- * expected to be of equal length and comparison is always byte for byte. That is -
- * differences can only involve exchanging each individual byte for another single byte.<br>
- * Both input streams are closed.
- *
- * @param allowableDifferenceRegions array of integer pairs: (offset, length).
+ * expected to be of equal length and comparison is always byte for byte. That is -
+ * differences can only involve exchanging each individual byte for another single byte.<br>
+ * Both input streams are closed.
+ *
+ * @param allowableDifferenceRegions array of integer pairs: (offset, length).
* Any differences encountered in these regions of the streams will be ignored
- * @return <code>null</code> if streams are identical, else the
+ * @return <code>null</code> if streams are identical, else the
* byte indexes of differing data. If streams were different lengths,
* the returned indexes will be -1 and the length of the shorter stream
*/
}
boolean success = false;
int[] result;
- try {
- result = diffInternal(isA, isB, allowableDifferenceRegions);
- success = true;
- } catch (IOException e) {
- throw new RuntimeException(e);
- } finally {
- close(isA, success);
- close(isB, success);
- }
- return result;
+ try {
+ result = diffInternal(isA, isB, allowableDifferenceRegions);
+ success = true;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ } finally {
+ close(isA, success);
+ close(isB, success);
+ }
+ return result;
}
/**
* @param success <code>false</code> if the outer method is throwing an exception.
*/
- private static void close(InputStream is, boolean success) {
- try {
- is.close();
- } catch (IOException e) {
- if(success) {
- // this is a new error. ok to throw
- throw new RuntimeException(e);
- }
- // else don't subvert original exception. just print stack trace for this one
- e.printStackTrace();
- }
- }
+ private static void close(InputStream is, boolean success) {
+ try {
+ is.close();
+ } catch (IOException e) {
+ if(success) {
+ // this is a new error. ok to throw
+ throw new RuntimeException(e);
+ }
+ // else don't subvert original exception. just print stack trace for this one
+ e.printStackTrace();
+ }
+ }
- private static int[] diffInternal(InputStream isA, InputStream isB, int[] allowableDifferenceRegions)
- throws IOException {
+ private static int[] diffInternal(InputStream isA, InputStream isB, int[] allowableDifferenceRegions)
+ throws IOException {
int offset = 0;
List temp = new ArrayList();
while (true) {
return new int[] { -1, offset, };
}
if (b != b2 && !isIgnoredRegion(allowableDifferenceRegions, offset)) {
- temp.add(new Integer(offset));
+ temp.add(Integer.valueOf(offset));
}
offset++;
}
- }
+ }
private static boolean isIgnoredRegion(int[] allowableDifferenceRegions, int offset) {
for (int i = 0; i < allowableDifferenceRegions.length; i+=2) {
}
Integer[] boxInts = new Integer[nItems];
temp.toArray(boxInts);
-
+
int[] result = new int[nItems];
for (int i = 0; i < result.length; i++) {
result[i] = boxInts[i].intValue();
Map<Integer, String> formats = BuiltinFormats.getBuiltinFormats();
for (int idx : formats.keySet()) {
- String fmt = formats.get(new Integer(idx));
+ String fmt = formats.get(Integer.valueOf(idx));
assertEquals(idx, df.getFormat(fmt));
}
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
package org.apache.poi.util;
LocalTestNode(final int key)
{
- _key = new Integer(key);
+ _key = Integer.valueOf(key);
_value = String.valueOf(key);
}
/**
* @return hash code
*/
-
public int hashCode()
{
return getKey().hashCode() ^ getValue().hashCode();
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.util;
-import junit.framework.*;
+import junit.framework.TestCase;
/**
* Unit test for ArrayUtil
*
* @author Nick Burch
*/
-public class TestArrayUtil extends TestCase
-{
+public class TestArrayUtil extends TestCase {
/**
* Test to ensure that our own arraycopy behaves as it should do
*/
public void testarraycopy() {
byte[] bytes = new byte[] { 0x01, 0x02, 0x03, 0x04 };
-
+
// Test copy whole thing
byte[] dest = new byte[4];
ArrayUtil.arraycopy(bytes, 0, dest, 0, 4);
-
+
assertEquals(dest.length, bytes.length);
for(int i=0; i<dest.length; i++) {
assertEquals(bytes[i], dest[i]);
}
-
+
// ToDo - test exceptions are as expected
}
-
-
+
+
/**
- * Helper for testArrayMoveWithin
+ * Helper for testArrayMoveWithin
*/
- private Integer[] getIntsList() {
+ private Integer[] getIntsList() {
return new Integer[] {
- new Integer(0),
- new Integer(1),
- new Integer(2),
- new Integer(3),
- new Integer(4),
- new Integer(5),
- new Integer(6),
- new Integer(7),
- new Integer(8),
- new Integer(9)
+ Integer.valueOf(0),
+ Integer.valueOf(1),
+ Integer.valueOf(2),
+ Integer.valueOf(3),
+ Integer.valueOf(4),
+ Integer.valueOf(5),
+ Integer.valueOf(6),
+ Integer.valueOf(7),
+ Integer.valueOf(8),
+ Integer.valueOf(9)
};
}
+
+ private static void assertEquals(int exp, Integer act) {
+ assertEquals(exp, act.intValue());
+ }
/**
* Test to ensure that arrayMoveWithin works as expected
*/
public void testArrayMoveWithin() {
Integer[] ints = getIntsList();
-
- assertEquals(new Integer(0), ints[0]);
- assertEquals(new Integer(1), ints[1]);
- assertEquals(new Integer(2), ints[2]);
- assertEquals(new Integer(3), ints[3]);
- assertEquals(new Integer(4), ints[4]);
- assertEquals(new Integer(5), ints[5]);
- assertEquals(new Integer(6), ints[6]);
- assertEquals(new Integer(7), ints[7]);
- assertEquals(new Integer(8), ints[8]);
- assertEquals(new Integer(9), ints[9]);
-
-
+
+ assertEquals(0, ints[0]);
+ assertEquals(1, ints[1]);
+ assertEquals(2, ints[2]);
+ assertEquals(3, ints[3]);
+ assertEquals(4, ints[4]);
+ assertEquals(5, ints[5]);
+ assertEquals(6, ints[6]);
+ assertEquals(7, ints[7]);
+ assertEquals(8, ints[8]);
+ assertEquals(9, ints[9]);
+
+
//
// Moving to a later point in the array
//
-
+
// Shift 1 back
ints = getIntsList();
ArrayUtil.arrayMoveWithin(ints, 4, 8, 1);
- assertEquals(new Integer(0), ints[0]);
- assertEquals(new Integer(1), ints[1]);
- assertEquals(new Integer(2), ints[2]);
- assertEquals(new Integer(3), ints[3]);
- assertEquals(new Integer(5), ints[4]);
- assertEquals(new Integer(6), ints[5]);
- assertEquals(new Integer(7), ints[6]);
- assertEquals(new Integer(8), ints[7]);
- assertEquals(new Integer(4), ints[8]);
- assertEquals(new Integer(9), ints[9]);
-
+ assertEquals(0, ints[0]);
+ assertEquals(1, ints[1]);
+ assertEquals(2, ints[2]);
+ assertEquals(3, ints[3]);
+ assertEquals(5, ints[4]);
+ assertEquals(6, ints[5]);
+ assertEquals(7, ints[6]);
+ assertEquals(8, ints[7]);
+ assertEquals(4, ints[8]);
+ assertEquals(9, ints[9]);
+
// Shift front 1 back
ints = getIntsList();
ArrayUtil.arrayMoveWithin(ints, 0, 7, 1);
- assertEquals(new Integer(1), ints[0]);
- assertEquals(new Integer(2), ints[1]);
- assertEquals(new Integer(3), ints[2]);
- assertEquals(new Integer(4), ints[3]);
- assertEquals(new Integer(5), ints[4]);
- assertEquals(new Integer(6), ints[5]);
- assertEquals(new Integer(7), ints[6]);
- assertEquals(new Integer(0), ints[7]);
- assertEquals(new Integer(8), ints[8]);
- assertEquals(new Integer(9), ints[9]);
-
+ assertEquals(1, ints[0]);
+ assertEquals(2, ints[1]);
+ assertEquals(3, ints[2]);
+ assertEquals(4, ints[3]);
+ assertEquals(5, ints[4]);
+ assertEquals(6, ints[5]);
+ assertEquals(7, ints[6]);
+ assertEquals(0, ints[7]);
+ assertEquals(8, ints[8]);
+ assertEquals(9, ints[9]);
+
// Shift 1 to end
ints = getIntsList();
ArrayUtil.arrayMoveWithin(ints, 4, 9, 1);
- assertEquals(new Integer(0), ints[0]);
- assertEquals(new Integer(1), ints[1]);
- assertEquals(new Integer(2), ints[2]);
- assertEquals(new Integer(3), ints[3]);
- assertEquals(new Integer(5), ints[4]);
- assertEquals(new Integer(6), ints[5]);
- assertEquals(new Integer(7), ints[6]);
- assertEquals(new Integer(8), ints[7]);
- assertEquals(new Integer(9), ints[8]);
- assertEquals(new Integer(4), ints[9]);
-
-
+ assertEquals(0, ints[0]);
+ assertEquals(1, ints[1]);
+ assertEquals(2, ints[2]);
+ assertEquals(3, ints[3]);
+ assertEquals(5, ints[4]);
+ assertEquals(6, ints[5]);
+ assertEquals(7, ints[6]);
+ assertEquals(8, ints[7]);
+ assertEquals(9, ints[8]);
+ assertEquals(4, ints[9]);
+
+
//
// Moving to an earlier point in the array
//
-
+
// Shift 1 forward
ints = getIntsList();
ArrayUtil.arrayMoveWithin(ints, 8, 3, 1);
- assertEquals(new Integer(0), ints[0]);
- assertEquals(new Integer(1), ints[1]);
- assertEquals(new Integer(2), ints[2]);
- assertEquals(new Integer(8), ints[3]);
- assertEquals(new Integer(3), ints[4]);
- assertEquals(new Integer(4), ints[5]);
- assertEquals(new Integer(5), ints[6]);
- assertEquals(new Integer(6), ints[7]);
- assertEquals(new Integer(7), ints[8]);
- assertEquals(new Integer(9), ints[9]);
-
+ assertEquals(0, ints[0]);
+ assertEquals(1, ints[1]);
+ assertEquals(2, ints[2]);
+ assertEquals(8, ints[3]);
+ assertEquals(3, ints[4]);
+ assertEquals(4, ints[5]);
+ assertEquals(5, ints[6]);
+ assertEquals(6, ints[7]);
+ assertEquals(7, ints[8]);
+ assertEquals(9, ints[9]);
+
// Shift end 1 forward
ints = getIntsList();
ArrayUtil.arrayMoveWithin(ints, 9, 2, 1);
- assertEquals(new Integer(0), ints[0]);
- assertEquals(new Integer(1), ints[1]);
- assertEquals(new Integer(9), ints[2]);
- assertEquals(new Integer(2), ints[3]);
- assertEquals(new Integer(3), ints[4]);
- assertEquals(new Integer(4), ints[5]);
- assertEquals(new Integer(5), ints[6]);
- assertEquals(new Integer(6), ints[7]);
- assertEquals(new Integer(7), ints[8]);
- assertEquals(new Integer(8), ints[9]);
-
+ assertEquals(0, ints[0]);
+ assertEquals(1, ints[1]);
+ assertEquals(9, ints[2]);
+ assertEquals(2, ints[3]);
+ assertEquals(3, ints[4]);
+ assertEquals(4, ints[5]);
+ assertEquals(5, ints[6]);
+ assertEquals(6, ints[7]);
+ assertEquals(7, ints[8]);
+ assertEquals(8, ints[9]);
+
// Shift 1 to front
ints = getIntsList();
ArrayUtil.arrayMoveWithin(ints, 5, 0, 1);
- assertEquals(new Integer(5), ints[0]);
- assertEquals(new Integer(0), ints[1]);
- assertEquals(new Integer(1), ints[2]);
- assertEquals(new Integer(2), ints[3]);
- assertEquals(new Integer(3), ints[4]);
- assertEquals(new Integer(4), ints[5]);
- assertEquals(new Integer(6), ints[6]);
- assertEquals(new Integer(7), ints[7]);
- assertEquals(new Integer(8), ints[8]);
- assertEquals(new Integer(9), ints[9]);
-
-
+ assertEquals(5, ints[0]);
+ assertEquals(0, ints[1]);
+ assertEquals(1, ints[2]);
+ assertEquals(2, ints[3]);
+ assertEquals(3, ints[4]);
+ assertEquals(4, ints[5]);
+ assertEquals(6, ints[6]);
+ assertEquals(7, ints[7]);
+ assertEquals(8, ints[8]);
+ assertEquals(9, ints[9]);
+
+
//
// Moving many to a later point in the array
//
-
+
// Shift 3 back
ints = getIntsList();
ArrayUtil.arrayMoveWithin(ints, 2, 6, 3);
- assertEquals(new Integer(0), ints[0]);
- assertEquals(new Integer(1), ints[1]);
- assertEquals(new Integer(5), ints[2]);
- assertEquals(new Integer(6), ints[3]);
- assertEquals(new Integer(7), ints[4]);
- assertEquals(new Integer(8), ints[5]);
- assertEquals(new Integer(2), ints[6]);
- assertEquals(new Integer(3), ints[7]);
- assertEquals(new Integer(4), ints[8]);
- assertEquals(new Integer(9), ints[9]);
-
+ assertEquals(0, ints[0]);
+ assertEquals(1, ints[1]);
+ assertEquals(5, ints[2]);
+ assertEquals(6, ints[3]);
+ assertEquals(7, ints[4]);
+ assertEquals(8, ints[5]);
+ assertEquals(2, ints[6]);
+ assertEquals(3, ints[7]);
+ assertEquals(4, ints[8]);
+ assertEquals(9, ints[9]);
+
// Shift 3 to back
ints = getIntsList();
ArrayUtil.arrayMoveWithin(ints, 2, 7, 3);
- assertEquals(new Integer(0), ints[0]);
- assertEquals(new Integer(1), ints[1]);
- assertEquals(new Integer(5), ints[2]);
- assertEquals(new Integer(6), ints[3]);
- assertEquals(new Integer(7), ints[4]);
- assertEquals(new Integer(8), ints[5]);
- assertEquals(new Integer(9), ints[6]);
- assertEquals(new Integer(2), ints[7]);
- assertEquals(new Integer(3), ints[8]);
- assertEquals(new Integer(4), ints[9]);
-
+ assertEquals(0, ints[0]);
+ assertEquals(1, ints[1]);
+ assertEquals(5, ints[2]);
+ assertEquals(6, ints[3]);
+ assertEquals(7, ints[4]);
+ assertEquals(8, ints[5]);
+ assertEquals(9, ints[6]);
+ assertEquals(2, ints[7]);
+ assertEquals(3, ints[8]);
+ assertEquals(4, ints[9]);
+
// Shift from 3 front
ints = getIntsList();
ArrayUtil.arrayMoveWithin(ints, 0, 5, 3);
- assertEquals(new Integer(3), ints[0]);
- assertEquals(new Integer(4), ints[1]);
- assertEquals(new Integer(5), ints[2]);
- assertEquals(new Integer(6), ints[3]);
- assertEquals(new Integer(7), ints[4]);
- assertEquals(new Integer(0), ints[5]);
- assertEquals(new Integer(1), ints[6]);
- assertEquals(new Integer(2), ints[7]);
- assertEquals(new Integer(8), ints[8]);
- assertEquals(new Integer(9), ints[9]);
-
-
+ assertEquals(3, ints[0]);
+ assertEquals(4, ints[1]);
+ assertEquals(5, ints[2]);
+ assertEquals(6, ints[3]);
+ assertEquals(7, ints[4]);
+ assertEquals(0, ints[5]);
+ assertEquals(1, ints[6]);
+ assertEquals(2, ints[7]);
+ assertEquals(8, ints[8]);
+ assertEquals(9, ints[9]);
+
+
//
// Moving many to an earlier point in the array
//
-
+
// Shift 3 forward
ints = getIntsList();
ArrayUtil.arrayMoveWithin(ints, 6, 2, 3);
- assertEquals(new Integer(0), ints[0]);
- assertEquals(new Integer(1), ints[1]);
- assertEquals(new Integer(6), ints[2]);
- assertEquals(new Integer(7), ints[3]);
- assertEquals(new Integer(8), ints[4]);
- assertEquals(new Integer(2), ints[5]);
- assertEquals(new Integer(3), ints[6]);
- assertEquals(new Integer(4), ints[7]);
- assertEquals(new Integer(5), ints[8]);
- assertEquals(new Integer(9), ints[9]);
-
+ assertEquals(0, ints[0]);
+ assertEquals(1, ints[1]);
+ assertEquals(6, ints[2]);
+ assertEquals(7, ints[3]);
+ assertEquals(8, ints[4]);
+ assertEquals(2, ints[5]);
+ assertEquals(3, ints[6]);
+ assertEquals(4, ints[7]);
+ assertEquals(5, ints[8]);
+ assertEquals(9, ints[9]);
+
// Shift 3 to front
ints = getIntsList();
ArrayUtil.arrayMoveWithin(ints, 6, 0, 3);
- assertEquals(new Integer(6), ints[0]);
- assertEquals(new Integer(7), ints[1]);
- assertEquals(new Integer(8), ints[2]);
- assertEquals(new Integer(0), ints[3]);
- assertEquals(new Integer(1), ints[4]);
- assertEquals(new Integer(2), ints[5]);
- assertEquals(new Integer(3), ints[6]);
- assertEquals(new Integer(4), ints[7]);
- assertEquals(new Integer(5), ints[8]);
- assertEquals(new Integer(9), ints[9]);
-
+ assertEquals(6, ints[0]);
+ assertEquals(7, ints[1]);
+ assertEquals(8, ints[2]);
+ assertEquals(0, ints[3]);
+ assertEquals(1, ints[4]);
+ assertEquals(2, ints[5]);
+ assertEquals(3, ints[6]);
+ assertEquals(4, ints[7]);
+ assertEquals(5, ints[8]);
+ assertEquals(9, ints[9]);
+
// Shift from 3 back
ints = getIntsList();
ArrayUtil.arrayMoveWithin(ints, 7, 3, 3);
- assertEquals(new Integer(0), ints[0]);
- assertEquals(new Integer(1), ints[1]);
- assertEquals(new Integer(2), ints[2]);
- assertEquals(new Integer(7), ints[3]);
- assertEquals(new Integer(8), ints[4]);
- assertEquals(new Integer(9), ints[5]);
- assertEquals(new Integer(3), ints[6]);
- assertEquals(new Integer(4), ints[7]);
- assertEquals(new Integer(5), ints[8]);
- assertEquals(new Integer(6), ints[9]);
-
-
+ assertEquals(0, ints[0]);
+ assertEquals(1, ints[1]);
+ assertEquals(2, ints[2]);
+ assertEquals(7, ints[3]);
+ assertEquals(8, ints[4]);
+ assertEquals(9, ints[5]);
+ assertEquals(3, ints[6]);
+ assertEquals(4, ints[7]);
+ assertEquals(5, ints[8]);
+ assertEquals(6, ints[9]);
+
+
// Check can't shift more than we have
try {
ints = getIntsList();
} catch(IllegalArgumentException e) {
// Good, we don't have 5 from 7 onwards
}
-
+
// Check can't shift where would overshoot
try {
ints = getIntsList();
}
}
}
-
m.put(nodes[ k ].getKey(), nodes[ k ]);
assertTrue(m.containsKey(nodes[ k ].getKey()));
}
- assertTrue(!m.containsKey(new Integer(-1)));
+ assertTrue(!m.containsKey(Integer.valueOf(-1)));
try
{
m.containsKey("foo");
m.put(nodes[ k ].getKey(), nodes[ k ]);
assertSame(m.get(nodes[ k ].getKey()), nodes[ k ]);
}
- assertNull(m.get(new Integer(-1)));
+ assertNull(m.get(Integer.valueOf(-1)));
try
{
m.get("foo");
catch (ClassCastException ignored)
{
}
- assertNull(m.remove(new Integer(-1)));
+ assertNull(m.remove(Integer.valueOf(-1)));
try
{
m.remove("foo");
Collection c1 = new LinkedList();
Collection c2 = new LinkedList();
- c2.add(new Integer(-99));
+ c2.add(Integer.valueOf(-99));
for (int k = 0; k < nodes.length; k++)
{
m.put(nodes[ k ].getKey(), nodes[ k ]);
assertTrue(!m.keySet().containsAll(c2));
m = new BinaryTree();
c1 = new LinkedList();
- c1.add(new Integer(-55));
+ c1.add(Integer.valueOf(-55));
try
{
m.keySet().addAll(c1);
}
// reject incompatible values
- m2.put("2", new Integer(2));
+ m2.put("2", Integer.valueOf(2));
try
{
m = new BinaryTree(m2);
// reject incompatible keys
m2.remove("2");
- m2.put(new Integer(2), "bad key");
+ m2.put(Integer.valueOf(2), "bad key");
try
{
m = new BinaryTree(m2);
catch (ClassCastException ignored)
{
}
- assertNull(m.remove(new Integer(-1)));
+ assertNull(m.remove(Integer.valueOf(-1)));
try
{
m.removeValue("foo");
Collection c1 = new LinkedList();
Collection c2 = new LinkedList();
- c2.add(new Integer(-99));
+ c2.add(Integer.valueOf(-99));
for (int k = 0; k < nodes.length; k++)
{
m.put(nodes[ k ].getKey(), nodes[ k ]);
assertTrue(!m.keySetByValue().containsAll(c2));
m = new BinaryTree();
c1 = new LinkedList();
- c1.add(new Integer(-55));
+ c1.add(Integer.valueOf(-55));
try
{
m.keySetByValue().addAll(c1);
}
for (int k = 0; k < m.size(); k++)
{
- assertTrue(s.contains(new Integer(k)));
+ assertTrue(s.contains(Integer.valueOf(k)));
}
int count = 0;
}
for (int k = 0; k < m.size(); k++)
{
- assertTrue(s.contains(new Integer(k)));
+ assertTrue(s.contains(Integer.valueOf(k)));
}
int count = 0;
POILogger log = POILogFactory.getLogger( "foo" );
- log.log( POILogger.WARN, "Test = ", new Integer( 1 ) );
- log.logFormatted( POILogger.ERROR, "Test param 1 = %, param 2 = %", "2", new Integer( 3 ) );
+ log.log( POILogger.WARN, "Test = ", Integer.valueOf( 1 ) );
+ log.logFormatted( POILogger.ERROR, "Test param 1 = %, param 2 = %", "2", Integer.valueOf( 3 ) );
log.logFormatted( POILogger.ERROR, "Test param 1 = %, param 2 = %", new int[]{4, 5} );
log.logFormatted( POILogger.ERROR,
"Test param 1 = %1.1, param 2 = %0.1", new double[]{4, 5.23} );
(byte) 'r', (byte) 'l', (byte) 'd', (byte) 0xAE
};
String input;
- try {
- input = new String( expected_output, StringUtil.getPreferredEncoding() );
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(e);
- }
+ try {
+ input = new String( expected_output, StringUtil.getPreferredEncoding() );
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException(e);
+ }
StringUtil.putCompressedUnicode( input, output, 0 );
for ( int j = 0; j < expected_output.length; j++ )
}
public void testFormat() {
- assertEquals( "This is a test " + fmt( 1.2345, 2, 2 ),
- StringUtil.format( "This is a test %2.2", new Object[]
- {
- new Double( 1.2345 )
- } ) );
- assertEquals( "This is a test " + fmt( 1.2345, -1, 3 ),
- StringUtil.format( "This is a test %.3", new Object[]
- {
- new Double( 1.2345 )
- } ) );
- assertEquals( "This is a great test " + fmt( 1.2345, -1, 3 ),
- StringUtil.format( "This is a % test %.3", new Object[]
- {
- "great", new Double( 1.2345 )
- } ) );
- assertEquals( "This is a test 1",
- StringUtil.format( "This is a test %", new Object[]
- {
- new Integer( 1 )
- } ) );
- assertEquals( "This is a test 1",
- StringUtil.format( "This is a test %", new Object[]
- {
- new Integer( 1 ), new Integer( 1 )
- } ) );
- assertEquals( "This is a test 1.x",
- StringUtil.format( "This is a test %1.x", new Object[]
- {
- new Integer( 1 )
- } ) );
- assertEquals( "This is a test ?missing data?1.x",
- StringUtil.format( "This is a test %1.x", new Object[]
- {
- } ) );
- assertEquals( "This is a test %1.x",
- StringUtil.format( "This is a test \\%1.x", new Object[]
- {
- } ) );
+
+ confirm("This is a test " + fmt(1.2345, 2, 2), "This is a test %2.2", new Double(1.2345));
+ confirm("This is a test " + fmt(1.2345, -1, 3), "This is a test %.3", new Double(1.2345));
+ confirm("This is a great test " + fmt(1.2345, -1, 3),
+ "This is a % test %.3", "great", new Double(1.2345));
+ confirm("This is a test 1", "This is a test %", Integer.valueOf(1));
+ confirm("This is a test 1", "This is a test %", Integer.valueOf(1), Integer.valueOf(1));
+ confirm("This is a test 1.x", "This is a test %1.x", Integer.valueOf(1));
+ confirm("This is a test ?missing data?1.x", "This is a test %1.x");
+ confirm("This is a test %1.x", "This is a test \\%1.x");
}
+ private static void confirm(String expectedResult, String fmtString, Object ... params) {
+ String actualResult = StringUtil.format(fmtString, params);
+ assertEquals(expectedResult, actualResult);
+ }
private static String fmt(double num, int minIntDigits, int maxFracDigitis) {
NumberFormat nf = NumberFormat.getInstance();
- if ( minIntDigits != -1 )
- {
- nf.setMinimumIntegerDigits( minIntDigits );
+ if (minIntDigits != -1) {
+ nf.setMinimumIntegerDigits(minIntDigits);
}
- if ( maxFracDigitis != -1 )
- {
- nf.setMaximumFractionDigits( maxFracDigitis );
+ if (maxFracDigitis != -1) {
+ nf.setMaximumFractionDigits(maxFracDigitis);
}
return nf.format( num );