Fixed compiler warnings - unnecessary else

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@805492 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Josh Micich 2009-08-18 16:50:24 +00:00
parent 95afcef9e6
commit a2cd9a942e
69 changed files with 2160 additions and 2334 deletions

View File

@ -136,10 +136,10 @@ public class ExtendableTreeCellRenderer implements TreeCellRenderer
/* The class has no renderer, try the superclass, if any. */ /* The class has no renderer, try the superclass, if any. */
final Class superclass = c.getSuperclass(); final Class superclass = c.getSuperclass();
if (superclass != null) if (superclass != null) {
return findRenderer(superclass); return findRenderer(superclass);
else }
return null; return null;
} }
} }

View File

@ -33,7 +33,7 @@ import org.apache.poi.poifs.filesystem.POIFSDocumentPath;
* <p>Organizes document information in a tree model in order to be * <p>Organizes document information in a tree model in order to be
* e.g. displayed in a Swing {@link javax.swing.JTree}. An instance of this * e.g. displayed in a Swing {@link javax.swing.JTree}. An instance of this
* class is created with a root tree node ({@link MutableTreeNode}) and * class is created with a root tree node ({@link MutableTreeNode}) and
* registered as a {@link POIFSReaderListener} with a {@link * registered as a {@link POIFSReaderListener} with a {@link
* org.apache.poi.poifs.eventfilesystem.POIFSReader}. While the latter processes * org.apache.poi.poifs.eventfilesystem.POIFSReader}. While the latter processes
* a POI filesystem it calls this class' {@link #processPOIFSReaderEvent} for * a POI filesystem it calls this class' {@link #processPOIFSReaderEvent} for
* each document it has been registered for. This method appends the document it * each document it has been registered for. This method appends the document it
@ -204,20 +204,16 @@ public class TreeReaderListener implements POIFSReaderListener
} }
return n; return n;
} }
else /* else - The path is somewhere down in the POI filesystem's
{ * hierarchy. We need the tree node of this path's parent
/* The path is somewhere down in the POI filesystem's * and attach our new node to it. */
* hierarchy. We need the tree node of this path's parent final String name = path.getComponent(path.length() - 1);
* and attach our new node to it. */ final POIFSDocumentPath parentPath = path.getParent();
final String name = path.getComponent(path.length() - 1); final MutableTreeNode parentNode =
final POIFSDocumentPath parentPath = path.getParent(); getNode(parentPath, fsName, root);
final MutableTreeNode parentNode = n = new DefaultMutableTreeNode(name);
getNode(parentPath, fsName, root); pathToNode.put(path, n);
n = new DefaultMutableTreeNode(name); parentNode.insert(n, 0);
pathToNode.put(path, n); return n;
parentNode.insert(n, 0);
return n;
}
} }
} }

View File

@ -15,7 +15,7 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.contrib.view; package org.apache.poi.hssf.contrib.view;
@ -196,7 +196,7 @@ public class SVFractionalFormat extends Format {
toAppendTo.append(format(((Number)obj).doubleValue())); toAppendTo.append(format(((Number)obj).doubleValue()));
return toAppendTo; return toAppendTo;
} }
else throw new IllegalArgumentException("Can only handle Numbers"); throw new IllegalArgumentException("Can only handle Numbers");
} }
public Object parseObject(String source, public Object parseObject(String source,

View File

@ -75,10 +75,10 @@ public class MutablePropertySet extends PropertySet
/** /**
* <p>Constructs a <code>MutablePropertySet</code> by doing a deep copy of * <p>Constructs a <code>MutablePropertySet</code> by doing a deep copy of
* an existing <code>PropertySet</code>. All nested elements, i.e. * an existing <code>PropertySet</code>. All nested elements, i.e.
* <code>Section</code>s and <code>Property</code> instances, will be their * <code>Section</code>s and <code>Property</code> instances, will be their
* mutable counterparts in the new <code>MutablePropertySet</code>.</p> * mutable counterparts in the new <code>MutablePropertySet</code>.</p>
* *
* @param ps The property set to copy * @param ps The property set to copy
*/ */
public MutablePropertySet(final PropertySet ps) public MutablePropertySet(final PropertySet ps)
@ -190,7 +190,7 @@ public class MutablePropertySet extends PropertySet
/** /**
* <p>Writes the property set to an output stream.</p> * <p>Writes the property set to an output stream.</p>
* *
* @param out the output stream to write the section to * @param out the output stream to write the section to
* @exception IOException if an error when writing to the output stream * @exception IOException if an error when writing to the output stream
* occurs * occurs
@ -232,10 +232,10 @@ public class MutablePropertySet extends PropertySet
catch (HPSFRuntimeException ex) catch (HPSFRuntimeException ex)
{ {
final Throwable cause = ex.getReason(); final Throwable cause = ex.getReason();
if (cause instanceof UnsupportedEncodingException) if (cause instanceof UnsupportedEncodingException) {
throw new IllegalPropertySetDataException(cause); throw new IllegalPropertySetDataException(cause);
else }
throw ex; throw ex;
} }
} }
@ -259,7 +259,7 @@ public class MutablePropertySet extends PropertySet
* the {@link MutablePropertySet} only.</p> * the {@link MutablePropertySet} only.</p>
* *
* @return the contents of this property set stream * @return the contents of this property set stream
* *
* @throws WritingNotSupportedException if HPSF does not yet support writing * @throws WritingNotSupportedException if HPSF does not yet support writing
* of a property's variant type. * of a property's variant type.
* @throws IOException if an I/O exception occurs. * @throws IOException if an I/O exception occurs.
@ -280,7 +280,7 @@ public class MutablePropertySet extends PropertySet
* @param dir The directory in the POI filesystem to write the document to. * @param dir The directory in the POI filesystem to write the document to.
* @param name The document's name. If there is already a document with the * @param name The document's name. If there is already a document with the
* same name in the directory the latter will be overwritten. * same name in the directory the latter will be overwritten.
* *
* @throws WritingNotSupportedException * @throws WritingNotSupportedException
* @throws IOException * @throws IOException
*/ */

View File

@ -46,7 +46,7 @@ import org.apache.poi.util.POILogger;
* over time but largely depends on your feedback so that the POI team knows * over time but largely depends on your feedback so that the POI team knows
* which variant types are really needed. So please feel free to submit error * which variant types are really needed. So please feel free to submit error
* reports or patches for the types you need.</p> * reports or patches for the types you need.</p>
* *
* <p>Microsoft documentation: <a * <p>Microsoft documentation: <a
* href="http://msdn.microsoft.com/library/en-us/stg/stg/property_set_display_name_dictionary.asp?frame=true"> * href="http://msdn.microsoft.com/library/en-us/stg/stg/property_set_display_name_dictionary.asp?frame=true">
* Property Set Display Name Dictionary</a>. * Property Set Display Name Dictionary</a>.
@ -110,7 +110,7 @@ public class Property
/** /**
* <p>Creates a property.</p> * <p>Creates a property.</p>
* *
* @param id the property's ID. * @param id the property's ID.
* @param type the property's type, see {@link Variant}. * @param type the property's type, see {@link Variant}.
* @param value the property's value. Only certain types are allowed, see * @param value the property's value. Only certain types are allowed, see
@ -183,7 +183,7 @@ public class Property
/** /**
* <p>Reads a dictionary.</p> * <p>Reads a dictionary.</p>
* *
* @param src The byte array containing the bytes making out the dictionary. * @param src The byte array containing the bytes making out the dictionary.
* @param offset At this offset within <var>src </var> the dictionary * @param offset At this offset within <var>src </var> the dictionary
* starts. * starts.
@ -296,7 +296,7 @@ public class Property
* 4.</p> * 4.</p>
* *
* @return the property's size in bytes * @return the property's size in bytes
* *
* @exception WritingNotSupportedException if HPSF does not yet support the * @exception WritingNotSupportedException if HPSF does not yet support the
* property's variant type. * property's variant type.
*/ */
@ -337,13 +337,14 @@ public class Property
* ID == 0 is a special case: It does not have a type, and its value is the * ID == 0 is a special case: It does not have a type, and its value is the
* section's dictionary. Another special case are strings: Two properties * section's dictionary. Another special case are strings: Two properties
* may have the different types Variant.VT_LPSTR and Variant.VT_LPWSTR;</p> * may have the different types Variant.VT_LPSTR and Variant.VT_LPWSTR;</p>
* *
* @see Object#equals(java.lang.Object) * @see Object#equals(java.lang.Object)
*/ */
public boolean equals(final Object o) public boolean equals(final Object o)
{ {
if (!(o instanceof Property)) if (!(o instanceof Property)) {
return false; return false;
}
final Property p = (Property) o; final Property p = (Property) o;
final Object pValue = p.getValue(); final Object pValue = p.getValue();
final long pId = p.getID(); final long pId = p.getID();
@ -355,8 +356,8 @@ public class Property
return false; return false;
/* It's clear now that both values are non-null. */ /* It's clear now that both values are non-null. */
final Class valueClass = value.getClass(); final Class<?> valueClass = value.getClass();
final Class pValueClass = pValue.getClass(); final Class<?> pValueClass = pValue.getClass();
if (!(valueClass.isAssignableFrom(pValueClass)) && if (!(valueClass.isAssignableFrom(pValueClass)) &&
!(pValueClass.isAssignableFrom(valueClass))) !(pValueClass.isAssignableFrom(valueClass)))
return false; return false;
@ -373,10 +374,10 @@ public class Property
{ {
if (t1 == t2 || if (t1 == t2 ||
(t1 == Variant.VT_LPSTR && t2 == Variant.VT_LPWSTR) || (t1 == Variant.VT_LPSTR && t2 == Variant.VT_LPWSTR) ||
(t2 == Variant.VT_LPSTR && t1 == Variant.VT_LPWSTR)) (t2 == Variant.VT_LPSTR && t1 == Variant.VT_LPWSTR)) {
return true; return true;
else }
return false; return false;
} }

View File

@ -146,7 +146,7 @@ public class Section
* @param src Contains the complete property set stream. * @param src Contains the complete property set stream.
* @param offset The position in the stream that points to the * @param offset The position in the stream that points to the
* section's format ID. * section's format ID.
* *
* @exception UnsupportedEncodingException if the section's codepage is not * @exception UnsupportedEncodingException if the section's codepage is not
* supported. * supported.
*/ */
@ -183,7 +183,7 @@ public class Section
/* /*
* Read the properties. The offset is positioned at the first * Read the properties. The offset is positioned at the first
* entry of the property list. There are two problems: * entry of the property list. There are two problems:
* *
* 1. For each property we have to find out its length. In the * 1. For each property we have to find out its length. In the
* property list we find each property's ID and its offset relative * property list we find each property's ID and its offset relative
* to the section's beginning. Unfortunately the properties in the * to the section's beginning. Unfortunately the properties in the
@ -191,8 +191,8 @@ public class Section
* possible to calculate the length as * possible to calculate the length as
* (offset of property(i+1) - offset of property(i)). Before we can * (offset of property(i+1) - offset of property(i)). Before we can
* that we first have to sort the property list by ascending offsets. * that we first have to sort the property list by ascending offsets.
* *
* 2. We have to read the property with ID 1 before we read other * 2. We have to read the property with ID 1 before we read other
* properties, at least before other properties containing strings. * properties, at least before other properties containing strings.
* The reason is that property 1 specifies the codepage. If it is * The reason is that property 1 specifies the codepage. If it is
* 1200, all strings are in Unicode. In other words: Before we can * 1200, all strings are in Unicode. In other words: Before we can
@ -205,10 +205,10 @@ public class Section
* seconds pass reads the other properties. * seconds pass reads the other properties.
*/ */
properties = new Property[propertyCount]; properties = new Property[propertyCount];
/* Pass 1: Read the property list. */ /* Pass 1: Read the property list. */
int pass1Offset = o1; int pass1Offset = o1;
final List propertyList = new ArrayList(propertyCount); final List<PropertyListEntry> propertyList = new ArrayList<PropertyListEntry>(propertyCount);
PropertyListEntry ple; PropertyListEntry ple;
for (int i = 0; i < properties.length; i++) for (int i = 0; i < properties.length; i++)
{ {
@ -232,15 +232,13 @@ public class Section
/* Calculate the properties' lengths. */ /* Calculate the properties' lengths. */
for (int i = 0; i < propertyCount - 1; i++) for (int i = 0; i < propertyCount - 1; i++)
{ {
final PropertyListEntry ple1 = PropertyListEntry ple1 = propertyList.get(i);
(PropertyListEntry) propertyList.get(i); PropertyListEntry ple2 = propertyList.get(i + 1);
final PropertyListEntry ple2 =
(PropertyListEntry) propertyList.get(i + 1);
ple1.length = ple2.offset - ple1.offset; ple1.length = ple2.offset - ple1.offset;
} }
if (propertyCount > 0) if (propertyCount > 0)
{ {
ple = (PropertyListEntry) propertyList.get(propertyCount - 1); ple = propertyList.get(propertyCount - 1);
ple.length = size - ple.offset; ple.length = size - ple.offset;
if (ple.length <= 0) if (ple.length <= 0)
{ {
@ -412,11 +410,11 @@ public class Section
protected boolean getPropertyBooleanValue(final int id) protected boolean getPropertyBooleanValue(final int id)
{ {
final Boolean b = (Boolean) getProperty(id); final Boolean b = (Boolean) getProperty(id);
if (b != null) if (b == null) {
return b.booleanValue();
else
return false; return false;
} }
return b.booleanValue();
}
@ -475,23 +473,23 @@ public class Section
/** /**
* <p>Checks whether this section is equal to another object. The result is * <p>Checks whether this section is equal to another object. The result is
* <code>false</code> if one of the the following conditions holds:</p> * <code>false</code> if one of the the following conditions holds:</p>
* *
* <ul> * <ul>
* *
* <li><p>The other object is not a {@link Section}.</p></li> * <li><p>The other object is not a {@link Section}.</p></li>
* *
* <li><p>The format IDs of the two sections are not equal.</p></li> * <li><p>The format IDs of the two sections are not equal.</p></li>
* *
* <li><p>The sections have a different number of properties. However, * <li><p>The sections have a different number of properties. However,
* properties with ID 1 (codepage) are not counted.</p></li> * properties with ID 1 (codepage) are not counted.</p></li>
* *
* <li><p>The other object is not a {@link Section}.</p></li> * <li><p>The other object is not a {@link Section}.</p></li>
* *
* <li><p>The properties have different values. The order of the properties * <li><p>The properties have different values. The order of the properties
* is irrelevant.</p></li> * is irrelevant.</p></li>
* *
* </ul> * </ul>
* *
* @param o The object to compare this section with * @param o The object to compare this section with
* @return <code>true</code> if the objects are equal, <code>false</code> if * @return <code>true</code> if the objects are equal, <code>false</code> if
* not * not
@ -504,7 +502,7 @@ public class Section
if (!s.getFormatID().equals(getFormatID())) if (!s.getFormatID().equals(getFormatID()))
return false; return false;
/* Compare all properties except 0 and 1 as they must be handled /* Compare all properties except 0 and 1 as they must be handled
* specially. */ * specially. */
Property[] pa1 = new Property[getProperties().length]; Property[] pa1 = new Property[getProperties().length];
Property[] pa2 = new Property[s.getProperties().length]; Property[] pa2 = new Property[s.getProperties().length];
@ -559,10 +557,10 @@ public class Section
dictionaryEqual = p10.getValue().equals(p20.getValue()); dictionaryEqual = p10.getValue().equals(p20.getValue());
else if (p10 != null || p20 != null) else if (p10 != null || p20 != null)
dictionaryEqual = false; dictionaryEqual = false;
if (!dictionaryEqual) if (dictionaryEqual) {
return false;
else
return Util.equals(pa1, pa2); return Util.equals(pa1, pa2);
}
return false;
} }
@ -571,7 +569,7 @@ public class Section
* <p>Removes a field from a property array. The resulting array is * <p>Removes a field from a property array. The resulting array is
* compactified and returned.</p> * compactified and returned.</p>
* *
* @param pa The property array. * @param pa The property array.
* @param i The index of the field to be removed. * @param i The index of the field to be removed.
* @return the compactified array. * @return the compactified array.
*/ */

View File

@ -24,13 +24,12 @@ import org.apache.poi.hpsf.wellknown.PropertyIDMap;
/** /**
* <p>Convenience class representing a Summary Information stream in a * <p>Convenience class representing a Summary Information stream in a
* Microsoft Office document.</p> * Microsoft Office document.</p>
* *
* @author Rainer Klute <a * @author Rainer Klute <a
* href="mailto:klute@rainer-klute.de">&lt;klute@rainer-klute.de&gt;</a> * href="mailto:klute@rainer-klute.de">&lt;klute@rainer-klute.de&gt;</a>
* @see DocumentSummaryInformation * @see DocumentSummaryInformation
*/ */
public class SummaryInformation extends SpecialPropertySet public final class SummaryInformation extends SpecialPropertySet {
{
/** /**
* <p>The document name a summary information stream usually has in a POIFS * <p>The document name a summary information stream usually has in a POIFS
@ -46,7 +45,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Creates a {@link SummaryInformation} from a given {@link * <p>Creates a {@link SummaryInformation} from a given {@link
* PropertySet}.</p> * PropertySet}.</p>
* *
* @param ps A property set which should be created from a summary * @param ps A property set which should be created from a summary
* information stream. * information stream.
* @throws UnexpectedPropertySetTypeException if <var>ps</var> does not * @throws UnexpectedPropertySetTypeException if <var>ps</var> does not
@ -65,7 +64,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the title (or <code>null</code>).</p> * <p>Returns the title (or <code>null</code>).</p>
* *
* @return The title or <code>null</code> * @return The title or <code>null</code>
*/ */
public String getTitle() public String getTitle()
@ -77,7 +76,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the title.</p> * <p>Sets the title.</p>
* *
* @param title The title to set. * @param title The title to set.
*/ */
public void setTitle(final String title) public void setTitle(final String title)
@ -101,7 +100,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the subject (or <code>null</code>).</p> * <p>Returns the subject (or <code>null</code>).</p>
* *
* @return The subject or <code>null</code> * @return The subject or <code>null</code>
*/ */
public String getSubject() public String getSubject()
@ -113,7 +112,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the subject.</p> * <p>Sets the subject.</p>
* *
* @param subject The subject to set. * @param subject The subject to set.
*/ */
public void setSubject(final String subject) public void setSubject(final String subject)
@ -137,7 +136,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the author (or <code>null</code>).</p> * <p>Returns the author (or <code>null</code>).</p>
* *
* @return The author or <code>null</code> * @return The author or <code>null</code>
*/ */
public String getAuthor() public String getAuthor()
@ -149,7 +148,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the author.</p> * <p>Sets the author.</p>
* *
* @param author The author to set. * @param author The author to set.
*/ */
public void setAuthor(final String author) public void setAuthor(final String author)
@ -173,7 +172,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the keywords (or <code>null</code>).</p> * <p>Returns the keywords (or <code>null</code>).</p>
* *
* @return The keywords or <code>null</code> * @return The keywords or <code>null</code>
*/ */
public String getKeywords() public String getKeywords()
@ -185,7 +184,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the keywords.</p> * <p>Sets the keywords.</p>
* *
* @param keywords The keywords to set. * @param keywords The keywords to set.
*/ */
public void setKeywords(final String keywords) public void setKeywords(final String keywords)
@ -209,7 +208,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the comments (or <code>null</code>).</p> * <p>Returns the comments (or <code>null</code>).</p>
* *
* @return The comments or <code>null</code> * @return The comments or <code>null</code>
*/ */
public String getComments() public String getComments()
@ -221,7 +220,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the comments.</p> * <p>Sets the comments.</p>
* *
* @param comments The comments to set. * @param comments The comments to set.
*/ */
public void setComments(final String comments) public void setComments(final String comments)
@ -245,7 +244,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the template (or <code>null</code>).</p> * <p>Returns the template (or <code>null</code>).</p>
* *
* @return The template or <code>null</code> * @return The template or <code>null</code>
*/ */
public String getTemplate() public String getTemplate()
@ -257,7 +256,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the template.</p> * <p>Sets the template.</p>
* *
* @param template The template to set. * @param template The template to set.
*/ */
public void setTemplate(final String template) public void setTemplate(final String template)
@ -281,7 +280,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the last author (or <code>null</code>).</p> * <p>Returns the last author (or <code>null</code>).</p>
* *
* @return The last author or <code>null</code> * @return The last author or <code>null</code>
*/ */
public String getLastAuthor() public String getLastAuthor()
@ -293,7 +292,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the last author.</p> * <p>Sets the last author.</p>
* *
* @param lastAuthor The last author to set. * @param lastAuthor The last author to set.
*/ */
public void setLastAuthor(final String lastAuthor) public void setLastAuthor(final String lastAuthor)
@ -317,7 +316,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the revision number (or <code>null</code>). </p> * <p>Returns the revision number (or <code>null</code>). </p>
* *
* @return The revision number or <code>null</code> * @return The revision number or <code>null</code>
*/ */
public String getRevNumber() public String getRevNumber()
@ -329,7 +328,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the revision number.</p> * <p>Sets the revision number.</p>
* *
* @param revNumber The revision number to set. * @param revNumber The revision number to set.
*/ */
public void setRevNumber(final String revNumber) public void setRevNumber(final String revNumber)
@ -354,24 +353,24 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the total time spent in editing the document (or * <p>Returns the total time spent in editing the document (or
* <code>0</code>).</p> * <code>0</code>).</p>
* *
* @return The total time spent in editing the document or 0 if the {@link * @return The total time spent in editing the document or 0 if the {@link
* SummaryInformation} does not contain this information. * SummaryInformation} does not contain this information.
*/ */
public long getEditTime() public long getEditTime()
{ {
final Date d = (Date) getProperty(PropertyIDMap.PID_EDITTIME); final Date d = (Date) getProperty(PropertyIDMap.PID_EDITTIME);
if (d == null) if (d == null) {
return 0; return 0;
else }
return Util.dateToFileTime(d); return Util.dateToFileTime(d);
} }
/** /**
* <p>Sets the total time spent in editing the document.</p> * <p>Sets the total time spent in editing the document.</p>
* *
* @param time The time to set. * @param time The time to set.
*/ */
public void setEditTime(final long time) public void setEditTime(final long time)
@ -396,7 +395,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the last printed time (or <code>null</code>).</p> * <p>Returns the last printed time (or <code>null</code>).</p>
* *
* @return The last printed time or <code>null</code> * @return The last printed time or <code>null</code>
*/ */
public Date getLastPrinted() public Date getLastPrinted()
@ -408,7 +407,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the lastPrinted.</p> * <p>Sets the lastPrinted.</p>
* *
* @param lastPrinted The lastPrinted to set. * @param lastPrinted The lastPrinted to set.
*/ */
public void setLastPrinted(final Date lastPrinted) public void setLastPrinted(final Date lastPrinted)
@ -433,7 +432,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the creation time (or <code>null</code>).</p> * <p>Returns the creation time (or <code>null</code>).</p>
* *
* @return The creation time or <code>null</code> * @return The creation time or <code>null</code>
*/ */
public Date getCreateDateTime() public Date getCreateDateTime()
@ -445,7 +444,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the creation time.</p> * <p>Sets the creation time.</p>
* *
* @param createDateTime The creation time to set. * @param createDateTime The creation time to set.
*/ */
public void setCreateDateTime(final Date createDateTime) public void setCreateDateTime(final Date createDateTime)
@ -470,7 +469,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the last save time (or <code>null</code>).</p> * <p>Returns the last save time (or <code>null</code>).</p>
* *
* @return The last save time or <code>null</code> * @return The last save time or <code>null</code>
*/ */
public Date getLastSaveDateTime() public Date getLastSaveDateTime()
@ -482,7 +481,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the total time spent in editing the document.</p> * <p>Sets the total time spent in editing the document.</p>
* *
* @param time The time to set. * @param time The time to set.
*/ */
public void setLastSaveDateTime(final Date time) public void setLastSaveDateTime(final Date time)
@ -509,7 +508,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the page count or 0 if the {@link SummaryInformation} does * <p>Returns the page count or 0 if the {@link SummaryInformation} does
* not contain a page count.</p> * not contain a page count.</p>
* *
* @return The page count or 0 if the {@link SummaryInformation} does not * @return The page count or 0 if the {@link SummaryInformation} does not
* contain a page count. * contain a page count.
*/ */
@ -522,7 +521,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the page count.</p> * <p>Sets the page count.</p>
* *
* @param pageCount The page count to set. * @param pageCount The page count to set.
*/ */
public void setPageCount(final int pageCount) public void setPageCount(final int pageCount)
@ -547,7 +546,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the word count or 0 if the {@link SummaryInformation} does * <p>Returns the word count or 0 if the {@link SummaryInformation} does
* not contain a word count.</p> * not contain a word count.</p>
* *
* @return The word count or <code>null</code> * @return The word count or <code>null</code>
*/ */
public int getWordCount() public int getWordCount()
@ -559,7 +558,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the word count.</p> * <p>Sets the word count.</p>
* *
* @param wordCount The word count to set. * @param wordCount The word count to set.
*/ */
public void setWordCount(final int wordCount) public void setWordCount(final int wordCount)
@ -584,7 +583,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the character count or 0 if the {@link SummaryInformation} * <p>Returns the character count or 0 if the {@link SummaryInformation}
* does not contain a char count.</p> * does not contain a char count.</p>
* *
* @return The character count or <code>null</code> * @return The character count or <code>null</code>
*/ */
public int getCharCount() public int getCharCount()
@ -596,7 +595,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the character count.</p> * <p>Sets the character count.</p>
* *
* @param charCount The character count to set. * @param charCount The character count to set.
*/ */
public void setCharCount(final int charCount) public void setCharCount(final int charCount)
@ -622,12 +621,12 @@ public class SummaryInformation extends SpecialPropertySet
* <p>Returns the thumbnail (or <code>null</code>) <strong>when this * <p>Returns the thumbnail (or <code>null</code>) <strong>when this
* method is implemented. Please note that the return type is likely to * method is implemented. Please note that the return type is likely to
* change!</strong></p> * change!</strong></p>
* *
* <p><strong>Hint to developers:</strong> Drew Varner &lt;Drew.Varner * <p><strong>Hint to developers:</strong> Drew Varner &lt;Drew.Varner
* -at- sc.edu&gt; said that this is an image in WMF or Clipboard (BMP?) * -at- sc.edu&gt; said that this is an image in WMF or Clipboard (BMP?)
* format. However, we won't do any conversion into any image type but * format. However, we won't do any conversion into any image type but
* instead just return a byte array.</p> * instead just return a byte array.</p>
* *
* @return The thumbnail or <code>null</code> * @return The thumbnail or <code>null</code>
*/ */
public byte[] getThumbnail() public byte[] getThumbnail()
@ -639,7 +638,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the thumbnail.</p> * <p>Sets the thumbnail.</p>
* *
* @param thumbnail The thumbnail to set. * @param thumbnail The thumbnail to set.
*/ */
public void setThumbnail(final byte[] thumbnail) public void setThumbnail(final byte[] thumbnail)
@ -664,7 +663,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns the application name (or <code>null</code>).</p> * <p>Returns the application name (or <code>null</code>).</p>
* *
* @return The application name or <code>null</code> * @return The application name or <code>null</code>
*/ */
public String getApplicationName() public String getApplicationName()
@ -676,7 +675,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the application name.</p> * <p>Sets the application name.</p>
* *
* @param applicationName The application name to set. * @param applicationName The application name to set.
*/ */
public void setApplicationName(final String applicationName) public void setApplicationName(final String applicationName)
@ -700,24 +699,24 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Returns a security code which is one of the following values:</p> * <p>Returns a security code which is one of the following values:</p>
* *
* <ul> * <ul>
* *
* <li><p>0 if the {@link SummaryInformation} does not contain a * <li><p>0 if the {@link SummaryInformation} does not contain a
* security field or if there is no security on the document. Use * security field or if there is no security on the document. Use
* {@link PropertySet#wasNull()} to distinguish between the two * {@link PropertySet#wasNull()} to distinguish between the two
* cases!</p></li> * cases!</p></li>
* *
* <li><p>1 if the document is password protected</p></li> * <li><p>1 if the document is password protected</p></li>
* *
* <li><p>2 if the document is read-only recommended</p></li> * <li><p>2 if the document is read-only recommended</p></li>
* *
* <li><p>4 if the document is read-only enforced</p></li> * <li><p>4 if the document is read-only enforced</p></li>
* *
* <li><p>8 if the document is locked for annotations</p></li> * <li><p>8 if the document is locked for annotations</p></li>
* *
* </ul> * </ul>
* *
* @return The security code or <code>null</code> * @return The security code or <code>null</code>
*/ */
public int getSecurity() public int getSecurity()
@ -729,7 +728,7 @@ public class SummaryInformation extends SpecialPropertySet
/** /**
* <p>Sets the security code.</p> * <p>Sets the security code.</p>
* *
* @param security The security code to set. * @param security The security code to set.
*/ */
public void setSecurity(final int security) public void setSecurity(final int security)

View File

@ -25,8 +25,7 @@ import org.apache.poi.util.LittleEndian;
* @author Drew Varner (Drew.Varner inOrAround sc.edu) * @author Drew Varner (Drew.Varner inOrAround sc.edu)
* @see SummaryInformation#getThumbnail() * @see SummaryInformation#getThumbnail()
*/ */
public class Thumbnail public final class Thumbnail {
{
/** /**
* <p>Offset in bytes where the Clipboard Format Tag starts in the * <p>Offset in bytes where the Clipboard Format Tag starts in the
@ -128,7 +127,7 @@ public class Thumbnail
* <p>A <code>byte[]</code> to hold a thumbnail image in ({@link * <p>A <code>byte[]</code> to hold a thumbnail image in ({@link
* Variant#VT_CF VT_CF}) format.</p> * Variant#VT_CF VT_CF}) format.</p>
*/ */
private byte[] thumbnailData = null; private byte[] _thumbnailData = null;
@ -154,7 +153,7 @@ public class Thumbnail
*/ */
public Thumbnail(final byte[] thumbnailData) public Thumbnail(final byte[] thumbnailData)
{ {
this.thumbnailData = thumbnailData; this._thumbnailData = thumbnailData;
} }
@ -168,7 +167,7 @@ public class Thumbnail
*/ */
public byte[] getThumbnail() public byte[] getThumbnail()
{ {
return thumbnailData; return _thumbnailData;
} }
@ -182,7 +181,7 @@ public class Thumbnail
*/ */
public void setThumbnail(final byte[] thumbnail) public void setThumbnail(final byte[] thumbnail)
{ {
this.thumbnailData = thumbnail; this._thumbnailData = thumbnail;
} }
@ -261,21 +260,18 @@ public class Thumbnail
if (!(getClipboardFormatTag() == CFTAG_WINDOWS)) if (!(getClipboardFormatTag() == CFTAG_WINDOWS))
throw new HPSFException("Clipboard Format Tag of Thumbnail must " + throw new HPSFException("Clipboard Format Tag of Thumbnail must " +
"be CFTAG_WINDOWS."); "be CFTAG_WINDOWS.");
if (!(getClipboardFormat() == CF_METAFILEPICT)) if (!(getClipboardFormat() == CF_METAFILEPICT)) {
throw new HPSFException("Clipboard Format of Thumbnail must " + throw new HPSFException("Clipboard Format of Thumbnail must " +
"be CF_METAFILEPICT."); "be CF_METAFILEPICT.");
else
{
byte[] thumbnail = getThumbnail();
int wmfImageLength = thumbnail.length - OFFSET_WMFDATA;
byte[] wmfImage = new byte[wmfImageLength];
System.arraycopy(thumbnail,
OFFSET_WMFDATA,
wmfImage,
0,
wmfImageLength);
return wmfImage;
} }
byte[] thumbnail = getThumbnail();
int wmfImageLength = thumbnail.length - OFFSET_WMFDATA;
byte[] wmfImage = new byte[wmfImageLength];
System.arraycopy(thumbnail,
OFFSET_WMFDATA,
wmfImage,
0,
wmfImageLength);
return wmfImage;
} }
} }

View File

@ -70,7 +70,7 @@ public class SectionIDMap extends HashMap {
}; };
/** /**
* <p>A property without a known name is described by this string.</p> * <p>A property without a known name is described by this string.</p>
*/ */
public static final String UNDEFINED = "[undefined]"; public static final String UNDEFINED = "[undefined]";
@ -121,15 +121,13 @@ public class SectionIDMap extends HashMap {
final long pid) final long pid)
{ {
final PropertyIDMap m = getInstance().get(sectionFormatID); final PropertyIDMap m = getInstance().get(sectionFormatID);
if (m == null) if (m == null) {
return UNDEFINED; return UNDEFINED;
else
{
final String s = (String) m.get(pid);
if (s == null)
return UNDEFINED;
return s;
} }
final String s = (String) m.get(pid);
if (s == null)
return UNDEFINED;
return s;
} }
@ -137,7 +135,7 @@ public class SectionIDMap extends HashMap {
/** /**
* <p>Returns the {@link PropertyIDMap} for a given section format * <p>Returns the {@link PropertyIDMap} for a given section format
* ID.</p> * ID.</p>
* *
* @param sectionFormatID the section format ID * @param sectionFormatID the section format ID
* @return the property ID map * @return the property ID map
*/ */
@ -166,7 +164,7 @@ public class SectionIDMap extends HashMap {
/** /**
* <p>Associates a section format ID with a {@link * <p>Associates a section format ID with a {@link
* PropertyIDMap}.</p> * PropertyIDMap}.</p>
* *
* @param sectionFormatID the section format ID * @param sectionFormatID the section format ID
* @param propertyIDMap the property ID map * @param propertyIDMap the property ID map
* @return as defined by {@link java.util.Map#put} * @return as defined by {@link java.util.Map#put}
@ -183,7 +181,7 @@ public class SectionIDMap extends HashMap {
* @deprecated Use {@link #put(byte[], PropertyIDMap)} instead! * @deprecated Use {@link #put(byte[], PropertyIDMap)} instead!
* *
* @see #put(byte[], PropertyIDMap) * @see #put(byte[], PropertyIDMap)
* *
* @param key This parameter remains undocumented since the method is * @param key This parameter remains undocumented since the method is
* deprecated. * deprecated.
* @param value This parameter remains undocumented since the method is * @param value This parameter remains undocumented since the method is

View File

@ -71,25 +71,22 @@ public class ModelFactory implements ERFListener
} }
//ERFListener //ERFListener
public boolean processRecord(Record rec) public boolean processRecord(Record rec) {
{ if (rec.getSid() == BOFRecord.sid) {
if (rec.getSid() == BOFRecord.sid) { if (lastEOF != true) {
if (lastEOF != true) { throw new RuntimeException("Not yet handled embedded models");
throw new RuntimeException("Not yet handled embedded models"); }
} else { BOFRecord bof = (BOFRecord)rec;
BOFRecord bof = (BOFRecord)rec; switch (bof.getType()) {
switch (bof.getType()) { case BOFRecord.TYPE_WORKBOOK:
case BOFRecord.TYPE_WORKBOOK: currentmodel = new Workbook();
currentmodel = new Workbook(); break;
break; case BOFRecord.TYPE_WORKSHEET:
case BOFRecord.TYPE_WORKSHEET: currentmodel = Sheet.createSheet();
currentmodel = Sheet.createSheet(); break;
break; default:
default:
throw new RuntimeException("Unsupported model type "+bof.getType()); throw new RuntimeException("Unsupported model type "+bof.getType());
} }
}
} }
if (rec.getSid() == EOFRecord.sid) { if (rec.getSid() == EOFRecord.sid) {
@ -98,8 +95,6 @@ public class ModelFactory implements ERFListener
} else { } else {
lastEOF = false; lastEOF = false;
} }
return true; return true;
} }
@ -115,6 +110,4 @@ public class ModelFactory implements ERFListener
mfl.process(model); mfl.process(model);
} }
} }
} }

View File

@ -31,130 +31,128 @@ import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDataFormatter; import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
/** /**
* A proxy HSSFListener that keeps track of the document * A proxy HSSFListener that keeps track of the document formatting records, and
* formatting records, and provides an easy way to look * provides an easy way to look up the format strings used by cells from their
* up the format strings used by cells from their ids. * ids.
*/ */
public class FormatTrackingHSSFListener implements HSSFListener { public class FormatTrackingHSSFListener implements HSSFListener {
private HSSFListener childListener; private final HSSFListener _childListener;
private HSSFDataFormatter formatter = new HSSFDataFormatter(); private HSSFDataFormatter _formatter = new HSSFDataFormatter();
private Map customFormatRecords = new Hashtable(); private final Map<Integer, FormatRecord> _customFormatRecords = new Hashtable<Integer, FormatRecord>();
private List xfRecords = new ArrayList(); private final List<ExtendedFormatRecord> _xfRecords = new ArrayList<ExtendedFormatRecord>();
public FormatTrackingHSSFListener(HSSFListener childListener) { public FormatTrackingHSSFListener(HSSFListener childListener) {
this.childListener = childListener; _childListener = childListener;
} }
protected int getNumberOfCustomFormats() { protected int getNumberOfCustomFormats() {
return customFormatRecords.size(); return _customFormatRecords.size();
} }
protected int getNumberOfExtendedFormats() { protected int getNumberOfExtendedFormats() {
return xfRecords.size(); return _xfRecords.size();
} }
/** /**
* Process this record ourselves, and then * Process this record ourselves, and then pass it on to our child listener
* pass it on to our child listener
*/ */
public void processRecord(Record record) { public void processRecord(Record record) {
// Handle it ourselves // Handle it ourselves
processRecordInternally(record); processRecordInternally(record);
// Now pass on to our child // Now pass on to our child
childListener.processRecord(record); _childListener.processRecord(record);
} }
/** /**
* Process the record ourselves, but do not * Process the record ourselves, but do not pass it on to the child
* pass it on to the child Listener. * Listener.
*
* @param record * @param record
*/ */
public void processRecordInternally(Record record) { public void processRecordInternally(Record record) {
if(record instanceof FormatRecord) { if (record instanceof FormatRecord) {
FormatRecord fr = (FormatRecord) record; FormatRecord fr = (FormatRecord) record;
customFormatRecords.put(new Integer(fr.getIndexCode()), fr); _customFormatRecords.put(new Integer(fr.getIndexCode()), fr);
} }
if(record instanceof ExtendedFormatRecord) { if (record instanceof ExtendedFormatRecord) {
ExtendedFormatRecord xr = (ExtendedFormatRecord) record; ExtendedFormatRecord xr = (ExtendedFormatRecord) record;
xfRecords.add(xr); _xfRecords.add(xr);
} }
} }
/** /**
* Formats the given numeric of date Cell's contents * Formats the given numeric of date Cell's contents as a String, in as
* as a String, in as close as we can to the way * close as we can to the way that Excel would do so. Uses the various
* that Excel would do so. * format records to manage this.
* Uses the various format records to manage this. *
* * TODO - move this to a central class in such a way that hssf.usermodel can
* TODO - move this to a central class in such a * make use of it too
* way that hssf.usermodel can make use of it too
*/ */
public String formatNumberDateCell(CellValueRecordInterface cell) { public String formatNumberDateCell(CellValueRecordInterface cell) {
double value; double value;
if(cell instanceof NumberRecord) { if (cell instanceof NumberRecord) {
value = ((NumberRecord)cell).getValue(); value = ((NumberRecord) cell).getValue();
} else if(cell instanceof FormulaRecord) { } else if (cell instanceof FormulaRecord) {
value = ((FormulaRecord)cell).getValue(); value = ((FormulaRecord) cell).getValue();
} else { } else {
throw new IllegalArgumentException("Unsupported CellValue Record passed in " + cell); throw new IllegalArgumentException("Unsupported CellValue Record passed in " + cell);
} }
// Get the built in format, if there is one // Get the built in format, if there is one
int formatIndex = getFormatIndex(cell); int formatIndex = getFormatIndex(cell);
String formatString = getFormatString(cell); String formatString = getFormatString(cell);
if(formatString == null) { if (formatString == null) {
return Double.toString(value); return Double.toString(value);
} else { }
// Format, using the nice new // Format, using the nice new
// HSSFDataFormatter to do the work for us // HSSFDataFormatter to do the work for us
return formatter.formatRawCellContents(value, formatIndex, formatString); return _formatter.formatRawCellContents(value, formatIndex, formatString);
}
} }
/** /**
* Returns the format string, eg $##.##, for the * Returns the format string, eg $##.##, for the given number format index.
* given number format index.
*/ */
public String getFormatString(int formatIndex) { public String getFormatString(int formatIndex) {
String format = null; String format = null;
if(formatIndex >= HSSFDataFormat.getNumberOfBuiltinBuiltinFormats()) { if (formatIndex >= HSSFDataFormat.getNumberOfBuiltinBuiltinFormats()) {
FormatRecord tfr = (FormatRecord)customFormatRecords.get(new Integer(formatIndex)); FormatRecord tfr = _customFormatRecords.get(new Integer(formatIndex));
if(tfr == null) { if (tfr == null) {
System.err.println("Requested format at index " + formatIndex + ", but it wasn't found"); System.err.println("Requested format at index " + formatIndex
} else { + ", but it wasn't found");
format = tfr.getFormatString(); } else {
} format = tfr.getFormatString();
} else { }
format = HSSFDataFormat.getBuiltinFormat((short)formatIndex); } else {
} format = HSSFDataFormat.getBuiltinFormat((short) formatIndex);
}
return format; return format;
} }
/** /**
* Returns the format string, eg $##.##, used * Returns the format string, eg $##.##, used by your cell
* by your cell
*/ */
public String getFormatString(CellValueRecordInterface cell) { public String getFormatString(CellValueRecordInterface cell) {
int formatIndex = getFormatIndex(cell); int formatIndex = getFormatIndex(cell);
if(formatIndex == -1) { if (formatIndex == -1) {
// Not found // Not found
return null; return null;
} }
return getFormatString(formatIndex); return getFormatString(formatIndex);
} }
/** /**
* Returns the index of the format string, used by your cell, * Returns the index of the format string, used by your cell, or -1 if none
* or -1 if none found * found
*/ */
public int getFormatIndex(CellValueRecordInterface cell) { public int getFormatIndex(CellValueRecordInterface cell) {
ExtendedFormatRecord xfr = (ExtendedFormatRecord) ExtendedFormatRecord xfr = _xfRecords.get(cell.getXFIndex());
xfRecords.get(cell.getXFIndex()); if (xfr == null) {
if(xfr == null) { System.err.println("Cell " + cell.getRow() + "," + cell.getColumn()
System.err.println("Cell " + cell.getRow() + "," + cell.getColumn() + " uses XF with index " + cell.getXFIndex() + ", but we don't have that"); + " uses XF with index " + cell.getXFIndex() + ", but we don't have that");
return -1; return -1;
} }
return xfr.getFormatIndex(); return xfr.getFormatIndex();
} }
} }

View File

@ -65,13 +65,13 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
* http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java</link> * http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java</link>
*/ */
public class EventBasedExcelExtractor extends POIOLE2TextExtractor { public class EventBasedExcelExtractor extends POIOLE2TextExtractor {
private POIFSFileSystem fs; private POIFSFileSystem _fs;
private boolean includeSheetNames = true; boolean _includeSheetNames = true;
private boolean formulasNotResults = false; boolean _formulasNotResults = false;
public EventBasedExcelExtractor(POIFSFileSystem fs) { public EventBasedExcelExtractor(POIFSFileSystem fs) {
super(null); super(null);
this.fs = fs; _fs = fs;
} }
/** /**
@ -94,14 +94,14 @@ public class EventBasedExcelExtractor extends POIOLE2TextExtractor {
* Should sheet names be included? Default is true * Should sheet names be included? Default is true
*/ */
public void setIncludeSheetNames(boolean includeSheetNames) { public void setIncludeSheetNames(boolean includeSheetNames) {
this.includeSheetNames = includeSheetNames; _includeSheetNames = includeSheetNames;
} }
/** /**
* Should we return the formula itself, and not * Should we return the formula itself, and not
* the result it produces? Default is false * the result it produces? Default is false
*/ */
public void setFormulasNotResults(boolean formulasNotResults) { public void setFormulasNotResults(boolean formulasNotResults) {
this.formulasNotResults = formulasNotResults; _formulasNotResults = formulasNotResults;
} }
@ -113,7 +113,7 @@ public class EventBasedExcelExtractor extends POIOLE2TextExtractor {
try { try {
TextListener tl = triggerExtraction(); TextListener tl = triggerExtraction();
text = tl.text.toString(); text = tl._text.toString();
if(! text.endsWith("\n")) { if(! text.endsWith("\n")) {
text = text + "\n"; text = text + "\n";
} }
@ -127,30 +127,33 @@ public class EventBasedExcelExtractor extends POIOLE2TextExtractor {
private TextListener triggerExtraction() throws IOException { private TextListener triggerExtraction() throws IOException {
TextListener tl = new TextListener(); TextListener tl = new TextListener();
FormatTrackingHSSFListener ft = new FormatTrackingHSSFListener(tl); FormatTrackingHSSFListener ft = new FormatTrackingHSSFListener(tl);
tl.ft = ft; tl._ft = ft;
// Register and process // Register and process
HSSFEventFactory factory = new HSSFEventFactory(); HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest(); HSSFRequest request = new HSSFRequest();
request.addListenerForAllRecords(ft); request.addListenerForAllRecords(ft);
factory.processWorkbookEvents(request, fs); factory.processWorkbookEvents(request, _fs);
return tl; return tl;
} }
private class TextListener implements HSSFListener { private class TextListener implements HSSFListener {
private FormatTrackingHSSFListener ft; FormatTrackingHSSFListener _ft;
private SSTRecord sstRecord; private SSTRecord sstRecord;
private List sheetNames = new ArrayList(); private final List<String> sheetNames;
private StringBuffer text = new StringBuffer(); final StringBuffer _text = new StringBuffer();
private int sheetNum = -1; private int sheetNum = -1;
private int rowNum; private int rowNum;
private boolean outputNextStringValue = false; private boolean outputNextStringValue = false;
private int nextRow = -1; private int nextRow = -1;
public TextListener() {
sheetNames = new ArrayList<String>();
}
public void processRecord(Record record) { public void processRecord(Record record) {
String thisText = null; String thisText = null;
int thisRow = -1; int thisRow = -1;
@ -166,9 +169,9 @@ public class EventBasedExcelExtractor extends POIOLE2TextExtractor {
sheetNum++; sheetNum++;
rowNum = -1; rowNum = -1;
if(includeSheetNames) { if(_includeSheetNames) {
if(text.length() > 0) text.append("\n"); if(_text.length() > 0) _text.append("\n");
text.append(sheetNames.get(sheetNum)); _text.append(sheetNames.get(sheetNum));
} }
} }
break; break;
@ -180,7 +183,7 @@ public class EventBasedExcelExtractor extends POIOLE2TextExtractor {
FormulaRecord frec = (FormulaRecord) record; FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow(); thisRow = frec.getRow();
if(formulasNotResults) { if(_formulasNotResults) {
thisText = HSSFFormulaParser.toFormulaString((HSSFWorkbook)null, frec.getParsedExpression()); thisText = HSSFFormulaParser.toFormulaString((HSSFWorkbook)null, frec.getParsedExpression());
} else { } else {
if(frec.hasCachedResultString()) { if(frec.hasCachedResultString()) {
@ -232,12 +235,12 @@ public class EventBasedExcelExtractor extends POIOLE2TextExtractor {
if(thisText != null) { if(thisText != null) {
if(thisRow != rowNum) { if(thisRow != rowNum) {
rowNum = thisRow; rowNum = thisRow;
if(text.length() > 0) if(_text.length() > 0)
text.append("\n"); _text.append("\n");
} else { } else {
text.append("\t"); _text.append("\t");
} }
text.append(thisText); _text.append(thisText);
} }
} }
@ -247,35 +250,33 @@ public class EventBasedExcelExtractor extends POIOLE2TextExtractor {
*/ */
private String formatNumberDateCell(CellValueRecordInterface cell, double value) { private String formatNumberDateCell(CellValueRecordInterface cell, double value) {
// Get the built in format, if there is one // Get the built in format, if there is one
int formatIndex = ft.getFormatIndex(cell); int formatIndex = _ft.getFormatIndex(cell);
String formatString = ft.getFormatString(cell); String formatString = _ft.getFormatString(cell);
if(formatString == null) { if(formatString == null) {
return Double.toString(value); return Double.toString(value);
} else {
// Is it a date?
if(HSSFDateUtil.isADateFormat(formatIndex,formatString) &&
HSSFDateUtil.isValidExcelDate(value)) {
// Java wants M not m for month
formatString = formatString.replace('m','M');
// Change \- into -, if it's there
formatString = formatString.replaceAll("\\\\-","-");
// Format as a date
Date d = HSSFDateUtil.getJavaDate(value, false);
DateFormat df = new SimpleDateFormat(formatString);
return df.format(d);
} else {
if(formatString == "General") {
// Some sort of wierd default
return Double.toString(value);
}
// Format as a number
DecimalFormat df = new DecimalFormat(formatString);
return df.format(value);
}
} }
// Is it a date?
if(HSSFDateUtil.isADateFormat(formatIndex,formatString) &&
HSSFDateUtil.isValidExcelDate(value)) {
// Java wants M not m for month
formatString = formatString.replace('m','M');
// Change \- into -, if it's there
formatString = formatString.replaceAll("\\\\-","-");
// Format as a date
Date d = HSSFDateUtil.getJavaDate(value, false);
DateFormat df = new SimpleDateFormat(formatString);
return df.format(d);
}
if(formatString == "General") {
// Some sort of wierd default
return Double.toString(value);
}
// Format as a number
DecimalFormat df = new DecimalFormat(formatString);
return df.format(value);
} }
} }
} }

View File

@ -50,18 +50,14 @@ public class ConvertAnchor
anchor.setDy2( (short) a.getDy2() ); anchor.setDy2( (short) a.getDy2() );
return anchor; return anchor;
} }
else HSSFChildAnchor a = (HSSFChildAnchor) userAnchor;
{ EscherChildAnchorRecord anchor = new EscherChildAnchorRecord();
HSSFChildAnchor a = (HSSFChildAnchor) userAnchor; anchor.setRecordId( EscherChildAnchorRecord.RECORD_ID );
EscherChildAnchorRecord anchor = new EscherChildAnchorRecord(); anchor.setOptions( (short) 0x0000 );
anchor.setRecordId( EscherChildAnchorRecord.RECORD_ID ); anchor.setDx1( (short) Math.min(a.getDx1(), a.getDx2()) );
anchor.setOptions( (short) 0x0000 ); anchor.setDy1( (short) Math.min(a.getDy1(), a.getDy2()) );
anchor.setDx1( (short) Math.min(a.getDx1(), a.getDx2()) ); anchor.setDx2( (short) Math.max(a.getDx2(), a.getDx1()) );
anchor.setDy1( (short) Math.min(a.getDy1(), a.getDy2()) ); anchor.setDy2( (short) Math.max(a.getDy2(), a.getDy1()) );
anchor.setDx2( (short) Math.max(a.getDx2(), a.getDx1()) ); return anchor;
anchor.setDy2( (short) Math.max(a.getDy2(), a.getDy1()) );
return anchor;
}
} }
} }

View File

@ -116,17 +116,14 @@ public abstract class AbstractEscherHolderRecord extends Record {
System.arraycopy( rawData, 0, data, 4 + offset, rawData.length); System.arraycopy( rawData, 0, data, 4 + offset, rawData.length);
return rawData.length + 4; return rawData.length + 4;
} }
else LittleEndian.putShort(data, 0 + offset, getSid());
{ LittleEndian.putShort(data, 2 + offset, (short)(getRecordSize() - 4));
LittleEndian.putShort(data, 0 + offset, getSid());
LittleEndian.putShort(data, 2 + offset, (short)(getRecordSize() - 4));
int pos = offset + 4; int pos = offset + 4;
for ( Iterator iterator = escherRecords.iterator(); iterator.hasNext(); ) for ( Iterator iterator = escherRecords.iterator(); iterator.hasNext(); )
{ {
EscherRecord r = (EscherRecord) iterator.next(); EscherRecord r = (EscherRecord) iterator.next();
pos += r.serialize( pos, data, new NullEscherSerializationListener() ); pos += r.serialize( pos, data, new NullEscherSerializationListener() );
}
} }
return getRecordSize(); return getRecordSize();
} }
@ -172,7 +169,7 @@ public abstract class AbstractEscherHolderRecord extends Record {
{ {
escherRecords.clear(); escherRecords.clear();
} }
/** /**
* If we have a EscherContainerRecord as one of our * If we have a EscherContainerRecord as one of our
* children (and most top level escher holders do), * children (and most top level escher holders do),
@ -204,7 +201,7 @@ public abstract class AbstractEscherHolderRecord extends Record {
return r; return r;
} }
} }
// Then check our children in turn // Then check our children in turn
for(Iterator<EscherRecord> it = records.iterator(); it.hasNext();) { for(Iterator<EscherRecord> it = records.iterator(); it.hasNext();) {
EscherRecord r = it.next(); EscherRecord r = it.next();
@ -215,7 +212,7 @@ public abstract class AbstractEscherHolderRecord extends Record {
} }
} }
} }
// Not found in this lot // Not found in this lot
return null; return null;
} }

View File

@ -95,11 +95,11 @@ public final class CFRuleRecord extends StandardRecord {
private short field_6_not_used; private short field_6_not_used;
private FontFormatting fontFormatting; private FontFormatting _fontFormatting;
private BorderFormatting borderFormatting; private BorderFormatting _borderFormatting;
private PatternFormatting patternFormatting; private PatternFormatting _patternFormatting;
private Formula field_17_formula1; private Formula field_17_formula1;
private Formula field_18_formula2; private Formula field_18_formula2;
@ -117,9 +117,9 @@ public final class CFRuleRecord extends StandardRecord {
field_5_options = undocumented.clear(field_5_options); field_5_options = undocumented.clear(field_5_options);
field_6_not_used = (short)0x8002; // Excel seems to write this value, but it doesn't seem to care what it reads field_6_not_used = (short)0x8002; // Excel seems to write this value, but it doesn't seem to care what it reads
fontFormatting=null; _fontFormatting=null;
borderFormatting=null; _borderFormatting=null;
patternFormatting=null; _patternFormatting=null;
field_17_formula1=Formula.create(Ptg.EMPTY_PTG_ARRAY); field_17_formula1=Formula.create(Ptg.EMPTY_PTG_ARRAY);
field_18_formula2=Formula.create(Ptg.EMPTY_PTG_ARRAY); field_18_formula2=Formula.create(Ptg.EMPTY_PTG_ARRAY);
} }
@ -157,15 +157,15 @@ public final class CFRuleRecord extends StandardRecord {
field_6_not_used = in.readShort(); field_6_not_used = in.readShort();
if (containsFontFormattingBlock()) { if (containsFontFormattingBlock()) {
fontFormatting = new FontFormatting(in); _fontFormatting = new FontFormatting(in);
} }
if (containsBorderFormattingBlock()) { if (containsBorderFormattingBlock()) {
borderFormatting = new BorderFormatting(in); _borderFormatting = new BorderFormatting(in);
} }
if (containsPatternFormattingBlock()) { if (containsPatternFormattingBlock()) {
patternFormatting = new PatternFormatting(in); _patternFormatting = new PatternFormatting(in);
} }
// "You may not use unions, intersections or array constants in Conditional Formatting criteria" // "You may not use unions, intersections or array constants in Conditional Formatting criteria"
@ -184,19 +184,16 @@ public final class CFRuleRecord extends StandardRecord {
} }
public void setFontFormatting(FontFormatting fontFormatting) public void setFontFormatting(FontFormatting fontFormatting)
{ {
this.fontFormatting = fontFormatting; _fontFormatting = fontFormatting;
setOptionFlag(fontFormatting != null, font); setOptionFlag(fontFormatting != null, font);
} }
public FontFormatting getFontFormatting() public FontFormatting getFontFormatting()
{ {
if( containsFontFormattingBlock()) if( containsFontFormattingBlock())
{ {
return fontFormatting; return _fontFormatting;
}
else
{
return null;
} }
return null;
} }
public boolean containsAlignFormattingBlock() public boolean containsAlignFormattingBlock()
@ -214,19 +211,16 @@ public final class CFRuleRecord extends StandardRecord {
} }
public void setBorderFormatting(BorderFormatting borderFormatting) public void setBorderFormatting(BorderFormatting borderFormatting)
{ {
this.borderFormatting = borderFormatting; _borderFormatting = borderFormatting;
setOptionFlag(borderFormatting != null, bord); setOptionFlag(borderFormatting != null, bord);
} }
public BorderFormatting getBorderFormatting() public BorderFormatting getBorderFormatting()
{ {
if( containsBorderFormattingBlock()) if( containsBorderFormattingBlock())
{ {
return borderFormatting; return _borderFormatting;
}
else
{
return null;
} }
return null;
} }
public boolean containsPatternFormattingBlock() public boolean containsPatternFormattingBlock()
@ -235,19 +229,16 @@ public final class CFRuleRecord extends StandardRecord {
} }
public void setPatternFormatting(PatternFormatting patternFormatting) public void setPatternFormatting(PatternFormatting patternFormatting)
{ {
this.patternFormatting = patternFormatting; _patternFormatting = patternFormatting;
setOptionFlag(patternFormatting!=null, patt); setOptionFlag(patternFormatting!=null, patt);
} }
public PatternFormatting getPatternFormatting() public PatternFormatting getPatternFormatting()
{ {
if( containsPatternFormattingBlock()) if( containsPatternFormattingBlock())
{ {
return patternFormatting; return _patternFormatting;
}
else
{
return null;
} }
return null;
} }
public boolean containsProtectionFormattingBlock() public boolean containsProtectionFormattingBlock()
@ -452,16 +443,16 @@ public final class CFRuleRecord extends StandardRecord {
out.writeShort(field_6_not_used); out.writeShort(field_6_not_used);
if (containsFontFormattingBlock()) { if (containsFontFormattingBlock()) {
byte[] fontFormattingRawRecord = fontFormatting.getRawRecord(); byte[] fontFormattingRawRecord = _fontFormatting.getRawRecord();
out.write(fontFormattingRawRecord); out.write(fontFormattingRawRecord);
} }
if (containsBorderFormattingBlock()) { if (containsBorderFormattingBlock()) {
borderFormatting.serialize(out); _borderFormatting.serialize(out);
} }
if (containsPatternFormattingBlock()) { if (containsPatternFormattingBlock()) {
patternFormatting.serialize(out); _patternFormatting.serialize(out);
} }
field_17_formula1.serializeTokens(out); field_17_formula1.serializeTokens(out);
@ -470,7 +461,7 @@ public final class CFRuleRecord extends StandardRecord {
protected int getDataSize() { protected int getDataSize() {
return 12 + return 12 +
(containsFontFormattingBlock()?fontFormatting.getRawRecord().length:0)+ (containsFontFormattingBlock()?_fontFormatting.getRawRecord().length:0)+
(containsBorderFormattingBlock()?8:0)+ (containsBorderFormattingBlock()?8:0)+
(containsPatternFormattingBlock()?4:0)+ (containsPatternFormattingBlock()?4:0)+
getFormulaSize(field_17_formula1)+ getFormulaSize(field_17_formula1)+
@ -486,13 +477,13 @@ public final class CFRuleRecord extends StandardRecord {
buffer.append(" OPTION FLAGS=0x"+Integer.toHexString(getOptions())); buffer.append(" OPTION FLAGS=0x"+Integer.toHexString(getOptions()));
if (false) { if (false) {
if (containsFontFormattingBlock()) { if (containsFontFormattingBlock()) {
buffer.append(fontFormatting.toString()); buffer.append(_fontFormatting.toString());
} }
if (containsBorderFormattingBlock()) { if (containsBorderFormattingBlock()) {
buffer.append(borderFormatting.toString()); buffer.append(_borderFormatting.toString());
} }
if (containsPatternFormattingBlock()) { if (containsPatternFormattingBlock()) {
buffer.append(patternFormatting.toString()); buffer.append(_patternFormatting.toString());
} }
buffer.append("[/CFRULE]\n"); buffer.append("[/CFRULE]\n");
} }
@ -504,13 +495,13 @@ public final class CFRuleRecord extends StandardRecord {
rec.field_5_options = field_5_options; rec.field_5_options = field_5_options;
rec.field_6_not_used = field_6_not_used; rec.field_6_not_used = field_6_not_used;
if (containsFontFormattingBlock()) { if (containsFontFormattingBlock()) {
rec.fontFormatting = (FontFormatting) fontFormatting.clone(); rec._fontFormatting = (FontFormatting) _fontFormatting.clone();
} }
if (containsBorderFormattingBlock()) { if (containsBorderFormattingBlock()) {
rec.borderFormatting = (BorderFormatting) borderFormatting.clone(); rec._borderFormatting = (BorderFormatting) _borderFormatting.clone();
} }
if (containsPatternFormattingBlock()) { if (containsPatternFormattingBlock()) {
rec.patternFormatting = (PatternFormatting) patternFormatting.clone(); rec._patternFormatting = (PatternFormatting) _patternFormatting.clone();
} }
rec.field_17_formula1 = field_17_formula1.copy(); rec.field_17_formula1 = field_17_formula1.copy();
rec.field_18_formula2 = field_17_formula1.copy(); rec.field_18_formula2 = field_17_formula1.copy();

View File

@ -58,24 +58,21 @@ public final class DrawingGroupRecord extends AbstractEscherHolderRecord {
{ {
return writeData( offset, data, rawData ); return writeData( offset, data, rawData );
} }
else byte[] buffer = new byte[getRawDataSize()];
int pos = 0;
for ( Iterator iterator = getEscherRecords().iterator(); iterator.hasNext(); )
{ {
byte[] buffer = new byte[getRawDataSize()]; EscherRecord r = (EscherRecord) iterator.next();
int pos = 0; pos += r.serialize(pos, buffer, new NullEscherSerializationListener() );
for ( Iterator iterator = getEscherRecords().iterator(); iterator.hasNext(); )
{
EscherRecord r = (EscherRecord) iterator.next();
pos += r.serialize(pos, buffer, new NullEscherSerializationListener() );
}
return writeData( offset, data, buffer );
} }
return writeData( offset, data, buffer );
} }
/** /**
* Process the bytes into escher records. * Process the bytes into escher records.
* (Not done by default in case we break things, * (Not done by default in case we break things,
* unless you set the "poi.deserialize.escher" * unless you set the "poi.deserialize.escher"
* system property) * system property)
*/ */
public void processChildRecords() { public void processChildRecords() {
@ -140,5 +137,4 @@ public final class DrawingGroupRecord extends AbstractEscherHolderRecord {
LittleEndian.putShort(data, 0 + offset, ContinueRecord.sid); LittleEndian.putShort(data, 0 + offset, ContinueRecord.sid);
LittleEndian.putShort(data, 2 + offset, (short) sizeExcludingHeader); LittleEndian.putShort(data, 2 + offset, (short) sizeExcludingHeader);
} }
} }

View File

@ -38,23 +38,23 @@ import org.apache.poi.util.LittleEndianOutput;
* @author Marc Johnson (mjohnson at apache dot org) * @author Marc Johnson (mjohnson at apache dot org)
* @author Glen Stampoultzis (glens at apache.org) * @author Glen Stampoultzis (glens at apache.org)
*/ */
public final class UnicodeString implements Comparable { public final class UnicodeString implements Comparable<UnicodeString> {
private short field_1_charCount; private short field_1_charCount;
private byte field_2_optionflags; private byte field_2_optionflags;
private String field_3_string; private String field_3_string;
private List field_4_format_runs; private List<FormatRun> field_4_format_runs;
private byte[] field_5_ext_rst; private byte[] field_5_ext_rst;
private static final BitField highByte = BitFieldFactory.getInstance(0x1); private static final BitField highByte = BitFieldFactory.getInstance(0x1);
private static final BitField extBit = BitFieldFactory.getInstance(0x4); private static final BitField extBit = BitFieldFactory.getInstance(0x4);
private static final BitField richText = BitFieldFactory.getInstance(0x8); private static final BitField richText = BitFieldFactory.getInstance(0x8);
public static class FormatRun implements Comparable { public static class FormatRun implements Comparable<FormatRun> {
short character; final short _character;
short fontIndex; short _fontIndex;
public FormatRun(short character, short fontIndex) { public FormatRun(short character, short fontIndex) {
this.character = character; this._character = character;
this.fontIndex = fontIndex; this._fontIndex = fontIndex;
} }
public FormatRun(LittleEndianInput in) { public FormatRun(LittleEndianInput in) {
@ -62,11 +62,11 @@ public final class UnicodeString implements Comparable {
} }
public short getCharacterPos() { public short getCharacterPos() {
return character; return _character;
} }
public short getFontIndex() { public short getFontIndex() {
return fontIndex; return _fontIndex;
} }
public boolean equals(Object o) { public boolean equals(Object o) {
@ -75,25 +75,26 @@ public final class UnicodeString implements Comparable {
} }
FormatRun other = ( FormatRun ) o; FormatRun other = ( FormatRun ) o;
return character == other.character && fontIndex == other.fontIndex; return _character == other._character && _fontIndex == other._fontIndex;
} }
public int compareTo(Object obj) { public int compareTo(FormatRun r) {
FormatRun r = (FormatRun)obj; if (_character == r._character && _fontIndex == r._fontIndex) {
if ((character == r.character) && (fontIndex == r.fontIndex))
return 0; return 0;
if (character == r.character) }
return fontIndex - r.fontIndex; if (_character == r._character) {
else return character - r.character; return _fontIndex - r._fontIndex;
}
return _character - r._character;
} }
public String toString() { public String toString() {
return "character="+character+",fontIndex="+fontIndex; return "character="+_character+",fontIndex="+_fontIndex;
} }
public void serialize(LittleEndianOutput out) { public void serialize(LittleEndianOutput out) {
out.writeShort(character); out.writeShort(_character);
out.writeShort(fontIndex); out.writeShort(_fontIndex);
} }
} }
@ -151,8 +152,8 @@ public final class UnicodeString implements Comparable {
return false; return false;
for (int i=0;i<size;i++) { for (int i=0;i<size;i++) {
FormatRun run1 = (FormatRun)field_4_format_runs.get(i); FormatRun run1 = field_4_format_runs.get(i);
FormatRun run2 = (FormatRun)other.field_4_format_runs.get(i); FormatRun run2 = other.field_4_format_runs.get(i);
if (!run1.equals(run2)) if (!run1.equals(run2))
return false; return false;
@ -206,10 +207,10 @@ public final class UnicodeString implements Comparable {
} else { } else {
field_3_string = in.readUnicodeLEString(getCharCount()); field_3_string = in.readUnicodeLEString(getCharCount());
} }
if (isRichText() && (runCount > 0)) { if (isRichText() && (runCount > 0)) {
field_4_format_runs = new ArrayList(runCount); field_4_format_runs = new ArrayList<FormatRun>(runCount);
for (int i=0;i<runCount;i++) { for (int i=0;i<runCount;i++) {
field_4_format_runs.add(new FormatRun(in)); field_4_format_runs.add(new FormatRun(in));
} }
@ -328,20 +329,22 @@ public final class UnicodeString implements Comparable {
} }
public FormatRun getFormatRun(int index) { public FormatRun getFormatRun(int index) {
if (field_4_format_runs == null) if (field_4_format_runs == null) {
return null; return null;
if ((index < 0) || (index >= field_4_format_runs.size())) }
return null; if (index < 0 || index >= field_4_format_runs.size()) {
return (FormatRun)field_4_format_runs.get(index); return null;
}
return field_4_format_runs.get(index);
} }
private int findFormatRunAt(int characterPos) { private int findFormatRunAt(int characterPos) {
int size = field_4_format_runs.size(); int size = field_4_format_runs.size();
for (int i=0;i<size;i++) { for (int i=0;i<size;i++) {
FormatRun r = (FormatRun)field_4_format_runs.get(i); FormatRun r = field_4_format_runs.get(i);
if (r.character == characterPos) if (r._character == characterPos)
return i; return i;
else if (r.character > characterPos) else if (r._character > characterPos)
return -1; return -1;
} }
return -1; return -1;
@ -353,10 +356,11 @@ public final class UnicodeString implements Comparable {
* replaced with the font run to be added. * replaced with the font run to be added.
*/ */
public void addFormatRun(FormatRun r) { public void addFormatRun(FormatRun r) {
if (field_4_format_runs == null) if (field_4_format_runs == null) {
field_4_format_runs = new ArrayList(); field_4_format_runs = new ArrayList<FormatRun>();
}
int index = findFormatRunAt(r.character); int index = findFormatRunAt(r._character);
if (index != -1) if (index != -1)
field_4_format_runs.remove(index); field_4_format_runs.remove(index);
@ -369,9 +373,10 @@ public final class UnicodeString implements Comparable {
field_2_optionflags = richText.setByte(field_2_optionflags); field_2_optionflags = richText.setByte(field_2_optionflags);
} }
public Iterator formatIterator() { public Iterator<FormatRun> formatIterator() {
if (field_4_format_runs != null) if (field_4_format_runs != null) {
return field_4_format_runs.iterator(); return field_4_format_runs.iterator();
}
return null; return null;
} }
@ -398,21 +403,19 @@ public final class UnicodeString implements Comparable {
/** /**
* Swaps all use in the string of one font index * Swaps all use in the string of one font index
* for use of a different font index. * for use of a different font index.
* Normally only called when fonts have been * Normally only called when fonts have been
* removed / re-ordered * removed / re-ordered
*/ */
public void swapFontUse(short oldFontIndex, short newFontIndex) { public void swapFontUse(short oldFontIndex, short newFontIndex) {
Iterator i = field_4_format_runs.iterator(); for (FormatRun run : field_4_format_runs) {
while(i.hasNext()) { if(run._fontIndex == oldFontIndex) {
FormatRun run = (FormatRun)i.next(); run._fontIndex = newFontIndex;
if(run.fontIndex == oldFontIndex) {
run.fontIndex = newFontIndex;
} }
} }
} }
/** /**
* unlike the real records we return the same as "getString()" rather than debug info * unlike the real records we return the same as "getString()" rather than debug info
* @see #getDebugInfo() * @see #getDebugInfo()
@ -431,7 +434,6 @@ public final class UnicodeString implements Comparable {
* @return String of output for biffviewer etc. * @return String of output for biffviewer etc.
* *
*/ */
public String getDebugInfo() public String getDebugInfo()
{ {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
@ -444,7 +446,7 @@ public final class UnicodeString implements Comparable {
buffer.append(" .string = ").append(getString()).append("\n"); buffer.append(" .string = ").append(getString()).append("\n");
if (field_4_format_runs != null) { if (field_4_format_runs != null) {
for (int i = 0; i < field_4_format_runs.size();i++) { for (int i = 0; i < field_4_format_runs.size();i++) {
FormatRun r = (FormatRun)field_4_format_runs.get(i); FormatRun r = field_4_format_runs.get(i);
buffer.append(" .format_run"+i+" = ").append(r.toString()).append("\n"); buffer.append(" .format_run"+i+" = ").append(r.toString()).append("\n");
} }
} }
@ -464,7 +466,7 @@ public final class UnicodeString implements Comparable {
if (isExtendedText() && field_5_ext_rst != null) { if (isExtendedText() && field_5_ext_rst != null) {
extendedDataSize = field_5_ext_rst.length; extendedDataSize = field_5_ext_rst.length;
} }
out.writeString(field_3_string, numberOfRichTextRuns, extendedDataSize); out.writeString(field_3_string, numberOfRichTextRuns, extendedDataSize);
if (numberOfRichTextRuns > 0) { if (numberOfRichTextRuns > 0) {
@ -474,7 +476,7 @@ public final class UnicodeString implements Comparable {
if (out.getAvailableSpace() < 4) { if (out.getAvailableSpace() < 4) {
out.writeContinue(); out.writeContinue();
} }
FormatRun r = (FormatRun)field_4_format_runs.get(i); FormatRun r = field_4_format_runs.get(i);
r.serialize(out); r.serialize(out);
} }
} }
@ -496,9 +498,7 @@ public final class UnicodeString implements Comparable {
} }
} }
public int compareTo(Object obj) public int compareTo(UnicodeString str) {
{
UnicodeString str = ( UnicodeString ) obj;
int result = getString().compareTo(str.getString()); int result = getString().compareTo(str.getString());
@ -524,8 +524,8 @@ public final class UnicodeString implements Comparable {
return size - str.field_4_format_runs.size(); return size - str.field_4_format_runs.size();
for (int i=0;i<size;i++) { for (int i=0;i<size;i++) {
FormatRun run1 = (FormatRun)field_4_format_runs.get(i); FormatRun run1 = field_4_format_runs.get(i);
FormatRun run2 = (FormatRun)str.field_4_format_runs.get(i); FormatRun run2 = str.field_4_format_runs.get(i);
result = run1.compareTo(run2); result = run1.compareTo(run2);
if (result != 0) if (result != 0)
@ -571,11 +571,9 @@ public final class UnicodeString implements Comparable {
str.field_2_optionflags = field_2_optionflags; str.field_2_optionflags = field_2_optionflags;
str.field_3_string = field_3_string; str.field_3_string = field_3_string;
if (field_4_format_runs != null) { if (field_4_format_runs != null) {
str.field_4_format_runs = new ArrayList(); str.field_4_format_runs = new ArrayList<FormatRun>();
int size = field_4_format_runs.size(); for (FormatRun r : field_4_format_runs) {
for (int i = 0; i < size; i++) { str.field_4_format_runs.add(new FormatRun(r._character, r._fontIndex));
FormatRun r = (FormatRun) field_4_format_runs.get(i);
str.field_4_format_runs.add(new FormatRun(r.character, r.fontIndex));
} }
} }
if (field_5_ext_rst != null) { if (field_5_ext_rst != null) {

View File

@ -29,9 +29,9 @@ import java.util.StringTokenizer;
*/ */
public class FontDetails public class FontDetails
{ {
private String fontName; private String _fontName;
private int height; private int _height;
private Map charWidths = new HashMap(); private final Map<Character, Integer> charWidths = new HashMap<Character, Integer>();
/** /**
* Construct the font details with the given name and height. * Construct the font details with the given name and height.
@ -41,18 +41,18 @@ public class FontDetails
*/ */
public FontDetails( String fontName, int height ) public FontDetails( String fontName, int height )
{ {
this.fontName = fontName; _fontName = fontName;
this.height = height; _height = height;
} }
public String getFontName() public String getFontName()
{ {
return fontName; return _fontName;
} }
public int getHeight() public int getHeight()
{ {
return height; return _height;
} }
public void addChar( char c, int width ) public void addChar( char c, int width )
@ -68,10 +68,10 @@ public class FontDetails
public int getCharWidth( char c ) public int getCharWidth( char c )
{ {
Integer widthInteger = (Integer)(charWidths.get(new Character(c))); Integer widthInteger = (Integer)(charWidths.get(new Character(c)));
if (widthInteger == null && c != 'W') if (widthInteger == null && c != 'W') {
return getCharWidth('W'); return getCharWidth('W');
else }
return widthInteger.intValue(); return widthInteger.intValue();
} }
public void addChars( char[] characters, int[] widths ) public void addChars( char[] characters, int[] widths )
@ -82,15 +82,15 @@ public class FontDetails
} }
} }
protected static String buildFontHeightProperty(String fontName) { protected static String buildFontHeightProperty(String fontName) {
return "font." + fontName + ".height"; return "font." + fontName + ".height";
} }
protected static String buildFontWidthsProperty(String fontName) { protected static String buildFontWidthsProperty(String fontName) {
return "font." + fontName + ".widths"; return "font." + fontName + ".widths";
} }
protected static String buildFontCharactersProperty(String fontName) { protected static String buildFontCharactersProperty(String fontName) {
return "font." + fontName + ".characters"; return "font." + fontName + ".characters";
} }
/** /**
* Create an instance of <code>FontDetails</code> by loading them from the * Create an instance of <code>FontDetails</code> by loading them from the
@ -173,6 +173,4 @@ public class FontDetails
return list; return list;
} }
} }

View File

@ -29,20 +29,16 @@ import org.apache.poi.ss.usermodel.Font;
/** /**
* High level representation of the style of a cell in a sheet of a workbook. * High level representation of the style of a cell in a sheet of a workbook.
* *
* @version 1.0-pre
*
* @author Andrew C. Oliver (acoliver at apache dot org) * @author Andrew C. Oliver (acoliver at apache dot org)
* @author Jason Height (jheight at chariot dot net dot au) * @author Jason Height (jheight at chariot dot net dot au)
* @see org.apache.poi.hssf.usermodel.HSSFWorkbook#createCellStyle() * @see org.apache.poi.hssf.usermodel.HSSFWorkbook#createCellStyle()
* @see org.apache.poi.hssf.usermodel.HSSFWorkbook#getCellStyleAt(short) * @see org.apache.poi.hssf.usermodel.HSSFWorkbook#getCellStyleAt(short)
* @see org.apache.poi.hssf.usermodel.HSSFCell#setCellStyle(HSSFCellStyle) * @see org.apache.poi.hssf.usermodel.HSSFCell#setCellStyle(HSSFCellStyle)
*/ */
public final class HSSFCellStyle implements CellStyle {
public class HSSFCellStyle implements CellStyle private ExtendedFormatRecord _format = null;
{ private short _index = 0;
private ExtendedFormatRecord format = null; private Workbook _workbook = null;
private short index = 0;
private Workbook workbook = null;
/** Creates new HSSFCellStyle why would you want to do this?? */ /** Creates new HSSFCellStyle why would you want to do this?? */
@ -52,9 +48,9 @@ public class HSSFCellStyle implements CellStyle
} }
protected HSSFCellStyle(short index, ExtendedFormatRecord rec, Workbook workbook) protected HSSFCellStyle(short index, ExtendedFormatRecord rec, Workbook workbook)
{ {
this.workbook = workbook; _workbook = workbook;
this.index = index; _index = index;
format = rec; _format = rec;
} }
/** /**
@ -62,25 +58,24 @@ public class HSSFCellStyle implements CellStyle
* @return unique index number of the underlying record this style represents (probably you don't care * @return unique index number of the underlying record this style represents (probably you don't care
* unless you're comparing which one is which) * unless you're comparing which one is which)
*/ */
public short getIndex() public short getIndex()
{ {
return index; return _index;
} }
/** /**
* Return the parent style for this cell style. * Return the parent style for this cell style.
* In most cases this will be null, but in a few * In most cases this will be null, but in a few
* cases there'll be a fully defined parent. * cases there'll be a fully defined parent.
*/ */
public HSSFCellStyle getParentStyle() { public HSSFCellStyle getParentStyle() {
if(format.getParentIndex() == 0) { if(_format.getParentIndex() == 0) {
return null; return null;
} }
return new HSSFCellStyle( return new HSSFCellStyle(
format.getParentIndex(), _format.getParentIndex(),
workbook.getExFormatAt(format.getParentIndex()), _workbook.getExFormatAt(_format.getParentIndex()),
workbook _workbook
); );
} }
@ -88,10 +83,9 @@ public class HSSFCellStyle implements CellStyle
* set the data format (must be a valid format) * set the data format (must be a valid format)
* @see org.apache.poi.hssf.usermodel.HSSFDataFormat * @see org.apache.poi.hssf.usermodel.HSSFDataFormat
*/ */
public void setDataFormat(short fmt) public void setDataFormat(short fmt)
{ {
format.setFormatIndex(fmt); _format.setFormatIndex(fmt);
} }
/** /**
@ -101,9 +95,9 @@ public class HSSFCellStyle implements CellStyle
public short getDataFormat() public short getDataFormat()
{ {
return format.getFormatIndex(); return _format.getFormatIndex();
} }
/** /**
* Get the contents of the format string, by looking up * Get the contents of the format string, by looking up
* the DataFormat against the bound workbook * the DataFormat against the bound workbook
@ -111,7 +105,7 @@ public class HSSFCellStyle implements CellStyle
* @return the format string or "General" if not found * @return the format string or "General" if not found
*/ */
public String getDataFormatString() { public String getDataFormatString() {
return getDataFormatString(workbook); return getDataFormatString(_workbook);
} }
/** /**
* Get the contents of the format string, by looking up * Get the contents of the format string, by looking up
@ -122,7 +116,7 @@ public class HSSFCellStyle implements CellStyle
*/ */
public String getDataFormatString(org.apache.poi.ss.usermodel.Workbook workbook) { public String getDataFormatString(org.apache.poi.ss.usermodel.Workbook workbook) {
HSSFDataFormat format = new HSSFDataFormat( ((HSSFWorkbook)workbook).getWorkbook() ); HSSFDataFormat format = new HSSFDataFormat( ((HSSFWorkbook)workbook).getWorkbook() );
int idx = getDataFormat(); int idx = getDataFormat();
return idx == -1 ? "General" : format.getFormat(getDataFormat()); return idx == -1 ? "General" : format.getFormat(getDataFormat());
} }
@ -133,7 +127,7 @@ public class HSSFCellStyle implements CellStyle
*/ */
public String getDataFormatString(org.apache.poi.hssf.model.Workbook workbook) { public String getDataFormatString(org.apache.poi.hssf.model.Workbook workbook) {
HSSFDataFormat format = new HSSFDataFormat( workbook ); HSSFDataFormat format = new HSSFDataFormat( workbook );
return format.getFormat(getDataFormat()); return format.getFormat(getDataFormat());
} }
@ -147,9 +141,9 @@ public class HSSFCellStyle implements CellStyle
setFont((HSSFFont)font); setFont((HSSFFont)font);
} }
public void setFont(HSSFFont font) { public void setFont(HSSFFont font) {
format.setIndentNotParentFont(true); _format.setIndentNotParentFont(true);
short fontindex = font.getIndex(); short fontindex = font.getIndex();
format.setFontIndex(fontindex); _format.setFontIndex(fontindex);
} }
/** /**
@ -158,9 +152,9 @@ public class HSSFCellStyle implements CellStyle
*/ */
public short getFontIndex() public short getFontIndex()
{ {
return format.getFontIndex(); return _format.getFontIndex();
} }
/** /**
* gets the font for this style * gets the font for this style
* @param parentWorkbook The HSSFWorkbook that this style belongs to * @param parentWorkbook The HSSFWorkbook that this style belongs to
@ -175,42 +169,38 @@ public class HSSFCellStyle implements CellStyle
* set the cell's using this style to be hidden * set the cell's using this style to be hidden
* @param hidden - whether the cell using this style should be hidden * @param hidden - whether the cell using this style should be hidden
*/ */
public void setHidden(boolean hidden) public void setHidden(boolean hidden)
{ {
format.setIndentNotParentCellOptions(true); _format.setIndentNotParentCellOptions(true);
format.setHidden(hidden); _format.setHidden(hidden);
} }
/** /**
* get whether the cell's using this style are to be hidden * get whether the cell's using this style are to be hidden
* @return hidden - whether the cell using this style should be hidden * @return hidden - whether the cell using this style should be hidden
*/ */
public boolean getHidden() public boolean getHidden()
{ {
return format.isHidden(); return _format.isHidden();
} }
/** /**
* set the cell's using this style to be locked * set the cell's using this style to be locked
* @param locked - whether the cell using this style should be locked * @param locked - whether the cell using this style should be locked
*/ */
public void setLocked(boolean locked) public void setLocked(boolean locked)
{ {
format.setIndentNotParentCellOptions(true); _format.setIndentNotParentCellOptions(true);
format.setLocked(locked); _format.setLocked(locked);
} }
/** /**
* get whether the cell's using this style are to be locked * get whether the cell's using this style are to be locked
* @return hidden - whether the cell using this style should be locked * @return hidden - whether the cell using this style should be locked
*/ */
public boolean getLocked() public boolean getLocked()
{ {
return format.isLocked(); return _format.isLocked();
} }
/** /**
@ -224,11 +214,10 @@ public class HSSFCellStyle implements CellStyle
* @see #ALIGN_JUSTIFY * @see #ALIGN_JUSTIFY
* @see #ALIGN_CENTER_SELECTION * @see #ALIGN_CENTER_SELECTION
*/ */
public void setAlignment(short align) public void setAlignment(short align)
{ {
format.setIndentNotParentAlignment(true); _format.setIndentNotParentAlignment(true);
format.setAlignment(align); _format.setAlignment(align);
} }
/** /**
@ -242,31 +231,28 @@ public class HSSFCellStyle implements CellStyle
* @see #ALIGN_JUSTIFY * @see #ALIGN_JUSTIFY
* @see #ALIGN_CENTER_SELECTION * @see #ALIGN_CENTER_SELECTION
*/ */
public short getAlignment() public short getAlignment()
{ {
return format.getAlignment(); return _format.getAlignment();
} }
/** /**
* set whether the text should be wrapped * set whether the text should be wrapped
* @param wrapped wrap text or not * @param wrapped wrap text or not
*/ */
public void setWrapText(boolean wrapped) public void setWrapText(boolean wrapped)
{ {
format.setIndentNotParentAlignment(true); _format.setIndentNotParentAlignment(true);
format.setWrapText(wrapped); _format.setWrapText(wrapped);
} }
/** /**
* get whether the text should be wrapped * get whether the text should be wrapped
* @return wrap text or not * @return wrap text or not
*/ */
public boolean getWrapText() public boolean getWrapText()
{ {
return format.getWrapText(); return _format.getWrapText();
} }
/** /**
@ -277,10 +263,9 @@ public class HSSFCellStyle implements CellStyle
* @see #VERTICAL_BOTTOM * @see #VERTICAL_BOTTOM
* @see #VERTICAL_JUSTIFY * @see #VERTICAL_JUSTIFY
*/ */
public void setVerticalAlignment(short align) public void setVerticalAlignment(short align)
{ {
format.setVerticalAlignment(align); _format.setVerticalAlignment(align);
} }
/** /**
@ -291,17 +276,15 @@ public class HSSFCellStyle implements CellStyle
* @see #VERTICAL_BOTTOM * @see #VERTICAL_BOTTOM
* @see #VERTICAL_JUSTIFY * @see #VERTICAL_JUSTIFY
*/ */
public short getVerticalAlignment() public short getVerticalAlignment()
{ {
return format.getVerticalAlignment(); return _format.getVerticalAlignment();
} }
/** /**
* set the degree of rotation for the text in the cell * set the degree of rotation for the text in the cell
* @param rotation degrees (between -90 and 90 degrees) * @param rotation degrees (between -90 and 90 degrees)
*/ */
public void setRotation(short rotation) public void setRotation(short rotation)
{ {
if ((rotation < 0)&&(rotation >= -90)) { if ((rotation < 0)&&(rotation >= -90)) {
@ -312,17 +295,16 @@ public class HSSFCellStyle implements CellStyle
else if ((rotation < -90) ||(rotation > 90)) else if ((rotation < -90) ||(rotation > 90))
//Do not allow an incorrect rotation to be set //Do not allow an incorrect rotation to be set
throw new IllegalArgumentException("The rotation must be between -90 and 90 degrees"); throw new IllegalArgumentException("The rotation must be between -90 and 90 degrees");
format.setRotation(rotation); _format.setRotation(rotation);
} }
/** /**
* get the degree of rotation for the text in the cell * get the degree of rotation for the text in the cell
* @return rotation degrees (between -90 and 90 degrees) * @return rotation degrees (between -90 and 90 degrees)
*/ */
public short getRotation() public short getRotation()
{ {
short rotation = format.getRotation(); short rotation = _format.getRotation();
if (rotation > 90) if (rotation > 90)
//This is actually the 4th quadrant //This is actually the 4th quadrant
rotation = (short)(90-rotation); rotation = (short)(90-rotation);
@ -333,20 +315,18 @@ public class HSSFCellStyle implements CellStyle
* set the number of spaces to indent the text in the cell * set the number of spaces to indent the text in the cell
* @param indent - number of spaces * @param indent - number of spaces
*/ */
public void setIndention(short indent) public void setIndention(short indent)
{ {
format.setIndent(indent); _format.setIndent(indent);
} }
/** /**
* get the number of spaces to indent the text in the cell * get the number of spaces to indent the text in the cell
* @return indent - number of spaces * @return indent - number of spaces
*/ */
public short getIndention() public short getIndention()
{ {
return format.getIndent(); return _format.getIndent();
} }
/** /**
@ -367,11 +347,10 @@ public class HSSFCellStyle implements CellStyle
* @see #BORDER_MEDIUM_DASH_DOT_DOT * @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT * @see #BORDER_SLANTED_DASH_DOT
*/ */
public void setBorderLeft(short border) public void setBorderLeft(short border)
{ {
format.setIndentNotParentBorder(true); _format.setIndentNotParentBorder(true);
format.setBorderLeft(border); _format.setBorderLeft(border);
} }
/** /**
@ -392,10 +371,9 @@ public class HSSFCellStyle implements CellStyle
* @see #BORDER_MEDIUM_DASH_DOT_DOT * @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT * @see #BORDER_SLANTED_DASH_DOT
*/ */
public short getBorderLeft() public short getBorderLeft()
{ {
return format.getBorderLeft(); return _format.getBorderLeft();
} }
/** /**
@ -416,11 +394,10 @@ public class HSSFCellStyle implements CellStyle
* @see #BORDER_MEDIUM_DASH_DOT_DOT * @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT * @see #BORDER_SLANTED_DASH_DOT
*/ */
public void setBorderRight(short border) public void setBorderRight(short border)
{ {
format.setIndentNotParentBorder(true); _format.setIndentNotParentBorder(true);
format.setBorderRight(border); _format.setBorderRight(border);
} }
/** /**
@ -441,10 +418,9 @@ public class HSSFCellStyle implements CellStyle
* @see #BORDER_MEDIUM_DASH_DOT_DOT * @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT * @see #BORDER_SLANTED_DASH_DOT
*/ */
public short getBorderRight() public short getBorderRight()
{ {
return format.getBorderRight(); return _format.getBorderRight();
} }
/** /**
@ -465,11 +441,10 @@ public class HSSFCellStyle implements CellStyle
* @see #BORDER_MEDIUM_DASH_DOT_DOT * @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT * @see #BORDER_SLANTED_DASH_DOT
*/ */
public void setBorderTop(short border) public void setBorderTop(short border)
{ {
format.setIndentNotParentBorder(true); _format.setIndentNotParentBorder(true);
format.setBorderTop(border); _format.setBorderTop(border);
} }
/** /**
@ -490,10 +465,9 @@ public class HSSFCellStyle implements CellStyle
* @see #BORDER_MEDIUM_DASH_DOT_DOT * @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT * @see #BORDER_SLANTED_DASH_DOT
*/ */
public short getBorderTop() public short getBorderTop()
{ {
return format.getBorderTop(); return _format.getBorderTop();
} }
/** /**
@ -514,11 +488,10 @@ public class HSSFCellStyle implements CellStyle
* @see #BORDER_MEDIUM_DASH_DOT_DOT * @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT * @see #BORDER_SLANTED_DASH_DOT
*/ */
public void setBorderBottom(short border) public void setBorderBottom(short border)
{ {
format.setIndentNotParentBorder(true); _format.setIndentNotParentBorder(true);
format.setBorderBottom(border); _format.setBorderBottom(border);
} }
/** /**
@ -541,7 +514,7 @@ public class HSSFCellStyle implements CellStyle
*/ */
public short getBorderBottom() public short getBorderBottom()
{ {
return format.getBorderBottom(); return _format.getBorderBottom();
} }
/** /**
@ -550,7 +523,7 @@ public class HSSFCellStyle implements CellStyle
*/ */
public void setLeftBorderColor(short color) public void setLeftBorderColor(short color)
{ {
format.setLeftBorderPaletteIdx(color); _format.setLeftBorderPaletteIdx(color);
} }
/** /**
@ -560,7 +533,7 @@ public class HSSFCellStyle implements CellStyle
*/ */
public short getLeftBorderColor() public short getLeftBorderColor()
{ {
return format.getLeftBorderPaletteIdx(); return _format.getLeftBorderPaletteIdx();
} }
/** /**
@ -569,7 +542,7 @@ public class HSSFCellStyle implements CellStyle
*/ */
public void setRightBorderColor(short color) public void setRightBorderColor(short color)
{ {
format.setRightBorderPaletteIdx(color); _format.setRightBorderPaletteIdx(color);
} }
/** /**
@ -579,7 +552,7 @@ public class HSSFCellStyle implements CellStyle
*/ */
public short getRightBorderColor() public short getRightBorderColor()
{ {
return format.getRightBorderPaletteIdx(); return _format.getRightBorderPaletteIdx();
} }
/** /**
@ -588,7 +561,7 @@ public class HSSFCellStyle implements CellStyle
*/ */
public void setTopBorderColor(short color) public void setTopBorderColor(short color)
{ {
format.setTopBorderPaletteIdx(color); _format.setTopBorderPaletteIdx(color);
} }
/** /**
@ -598,7 +571,7 @@ public class HSSFCellStyle implements CellStyle
*/ */
public short getTopBorderColor() public short getTopBorderColor()
{ {
return format.getTopBorderPaletteIdx(); return _format.getTopBorderPaletteIdx();
} }
/** /**
@ -607,7 +580,7 @@ public class HSSFCellStyle implements CellStyle
*/ */
public void setBottomBorderColor(short color) public void setBottomBorderColor(short color)
{ {
format.setBottomBorderPaletteIdx(color); _format.setBottomBorderPaletteIdx(color);
} }
/** /**
@ -617,7 +590,7 @@ public class HSSFCellStyle implements CellStyle
*/ */
public short getBottomBorderColor() public short getBottomBorderColor()
{ {
return format.getBottomBorderPaletteIdx(); return _format.getBottomBorderPaletteIdx();
} }
/** /**
@ -646,19 +619,18 @@ public class HSSFCellStyle implements CellStyle
*/ */
public void setFillPattern(short fp) public void setFillPattern(short fp)
{ {
format.setAdtlFillPattern(fp); _format.setAdtlFillPattern(fp);
} }
/** /**
* get the fill pattern (??) - set to 1 to fill with foreground color * get the fill pattern (??) - set to 1 to fill with foreground color
* @return fill pattern * @return fill pattern
*/ */
public short getFillPattern() public short getFillPattern()
{ {
return format.getAdtlFillPattern(); return _format.getAdtlFillPattern();
} }
/** /**
* Checks if the background and foreground fills are set correctly when one * Checks if the background and foreground fills are set correctly when one
* or the other is set to the default color. * or the other is set to the default color.
@ -667,18 +639,18 @@ public class HSSFCellStyle implements CellStyle
* <p>NONE AUTOMATIC</p> * <p>NONE AUTOMATIC</p>
* <p>0x41 0x40</p> * <p>0x41 0x40</p>
* <p>NONE RED/ANYTHING</p> * <p>NONE RED/ANYTHING</p>
* <p>0x40 0xSOMETHING</p> * <p>0x40 0xSOMETHING</p>
*/ */
private void checkDefaultBackgroundFills() { private void checkDefaultBackgroundFills() {
if (format.getFillForeground() == org.apache.poi.hssf.util.HSSFColor.AUTOMATIC.index) { if (_format.getFillForeground() == org.apache.poi.hssf.util.HSSFColor.AUTOMATIC.index) {
//JMH: Why +1, hell why not. I guess it made some sense to someone at the time. Doesnt //JMH: Why +1, hell why not. I guess it made some sense to someone at the time. Doesnt
//to me now.... But experience has shown that when the fore is set to AUTOMATIC then the //to me now.... But experience has shown that when the fore is set to AUTOMATIC then the
//background needs to be incremented...... //background needs to be incremented......
if (format.getFillBackground() != (org.apache.poi.hssf.util.HSSFColor.AUTOMATIC.index+1)) if (_format.getFillBackground() != (org.apache.poi.hssf.util.HSSFColor.AUTOMATIC.index+1))
setFillBackgroundColor((short)(org.apache.poi.hssf.util.HSSFColor.AUTOMATIC.index+1)); setFillBackgroundColor((short)(org.apache.poi.hssf.util.HSSFColor.AUTOMATIC.index+1));
} else if (format.getFillBackground() == org.apache.poi.hssf.util.HSSFColor.AUTOMATIC.index+1) } else if (_format.getFillBackground() == org.apache.poi.hssf.util.HSSFColor.AUTOMATIC.index+1)
//Now if the forground changes to a non-AUTOMATIC color the background resets itself!!! //Now if the forground changes to a non-AUTOMATIC color the background resets itself!!!
if (format.getFillForeground() != org.apache.poi.hssf.util.HSSFColor.AUTOMATIC.index) if (_format.getFillForeground() != org.apache.poi.hssf.util.HSSFColor.AUTOMATIC.index)
setFillBackgroundColor(org.apache.poi.hssf.util.HSSFColor.AUTOMATIC.index); setFillBackgroundColor(org.apache.poi.hssf.util.HSSFColor.AUTOMATIC.index);
} }
@ -688,14 +660,14 @@ public class HSSFCellStyle implements CellStyle
* For example: * For example:
* <pre> * <pre>
* cs.setFillPattern(HSSFCellStyle.FINE_DOTS ); * cs.setFillPattern(HSSFCellStyle.FINE_DOTS );
* cs.setFillBackgroundColor(new HSSFColor.RED().getIndex()); * cs.setFillBackgroundColor(new HSSFColor.RED().getIndex());
* </pre> * </pre>
* optionally a Foreground and background fill can be applied: * optionally a Foreground and background fill can be applied:
* <i>Note: Ensure Foreground color is set prior to background</i> * <i>Note: Ensure Foreground color is set prior to background</i>
* <pre> * <pre>
* cs.setFillPattern(HSSFCellStyle.FINE_DOTS ); * cs.setFillPattern(HSSFCellStyle.FINE_DOTS );
* cs.setFillForegroundColor(new HSSFColor.BLUE().getIndex()); * cs.setFillForegroundColor(new HSSFColor.BLUE().getIndex());
* cs.setFillBackgroundColor(new HSSFColor.RED().getIndex()); * cs.setFillBackgroundColor(new HSSFColor.RED().getIndex());
* </pre> * </pre>
* or, for the special case of SOLID_FILL: * or, for the special case of SOLID_FILL:
* <pre> * <pre>
@ -707,10 +679,9 @@ public class HSSFCellStyle implements CellStyle
* *
* @param bg color * @param bg color
*/ */
public void setFillBackgroundColor(short bg) public void setFillBackgroundColor(short bg)
{ {
format.setFillBackground(bg); _format.setFillBackground(bg);
checkDefaultBackgroundFills(); checkDefaultBackgroundFills();
} }
@ -723,12 +694,13 @@ public class HSSFCellStyle implements CellStyle
*/ */
public short getFillBackgroundColor() public short getFillBackgroundColor()
{ {
short result = format.getFillBackground(); short result = _format.getFillBackground();
//JMH: Do this ridiculous conversion, and let HSSFCellStyle //JMH: Do this ridiculous conversion, and let HSSFCellStyle
//internally migrate back and forth //internally migrate back and forth
if (result == (HSSFColor.AUTOMATIC.index+1)) if (result == (HSSFColor.AUTOMATIC.index+1)) {
return HSSFColor.AUTOMATIC.index; return HSSFColor.AUTOMATIC.index;
else return result; }
return result;
} }
/** /**
@ -738,29 +710,29 @@ public class HSSFCellStyle implements CellStyle
*/ */
public void setFillForegroundColor(short bg) public void setFillForegroundColor(short bg)
{ {
format.setFillForeground(bg); _format.setFillForeground(bg);
checkDefaultBackgroundFills(); checkDefaultBackgroundFills();
} }
/** /**
* Get the foreground fill color. * Get the foreground fill color.
* Many cells are filled with this, instead of a * Many cells are filled with this, instead of a
* background color ({@link #getFillBackgroundColor()}) * background color ({@link #getFillBackgroundColor()})
* @see org.apache.poi.hssf.usermodel.HSSFPalette#getColor(short) * @see org.apache.poi.hssf.usermodel.HSSFPalette#getColor(short)
* @return fill color * @return fill color
*/ */
public short getFillForegroundColor() public short getFillForegroundColor()
{ {
return format.getFillForeground(); return _format.getFillForeground();
} }
/** /**
* Gets the name of the user defined style. * Gets the name of the user defined style.
* Returns null for built in styles, and * Returns null for built in styles, and
* styles where no name has been defined * styles where no name has been defined
*/ */
public String getUserStyleName() { public String getUserStyleName() {
StyleRecord sr = workbook.getStyleRecord(index); StyleRecord sr = _workbook.getStyleRecord(_index);
if(sr == null) { if(sr == null) {
return null; return null;
} }
@ -769,15 +741,15 @@ public class HSSFCellStyle implements CellStyle
} }
return sr.getName(); return sr.getName();
} }
/** /**
* Sets the name of the user defined style. * Sets the name of the user defined style.
* Will complain if you try this on a built in style. * Will complain if you try this on a built in style.
*/ */
public void setUserStyleName(String styleName) { public void setUserStyleName(String styleName) {
StyleRecord sr = workbook.getStyleRecord(index); StyleRecord sr = _workbook.getStyleRecord(_index);
if(sr == null) { if(sr == null) {
sr = workbook.createStyleRecord(index); sr = _workbook.createStyleRecord(_index);
} }
if(sr.isBuiltin()) { if(sr.isBuiltin()) {
throw new IllegalArgumentException("Unable to set user specified style names for built in styles!"); throw new IllegalArgumentException("Unable to set user specified style names for built in styles!");
@ -794,19 +766,19 @@ public class HSSFCellStyle implements CellStyle
* @throws IllegalArgumentException if there's a workbook mis-match * @throws IllegalArgumentException if there's a workbook mis-match
*/ */
public void verifyBelongsToWorkbook(HSSFWorkbook wb) { public void verifyBelongsToWorkbook(HSSFWorkbook wb) {
if(wb.getWorkbook() != workbook) { if(wb.getWorkbook() != _workbook) {
throw new IllegalArgumentException("This Style does not belong to the supplied Workbook. Are you trying to assign a style from one workbook to the cell of a differnt workbook?"); throw new IllegalArgumentException("This Style does not belong to the supplied Workbook. Are you trying to assign a style from one workbook to the cell of a differnt workbook?");
} }
} }
/** /**
* Clones all the style information from another * Clones all the style information from another
* HSSFCellStyle, onto this one. This * HSSFCellStyle, onto this one. This
* HSSFCellStyle will then have all the same * HSSFCellStyle will then have all the same
* properties as the source, but the two may * properties as the source, but the two may
* be edited independently. * be edited independently.
* Any stylings on this HSSFCellStyle will be lost! * Any stylings on this HSSFCellStyle will be lost!
* *
* The source HSSFCellStyle could be from another * The source HSSFCellStyle could be from another
* HSSFWorkbook if you like. This allows you to * HSSFWorkbook if you like. This allows you to
* copy styles from one HSSFWorkbook to another. * copy styles from one HSSFWorkbook to another.
@ -821,37 +793,37 @@ public class HSSFCellStyle implements CellStyle
public void cloneStyleFrom(HSSFCellStyle source) { public void cloneStyleFrom(HSSFCellStyle source) {
// First we need to clone the extended format // First we need to clone the extended format
// record // record
format.cloneStyleFrom(source.format); _format.cloneStyleFrom(source._format);
// Handle matching things if we cross workbooks // Handle matching things if we cross workbooks
if(workbook != source.workbook) { if(_workbook != source._workbook) {
// Then we need to clone the format string, // Then we need to clone the format string,
// and update the format record for this // and update the format record for this
short fmt = (short)workbook.createFormat(source.getDataFormatString() ); short fmt = (short)_workbook.createFormat(source.getDataFormatString() );
setDataFormat(fmt); setDataFormat(fmt);
// Finally we need to clone the font, // Finally we need to clone the font,
// and update the format record for this // and update the format record for this
FontRecord fr = workbook.createNewFont(); FontRecord fr = _workbook.createNewFont();
fr.cloneStyleFrom( fr.cloneStyleFrom(
source.workbook.getFontRecordAt( source._workbook.getFontRecordAt(
source.getFontIndex() source.getFontIndex()
) )
); );
HSSFFont font = new HSSFFont( HSSFFont font = new HSSFFont(
(short)workbook.getFontIndex(fr), fr (short)_workbook.getFontIndex(fr), fr
); );
setFont(font); setFont(font);
} }
} }
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((format == null) ? 0 : format.hashCode()); result = prime * result + ((_format == null) ? 0 : _format.hashCode());
result = prime * result + index; result = prime * result + _index;
return result; return result;
} }
@ -860,12 +832,12 @@ public class HSSFCellStyle implements CellStyle
if (obj == null) return false; if (obj == null) return false;
if (obj instanceof HSSFCellStyle) { if (obj instanceof HSSFCellStyle) {
final HSSFCellStyle other = (HSSFCellStyle) obj; final HSSFCellStyle other = (HSSFCellStyle) obj;
if (format == null) { if (_format == null) {
if (other.format != null) if (other._format != null)
return false; return false;
} else if (!format.equals(other.format)) } else if (!_format.equals(other._format))
return false; return false;
if (index != other.index) if (_index != other._index)
return false; return false;
return true; return true;
} }

View File

@ -26,9 +26,7 @@ import org.apache.poi.ss.usermodel.ClientAnchor;
* *
* @author Glen Stampoultzis (glens at apache.org) * @author Glen Stampoultzis (glens at apache.org)
*/ */
public class HSSFClientAnchor public final class HSSFClientAnchor extends HSSFAnchor implements ClientAnchor {
extends HSSFAnchor implements ClientAnchor
{
short col1; short col1;
int row1; int row1;
short col2; short col2;
@ -108,10 +106,10 @@ public class HSSFClientAnchor
private float getRowHeightInPoints(HSSFSheet sheet, int rowNum) private float getRowHeightInPoints(HSSFSheet sheet, int rowNum)
{ {
HSSFRow row = sheet.getRow(rowNum); HSSFRow row = sheet.getRow(rowNum);
if (row == null) if (row == null) {
return sheet.getDefaultRowHeightInPoints(); return sheet.getDefaultRowHeightInPoints();
else }
return row.getHeightInPoints(); return row.getHeightInPoints();
} }
public short getCol1() public short getCol1()
@ -204,10 +202,10 @@ public class HSSFClientAnchor
*/ */
public boolean isHorizontallyFlipped() public boolean isHorizontallyFlipped()
{ {
if (col1 == col2) if (col1 == col2) {
return dx1 > dx2; return dx1 > dx2;
else }
return col1 > col2; return col1 > col2;
} }
/** /**
@ -215,10 +213,10 @@ public class HSSFClientAnchor
*/ */
public boolean isVerticallyFlipped() public boolean isVerticallyFlipped()
{ {
if (row1 == row2) if (row1 == row2) {
return dy1 > dy2; return dy1 > dy2;
else }
return row1 > row2; return row1 > row2;
} }
/** /**

View File

@ -23,6 +23,7 @@ import java.util.Iterator;
import org.apache.poi.hssf.record.EmbeddedObjectRefSubRecord; import org.apache.poi.hssf.record.EmbeddedObjectRefSubRecord;
import org.apache.poi.hssf.record.ObjRecord; import org.apache.poi.hssf.record.ObjRecord;
import org.apache.poi.hssf.record.SubRecord;
import org.apache.poi.poifs.filesystem.DirectoryEntry; import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.Entry; import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
@ -33,17 +34,16 @@ import org.apache.poi.util.HexDump;
* *
* @author Daniel Noll * @author Daniel Noll
*/ */
public final class HSSFObjectData public final class HSSFObjectData {
{
/** /**
* Underlying object record ultimately containing a reference to the object. * Underlying object record ultimately containing a reference to the object.
*/ */
private ObjRecord record; private final ObjRecord _record;
/** /**
* Reference to the filesystem, required for retrieving the object data. * Reference to the filesystem, required for retrieving the object data.
*/ */
private POIFSFileSystem poifs; private final POIFSFileSystem _poifs;
/** /**
* Constructs object data by wrapping a lower level object record. * Constructs object data by wrapping a lower level object record.
@ -53,10 +53,10 @@ public final class HSSFObjectData
*/ */
public HSSFObjectData(ObjRecord record, POIFSFileSystem poifs) public HSSFObjectData(ObjRecord record, POIFSFileSystem poifs)
{ {
this.record = record; _record = record;
this.poifs = poifs; _poifs = poifs;
} }
/** /**
* Returns the OLE2 Class Name of the object * Returns the OLE2 Class Name of the object
*/ */
@ -77,14 +77,13 @@ public final class HSSFObjectData
int streamId = subRecord.getStreamId().intValue(); int streamId = subRecord.getStreamId().intValue();
String streamName = "MBD" + HexDump.toHex(streamId); String streamName = "MBD" + HexDump.toHex(streamId);
Entry entry = poifs.getRoot().getEntry(streamName); Entry entry = _poifs.getRoot().getEntry(streamName);
if (entry instanceof DirectoryEntry) { if (entry instanceof DirectoryEntry) {
return (DirectoryEntry) entry; return (DirectoryEntry) entry;
} else {
throw new IOException("Stream " + streamName + " was not an OLE2 directory");
} }
throw new IOException("Stream " + streamName + " was not an OLE2 directory");
} }
/** /**
* Returns the data portion, for an ObjectData * Returns the data portion, for an ObjectData
* that doesn't have an associated POIFS Directory * that doesn't have an associated POIFS Directory
@ -93,34 +92,34 @@ public final class HSSFObjectData
public byte[] getObjectData() { public byte[] getObjectData() {
return findObjectRecord().getObjectData(); return findObjectRecord().getObjectData();
} }
/** /**
* Does this ObjectData have an associated POIFS * Does this ObjectData have an associated POIFS
* Directory Entry? * Directory Entry?
* (Not all do, those that don't have a data portion) * (Not all do, those that don't have a data portion)
*/ */
public boolean hasDirectoryEntry() { public boolean hasDirectoryEntry() {
EmbeddedObjectRefSubRecord subRecord = findObjectRecord(); EmbeddedObjectRefSubRecord subRecord = findObjectRecord();
// 'stream id' field tells you // 'stream id' field tells you
Integer streamId = subRecord.getStreamId(); Integer streamId = subRecord.getStreamId();
return streamId != null && streamId.intValue() != 0; return streamId != null && streamId.intValue() != 0;
} }
/** /**
* Finds the EmbeddedObjectRefSubRecord, or throws an * Finds the EmbeddedObjectRefSubRecord, or throws an
* Exception if there wasn't one * Exception if there wasn't one
*/ */
protected EmbeddedObjectRefSubRecord findObjectRecord() { protected EmbeddedObjectRefSubRecord findObjectRecord() {
Iterator subRecordIter = record.getSubRecords().iterator(); Iterator<SubRecord> subRecordIter = _record.getSubRecords().iterator();
while (subRecordIter.hasNext()) { while (subRecordIter.hasNext()) {
Object subRecord = subRecordIter.next(); Object subRecord = subRecordIter.next();
if (subRecord instanceof EmbeddedObjectRefSubRecord) { if (subRecord instanceof EmbeddedObjectRefSubRecord) {
return (EmbeddedObjectRefSubRecord)subRecord; return (EmbeddedObjectRefSubRecord)subRecord;
} }
} }
throw new IllegalStateException("Object data does not contain a reference to an embedded object OLE2 directory"); throw new IllegalStateException("Object data does not contain a reference to an embedded object OLE2 directory");
} }
} }

View File

@ -31,60 +31,59 @@ import org.apache.poi.ss.usermodel.RichTextString;
* @author Glen Stampoultzis (glens at apache.org) * @author Glen Stampoultzis (glens at apache.org)
* @author Jason Height (jheight at apache.org) * @author Jason Height (jheight at apache.org)
*/ */
public class HSSFRichTextString public final class HSSFRichTextString implements Comparable<HSSFRichTextString>, RichTextString {
implements Comparable, RichTextString
{
/** Place holder for indicating that NO_FONT has been applied here */ /** Place holder for indicating that NO_FONT has been applied here */
public static final short NO_FONT = 0; public static final short NO_FONT = 0;
private UnicodeString string; private UnicodeString _string;
private Workbook book; private Workbook _book;
private LabelSSTRecord record; private LabelSSTRecord _record;
public HSSFRichTextString() public HSSFRichTextString()
{ {
this(""); this("");
} }
public HSSFRichTextString( String string ) public HSSFRichTextString(String string) {
{ if (string == null) {
if (string == null) _string = new UnicodeString("");
string = ""; } else {
this.string = new UnicodeString(string); _string = new UnicodeString(string);
}
} }
HSSFRichTextString(Workbook book, LabelSSTRecord record) { HSSFRichTextString(Workbook book, LabelSSTRecord record) {
setWorkbookReferences(book, record); setWorkbookReferences(book, record);
this.string = book.getSSTString(record.getSSTIndex()); _string = book.getSSTString(record.getSSTIndex());
} }
/** This must be called to setup the internal work book references whenever /** This must be called to setup the internal work book references whenever
* a RichTextString is added to a cell * a RichTextString is added to a cell
*/ */
void setWorkbookReferences(Workbook book, LabelSSTRecord record) { void setWorkbookReferences(Workbook book, LabelSSTRecord record) {
this.book = book; _book = book;
this.record = record; _record = record;
} }
/** Called whenever the unicode string is modified. When it is modified /** Called whenever the unicode string is modified. When it is modified
* we need to create a new SST index, so that other LabelSSTRecords will not * we need to create a new SST index, so that other LabelSSTRecords will not
* be affected by changes that we make to this string. * be affected by changes that we make to this string.
*/ */
private UnicodeString cloneStringIfRequired() { private UnicodeString cloneStringIfRequired() {
if (book == null) if (_book == null)
return string; return _string;
UnicodeString s = (UnicodeString)string.clone(); UnicodeString s = (UnicodeString)_string.clone();
return s; return s;
} }
private void addToSSTIfRequired() { private void addToSSTIfRequired() {
if (book != null) { if (_book != null) {
int index = book.addSSTString(string); int index = _book.addSSTString(_string);
record.setSSTIndex(index); _record.setSSTIndex(index);
//The act of adding the string to the SST record may have meant that //The act of adding the string to the SST record may have meant that
//a extsing string was returned for the index, so update our local version //an existing string was returned for the index, so update our local version
string = book.getSSTString(index); _string = _book.getSSTString(index);
} }
} }
@ -113,8 +112,8 @@ public class HSSFRichTextString
} }
//Need to clear the current formatting between the startIndex and endIndex //Need to clear the current formatting between the startIndex and endIndex
string = cloneStringIfRequired(); _string = cloneStringIfRequired();
Iterator formatting = string.formatIterator(); Iterator formatting = _string.formatIterator();
if (formatting != null) { if (formatting != null) {
while (formatting.hasNext()) { while (formatting.hasNext()) {
UnicodeString.FormatRun r = (UnicodeString.FormatRun)formatting.next(); UnicodeString.FormatRun r = (UnicodeString.FormatRun)formatting.next();
@ -124,10 +123,10 @@ public class HSSFRichTextString
} }
string.addFormatRun(new UnicodeString.FormatRun((short)startIndex, fontIndex)); _string.addFormatRun(new UnicodeString.FormatRun((short)startIndex, fontIndex));
if (endIndex != length()) if (endIndex != length())
string.addFormatRun(new UnicodeString.FormatRun((short)endIndex, currentFont)); _string.addFormatRun(new UnicodeString.FormatRun((short)endIndex, currentFont));
addToSSTIfRequired(); addToSSTIfRequired();
} }
@ -149,15 +148,15 @@ public class HSSFRichTextString
*/ */
public void applyFont(Font font) public void applyFont(Font font)
{ {
applyFont(0, string.getCharCount(), font); applyFont(0, _string.getCharCount(), font);
} }
/** /**
* Removes any formatting that may have been applied to the string. * Removes any formatting that may have been applied to the string.
*/ */
public void clearFormatting() { public void clearFormatting() {
string = cloneStringIfRequired(); _string = cloneStringIfRequired();
string.clearFormatting(); _string.clearFormatting();
addToSSTIfRequired(); addToSSTIfRequired();
} }
@ -166,40 +165,40 @@ public class HSSFRichTextString
*/ */
public String getString() public String getString()
{ {
return string.getString(); return _string.getString();
} }
/** /**
* Used internally by the HSSFCell to get the internal * Used internally by the HSSFCell to get the internal
* string value. * string value.
* Will ensure the string is not shared * Will ensure the string is not shared
*/ */
UnicodeString getUnicodeString() { UnicodeString getUnicodeString() {
return cloneStringIfRequired(); return cloneStringIfRequired();
} }
/** /**
* Returns the raw, probably shared Unicode String. * Returns the raw, probably shared Unicode String.
* Used when tweaking the styles, eg updating font * Used when tweaking the styles, eg updating font
* positions. * positions.
* Changes to this string may well effect * Changes to this string may well effect
* other RichTextStrings too! * other RichTextStrings too!
*/ */
UnicodeString getRawUnicodeString() { UnicodeString getRawUnicodeString() {
return string; return _string;
} }
/** Used internally by the HSSFCell to set the internal string value*/ /** Used internally by the HSSFCell to set the internal string value*/
void setUnicodeString(UnicodeString str) { void setUnicodeString(UnicodeString str) {
this.string = str; this._string = str;
} }
/** /**
* @return the number of characters in the text. * @return the number of characters in the text.
*/ */
public int length() { public int length() {
return string.getCharCount(); return _string.getCharCount();
} }
/** /**
@ -212,17 +211,19 @@ public class HSSFRichTextString
*/ */
public short getFontAtIndex( int index ) public short getFontAtIndex( int index )
{ {
int size = string.getFormatRunCount(); int size = _string.getFormatRunCount();
UnicodeString.FormatRun currentRun = null; UnicodeString.FormatRun currentRun = null;
for (int i=0;i<size;i++) { for (int i=0;i<size;i++) {
UnicodeString.FormatRun r = string.getFormatRun(i); UnicodeString.FormatRun r = _string.getFormatRun(i);
if (r.getCharacterPos() > index) if (r.getCharacterPos() > index) {
break; break;
else currentRun = r; }
currentRun = r;
} }
if (currentRun == null) if (currentRun == null) {
return NO_FONT; return NO_FONT;
else return currentRun.getFontIndex(); }
return currentRun.getFontIndex();
} }
/** /**
@ -233,7 +234,7 @@ public class HSSFRichTextString
*/ */
public int numFormattingRuns() public int numFormattingRuns()
{ {
return string.getFormatRunCount(); return _string.getFormatRunCount();
} }
/** /**
@ -243,7 +244,7 @@ public class HSSFRichTextString
*/ */
public int getIndexOfFormattingRun(int index) public int getIndexOfFormattingRun(int index)
{ {
UnicodeString.FormatRun r = string.getFormatRun(index); UnicodeString.FormatRun r = _string.getFormatRun(index);
return r.getCharacterPos(); return r.getCharacterPos();
} }
@ -255,25 +256,23 @@ public class HSSFRichTextString
*/ */
public short getFontOfFormattingRun(int index) public short getFontOfFormattingRun(int index)
{ {
UnicodeString.FormatRun r = string.getFormatRun(index); UnicodeString.FormatRun r = _string.getFormatRun(index);
return r.getFontIndex(); return r.getFontIndex();
} }
/** /**
* Compares one rich text string to another. * Compares one rich text string to another.
*/ */
public int compareTo( Object o ) public int compareTo(HSSFRichTextString r) {
{ return _string.compareTo(r._string);
HSSFRichTextString r = (HSSFRichTextString)o;
return string.compareTo(r.string);
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (o instanceof HSSFRichTextString) { if (o instanceof HSSFRichTextString) {
return string.equals(((HSSFRichTextString)o).string); return _string.equals(((HSSFRichTextString)o)._string);
} }
return false; return false;
} }
/** /**
@ -281,7 +280,7 @@ public class HSSFRichTextString
*/ */
public String toString() public String toString()
{ {
return string.toString(); return _string.toString();
} }
/** /**
@ -291,6 +290,6 @@ public class HSSFRichTextString
*/ */
public void applyFont( short fontIndex ) public void applyFont( short fontIndex )
{ {
applyFont(0, string.getCharCount(), fontIndex); applyFont(0, _string.getCharCount(), fontIndex);
} }
} }

View File

@ -17,107 +17,110 @@
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
import java.util.*; import java.awt.Font;
import java.awt.*; import java.io.File;
import java.io.*; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/** /**
* Allows the user to lookup the font metrics for a particular font without * Allows the user to lookup the font metrics for a particular font without
* actually having the font on the system. The font details are loaded * actually having the font on the system. The font details are loaded as a
* as a resource from the POI jar file (or classpath) and should be contained * resource from the POI jar file (or classpath) and should be contained in path
* in path "/font_metrics.properties". The font widths are for a 10 point * "/font_metrics.properties". The font widths are for a 10 point version of the
* version of the font. Use a multiplier for other sizes. * font. Use a multiplier for other sizes.
* *
* @author Glen Stampoultzis (glens at apache.org) * @author Glen Stampoultzis (glens at apache.org)
*/ */
class StaticFontMetrics final class StaticFontMetrics {
{
/** The font metrics property file we're using */ /** The font metrics property file we're using */
private static Properties fontMetricsProps; private static Properties fontMetricsProps;
/** Our cache of font details we've already looked up */ /** Our cache of font details we've already looked up */
private static Map fontDetailsMap = new HashMap(); private static Map<String, FontDetails> fontDetailsMap = new HashMap<String, FontDetails>();
/** /**
* Retrieves the fake font details for a given font. * Retrieves the fake font details for a given font.
* @param font the font to lookup. *
* @return the fake font. * @param font
*/ * the font to lookup.
public static FontDetails getFontDetails(Font font) * @return the fake font.
{ */
public static FontDetails getFontDetails(Font font) {
// If we haven't already identified out font metrics file, // If we haven't already identified out font metrics file,
// figure out which one to use and load it // figure out which one to use and load it
if (fontMetricsProps == null) if (fontMetricsProps == null) {
{ InputStream metricsIn = null;
InputStream metricsIn = null; try {
try fontMetricsProps = new Properties();
{
fontMetricsProps = new Properties();
// Check to see if the font metric file was specified // Check to see if the font metric file was specified
// as a system property // as a system property
String propFileName = null; String propFileName = null;
try { try {
propFileName = System.getProperty("font.metrics.filename"); propFileName = System.getProperty("font.metrics.filename");
} catch(SecurityException e) {} } catch (SecurityException e) {
}
if (propFileName != null) { if (propFileName != null) {
File file = new File(propFileName); File file = new File(propFileName);
if (!file.exists()) if (!file.exists())
throw new FileNotFoundException("font_metrics.properties not found at path " + file.getAbsolutePath()); throw new FileNotFoundException(
metricsIn = new FileInputStream(file); "font_metrics.properties not found at path "
} + file.getAbsolutePath());
else { metricsIn = new FileInputStream(file);
// Use the built-in font metrics file off the classpath } else {
metricsIn = FontDetails.class.getResourceAsStream("/font_metrics.properties"); // Use the built-in font metrics file off the classpath
if (metricsIn == null) metricsIn = FontDetails.class.getResourceAsStream("/font_metrics.properties");
throw new FileNotFoundException("font_metrics.properties not found in classpath"); if (metricsIn == null)
} throw new FileNotFoundException(
fontMetricsProps.load(metricsIn); "font_metrics.properties not found in classpath");
} }
catch ( IOException e ) fontMetricsProps.load(metricsIn);
{ } catch (IOException e) {
throw new RuntimeException("Could not load font metrics: " + e.getMessage()); throw new RuntimeException("Could not load font metrics: " + e.getMessage());
} } finally {
finally if (metricsIn != null) {
{ try {
if (metricsIn != null) metricsIn.close();
{ } catch (IOException ignore) {
try }
{ }
metricsIn.close(); }
} }
catch ( IOException ignore ) { }
}
}
}
// Grab the base name of the font they've asked about // Grab the base name of the font they've asked about
String fontName = font.getName(); String fontName = font.getName();
// Some fonts support plain/bold/italic/bolditalic variants // Some fonts support plain/bold/italic/bolditalic variants
// Others have different font instances for bold etc // Others have different font instances for bold etc
// (eg font.dialog.plain.* vs font.Californian FB Bold.*) // (eg font.dialog.plain.* vs font.Californian FB Bold.*)
String fontStyle = ""; String fontStyle = "";
if(font.isPlain()) fontStyle += "plain"; if (font.isPlain())
if(font.isBold()) fontStyle += "bold"; fontStyle += "plain";
if(font.isItalic()) fontStyle += "italic"; if (font.isBold())
fontStyle += "bold";
if (font.isItalic())
fontStyle += "italic";
// Do we have a definition for this font with just the name? // Do we have a definition for this font with just the name?
// If not, check with the font style added // If not, check with the font style added
if(fontMetricsProps.get(FontDetails.buildFontHeightProperty(fontName)) == null && if (fontMetricsProps.get(FontDetails.buildFontHeightProperty(fontName)) == null
fontMetricsProps.get(FontDetails.buildFontHeightProperty(fontName+"."+fontStyle)) != null) { && fontMetricsProps.get(FontDetails.buildFontHeightProperty(fontName + "."
+ fontStyle)) != null) {
// Need to add on the style to the font name // Need to add on the style to the font name
fontName += "." + fontStyle; fontName += "." + fontStyle;
} }
// Get the details on this font // Get the details on this font
if (fontDetailsMap.get(fontName) == null) { if (fontDetailsMap.get(fontName) == null) {
FontDetails fontDetails = FontDetails.create(fontName, fontMetricsProps); FontDetails fontDetails = FontDetails.create(fontName, fontMetricsProps);
fontDetailsMap.put( fontName, fontDetails ); fontDetailsMap.put(fontName, fontDetails);
return fontDetails; return fontDetails;
} else { }
return (FontDetails) fontDetailsMap.get(fontName); return fontDetailsMap.get(fontName);
} }
}
} }

View File

@ -15,7 +15,7 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.poifs.filesystem; package org.apache.poi.poifs.filesystem;
@ -64,7 +64,7 @@ public class POIFSFileSystem
{ {
private static final POILogger _logger = private static final POILogger _logger =
POILogFactory.getLogger(POIFSFileSystem.class); POILogFactory.getLogger(POIFSFileSystem.class);
private static final class CloseIgnoringInputStream extends InputStream { private static final class CloseIgnoringInputStream extends InputStream {
private final InputStream _is; private final InputStream _is;
@ -81,18 +81,18 @@ public class POIFSFileSystem
// do nothing // do nothing
} }
} }
/** /**
* Convenience method for clients that want to avoid the auto-close behaviour of the constructor. * Convenience method for clients that want to avoid the auto-close behaviour of the constructor.
*/ */
public static InputStream createNonClosingInputStream(InputStream is) { public static InputStream createNonClosingInputStream(InputStream is) {
return new CloseIgnoringInputStream(is); return new CloseIgnoringInputStream(is);
} }
private PropertyTable _property_table; private PropertyTable _property_table;
private List _documents; private List _documents;
private DirectoryNode _root; private DirectoryNode _root;
/** /**
* What big block size the file uses. Most files * What big block size the file uses. Most files
* use 512 bytes, but a few use 4096 * use 512 bytes, but a few use 4096
@ -112,20 +112,20 @@ public class POIFSFileSystem
/** /**
* Create a POIFSFileSystem from an <tt>InputStream</tt>. Normally the stream is read until * Create a POIFSFileSystem from an <tt>InputStream</tt>. Normally the stream is read until
* EOF. The stream is always closed.<p/> * EOF. The stream is always closed.<p/>
* *
* Some streams are usable after reaching EOF (typically those that return <code>true</code> * Some streams are usable after reaching EOF (typically those that return <code>true</code>
* for <tt>markSupported()</tt>). In the unlikely case that the caller has such a stream * for <tt>markSupported()</tt>). In the unlikely case that the caller has such a stream
* <i>and</i> needs to use it after this constructor completes, a work around is to wrap the * <i>and</i> needs to use it after this constructor completes, a work around is to wrap the
* stream in order to trap the <tt>close()</tt> call. A convenience method ( * stream in order to trap the <tt>close()</tt> call. A convenience method (
* <tt>createNonClosingInputStream()</tt>) has been provided for this purpose: * <tt>createNonClosingInputStream()</tt>) has been provided for this purpose:
* <pre> * <pre>
* InputStream wrappedStream = POIFSFileSystem.createNonClosingInputStream(is); * InputStream wrappedStream = POIFSFileSystem.createNonClosingInputStream(is);
* HSSFWorkbook wb = new HSSFWorkbook(wrappedStream); * HSSFWorkbook wb = new HSSFWorkbook(wrappedStream);
* is.reset(); * is.reset();
* doSomethingElse(is); * doSomethingElse(is);
* </pre> * </pre>
* Note also the special case of <tt>ByteArrayInputStream</tt> for which the <tt>close()</tt> * Note also the special case of <tt>ByteArrayInputStream</tt> for which the <tt>close()</tt>
* method does nothing. * method does nothing.
* <pre> * <pre>
* ByteArrayInputStream bais = ... * ByteArrayInputStream bais = ...
* HSSFWorkbook wb = new HSSFWorkbook(bais); // calls bais.close() ! * HSSFWorkbook wb = new HSSFWorkbook(bais); // calls bais.close() !
@ -150,14 +150,14 @@ public class POIFSFileSystem
// read the header block from the stream // read the header block from the stream
header_block_reader = new HeaderBlockReader(stream); header_block_reader = new HeaderBlockReader(stream);
bigBlockSize = header_block_reader.getBigBlockSize(); bigBlockSize = header_block_reader.getBigBlockSize();
// read the rest of the stream into blocks // read the rest of the stream into blocks
data_blocks = new RawDataBlockList(stream, bigBlockSize); data_blocks = new RawDataBlockList(stream, bigBlockSize);
success = true; success = true;
} finally { } finally {
closeInputStream(stream, success); closeInputStream(stream, success);
} }
// set up the block allocation table (necessary for the // set up the block allocation table (necessary for the
// data_blocks to be manageable // data_blocks to be manageable
@ -175,11 +175,11 @@ public class POIFSFileSystem
// init documents // init documents
processProperties( processProperties(
SmallBlockTableReader.getSmallDocumentBlocks( SmallBlockTableReader.getSmallDocumentBlocks(
data_blocks, properties.getRoot(), data_blocks, properties.getRoot(),
header_block_reader.getSBATStart() header_block_reader.getSBATStart()
), ),
data_blocks, data_blocks,
properties.getRoot().getChildren(), properties.getRoot().getChildren(),
null, null,
header_block_reader.getPropertyStart() header_block_reader.getPropertyStart()
); );
@ -192,9 +192,9 @@ public class POIFSFileSystem
* @param success <code>false</code> if an exception is currently being thrown in the calling method * @param success <code>false</code> if an exception is currently being thrown in the calling method
*/ */
private void closeInputStream(InputStream stream, boolean success) { private void closeInputStream(InputStream stream, boolean success) {
if(stream.markSupported() && !(stream instanceof ByteArrayInputStream)) { if(stream.markSupported() && !(stream instanceof ByteArrayInputStream)) {
String msg = "POIFS is closing the supplied input stream of type (" String msg = "POIFS is closing the supplied input stream of type ("
+ stream.getClass().getName() + ") which supports mark/reset. " + stream.getClass().getName() + ") which supports mark/reset. "
+ "This will be a problem for the caller if the stream will still be used. " + "This will be a problem for the caller if the stream will still be used. "
+ "If that is the case the caller should wrap the input stream to avoid this close logic. " + "If that is the case the caller should wrap the input stream to avoid this close logic. "
@ -207,7 +207,7 @@ public class POIFSFileSystem
if(success) { if(success) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
// else not success? Try block did not complete normally // else not success? Try block did not complete normally
// just print stack trace and leave original ex to be thrown // just print stack trace and leave original ex to be thrown
e.printStackTrace(); e.printStackTrace();
} }
@ -215,15 +215,15 @@ public class POIFSFileSystem
/** /**
* Checks that the supplied InputStream (which MUST * Checks that the supplied InputStream (which MUST
* support mark and reset, or be a PushbackInputStream) * support mark and reset, or be a PushbackInputStream)
* has a POIFS (OLE2) header at the start of it. * has a POIFS (OLE2) header at the start of it.
* If your InputStream does not support mark / reset, * If your InputStream does not support mark / reset,
* then wrap it in a PushBackInputStream, then be * then wrap it in a PushBackInputStream, then be
* sure to always use that, and not the original! * sure to always use that, and not the original!
* @param inp An InputStream which supports either mark/reset, or is a PushbackInputStream * @param inp An InputStream which supports either mark/reset, or is a PushbackInputStream
*/ */
public static boolean hasPOIFSHeader(InputStream inp) throws IOException { public static boolean hasPOIFSHeader(InputStream inp) throws IOException {
// We want to peek at the first 8 bytes // We want to peek at the first 8 bytes
inp.mark(8); inp.mark(8);
byte[] header = new byte[8]; byte[] header = new byte[8];
@ -237,7 +237,7 @@ public class POIFSFileSystem
} else { } else {
inp.reset(); inp.reset();
} }
// Did it match the signature? // Did it match the signature?
return (signature.get() == HeaderBlockConstants._signature); return (signature.get() == HeaderBlockConstants._signature);
} }
@ -296,7 +296,7 @@ public class POIFSFileSystem
{ {
return getRoot().createDirectory(name); return getRoot().createDirectory(name);
} }
/** /**
* Write the filesystem out * Write the filesystem out
* *
@ -520,7 +520,7 @@ public class POIFSFileSystem
processProperties( processProperties(
small_blocks, big_blocks, small_blocks, big_blocks,
(( DirectoryProperty ) property).getChildren(), (( DirectoryProperty ) property).getChildren(),
new_dir, headerPropertiesStartAt); new_dir, headerPropertiesStartAt);
} }
else else
@ -532,8 +532,8 @@ public class POIFSFileSystem
if (property.shouldUseSmallBlocks()) if (property.shouldUseSmallBlocks())
{ {
document = document =
new POIFSDocument(name, new POIFSDocument(name,
small_blocks.fetchBlocks(startBlock, headerPropertiesStartAt), small_blocks.fetchBlocks(startBlock, headerPropertiesStartAt),
size); size);
} }
else else
@ -563,10 +563,7 @@ public class POIFSFileSystem
{ {
return (( POIFSViewable ) getRoot()).getViewableArray(); return (( POIFSViewable ) getRoot()).getViewableArray();
} }
else return new Object[ 0 ];
{
return new Object[ 0 ];
}
} }
/** /**
@ -583,10 +580,7 @@ public class POIFSFileSystem
{ {
return (( POIFSViewable ) getRoot()).getViewableIterator(); return (( POIFSViewable ) getRoot()).getViewableIterator();
} }
else return Collections.EMPTY_LIST.iterator();
{
return Collections.EMPTY_LIST.iterator();
}
} }
/** /**
@ -620,7 +614,7 @@ public class POIFSFileSystem
public int getBigBlockSize() { public int getBigBlockSize() {
return bigBlockSize; return bigBlockSize;
} }
/* ********** END begin implementation of POIFSViewable ********** */ /* ********** END begin implementation of POIFSViewable ********** */
} // end public class POIFSFileSystem } // end public class POIFSFileSystem

View File

@ -169,7 +169,7 @@ public class HexDump {
* outside the data array's bounds * outside the data array's bounds
* @return output string * @return output string
*/ */
public static String dump(final byte [] data, final long offset, public static String dump(final byte [] data, final long offset,
final int index) { final int index) {
StringBuffer buffer; StringBuffer buffer;
@ -216,10 +216,10 @@ public class HexDump {
} }
buffer.append(EOL); buffer.append(EOL);
display_offset += chars_read; display_offset += chars_read;
} }
return buffer.toString(); return buffer.toString();
} }
private static String dump(final long value) private static String dump(final long value)
{ {
@ -399,10 +399,10 @@ public class HexDump {
while (bytesRemaining-- > 0) while (bytesRemaining-- > 0)
{ {
int c = in.read(); int c = in.read();
if (c == -1) if (c == -1) {
break; break;
else }
buf.write(c); buf.write(c);
} }
} }
@ -417,13 +417,13 @@ public class HexDump {
// The return type is char array because most callers will probably append the value to a // The return type is char array because most callers will probably append the value to a
// StringBuffer, or write it to a Stream / Writer so there is no need to create a String; // StringBuffer, or write it to a Stream / Writer so there is no need to create a String;
char[] result = new char[charPos]; char[] result = new char[charPos];
long value = pValue; long value = pValue;
do { do {
result[--charPos] = _hexcodes[(int) (value & 0x0F)]; result[--charPos] = _hexcodes[(int) (value & 0x0F)];
value >>>= 4; value >>>= 4;
} while (charPos > 1); } while (charPos > 1);
// Prefix added to avoid ambiguity // Prefix added to avoid ambiguity
result[0] = '0'; result[0] = '0';
result[1] = 'x'; result[1] = 'x';
@ -456,7 +456,7 @@ public class HexDump {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
File file = new File(args[0]); File file = new File(args[0]);
InputStream in = new BufferedInputStream(new FileInputStream(file)); InputStream in = new BufferedInputStream(new FileInputStream(file));
byte[] b = new byte[(int)file.length()]; byte[] b = new byte[(int)file.length()];
in.read(b); in.read(b);
System.out.println(HexDump.dump(b, 0, 0)); System.out.println(HexDump.dump(b, 0, 0));

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,7 +14,6 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.util; package org.apache.poi.util;
@ -24,80 +22,70 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
public class IOUtils public final class IOUtils {
{ private IOUtils() {
private IOUtils() // no instances of this class
{ }
}
/** /**
* Reads all the data from the input stream, and returns * Reads all the data from the input stream, and returns the bytes read.
* the bytes read. */
*/ public static byte[] toByteArray(InputStream stream) throws IOException {
public static byte[] toByteArray(InputStream stream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int read = 0;
while(read != -1) {
read = stream.read(buffer);
if(read > 0) {
baos.write(buffer, 0, read);
}
}
return baos.toByteArray();
}
/** byte[] buffer = new byte[4096];
* Helper method, just calls <tt>readFully(in, b, 0, b.length)</tt> int read = 0;
*/ while (read != -1) {
public static int readFully(InputStream in, byte[] b) read = stream.read(buffer);
throws IOException if (read > 0) {
{ baos.write(buffer, 0, read);
return readFully(in, b, 0, b.length); }
} }
/** return baos.toByteArray();
* Same as the normal <tt>in.read(b, off, len)</tt>, but }
* tries to ensure that the entire len number of bytes
* is read.
* <p>
* If the end of file is reached before any bytes
* are read, returns -1.
* If the end of the file is reached after some bytes are
* read, returns the number of bytes read.
* If the end of the file isn't reached before len
* bytes have been read, will return len bytes.
*/
public static int readFully(InputStream in, byte[] b, int off, int len)
throws IOException
{
int total = 0;
for (;;) {
int got = in.read(b, off + total, len - total);
if (got < 0) {
return (total == 0) ? -1 : total;
} else {
total += got;
if (total == len)
return total;
}
}
}
/** /**
* Copies all the data from the given InputStream to the * Helper method, just calls <tt>readFully(in, b, 0, b.length)</tt>
* OutputStream. It leaves both streams open, so you */
* will still need to close them once done. public static int readFully(InputStream in, byte[] b) throws IOException {
*/ return readFully(in, b, 0, b.length);
}
/**
* Same as the normal <tt>in.read(b, off, len)</tt>, but tries to ensure
* that the entire len number of bytes is read.
* <p>
* If the end of file is reached before any bytes are read, returns -1. If
* the end of the file is reached after some bytes are read, returns the
* number of bytes read. If the end of the file isn't reached before len
* bytes have been read, will return len bytes.
*/
public static int readFully(InputStream in, byte[] b, int off, int len) throws IOException {
int total = 0;
while (true) {
int got = in.read(b, off + total, len - total);
if (got < 0) {
return (total == 0) ? -1 : total;
}
total += got;
if (total == len) {
return total;
}
}
}
/**
* Copies all the data from the given InputStream to the OutputStream. It
* leaves both streams open, so you will still need to close them once done.
*/
public static void copy(InputStream inp, OutputStream out) throws IOException { public static void copy(InputStream inp, OutputStream out) throws IOException {
byte[] buff = new byte[4096]; byte[] buff = new byte[4096];
int count; int count;
while( (count = inp.read(buff)) != -1 ) { while ((count = inp.read(buff)) != -1) {
if(count > 0) { if (count > 0) {
out.write(buff, 0, count); out.write(buff, 0, count);
} }
} }
} }
} }

View File

@ -1,4 +1,3 @@
/* ==================================================================== /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
@ -15,7 +14,6 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.util; package org.apache.poi.util;
@ -33,11 +31,11 @@ package org.apache.poi.util;
*/ */
public class SystemOutLogger extends POILogger public class SystemOutLogger extends POILogger
{ {
private String cat; private String _cat;
public void initialize(final String cat) public void initialize(final String cat)
{ {
this.cat=cat; this._cat=cat;
} }
/** /**
@ -51,7 +49,7 @@ public class SystemOutLogger extends POILogger
{ {
log(level, obj1, null); log(level, obj1, null);
} }
/** /**
* Log a message * Log a message
* *
@ -62,7 +60,7 @@ public class SystemOutLogger extends POILogger
public void log(final int level, final Object obj1, public void log(final int level, final Object obj1,
final Throwable exception) { final Throwable exception) {
if (check(level)) { if (check(level)) {
System.out.println("["+cat+"] "+obj1); System.out.println("["+_cat+"] "+obj1);
if(exception != null) { if(exception != null) {
exception.printStackTrace(System.out); exception.printStackTrace(System.out);
} }
@ -88,10 +86,10 @@ public class SystemOutLogger extends POILogger
currentLevel = POILogger.DEBUG; currentLevel = POILogger.DEBUG;
} }
if (level >= currentLevel) if (level >= currentLevel) {
return true; return true;
else }
return false; return false;
} }

View File

@ -35,11 +35,10 @@ import org.apache.poi.openxml4j.util.Nullable;
/** /**
* Represents the core properties part of a package. * Represents the core properties part of a package.
* *
* @author Julien Chable * @author Julien Chable
* @version 1.0
*/ */
public class PackagePropertiesPart extends PackagePart implements public final class PackagePropertiesPart extends PackagePart implements
PackageProperties { PackageProperties {
public final static String NAMESPACE_DC_URI = "http://purl.org/dc/elements/1.1/"; public final static String NAMESPACE_DC_URI = "http://purl.org/dc/elements/1.1/";
@ -52,7 +51,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Constructor. * Constructor.
* *
* @param pack * @param pack
* Container package. * Container package.
* @param partName * @param partName
@ -67,7 +66,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* A categorization of the content of this package. * A categorization of the content of this package.
* *
* [Example: Example values for this property might include: Resume, Letter, * [Example: Example values for this property might include: Resume, Letter,
* Financial Forecast, Proposal, Technical Presentation, and so on. This * Financial Forecast, Proposal, Technical Presentation, and so on. This
* value might be used by an application's user interface to facilitate * value might be used by an application's user interface to facilitate
@ -77,7 +76,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* The status of the content. * The status of the content.
* *
* [Example: Values might include "Draft", "Reviewed", and "Final". end * [Example: Values might include "Draft", "Reviewed", and "Final". end
* example] * example]
*/ */
@ -86,7 +85,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* The type of content represented, generally defined by a specific use and * The type of content represented, generally defined by a specific use and
* intended audience. * intended audience.
* *
* [Example: Values might include "Whitepaper", "Security Bulletin", and * [Example: Values might include "Whitepaper", "Security Bulletin", and
* "Exam". end example] [Note: This property is distinct from MIME content * "Exam". end example] [Note: This property is distinct from MIME content
* types as defined in RFC 2616. end note] * types as defined in RFC 2616. end note]
@ -105,7 +104,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* An explanation of the content of the resource. * An explanation of the content of the resource.
* *
* [Example: Values might include an abstract, table of contents, reference * [Example: Values might include an abstract, table of contents, reference
* to a graphical representation of content, and a free-text account of the * to a graphical representation of content, and a free-text account of the
* content. end example] * content. end example]
@ -126,7 +125,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* The language of the intellectual content of the resource. * The language of the intellectual content of the resource.
* *
* [Note: IETF RFC 3066 provides guidance on encoding to represent * [Note: IETF RFC 3066 provides guidance on encoding to represent
* languages. end note] * languages. end note]
*/ */
@ -135,7 +134,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* The user who performed the last modification. The identification is * The user who performed the last modification. The identification is
* environment-specific. * environment-specific.
* *
* [Example: A name, email address, or employee ID. end example] It is * [Example: A name, email address, or employee ID. end example] It is
* recommended that this value be as concise as possible. * recommended that this value be as concise as possible.
*/ */
@ -153,7 +152,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* The revision number. * The revision number.
* *
* [Example: This value might indicate the number of saves or revisions, * [Example: This value might indicate the number of saves or revisions,
* provided the application updates it after each revision. end example] * provided the application updates it after each revision. end example]
*/ */
@ -180,7 +179,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get the category property. * Get the category property.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getCategoryProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getCategoryProperty()
*/ */
public Nullable<String> getCategoryProperty() { public Nullable<String> getCategoryProperty() {
@ -189,7 +188,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get content status. * Get content status.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getContentStatusProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getContentStatusProperty()
*/ */
public Nullable<String> getContentStatusProperty() { public Nullable<String> getContentStatusProperty() {
@ -198,7 +197,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get content type. * Get content type.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getContentTypeProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getContentTypeProperty()
*/ */
public Nullable<String> getContentTypeProperty() { public Nullable<String> getContentTypeProperty() {
@ -207,7 +206,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get created date. * Get created date.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getCreatedProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getCreatedProperty()
*/ */
public Nullable<Date> getCreatedProperty() { public Nullable<Date> getCreatedProperty() {
@ -216,7 +215,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get created date formated into a String. * Get created date formated into a String.
* *
* @return A string representation of the created date. * @return A string representation of the created date.
*/ */
public String getCreatedPropertyString() { public String getCreatedPropertyString() {
@ -225,7 +224,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get creator. * Get creator.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getCreatorProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getCreatorProperty()
*/ */
public Nullable<String> getCreatorProperty() { public Nullable<String> getCreatorProperty() {
@ -234,7 +233,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get description. * Get description.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getDescriptionProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getDescriptionProperty()
*/ */
public Nullable<String> getDescriptionProperty() { public Nullable<String> getDescriptionProperty() {
@ -243,7 +242,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get identifier. * Get identifier.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getIdentifierProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getIdentifierProperty()
*/ */
public Nullable<String> getIdentifierProperty() { public Nullable<String> getIdentifierProperty() {
@ -252,7 +251,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get keywords. * Get keywords.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getKeywordsProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getKeywordsProperty()
*/ */
public Nullable<String> getKeywordsProperty() { public Nullable<String> getKeywordsProperty() {
@ -261,7 +260,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get the language. * Get the language.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getLanguageProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getLanguageProperty()
*/ */
public Nullable<String> getLanguageProperty() { public Nullable<String> getLanguageProperty() {
@ -270,7 +269,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get the author of last modifications. * Get the author of last modifications.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getLastModifiedByProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getLastModifiedByProperty()
*/ */
public Nullable<String> getLastModifiedByProperty() { public Nullable<String> getLastModifiedByProperty() {
@ -279,7 +278,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get last printed date. * Get last printed date.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getLastPrintedProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getLastPrintedProperty()
*/ */
public Nullable<Date> getLastPrintedProperty() { public Nullable<Date> getLastPrintedProperty() {
@ -288,7 +287,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get last printed date formated into a String. * Get last printed date formated into a String.
* *
* @return A string representation of the last printed date. * @return A string representation of the last printed date.
*/ */
public String getLastPrintedPropertyString() { public String getLastPrintedPropertyString() {
@ -297,7 +296,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get modified date. * Get modified date.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getModifiedProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getModifiedProperty()
*/ */
public Nullable<Date> getModifiedProperty() { public Nullable<Date> getModifiedProperty() {
@ -306,19 +305,19 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get modified date formated into a String. * Get modified date formated into a String.
* *
* @return A string representation of the modified date. * @return A string representation of the modified date.
*/ */
public String getModifiedPropertyString() { public String getModifiedPropertyString() {
if (!modified.hasValue()) if (modified.hasValue()) {
return getDateValue(new Nullable<Date>(new Date()));
else
return getDateValue(modified); return getDateValue(modified);
}
return getDateValue(new Nullable<Date>(new Date()));
} }
/** /**
* Get revision. * Get revision.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getRevisionProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getRevisionProperty()
*/ */
public Nullable<String> getRevisionProperty() { public Nullable<String> getRevisionProperty() {
@ -327,7 +326,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get subject. * Get subject.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getSubjectProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getSubjectProperty()
*/ */
public Nullable<String> getSubjectProperty() { public Nullable<String> getSubjectProperty() {
@ -336,7 +335,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get title. * Get title.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getTitleProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getTitleProperty()
*/ */
public Nullable<String> getTitleProperty() { public Nullable<String> getTitleProperty() {
@ -345,7 +344,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Get version. * Get version.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getVersionProperty() * @see org.apache.poi.openxml4j.opc.PackageProperties#getVersionProperty()
*/ */
public Nullable<String> getVersionProperty() { public Nullable<String> getVersionProperty() {
@ -354,7 +353,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set the category. * Set the category.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setCategoryProperty(java.lang.String) * @see org.apache.poi.openxml4j.opc.PackageProperties#setCategoryProperty(java.lang.String)
*/ */
public void setCategoryProperty(String category) { public void setCategoryProperty(String category) {
@ -363,7 +362,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set the content status. * Set the content status.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setContentStatusProperty(java.lang.String) * @see org.apache.poi.openxml4j.opc.PackageProperties#setContentStatusProperty(java.lang.String)
*/ */
public void setContentStatusProperty(String contentStatus) { public void setContentStatusProperty(String contentStatus) {
@ -372,7 +371,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set the content type. * Set the content type.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setContentTypeProperty(java.lang.String) * @see org.apache.poi.openxml4j.opc.PackageProperties#setContentTypeProperty(java.lang.String)
*/ */
public void setContentTypeProperty(String contentType) { public void setContentTypeProperty(String contentType) {
@ -381,7 +380,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set the created date. * Set the created date.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatedProperty(org.apache.poi.openxml4j.util.Nullable) * @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatedProperty(org.apache.poi.openxml4j.util.Nullable)
*/ */
public void setCreatedProperty(String created) { public void setCreatedProperty(String created) {
@ -395,7 +394,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set the created date. * Set the created date.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatedProperty(org.apache.poi.openxml4j.util.Nullable) * @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatedProperty(org.apache.poi.openxml4j.util.Nullable)
*/ */
public void setCreatedProperty(Nullable<Date> created) { public void setCreatedProperty(Nullable<Date> created) {
@ -405,7 +404,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set the creator. * Set the creator.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatorProperty(java.lang.String) * @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatorProperty(java.lang.String)
*/ */
public void setCreatorProperty(String creator) { public void setCreatorProperty(String creator) {
@ -414,7 +413,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set the description. * Set the description.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setDescriptionProperty(java.lang.String) * @see org.apache.poi.openxml4j.opc.PackageProperties#setDescriptionProperty(java.lang.String)
*/ */
public void setDescriptionProperty(String description) { public void setDescriptionProperty(String description) {
@ -423,7 +422,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set identifier. * Set identifier.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setIdentifierProperty(java.lang.String) * @see org.apache.poi.openxml4j.opc.PackageProperties#setIdentifierProperty(java.lang.String)
*/ */
public void setIdentifierProperty(String identifier) { public void setIdentifierProperty(String identifier) {
@ -432,7 +431,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set keywords. * Set keywords.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setKeywordsProperty(java.lang.String) * @see org.apache.poi.openxml4j.opc.PackageProperties#setKeywordsProperty(java.lang.String)
*/ */
public void setKeywordsProperty(String keywords) { public void setKeywordsProperty(String keywords) {
@ -441,7 +440,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set language. * Set language.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setLanguageProperty(java.lang.String) * @see org.apache.poi.openxml4j.opc.PackageProperties#setLanguageProperty(java.lang.String)
*/ */
public void setLanguageProperty(String language) { public void setLanguageProperty(String language) {
@ -450,7 +449,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set last modifications author. * Set last modifications author.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setLastModifiedByProperty(java.lang.String) * @see org.apache.poi.openxml4j.opc.PackageProperties#setLastModifiedByProperty(java.lang.String)
*/ */
public void setLastModifiedByProperty(String lastModifiedBy) { public void setLastModifiedByProperty(String lastModifiedBy) {
@ -459,7 +458,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set last printed date. * Set last printed date.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setLastPrintedProperty(org.apache.poi.openxml4j.util.Nullable) * @see org.apache.poi.openxml4j.opc.PackageProperties#setLastPrintedProperty(org.apache.poi.openxml4j.util.Nullable)
*/ */
public void setLastPrintedProperty(String lastPrinted) { public void setLastPrintedProperty(String lastPrinted) {
@ -473,7 +472,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set last printed date. * Set last printed date.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setLastPrintedProperty(org.apache.poi.openxml4j.util.Nullable) * @see org.apache.poi.openxml4j.opc.PackageProperties#setLastPrintedProperty(org.apache.poi.openxml4j.util.Nullable)
*/ */
public void setLastPrintedProperty(Nullable<Date> lastPrinted) { public void setLastPrintedProperty(Nullable<Date> lastPrinted) {
@ -483,7 +482,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set last modification date. * Set last modification date.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setModifiedProperty(org.apache.poi.openxml4j.util.Nullable) * @see org.apache.poi.openxml4j.opc.PackageProperties#setModifiedProperty(org.apache.poi.openxml4j.util.Nullable)
*/ */
public void setModifiedProperty(String modified) { public void setModifiedProperty(String modified) {
@ -497,7 +496,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set last modification date. * Set last modification date.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setModifiedProperty(org.apache.poi.openxml4j.util.Nullable) * @see org.apache.poi.openxml4j.opc.PackageProperties#setModifiedProperty(org.apache.poi.openxml4j.util.Nullable)
*/ */
public void setModifiedProperty(Nullable<Date> modified) { public void setModifiedProperty(Nullable<Date> modified) {
@ -507,7 +506,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set revision. * Set revision.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setRevisionProperty(java.lang.String) * @see org.apache.poi.openxml4j.opc.PackageProperties#setRevisionProperty(java.lang.String)
*/ */
public void setRevisionProperty(String revision) { public void setRevisionProperty(String revision) {
@ -516,7 +515,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set subject. * Set subject.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setSubjectProperty(java.lang.String) * @see org.apache.poi.openxml4j.opc.PackageProperties#setSubjectProperty(java.lang.String)
*/ */
public void setSubjectProperty(String subject) { public void setSubjectProperty(String subject) {
@ -525,7 +524,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set title. * Set title.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setTitleProperty(java.lang.String) * @see org.apache.poi.openxml4j.opc.PackageProperties#setTitleProperty(java.lang.String)
*/ */
public void setTitleProperty(String title) { public void setTitleProperty(String title) {
@ -534,7 +533,7 @@ public class PackagePropertiesPart extends PackagePart implements
/** /**
* Set version. * Set version.
* *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setVersionProperty(java.lang.String) * @see org.apache.poi.openxml4j.opc.PackageProperties#setVersionProperty(java.lang.String)
*/ */
public void setVersionProperty(String version) { public void setVersionProperty(String version) {
@ -545,47 +544,46 @@ public class PackagePropertiesPart extends PackagePart implements
* Convert a strig value into a Nullable<String> * Convert a strig value into a Nullable<String>
*/ */
private Nullable<String> setStringValue(String s) { private Nullable<String> setStringValue(String s) {
if (s == null || s.equals("")) if (s == null || s.equals("")) {
return new Nullable<String>(); return new Nullable<String>();
else }
return new Nullable<String>(s); return new Nullable<String>(s);
} }
/** /**
* Convert a string value represented a date into a Nullable<Date>. * Convert a string value represented a date into a Nullable<Date>.
* *
* @throws InvalidFormatException * @throws InvalidFormatException
* Throws if the date format isnot valid. * Throws if the date format isnot valid.
*/ */
private Nullable<Date> setDateValue(String s) throws InvalidFormatException { private Nullable<Date> setDateValue(String s) throws InvalidFormatException {
if (s == null || s.equals("")) if (s == null || s.equals("")) {
return new Nullable<Date>(); return new Nullable<Date>();
else {
SimpleDateFormat df = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
Date d = df.parse(s, new ParsePosition(0));
if (d == null)
throw new InvalidFormatException("Date not well formated");
return new Nullable<Date>(d);
} }
SimpleDateFormat df = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
Date d = df.parse(s, new ParsePosition(0));
if (d == null) {
throw new InvalidFormatException("Date not well formated");
}
return new Nullable<Date>(d);
} }
/** /**
* Convert a Nullable<Date> into a String. * Convert a Nullable<Date> into a String.
* *
* @param d * @param d
* The Date to convert. * The Date to convert.
* @return The formated date or null. * @return The formated date or null.
* @see java.util.SimpleDateFormat * @see java.util.SimpleDateFormat
*/ */
private String getDateValue(Nullable<Date> d) { private String getDateValue(Nullable<Date> d) {
if (d == null || d.equals("")) if (d == null || d.equals("")) {
return ""; return "";
else {
SimpleDateFormat df = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
return df.format(d.getValue());
} }
SimpleDateFormat df = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
return df.format(d.getValue());
} }
@Override @Override
@ -600,12 +598,12 @@ public class PackagePropertiesPart extends PackagePart implements
} }
@Override @Override
public boolean save(OutputStream zos) throws OpenXML4JException { public boolean save(OutputStream zos) {
throw new InvalidOperationException("Operation not authorized"); throw new InvalidOperationException("Operation not authorized");
} }
@Override @Override
public boolean load(InputStream ios) throws InvalidFormatException { public boolean load(InputStream ios) {
throw new InvalidOperationException("Operation not authorized"); throw new InvalidOperationException("Operation not authorized");
} }

View File

@ -34,7 +34,7 @@ import org.dom4j.Document;
/** /**
* Zip implementation of the ContentTypeManager. * Zip implementation of the ContentTypeManager.
* *
* @author Julien Chable * @author Julien Chable
* @version 1.0 * @version 1.0
* @see ContentTypeManager * @see ContentTypeManager
@ -44,7 +44,7 @@ public class ZipContentTypeManager extends ContentTypeManager {
/** /**
* Delegate constructor to the super constructor. * Delegate constructor to the super constructor.
* *
* @param in * @param in
* The input stream to parse to fill internal content type * The input stream to parse to fill internal content type
* collections. * collections.
@ -78,9 +78,8 @@ public class ZipContentTypeManager extends ContentTypeManager {
if (resultRead == -1) { if (resultRead == -1) {
// end of file reached // end of file reached
break; break;
} else {
zos.write(buff, 0, resultRead);
} }
zos.write(buff, 0, resultRead);
} }
zos.closeEntry(); zos.closeEntry();
} catch (IOException ioe) { } catch (IOException ioe) {

View File

@ -58,8 +58,7 @@ public final class ZipHelper {
* @throws OpenXML4JException * @throws OpenXML4JException
* Throws if internal error occurs. * Throws if internal error occurs.
*/ */
public static ZipEntry getCorePropertiesZipEntry(ZipPackage pkg) public static ZipEntry getCorePropertiesZipEntry(ZipPackage pkg) {
throws OpenXML4JException {
PackageRelationship corePropsRel = pkg.getRelationshipsByType( PackageRelationship corePropsRel = pkg.getRelationshipsByType(
PackageRelationshipTypes.CORE_PROPERTIES).getRelationship(0); PackageRelationshipTypes.CORE_PROPERTIES).getRelationship(0);
@ -96,10 +95,10 @@ public final class ZipHelper {
public static String getOPCNameFromZipItemName(String zipItemName) { public static String getOPCNameFromZipItemName(String zipItemName) {
if (zipItemName == null) if (zipItemName == null)
throw new IllegalArgumentException("zipItemName"); throw new IllegalArgumentException("zipItemName");
if (zipItemName.startsWith(FORWARD_SLASH)) if (zipItemName.startsWith(FORWARD_SLASH)) {
return zipItemName; return zipItemName;
else }
return FORWARD_SLASH + zipItemName; return FORWARD_SLASH + zipItemName;
} }
/** /**

View File

@ -31,7 +31,6 @@ import org.dom4j.Namespace;
import org.dom4j.QName; import org.dom4j.QName;
import org.dom4j.io.SAXReader; import org.dom4j.io.SAXReader;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.PackageNamespaces; import org.apache.poi.openxml4j.opc.PackageNamespaces;
import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackageProperties; import org.apache.poi.openxml4j.opc.PackageProperties;
@ -44,7 +43,6 @@ import org.apache.poi.openxml4j.opc.internal.ZipHelper;
* Package properties unmarshaller. * Package properties unmarshaller.
* *
* @author Julien Chable * @author Julien Chable
* @version 1.0
*/ */
public final class PackagePropertiesUnmarshaller implements PartUnmarshaller { public final class PackagePropertiesUnmarshaller implements PartUnmarshaller {
@ -110,15 +108,9 @@ public final class PackagePropertiesUnmarshaller implements PartUnmarshaller {
.getInputStream(context.getZipEntry()); .getInputStream(context.getZipEntry());
} else if (context.getPackage() != null) { } else if (context.getPackage() != null) {
// Try to retrieve the part inputstream from the URI // Try to retrieve the part inputstream from the URI
ZipEntry zipEntry; ZipEntry zipEntry = ZipHelper
try { .getCorePropertiesZipEntry((ZipPackage) context
zipEntry = ZipHelper .getPackage());
.getCorePropertiesZipEntry((ZipPackage) context
.getPackage());
} catch (OpenXML4JException e) {
throw new IOException(
"Error while trying to get the part input stream.");
}
in = ((ZipPackage) context.getPackage()).getZipArchive() in = ((ZipPackage) context.getPackage()).getZipArchive()
.getInputStream(zipEntry); .getInputStream(zipEntry);
} else } else

View File

@ -14,6 +14,7 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.util; package org.apache.poi.util;
import org.apache.poi.openxml4j.opc.*; import org.apache.poi.openxml4j.opc.*;
@ -31,7 +32,7 @@ import java.net.URI;
* *
* @author Yegor Kozlov * @author Yegor Kozlov
*/ */
public class PackageHelper { public final class PackageHelper {
/** /**
* Clone the specified package. * Clone the specified package.
@ -74,10 +75,9 @@ public class PackageHelper {
if (rel.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) { if (rel.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) {
copyProperties(pkg.getPackageProperties(), dest.getPackageProperties()); copyProperties(pkg.getPackageProperties(), dest.getPackageProperties());
continue; continue;
} else {
dest.addRelationship(part.getPartName(), rel.getTargetMode(), rel.getRelationshipType());
part_tgt = dest.createPart(part.getPartName(), part.getContentType());
} }
dest.addRelationship(part.getPartName(), rel.getTargetMode(), rel.getRelationshipType());
part_tgt = dest.createPart(part.getPartName(), part.getContentType());
OutputStream out = part_tgt.getOutputStream(); OutputStream out = part_tgt.getOutputStream();
IOUtils.copy(part.getInputStream(), out); IOUtils.copy(part.getInputStream(), out);
@ -95,7 +95,7 @@ public class PackageHelper {
} }
/** /**
* Creates an empty file in the default temporary-file directory, * Creates an empty file in the default temporary-file directory,
*/ */
public static File createTempFile() throws IOException { public static File createTempFile() throws IOException {
File file = TempFile.createTempFile("poi-ooxml-", ".tmp"); File file = TempFile.createTempFile("poi-ooxml-", ".tmp");
@ -117,18 +117,18 @@ public class PackageHelper {
part_tgt.addExternalRelationship(rel.getTargetURI().toString(), rel.getRelationshipType(), rel.getId()); part_tgt.addExternalRelationship(rel.getTargetURI().toString(), rel.getRelationshipType(), rel.getId());
//external relations don't have associated package parts //external relations don't have associated package parts
continue; continue;
} else {
URI uri = rel.getTargetURI();
if(uri.getRawFragment() != null) {
part_tgt.addRelationship(uri, rel.getTargetMode(), rel.getRelationshipType(), rel.getId());
continue;
} else {
PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI());
p = pkg.getPart(relName);
part_tgt.addRelationship(p.getPartName(), rel.getTargetMode(), rel.getRelationshipType(), rel.getId());
}
} }
URI uri = rel.getTargetURI();
if(uri.getRawFragment() != null) {
part_tgt.addRelationship(uri, rel.getTargetMode(), rel.getRelationshipType(), rel.getId());
continue;
}
PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI());
p = pkg.getPart(relName);
part_tgt.addRelationship(p.getPartName(), rel.getTargetMode(), rel.getRelationshipType(), rel.getId());
PackagePart dest; PackagePart dest;

View File

@ -440,9 +440,9 @@ public class StylesTable extends POIXMLDocumentPart {
} }
protected CTDxf getDxf(int idx) { protected CTDxf getDxf(int idx) {
if(dxfs.size()==0) if (dxfs.size()==0) {
return CTDxf.Factory.newInstance(); return CTDxf.Factory.newInstance();
else }
return dxfs.get(idx); return dxfs.get(idx);
} }

View File

@ -33,8 +33,6 @@ import org.apache.poi.ss.formula.FormulaRenderer;
import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.xssf.model.StylesTable; import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.model.SharedStringsTable; import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.util.POILogger;
import org.apache.poi.util.POILogFactory;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType; import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;
@ -55,7 +53,6 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellFormulaType;
* </p> * </p>
*/ */
public final class XSSFCell implements Cell { public final class XSSFCell implements Cell {
private static POILogger logger = POILogFactory.getLogger(XSSFCell.class);
private static final String FALSE_AS_STRING = "0"; private static final String FALSE_AS_STRING = "0";
private static final String TRUE_AS_STRING = "1"; private static final String TRUE_AS_STRING = "1";
@ -64,28 +61,28 @@ public final class XSSFCell implements Cell {
* the xml bean containing information about the cell's location, value, * the xml bean containing information about the cell's location, value,
* data type, formatting, and formula * data type, formatting, and formula
*/ */
private final CTCell cell; private final CTCell _cell;
/** /**
* the XSSFRow this cell belongs to * the XSSFRow this cell belongs to
*/ */
private final XSSFRow row; private final XSSFRow _row;
/** /**
* 0-based column index * 0-based column index
*/ */
private int cellNum; private int _cellNum;
/** /**
* Table of strings shared across this workbook. * Table of strings shared across this workbook.
* If two cells contain the same string, then the cell value is the same index into SharedStringsTable * If two cells contain the same string, then the cell value is the same index into SharedStringsTable
*/ */
private SharedStringsTable sharedStringSource; private SharedStringsTable _sharedStringSource;
/** /**
* Table of cell styles shared across all cells in a workbook. * Table of cell styles shared across all cells in a workbook.
*/ */
private StylesTable stylesSource; private StylesTable _stylesSource;
/** /**
* Construct a XSSFCell. * Construct a XSSFCell.
@ -94,27 +91,27 @@ public final class XSSFCell implements Cell {
* @param cell the xml bean containing information about the cell. * @param cell the xml bean containing information about the cell.
*/ */
protected XSSFCell(XSSFRow row, CTCell cell) { protected XSSFCell(XSSFRow row, CTCell cell) {
this.cell = cell; _cell = cell;
this.row = row; _row = row;
if (cell.getR() != null) { if (cell.getR() != null) {
this.cellNum = new CellReference(cell.getR()).getCol(); _cellNum = new CellReference(cell.getR()).getCol();
} }
this.sharedStringSource = row.getSheet().getWorkbook().getSharedStringSource(); _sharedStringSource = row.getSheet().getWorkbook().getSharedStringSource();
this.stylesSource = row.getSheet().getWorkbook().getStylesSource(); _stylesSource = row.getSheet().getWorkbook().getStylesSource();
} }
/** /**
* @return table of strings shared across this workbook * @return table of strings shared across this workbook
*/ */
protected SharedStringsTable getSharedStringSource() { protected SharedStringsTable getSharedStringSource() {
return sharedStringSource; return _sharedStringSource;
} }
/** /**
* @return table of cell styles shared across this workbook * @return table of cell styles shared across this workbook
*/ */
protected StylesTable getStylesSource() { protected StylesTable getStylesSource() {
return stylesSource; return _stylesSource;
} }
/** /**
@ -132,7 +129,7 @@ public final class XSSFCell implements Cell {
* @return the row this cell belongs to * @return the row this cell belongs to
*/ */
public XSSFRow getRow() { public XSSFRow getRow() {
return row; return _row;
} }
/** /**
@ -150,10 +147,10 @@ public final class XSSFCell implements Cell {
case CELL_TYPE_BLANK: case CELL_TYPE_BLANK:
return false; return false;
case CELL_TYPE_BOOLEAN: case CELL_TYPE_BOOLEAN:
return cell.isSetV() && TRUE_AS_STRING.equals(cell.getV()); return _cell.isSetV() && TRUE_AS_STRING.equals(_cell.getV());
case CELL_TYPE_FORMULA: case CELL_TYPE_FORMULA:
//YK: should throw an exception if requesting boolean value from a non-boolean formula //YK: should throw an exception if requesting boolean value from a non-boolean formula
return cell.isSetV() && TRUE_AS_STRING.equals(cell.getV()); return _cell.isSetV() && TRUE_AS_STRING.equals(_cell.getV());
default: default:
throw typeMismatch(CELL_TYPE_BOOLEAN, cellType, false); throw typeMismatch(CELL_TYPE_BOOLEAN, cellType, false);
} }
@ -167,8 +164,8 @@ public final class XSSFCell implements Cell {
* will change the cell to a boolean cell and set its value. * will change the cell to a boolean cell and set its value.
*/ */
public void setCellValue(boolean value) { public void setCellValue(boolean value) {
cell.setT(STCellType.B); _cell.setT(STCellType.B);
cell.setV(value ? TRUE_AS_STRING : FALSE_AS_STRING); _cell.setV(value ? TRUE_AS_STRING : FALSE_AS_STRING);
} }
/** /**
@ -189,7 +186,7 @@ public final class XSSFCell implements Cell {
return 0.0; return 0.0;
case CELL_TYPE_FORMULA: case CELL_TYPE_FORMULA:
case CELL_TYPE_NUMERIC: case CELL_TYPE_NUMERIC:
return cell.isSetV() ? Double.parseDouble(cell.getV()) : 0.0; return _cell.isSetV() ? Double.parseDouble(_cell.getV()) : 0.0;
default: default:
throw typeMismatch(CELL_TYPE_NUMERIC, cellType, false); throw typeMismatch(CELL_TYPE_NUMERIC, cellType, false);
} }
@ -205,11 +202,11 @@ public final class XSSFCell implements Cell {
*/ */
public void setCellValue(double value) { public void setCellValue(double value) {
if(Double.isInfinite(value) || Double.isNaN(value)) { if(Double.isInfinite(value) || Double.isNaN(value)) {
cell.setT(STCellType.E); _cell.setT(STCellType.E);
cell.setV(FormulaError.NUM.getString()); _cell.setV(FormulaError.NUM.getString());
} else { } else {
cell.setT(STCellType.N); _cell.setT(STCellType.N);
cell.setV(String.valueOf(value)); _cell.setV(String.valueOf(value));
} }
} }
@ -242,20 +239,20 @@ public final class XSSFCell implements Cell {
rt = new XSSFRichTextString(""); rt = new XSSFRichTextString("");
break; break;
case CELL_TYPE_STRING: case CELL_TYPE_STRING:
if (cell.getT() == STCellType.INLINE_STR) { if (_cell.getT() == STCellType.INLINE_STR) {
if(cell.isSetIs()) { if(_cell.isSetIs()) {
//string is expressed directly in the cell definition instead of implementing the shared string table. //string is expressed directly in the cell definition instead of implementing the shared string table.
rt = new XSSFRichTextString(cell.getIs()); rt = new XSSFRichTextString(_cell.getIs());
} else if (cell.isSetV()) { } else if (_cell.isSetV()) {
//cached result of a formula //cached result of a formula
rt = new XSSFRichTextString(cell.getV()); rt = new XSSFRichTextString(_cell.getV());
} else { } else {
rt = new XSSFRichTextString(""); rt = new XSSFRichTextString("");
} }
} else { } else {
if (cell.isSetV()) { if (_cell.isSetV()) {
int idx = Integer.parseInt(cell.getV()); int idx = Integer.parseInt(_cell.getV());
rt = new XSSFRichTextString(sharedStringSource.getEntryAt(idx)); rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(idx));
} }
else { else {
rt = new XSSFRichTextString(""); rt = new XSSFRichTextString("");
@ -263,12 +260,12 @@ public final class XSSFCell implements Cell {
} }
break; break;
case CELL_TYPE_FORMULA: case CELL_TYPE_FORMULA:
rt = new XSSFRichTextString(cell.isSetV() ? cell.getV() : ""); rt = new XSSFRichTextString(_cell.isSetV() ? _cell.getV() : "");
break; break;
default: default:
throw typeMismatch(CELL_TYPE_STRING, cellType, false); throw typeMismatch(CELL_TYPE_STRING, cellType, false);
} }
rt.setStylesTableReference(stylesSource); rt.setStylesTableReference(_stylesSource);
return rt; return rt;
} }
@ -300,19 +297,19 @@ public final class XSSFCell implements Cell {
int cellType = getCellType(); int cellType = getCellType();
switch(cellType){ switch(cellType){
case Cell.CELL_TYPE_FORMULA: case Cell.CELL_TYPE_FORMULA:
cell.setV(str.getString()); _cell.setV(str.getString());
cell.setT(STCellType.STR); _cell.setT(STCellType.STR);
break; break;
default: default:
if(cell.getT() == STCellType.INLINE_STR) { if(_cell.getT() == STCellType.INLINE_STR) {
//set the 'pre-evaluated result //set the 'pre-evaluated result
cell.setV(str.getString()); _cell.setV(str.getString());
} else { } else {
cell.setT(STCellType.S); _cell.setT(STCellType.S);
XSSFRichTextString rt = (XSSFRichTextString)str; XSSFRichTextString rt = (XSSFRichTextString)str;
rt.setStylesTableReference(stylesSource); rt.setStylesTableReference(_stylesSource);
int sRef = sharedStringSource.addEntry(rt.getCTRst()); int sRef = _sharedStringSource.addEntry(rt.getCTRst());
cell.setV(Integer.toString(sRef)); _cell.setV(Integer.toString(sRef));
} }
break; break;
} }
@ -328,12 +325,11 @@ public final class XSSFCell implements Cell {
int cellType = getCellType(); int cellType = getCellType();
if(cellType != CELL_TYPE_FORMULA) throw typeMismatch(CELL_TYPE_FORMULA, cellType, false); if(cellType != CELL_TYPE_FORMULA) throw typeMismatch(CELL_TYPE_FORMULA, cellType, false);
CTCellFormula f = cell.getF(); CTCellFormula f = _cell.getF();
if(f.getT() == STCellFormulaType.SHARED){ if(f.getT() == STCellFormulaType.SHARED){
return convertSharedFormula((int)f.getSi()); return convertSharedFormula((int)f.getSi());
} else {
return f.getStringValue();
} }
return f.getStringValue();
} }
/** /**
@ -368,10 +364,10 @@ public final class XSSFCell implements Cell {
* @throws IllegalArgumentException if the formula is invalid * @throws IllegalArgumentException if the formula is invalid
*/ */
public void setCellFormula(String formula) { public void setCellFormula(String formula) {
XSSFWorkbook wb = row.getSheet().getWorkbook(); XSSFWorkbook wb = _row.getSheet().getWorkbook();
if (formula == null) { if (formula == null) {
wb.onDeleteFormula(this); wb.onDeleteFormula(this);
if(cell.isSetF()) cell.unsetF(); if(_cell.isSetF()) _cell.unsetF();
return; return;
} }
@ -381,8 +377,8 @@ public final class XSSFCell implements Cell {
CTCellFormula f = CTCellFormula.Factory.newInstance(); CTCellFormula f = CTCellFormula.Factory.newInstance();
f.setStringValue(formula); f.setStringValue(formula);
cell.setF(f); _cell.setF(f);
if(cell.isSetV()) cell.unsetV(); if(_cell.isSetV()) _cell.unsetV();
} }
/** /**
@ -391,7 +387,7 @@ public final class XSSFCell implements Cell {
* @return zero-based column index of a column in a sheet. * @return zero-based column index of a column in a sheet.
*/ */
public int getColumnIndex() { public int getColumnIndex() {
return this.cellNum; return this._cellNum;
} }
/** /**
@ -400,7 +396,7 @@ public final class XSSFCell implements Cell {
* @return zero-based row index of a row in the sheet that contains this cell * @return zero-based row index of a row in the sheet that contains this cell
*/ */
public int getRowIndex() { public int getRowIndex() {
return row.getRowNum(); return _row.getRowNum();
} }
/** /**
@ -409,7 +405,7 @@ public final class XSSFCell implements Cell {
* @return A1 style reference to the location of this cell * @return A1 style reference to the location of this cell
*/ */
public String getReference() { public String getReference() {
return cell.getR(); return _cell.getR();
} }
/** /**
@ -419,8 +415,8 @@ public final class XSSFCell implements Cell {
* <code>workbook.getCellStyleAt(0)</code> * <code>workbook.getCellStyleAt(0)</code>
*/ */
public XSSFCellStyle getCellStyle() { public XSSFCellStyle getCellStyle() {
long idx = cell.isSetS() ? cell.getS() : 0; long idx = _cell.isSetS() ? _cell.getS() : 0;
return stylesSource.getStyleAt((int)idx); return _stylesSource.getStyleAt((int)idx);
} }
/** /**
@ -432,13 +428,13 @@ public final class XSSFCell implements Cell {
*/ */
public void setCellStyle(CellStyle style) { public void setCellStyle(CellStyle style) {
if(style == null) { if(style == null) {
if(cell.isSetS()) cell.unsetS(); if(_cell.isSetS()) _cell.unsetS();
} else { } else {
XSSFCellStyle xStyle = (XSSFCellStyle)style; XSSFCellStyle xStyle = (XSSFCellStyle)style;
xStyle.verifyBelongsToStylesSource(stylesSource); xStyle.verifyBelongsToStylesSource(_stylesSource);
long idx = stylesSource.putStyle(xStyle); long idx = _stylesSource.putStyle(xStyle);
cell.setS(idx); _cell.setS(idx);
} }
} }
@ -455,7 +451,7 @@ public final class XSSFCell implements Cell {
*/ */
public int getCellType() { public int getCellType() {
if (cell.getF() != null) { if (_cell.getF() != null) {
return CELL_TYPE_FORMULA; return CELL_TYPE_FORMULA;
} }
@ -469,7 +465,7 @@ public final class XSSFCell implements Cell {
* on the cached value of the formula * on the cached value of the formula
*/ */
public int getCachedFormulaResultType() { public int getCachedFormulaResultType() {
if (cell.getF() == null) { if (_cell.getF() == null) {
throw new IllegalStateException("Only formula cells have cached results"); throw new IllegalStateException("Only formula cells have cached results");
} }
@ -480,11 +476,11 @@ public final class XSSFCell implements Cell {
* Detect cell type based on the "t" attribute of the CTCell bean * Detect cell type based on the "t" attribute of the CTCell bean
*/ */
private int getBaseCellType(boolean blankCells) { private int getBaseCellType(boolean blankCells) {
switch (cell.getT().intValue()) { switch (_cell.getT().intValue()) {
case STCellType.INT_B: case STCellType.INT_B:
return CELL_TYPE_BOOLEAN; return CELL_TYPE_BOOLEAN;
case STCellType.INT_N: case STCellType.INT_N:
if (!cell.isSetV() && blankCells) { if (!_cell.isSetV() && blankCells) {
// ooxml does have a separate cell type of 'blank'. A blank cell gets encoded as // ooxml does have a separate cell type of 'blank'. A blank cell gets encoded as
// (either not present or) a numeric cell with no value set. // (either not present or) a numeric cell with no value set.
// The formula evaluator (and perhaps other clients of this interface) needs to // The formula evaluator (and perhaps other clients of this interface) needs to
@ -500,7 +496,7 @@ public final class XSSFCell implements Cell {
case STCellType.INT_STR: case STCellType.INT_STR:
return CELL_TYPE_STRING; return CELL_TYPE_STRING;
default: default:
throw new IllegalStateException("Illegal cell type: " + this.cell.getT()); throw new IllegalStateException("Illegal cell type: " + this._cell.getT());
} }
} }
@ -570,7 +566,7 @@ public final class XSSFCell implements Cell {
int cellType = getCellType(); int cellType = getCellType();
if(cellType != CELL_TYPE_ERROR) throw typeMismatch(CELL_TYPE_ERROR, cellType, false); if(cellType != CELL_TYPE_ERROR) throw typeMismatch(CELL_TYPE_ERROR, cellType, false);
return cell.getV(); return _cell.getV();
} }
/** /**
* Get the value of the cell as an error code. * Get the value of the cell as an error code.
@ -615,15 +611,15 @@ public final class XSSFCell implements Cell {
* cell and set its value. * cell and set its value.
*/ */
public void setCellErrorValue(FormulaError error) { public void setCellErrorValue(FormulaError error) {
cell.setT(STCellType.E); _cell.setT(STCellType.E);
cell.setV(error.getString()); _cell.setV(error.getString());
} }
/** /**
* Sets this cell as the active cell for the worksheet. * Sets this cell as the active cell for the worksheet.
*/ */
public void setAsActiveCell() { public void setAsActiveCell() {
getSheet().setActiveCell(cell.getR()); getSheet().setActiveCell(_cell.getR());
} }
/** /**
@ -632,9 +628,9 @@ public final class XSSFCell implements Cell {
*/ */
private void setBlank(){ private void setBlank(){
CTCell blank = CTCell.Factory.newInstance(); CTCell blank = CTCell.Factory.newInstance();
blank.setR(cell.getR()); blank.setR(_cell.getR());
blank.setS(cell.getS()); blank.setS(_cell.getS());
cell.set(blank); _cell.set(blank);
} }
/** /**
@ -644,9 +640,9 @@ public final class XSSFCell implements Cell {
*/ */
protected void setCellNum(int num) { protected void setCellNum(int num) {
checkBounds(num); checkBounds(num);
cellNum = num; _cellNum = num;
String ref = new CellReference(getRowIndex(), getColumnIndex()).formatAsString(); String ref = new CellReference(getRowIndex(), getColumnIndex()).formatAsString();
cell.setR(ref); _cell.setR(ref);
} }
/** /**
@ -668,31 +664,31 @@ public final class XSSFCell implements Cell {
break; break;
case CELL_TYPE_BOOLEAN: case CELL_TYPE_BOOLEAN:
String newVal = convertCellValueToBoolean() ? TRUE_AS_STRING : FALSE_AS_STRING; String newVal = convertCellValueToBoolean() ? TRUE_AS_STRING : FALSE_AS_STRING;
cell.setT(STCellType.B); _cell.setT(STCellType.B);
cell.setV(newVal); _cell.setV(newVal);
break; break;
case CELL_TYPE_NUMERIC: case CELL_TYPE_NUMERIC:
cell.setT(STCellType.N); _cell.setT(STCellType.N);
break; break;
case CELL_TYPE_ERROR: case CELL_TYPE_ERROR:
cell.setT(STCellType.E); _cell.setT(STCellType.E);
break; break;
case CELL_TYPE_STRING: case CELL_TYPE_STRING:
if(prevType != CELL_TYPE_STRING){ if(prevType != CELL_TYPE_STRING){
String str = convertCellValueToString(); String str = convertCellValueToString();
XSSFRichTextString rt = new XSSFRichTextString(str); XSSFRichTextString rt = new XSSFRichTextString(str);
rt.setStylesTableReference(stylesSource); rt.setStylesTableReference(_stylesSource);
int sRef = sharedStringSource.addEntry(rt.getCTRst()); int sRef = _sharedStringSource.addEntry(rt.getCTRst());
cell.setV(Integer.toString(sRef)); _cell.setV(Integer.toString(sRef));
} }
cell.setT(STCellType.S); _cell.setT(STCellType.S);
break; break;
case CELL_TYPE_FORMULA: case CELL_TYPE_FORMULA:
if(!cell.isSetF()){ if(!_cell.isSetF()){
CTCellFormula f = CTCellFormula.Factory.newInstance(); CTCellFormula f = CTCellFormula.Factory.newInstance();
f.setStringValue("0"); f.setStringValue("0");
cell.setF(f); _cell.setF(f);
if(cell.isSetT()) cell.unsetT(); if(_cell.isSetT()) _cell.unsetT();
} }
break; break;
default: default:
@ -722,9 +718,8 @@ public final class XSSFCell implements Cell {
if (DateUtil.isCellDateFormatted(this)) { if (DateUtil.isCellDateFormatted(this)) {
DateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); DateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
return sdf.format(getDateCellValue()); return sdf.format(getDateCellValue());
} else {
return getNumericCellValue() + "";
} }
return getNumericCellValue() + "";
case CELL_TYPE_STRING: case CELL_TYPE_STRING:
return getRichStringCellValue().toString(); return getRichStringCellValue().toString();
default: default:
@ -745,7 +740,7 @@ public final class XSSFCell implements Cell {
* <code>null</code> for blank cells. * <code>null</code> for blank cells.
*/ */
public String getRawValue() { public String getRawValue() {
return cell.getV(); return _cell.getV();
} }
/** /**
@ -792,7 +787,7 @@ public final class XSSFCell implements Cell {
* @return the cell comment associated with this cell or <code>null</code> * @return the cell comment associated with this cell or <code>null</code>
*/ */
public XSSFComment getCellComment() { public XSSFComment getCellComment() {
return getSheet().getCellComment(row.getRowNum(), getColumnIndex()); return getSheet().getCellComment(_row.getRowNum(), getColumnIndex());
} }
/** /**
@ -802,7 +797,7 @@ public final class XSSFCell implements Cell {
* @param comment comment associated with this cell * @param comment comment associated with this cell
*/ */
public void setCellComment(Comment comment) { public void setCellComment(Comment comment) {
String cellRef = new CellReference(row.getRowNum(), getColumnIndex()).formatAsString(); String cellRef = new CellReference(_row.getRowNum(), getColumnIndex()).formatAsString();
getSheet().setCellComment(cellRef, (XSSFComment)comment); getSheet().setCellComment(cellRef, (XSSFComment)comment);
} }
@ -812,7 +807,7 @@ public final class XSSFCell implements Cell {
* @return hyperlink associated with this cell or <code>null</code> if not found * @return hyperlink associated with this cell or <code>null</code> if not found
*/ */
public XSSFHyperlink getHyperlink() { public XSSFHyperlink getHyperlink() {
return getSheet().getHyperlink(row.getRowNum(), cellNum); return getSheet().getHyperlink(_row.getRowNum(), _cellNum);
} }
/** /**
@ -824,7 +819,7 @@ public final class XSSFCell implements Cell {
XSSFHyperlink link = (XSSFHyperlink)hyperlink; XSSFHyperlink link = (XSSFHyperlink)hyperlink;
// Assign to us // Assign to us
link.setCellReference( new CellReference(row.getRowNum(), cellNum).formatAsString() ); link.setCellReference( new CellReference(_row.getRowNum(), _cellNum).formatAsString() );
// Add to the lists // Add to the lists
getSheet().setCellHyperlink(link); getSheet().setCellHyperlink(link);
@ -837,7 +832,7 @@ public final class XSSFCell implements Cell {
* @return the xml bean containing information about this cell * @return the xml bean containing information about this cell
*/ */
public CTCell getCTCell(){ public CTCell getCTCell(){
return cell; return _cell;
} }
/** /**
@ -857,14 +852,14 @@ public final class XSSFCell implements Cell {
switch (cellType) { switch (cellType) {
case CELL_TYPE_BOOLEAN: case CELL_TYPE_BOOLEAN:
return TRUE_AS_STRING.equals(cell.getV()); return TRUE_AS_STRING.equals(_cell.getV());
case CELL_TYPE_STRING: case CELL_TYPE_STRING:
int sstIndex = Integer.parseInt(cell.getV()); int sstIndex = Integer.parseInt(_cell.getV());
XSSFRichTextString rt = new XSSFRichTextString(sharedStringSource.getEntryAt(sstIndex)); XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(sstIndex));
String text = rt.getString(); String text = rt.getString();
return Boolean.valueOf(text); return Boolean.valueOf(text).booleanValue();
case CELL_TYPE_NUMERIC: case CELL_TYPE_NUMERIC:
return Double.parseDouble(cell.getV()) != 0; return Double.parseDouble(_cell.getV()) != 0;
case CELL_TYPE_ERROR: case CELL_TYPE_ERROR:
case CELL_TYPE_BLANK: case CELL_TYPE_BLANK:
@ -880,15 +875,15 @@ public final class XSSFCell implements Cell {
case CELL_TYPE_BLANK: case CELL_TYPE_BLANK:
return ""; return "";
case CELL_TYPE_BOOLEAN: case CELL_TYPE_BOOLEAN:
return TRUE_AS_STRING.equals(cell.getV()) ? "TRUE" : "FALSE"; return TRUE_AS_STRING.equals(_cell.getV()) ? "TRUE" : "FALSE";
case CELL_TYPE_STRING: case CELL_TYPE_STRING:
int sstIndex = Integer.parseInt(cell.getV()); int sstIndex = Integer.parseInt(_cell.getV());
XSSFRichTextString rt = new XSSFRichTextString(sharedStringSource.getEntryAt(sstIndex)); XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(sstIndex));
return rt.getString(); return rt.getString();
case CELL_TYPE_NUMERIC: case CELL_TYPE_NUMERIC:
return String.valueOf(Double.parseDouble(cell.getV())); return String.valueOf(Double.parseDouble(_cell.getV()));
case CELL_TYPE_ERROR: case CELL_TYPE_ERROR:
return cell.getV(); return _cell.getV();
case CELL_TYPE_FORMULA: case CELL_TYPE_FORMULA:
// should really evaluate, but HSSFCell can't call HSSFFormulaEvaluator // should really evaluate, but HSSFCell can't call HSSFFormulaEvaluator
return ""; return "";

View File

@ -37,12 +37,12 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
*/ */
public class XSSFCellStyle implements CellStyle { public class XSSFCellStyle implements CellStyle {
private int cellXfId; private int _cellXfId;
private StylesTable stylesSource; private StylesTable _stylesSource;
private CTXf cellXf; private CTXf _cellXf;
private CTXf cellStyleXf; private CTXf _cellStyleXf;
private XSSFFont font; private XSSFFont _font;
private XSSFCellAlignment cellAlignment; private XSSFCellAlignment _cellAlignment;
/** /**
* Creates a Cell Style from the supplied parts * Creates a Cell Style from the supplied parts
@ -51,35 +51,35 @@ public class XSSFCellStyle implements CellStyle {
* @param stylesSource Styles Source to work off * @param stylesSource Styles Source to work off
*/ */
public XSSFCellStyle(int cellXfId, int cellStyleXfId, StylesTable stylesSource) { public XSSFCellStyle(int cellXfId, int cellStyleXfId, StylesTable stylesSource) {
this.cellXfId = cellXfId; _cellXfId = cellXfId;
this.stylesSource = stylesSource; _stylesSource = stylesSource;
this.cellXf = stylesSource.getCellXfAt(this.cellXfId); _cellXf = stylesSource.getCellXfAt(this._cellXfId);
this.cellStyleXf = stylesSource.getCellStyleXfAt(cellStyleXfId); _cellStyleXf = stylesSource.getCellStyleXfAt(cellStyleXfId);
} }
/** /**
* Used so that StylesSource can figure out our location * Used so that StylesSource can figure out our location
*/ */
public CTXf getCoreXf() { public CTXf getCoreXf() {
return cellXf; return _cellXf;
} }
/** /**
* Used so that StylesSource can figure out our location * Used so that StylesSource can figure out our location
*/ */
public CTXf getStyleXf() { public CTXf getStyleXf() {
return cellStyleXf; return _cellStyleXf;
} }
/** /**
* Creates an empty Cell Style * Creates an empty Cell Style
*/ */
public XSSFCellStyle(StylesTable stylesSource) { public XSSFCellStyle(StylesTable stylesSource) {
this.stylesSource = stylesSource; _stylesSource = stylesSource;
// We need a new CTXf for the main styles // We need a new CTXf for the main styles
// TODO decide on a style ctxf // TODO decide on a style ctxf
cellXf = CTXf.Factory.newInstance(); _cellXf = CTXf.Factory.newInstance();
cellStyleXf = null; _cellStyleXf = null;
} }
/** /**
@ -92,7 +92,7 @@ public class XSSFCellStyle implements CellStyle {
* @throws IllegalArgumentException if there's a workbook mis-match * @throws IllegalArgumentException if there's a workbook mis-match
*/ */
public void verifyBelongsToStylesSource(StylesTable src) { public void verifyBelongsToStylesSource(StylesTable src) {
if(this.stylesSource != src) { if(this._stylesSource != src) {
throw new IllegalArgumentException("This Style does not belong to the supplied Workbook Stlyes Source. Are you trying to assign a style from one workbook to the cell of a differnt workbook?"); throw new IllegalArgumentException("This Style does not belong to the supplied Workbook Stlyes Source. Are you trying to assign a style from one workbook to the cell of a differnt workbook?");
} }
} }
@ -112,8 +112,8 @@ public class XSSFCellStyle implements CellStyle {
public void cloneStyleFrom(CellStyle source) { public void cloneStyleFrom(CellStyle source) {
if(source instanceof XSSFCellStyle) { if(source instanceof XSSFCellStyle) {
XSSFCellStyle src = (XSSFCellStyle)source; XSSFCellStyle src = (XSSFCellStyle)source;
cellXf.set(src.getCoreXf()); _cellXf.set(src.getCoreXf());
cellStyleXf.set(src.getStyleXf()); _cellStyleXf.set(src.getStyleXf());
} else { } else {
throw new IllegalArgumentException("Can only clone from one XSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle"); throw new IllegalArgumentException("Can only clone from one XSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle");
} }
@ -142,7 +142,7 @@ public class XSSFCellStyle implements CellStyle {
* @see org.apache.poi.ss.usermodel.HorizontalAlignment * @see org.apache.poi.ss.usermodel.HorizontalAlignment
*/ */
public HorizontalAlignment getAlignmentEnum() { public HorizontalAlignment getAlignmentEnum() {
CTCellAlignment align = cellXf.getAlignment(); CTCellAlignment align = _cellXf.getAlignment();
if(align != null && align.isSetHorizontal()) { if(align != null && align.isSetHorizontal()) {
return HorizontalAlignment.values()[align.getHorizontal().intValue()-1]; return HorizontalAlignment.values()[align.getHorizontal().intValue()-1];
} }
@ -169,10 +169,10 @@ public class XSSFCellStyle implements CellStyle {
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT * @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/ */
public short getBorderBottom() { public short getBorderBottom() {
if(!cellXf.getApplyBorder()) return BORDER_NONE; if(!_cellXf.getApplyBorder()) return BORDER_NONE;
int idx = (int)cellXf.getBorderId(); int idx = (int)_cellXf.getBorderId();
CTBorder ct = stylesSource.getBorderAt(idx).getCTBorder(); CTBorder ct = _stylesSource.getBorderAt(idx).getCTBorder();
STBorderStyle.Enum ptrn = ct.isSetBottom() ? ct.getBottom().getStyle() : null; STBorderStyle.Enum ptrn = ct.isSetBottom() ? ct.getBottom().getStyle() : null;
return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1); return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1);
} }
@ -208,10 +208,10 @@ public class XSSFCellStyle implements CellStyle {
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT * @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/ */
public short getBorderLeft() { public short getBorderLeft() {
if(!cellXf.getApplyBorder()) return BORDER_NONE; if(!_cellXf.getApplyBorder()) return BORDER_NONE;
int idx = (int)cellXf.getBorderId(); int idx = (int)_cellXf.getBorderId();
CTBorder ct = stylesSource.getBorderAt(idx).getCTBorder(); CTBorder ct = _stylesSource.getBorderAt(idx).getCTBorder();
STBorderStyle.Enum ptrn = ct.isSetLeft() ? ct.getLeft().getStyle() : null; STBorderStyle.Enum ptrn = ct.isSetLeft() ? ct.getLeft().getStyle() : null;
return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1); return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1);
} }
@ -246,10 +246,10 @@ public class XSSFCellStyle implements CellStyle {
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT * @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/ */
public short getBorderRight() { public short getBorderRight() {
if(!cellXf.getApplyBorder()) return BORDER_NONE; if(!_cellXf.getApplyBorder()) return BORDER_NONE;
int idx = (int)cellXf.getBorderId(); int idx = (int)_cellXf.getBorderId();
CTBorder ct = stylesSource.getBorderAt(idx).getCTBorder(); CTBorder ct = _stylesSource.getBorderAt(idx).getCTBorder();
STBorderStyle.Enum ptrn = ct.isSetRight() ? ct.getRight().getStyle() : null; STBorderStyle.Enum ptrn = ct.isSetRight() ? ct.getRight().getStyle() : null;
return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1); return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1);
} }
@ -284,10 +284,10 @@ public class XSSFCellStyle implements CellStyle {
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT * @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/ */
public short getBorderTop() { public short getBorderTop() {
if(!cellXf.getApplyBorder()) return BORDER_NONE; if(!_cellXf.getApplyBorder()) return BORDER_NONE;
int idx = (int)cellXf.getBorderId(); int idx = (int)_cellXf.getBorderId();
CTBorder ct = stylesSource.getBorderAt(idx).getCTBorder(); CTBorder ct = _stylesSource.getBorderAt(idx).getCTBorder();
STBorderStyle.Enum ptrn = ct.isSetTop() ? ct.getTop().getStyle() : null; STBorderStyle.Enum ptrn = ct.isSetTop() ? ct.getTop().getStyle() : null;
return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1); return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1);
} }
@ -320,10 +320,10 @@ public class XSSFCellStyle implements CellStyle {
* @return the used color or <code>null</code> if not set * @return the used color or <code>null</code> if not set
*/ */
public XSSFColor getBottomBorderXSSFColor() { public XSSFColor getBottomBorderXSSFColor() {
if(!cellXf.getApplyBorder()) return null; if(!_cellXf.getApplyBorder()) return null;
int idx = (int)cellXf.getBorderId(); int idx = (int)_cellXf.getBorderId();
XSSFCellBorder border = stylesSource.getBorderAt(idx); XSSFCellBorder border = _stylesSource.getBorderAt(idx);
return border.getBorderColor(BorderSide.BOTTOM); return border.getBorderColor(BorderSide.BOTTOM);
} }
@ -334,7 +334,7 @@ public class XSSFCellStyle implements CellStyle {
* @return the index of the number format * @return the index of the number format
*/ */
public short getDataFormat() { public short getDataFormat() {
return (short)cellXf.getNumFmtId(); return (short)_cellXf.getNumFmtId();
} }
/** /**
@ -345,7 +345,7 @@ public class XSSFCellStyle implements CellStyle {
*/ */
public String getDataFormatString() { public String getDataFormatString() {
int idx = getDataFormat(); int idx = getDataFormat();
return new XSSFDataFormat(stylesSource).getFormat((short)idx); return new XSSFDataFormat(_stylesSource).getFormat((short)idx);
} }
/** /**
@ -372,10 +372,10 @@ public class XSSFCellStyle implements CellStyle {
* @return XSSFColor - fill color or <code>null</code> if not set * @return XSSFColor - fill color or <code>null</code> if not set
*/ */
public XSSFColor getFillBackgroundXSSFColor() { public XSSFColor getFillBackgroundXSSFColor() {
if(!cellXf.getApplyFill()) return null; if(!_cellXf.getApplyFill()) return null;
int fillIndex = (int)cellXf.getFillId(); int fillIndex = (int)_cellXf.getFillId();
XSSFCellFill fg = stylesSource.getFillAt(fillIndex); XSSFCellFill fg = _stylesSource.getFillAt(fillIndex);
return fg.getFillBackgroundColor(); return fg.getFillBackgroundColor();
} }
@ -400,10 +400,10 @@ public class XSSFCellStyle implements CellStyle {
* @return XSSFColor - fill color or <code>null</code> if not set * @return XSSFColor - fill color or <code>null</code> if not set
*/ */
public XSSFColor getFillForegroundXSSFColor() { public XSSFColor getFillForegroundXSSFColor() {
if(!cellXf.getApplyFill()) return null; if(!_cellXf.getApplyFill()) return null;
int fillIndex = (int)cellXf.getFillId(); int fillIndex = (int)_cellXf.getFillId();
XSSFCellFill fg = stylesSource.getFillAt(fillIndex); XSSFCellFill fg = _stylesSource.getFillAt(fillIndex);
return fg.getFillForegroundColor(); return fg.getFillForegroundColor();
} }
@ -431,10 +431,10 @@ public class XSSFCellStyle implements CellStyle {
* @see org.apache.poi.ss.usermodel.CellStyle#DIAMONDS * @see org.apache.poi.ss.usermodel.CellStyle#DIAMONDS
*/ */
public short getFillPattern() { public short getFillPattern() {
if(!cellXf.getApplyFill()) return 0; if(!_cellXf.getApplyFill()) return 0;
int fillIndex = (int)cellXf.getFillId(); int fillIndex = (int)_cellXf.getFillId();
XSSFCellFill fill = stylesSource.getFillAt(fillIndex); XSSFCellFill fill = _stylesSource.getFillAt(fillIndex);
STPatternType.Enum ptrn = fill.getPatternType(); STPatternType.Enum ptrn = fill.getPatternType();
if(ptrn == null) return CellStyle.NO_FILL; if(ptrn == null) return CellStyle.NO_FILL;
@ -456,10 +456,10 @@ public class XSSFCellStyle implements CellStyle {
* @return Font - font * @return Font - font
*/ */
public XSSFFont getFont() { public XSSFFont getFont() {
if (font == null) { if (_font == null) {
font = stylesSource.getFontAt(getFontId()); _font = _stylesSource.getFontAt(getFontId());
} }
return font; return _font;
} }
/** /**
@ -487,7 +487,7 @@ public class XSSFCellStyle implements CellStyle {
* @return indent - number of spaces * @return indent - number of spaces
*/ */
public short getIndention() { public short getIndention() {
CTCellAlignment align = cellXf.getAlignment(); CTCellAlignment align = _cellXf.getAlignment();
return (short)(align == null ? 0 : align.getIndent()); return (short)(align == null ? 0 : align.getIndent());
} }
@ -497,7 +497,7 @@ public class XSSFCellStyle implements CellStyle {
* @return unique index number of the underlying record this style represents * @return unique index number of the underlying record this style represents
*/ */
public short getIndex() { public short getIndex() {
return (short)this.cellXfId; return (short)this._cellXfId;
} }
/** /**
@ -518,10 +518,10 @@ public class XSSFCellStyle implements CellStyle {
* @see org.apache.poi.ss.usermodel.IndexedColors * @see org.apache.poi.ss.usermodel.IndexedColors
*/ */
public XSSFColor getLeftBorderXSSFColor() { public XSSFColor getLeftBorderXSSFColor() {
if(!cellXf.getApplyBorder()) return null; if(!_cellXf.getApplyBorder()) return null;
int idx = (int)cellXf.getBorderId(); int idx = (int)_cellXf.getBorderId();
XSSFCellBorder border = stylesSource.getBorderAt(idx); XSSFCellBorder border = _stylesSource.getBorderAt(idx);
return border.getBorderColor(BorderSide.LEFT); return border.getBorderColor(BorderSide.LEFT);
} }
@ -551,10 +551,10 @@ public class XSSFCellStyle implements CellStyle {
* @return the used color or <code>null</code> if not set * @return the used color or <code>null</code> if not set
*/ */
public XSSFColor getRightBorderXSSFColor() { public XSSFColor getRightBorderXSSFColor() {
if(!cellXf.getApplyBorder()) return null; if(!_cellXf.getApplyBorder()) return null;
int idx = (int)cellXf.getBorderId(); int idx = (int)_cellXf.getBorderId();
XSSFCellBorder border = stylesSource.getBorderAt(idx); XSSFCellBorder border = _stylesSource.getBorderAt(idx);
return border.getBorderColor(BorderSide.RIGHT); return border.getBorderColor(BorderSide.RIGHT);
} }
@ -574,7 +574,7 @@ public class XSSFCellStyle implements CellStyle {
* @return rotation degrees (between 0 and 180 degrees) * @return rotation degrees (between 0 and 180 degrees)
*/ */
public short getRotation() { public short getRotation() {
CTCellAlignment align = cellXf.getAlignment(); CTCellAlignment align = _cellXf.getAlignment();
return (short)(align == null ? 0 : align.getTextRotation()); return (short)(align == null ? 0 : align.getTextRotation());
} }
@ -595,10 +595,10 @@ public class XSSFCellStyle implements CellStyle {
* @return the used color or <code>null</code> if not set * @return the used color or <code>null</code> if not set
*/ */
public XSSFColor getTopBorderXSSFColor() { public XSSFColor getTopBorderXSSFColor() {
if(!cellXf.getApplyBorder()) return null; if(!_cellXf.getApplyBorder()) return null;
int idx = (int)cellXf.getBorderId(); int idx = (int)_cellXf.getBorderId();
XSSFCellBorder border = stylesSource.getBorderAt(idx); XSSFCellBorder border = _stylesSource.getBorderAt(idx);
return border.getBorderColor(BorderSide.TOP); return border.getBorderColor(BorderSide.TOP);
} }
@ -623,12 +623,11 @@ public class XSSFCellStyle implements CellStyle {
* @see org.apache.poi.ss.usermodel.VerticalAlignment * @see org.apache.poi.ss.usermodel.VerticalAlignment
*/ */
public VerticalAlignment getVerticalAlignmentEnum() { public VerticalAlignment getVerticalAlignmentEnum() {
CTCellAlignment align = cellXf.getAlignment(); CTCellAlignment align = _cellXf.getAlignment();
if(align != null && align.isSetVertical()) { if(align != null && align.isSetVertical()) {
return VerticalAlignment.values()[align.getVertical().intValue()-1]; return VerticalAlignment.values()[align.getVertical().intValue()-1];
} else {
return VerticalAlignment.BOTTOM;
} }
return VerticalAlignment.BOTTOM;
} }
/** /**
@ -637,7 +636,7 @@ public class XSSFCellStyle implements CellStyle {
* @return a boolean value indicating if the text in a cell should be line-wrapped within the cell. * @return a boolean value indicating if the text in a cell should be line-wrapped within the cell.
*/ */
public boolean getWrapText() { public boolean getWrapText() {
CTCellAlignment align = cellXf.getAlignment(); CTCellAlignment align = _cellXf.getAlignment();
return align != null && align.getWrapText(); return align != null && align.getWrapText();
} }
@ -692,10 +691,10 @@ public class XSSFCellStyle implements CellStyle {
if(border == BORDER_NONE) ct.unsetBottom(); if(border == BORDER_NONE) ct.unsetBottom();
else pr.setStyle(STBorderStyle.Enum.forInt(border + 1)); else pr.setStyle(STBorderStyle.Enum.forInt(border + 1));
int idx = stylesSource.putBorder(new XSSFCellBorder(ct)); int idx = _stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx); _cellXf.setBorderId(idx);
cellXf.setApplyBorder(true); _cellXf.setApplyBorder(true);
} }
/** /**
@ -732,10 +731,10 @@ public class XSSFCellStyle implements CellStyle {
if(border == BORDER_NONE) ct.unsetLeft(); if(border == BORDER_NONE) ct.unsetLeft();
else pr.setStyle(STBorderStyle.Enum.forInt(border + 1)); else pr.setStyle(STBorderStyle.Enum.forInt(border + 1));
int idx = stylesSource.putBorder(new XSSFCellBorder(ct)); int idx = _stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx); _cellXf.setBorderId(idx);
cellXf.setApplyBorder(true); _cellXf.setApplyBorder(true);
} }
/** /**
@ -772,10 +771,10 @@ public class XSSFCellStyle implements CellStyle {
if(border == BORDER_NONE) ct.unsetRight(); if(border == BORDER_NONE) ct.unsetRight();
else pr.setStyle(STBorderStyle.Enum.forInt(border + 1)); else pr.setStyle(STBorderStyle.Enum.forInt(border + 1));
int idx = stylesSource.putBorder(new XSSFCellBorder(ct)); int idx = _stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx); _cellXf.setBorderId(idx);
cellXf.setApplyBorder(true); _cellXf.setApplyBorder(true);
} }
/** /**
@ -812,10 +811,10 @@ public class XSSFCellStyle implements CellStyle {
if(border == BORDER_NONE) ct.unsetTop(); if(border == BORDER_NONE) ct.unsetTop();
else pr.setStyle(STBorderStyle.Enum.forInt(border + 1)); else pr.setStyle(STBorderStyle.Enum.forInt(border + 1));
int idx = stylesSource.putBorder(new XSSFCellBorder(ct)); int idx = _stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx); _cellXf.setBorderId(idx);
cellXf.setApplyBorder(true); _cellXf.setApplyBorder(true);
} }
/** /**
@ -851,10 +850,10 @@ public class XSSFCellStyle implements CellStyle {
if(color != null) pr.setColor(color.getCTColor()); if(color != null) pr.setColor(color.getCTColor());
else pr.unsetColor(); else pr.unsetColor();
int idx = stylesSource.putBorder(new XSSFCellBorder(ct)); int idx = _stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx); _cellXf.setBorderId(idx);
cellXf.setApplyBorder(true); _cellXf.setApplyBorder(true);
} }
/** /**
@ -863,8 +862,8 @@ public class XSSFCellStyle implements CellStyle {
* @param fmt the index of a data format * @param fmt the index of a data format
*/ */
public void setDataFormat(short fmt) { public void setDataFormat(short fmt) {
cellXf.setApplyNumberFormat(true); _cellXf.setApplyNumberFormat(true);
cellXf.setNumFmtId(fmt); _cellXf.setNumFmtId(fmt);
} }
/** /**
@ -902,10 +901,10 @@ public class XSSFCellStyle implements CellStyle {
ptrn.setBgColor(color.getCTColor()); ptrn.setBgColor(color.getCTColor());
} }
int idx = stylesSource.putFill(new XSSFCellFill(ct)); int idx = _stylesSource.putFill(new XSSFCellFill(ct));
cellXf.setFillId(idx); _cellXf.setFillId(idx);
cellXf.setApplyFill(true); _cellXf.setApplyFill(true);
} }
/** /**
@ -958,10 +957,10 @@ public class XSSFCellStyle implements CellStyle {
ptrn.setFgColor(color.getCTColor()); ptrn.setFgColor(color.getCTColor());
} }
int idx = stylesSource.putFill(new XSSFCellFill(ct)); int idx = _stylesSource.putFill(new XSSFCellFill(ct));
cellXf.setFillId(idx); _cellXf.setFillId(idx);
cellXf.setApplyFill(true); _cellXf.setApplyFill(true);
} }
/** /**
@ -982,9 +981,9 @@ public class XSSFCellStyle implements CellStyle {
*/ */
private CTFill getCTFill(){ private CTFill getCTFill(){
CTFill ct; CTFill ct;
if(cellXf.getApplyFill()) { if(_cellXf.getApplyFill()) {
int fillIndex = (int)cellXf.getFillId(); int fillIndex = (int)_cellXf.getFillId();
XSSFCellFill cf = stylesSource.getFillAt(fillIndex); XSSFCellFill cf = _stylesSource.getFillAt(fillIndex);
ct = (CTFill)cf.getCTFill().copy(); ct = (CTFill)cf.getCTFill().copy();
} else { } else {
@ -998,9 +997,9 @@ public class XSSFCellStyle implements CellStyle {
*/ */
private CTBorder getCTBorder(){ private CTBorder getCTBorder(){
CTBorder ct; CTBorder ct;
if(cellXf.getApplyBorder()) { if(_cellXf.getApplyBorder()) {
int idx = (int)cellXf.getBorderId(); int idx = (int)_cellXf.getBorderId();
XSSFCellBorder cf = stylesSource.getBorderAt(idx); XSSFCellBorder cf = _stylesSource.getBorderAt(idx);
ct = (CTBorder)cf.getCTBorder().copy(); ct = (CTBorder)cf.getCTBorder().copy();
} else { } else {
@ -1041,10 +1040,10 @@ public class XSSFCellStyle implements CellStyle {
if(fp == NO_FILL && ptrn.isSetPatternType()) ptrn.unsetPatternType(); if(fp == NO_FILL && ptrn.isSetPatternType()) ptrn.unsetPatternType();
else ptrn.setPatternType(STPatternType.Enum.forInt(fp + 1)); else ptrn.setPatternType(STPatternType.Enum.forInt(fp + 1));
int idx = stylesSource.putFill(new XSSFCellFill(ct)); int idx = _stylesSource.putFill(new XSSFCellFill(ct));
cellXf.setFillId(idx); _cellXf.setFillId(idx);
cellXf.setApplyFill(true); _cellXf.setApplyFill(true);
} }
/** /**
@ -1070,10 +1069,10 @@ public class XSSFCellStyle implements CellStyle {
public void setFont(Font font) { public void setFont(Font font) {
if(font != null){ if(font != null){
long index = font.getIndex(); long index = font.getIndex();
this.cellXf.setFontId(index); this._cellXf.setFontId(index);
this.cellXf.setApplyFont(true); this._cellXf.setApplyFont(true);
} else { } else {
this.cellXf.setApplyFont(false); this._cellXf.setApplyFont(false);
} }
} }
@ -1120,10 +1119,10 @@ public class XSSFCellStyle implements CellStyle {
if(color != null) pr.setColor(color.getCTColor()); if(color != null) pr.setColor(color.getCTColor());
else pr.unsetColor(); else pr.unsetColor();
int idx = stylesSource.putBorder(new XSSFCellBorder(ct)); int idx = _stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx); _cellXf.setBorderId(idx);
cellXf.setApplyBorder(true); _cellXf.setApplyBorder(true);
} }
/** /**
@ -1160,10 +1159,10 @@ public class XSSFCellStyle implements CellStyle {
if(color != null) pr.setColor(color.getCTColor()); if(color != null) pr.setColor(color.getCTColor());
else pr.unsetColor(); else pr.unsetColor();
int idx = stylesSource.putBorder(new XSSFCellBorder(ct)); int idx = _stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx); _cellXf.setBorderId(idx);
cellXf.setApplyBorder(true); _cellXf.setApplyBorder(true);
} }
/** /**
@ -1210,10 +1209,10 @@ public class XSSFCellStyle implements CellStyle {
if(color != null) pr.setColor(color.getCTColor()); if(color != null) pr.setColor(color.getCTColor());
else pr.unsetColor(); else pr.unsetColor();
int idx = stylesSource.putBorder(new XSSFCellBorder(ct)); int idx = _stylesSource.putBorder(new XSSFCellBorder(ct));
cellXf.setBorderId(idx); _cellXf.setBorderId(idx);
cellXf.setApplyBorder(true); _cellXf.setApplyBorder(true);
} }
/** /**
@ -1296,10 +1295,10 @@ public class XSSFCellStyle implements CellStyle {
} }
} }
private int getFontId() { private int getFontId() {
if (cellXf.isSetFontId()) { if (_cellXf.isSetFontId()) {
return (int) cellXf.getFontId(); return (int) _cellXf.getFontId();
} }
return (int) cellStyleXf.getFontId(); return (int) _cellStyleXf.getFontId();
} }
/** /**
@ -1307,10 +1306,10 @@ public class XSSFCellStyle implements CellStyle {
* @return CTCellProtection * @return CTCellProtection
*/ */
private CTCellProtection getCellProtection() { private CTCellProtection getCellProtection() {
if (cellXf.getProtection() == null) { if (_cellXf.getProtection() == null) {
cellXf.addNewProtection(); _cellXf.addNewProtection();
} }
return cellXf.getProtection(); return _cellXf.getProtection();
} }
/** /**
@ -1318,10 +1317,10 @@ public class XSSFCellStyle implements CellStyle {
* @return XSSFCellAlignment - cell alignment * @return XSSFCellAlignment - cell alignment
*/ */
protected XSSFCellAlignment getCellAlignment() { protected XSSFCellAlignment getCellAlignment() {
if (this.cellAlignment == null) { if (this._cellAlignment == null) {
this.cellAlignment = new XSSFCellAlignment(getCTCellAlignment()); this._cellAlignment = new XSSFCellAlignment(getCTCellAlignment());
} }
return this.cellAlignment; return this._cellAlignment;
} }
/** /**
@ -1330,10 +1329,10 @@ public class XSSFCellStyle implements CellStyle {
* @return CTCellAlignment * @return CTCellAlignment
*/ */
private CTCellAlignment getCTCellAlignment() { private CTCellAlignment getCTCellAlignment() {
if (cellXf.getAlignment() == null) { if (_cellXf.getAlignment() == null) {
cellXf.setAlignment(CTCellAlignment.Factory.newInstance()); _cellXf.setAlignment(CTCellAlignment.Factory.newInstance());
} }
return cellXf.getAlignment(); return _cellXf.getAlignment();
} }
/** /**
@ -1342,7 +1341,7 @@ public class XSSFCellStyle implements CellStyle {
* @return the hash code value for this style * @return the hash code value for this style
*/ */
public int hashCode(){ public int hashCode(){
return cellXf.toString().hashCode(); return _cellXf.toString().hashCode();
} }
/** /**
@ -1355,7 +1354,7 @@ public class XSSFCellStyle implements CellStyle {
if(o == null || !(o instanceof XSSFCellStyle)) return false; if(o == null || !(o instanceof XSSFCellStyle)) return false;
XSSFCellStyle cf = (XSSFCellStyle)o; XSSFCellStyle cf = (XSSFCellStyle)o;
return cellXf.toString().equals(cf.getCoreXf().toString()); return _cellXf.toString().equals(cf.getCoreXf().toString());
} }
/** /**
@ -1365,11 +1364,11 @@ public class XSSFCellStyle implements CellStyle {
* @return a copy of this style * @return a copy of this style
*/ */
public Object clone(){ public Object clone(){
CTXf xf = (CTXf)cellXf.copy(); CTXf xf = (CTXf)_cellXf.copy();
int xfSize = stylesSource._getStyleXfsSize(); int xfSize = _stylesSource._getStyleXfsSize();
int indexXf = stylesSource.putCellXf(xf); int indexXf = _stylesSource.putCellXf(xf);
return new XSSFCellStyle(indexXf-1, xfSize-1, stylesSource); return new XSSFCellStyle(indexXf-1, xfSize-1, _stylesSource);
} }
} }

View File

@ -42,8 +42,8 @@ public class XSSFFont implements Font {
*/ */
public static final short DEFAULT_FONT_COLOR = IndexedColors.BLACK.getIndex(); public static final short DEFAULT_FONT_COLOR = IndexedColors.BLACK.getIndex();
private CTFont ctFont; private CTFont _ctFont;
private short index; private short _index;
/** /**
* Create a new XSSFFont * Create a new XSSFFont
@ -51,20 +51,20 @@ public class XSSFFont implements Font {
* @param font the underlying CTFont bean * @param font the underlying CTFont bean
*/ */
public XSSFFont(CTFont font) { public XSSFFont(CTFont font) {
this.ctFont = font; _ctFont = font;
this.index = 0; _index = 0;
} }
public XSSFFont(CTFont font, int index) { public XSSFFont(CTFont font, int index) {
this.ctFont = font; _ctFont = font;
this.index = (short)index; _index = (short)index;
} }
/** /**
* Create a new XSSFont. This method is protected to be used only by XSSFWorkbook * Create a new XSSFont. This method is protected to be used only by XSSFWorkbook
*/ */
protected XSSFFont() { protected XSSFFont() {
this.ctFont = CTFont.Factory.newInstance(); this._ctFont = CTFont.Factory.newInstance();
setFontName(DEFAULT_FONT_NAME); setFontName(DEFAULT_FONT_NAME);
setFontHeight((double)DEFAULT_FONT_SIZE); setFontHeight((double)DEFAULT_FONT_SIZE);
} }
@ -73,7 +73,7 @@ public class XSSFFont implements Font {
* get the underlying CTFont font * get the underlying CTFont font
*/ */
public CTFont getCTFont() { public CTFont getCTFont() {
return ctFont; return _ctFont;
} }
/** /**
@ -82,7 +82,7 @@ public class XSSFFont implements Font {
* @return boolean - bold * @return boolean - bold
*/ */
public boolean getBold() { public boolean getBold() {
CTBooleanProperty bold = ctFont.sizeOfBArray() == 0 ? null : ctFont.getBArray(0); CTBooleanProperty bold = _ctFont.sizeOfBArray() == 0 ? null : _ctFont.getBArray(0);
return (bold != null && bold.getVal()); return (bold != null && bold.getVal());
} }
@ -93,7 +93,7 @@ public class XSSFFont implements Font {
* @see org.apache.poi.ss.usermodel.FontCharset * @see org.apache.poi.ss.usermodel.FontCharset
*/ */
public byte getCharSet() { public byte getCharSet() {
CTIntProperty charset = ctFont.sizeOfCharsetArray() == 0 ? null : ctFont.getCharsetArray(0); CTIntProperty charset = _ctFont.sizeOfCharsetArray() == 0 ? null : _ctFont.getCharsetArray(0);
int val = charset == null ? FontCharset.ANSI.getValue() : FontCharset.valueOf(charset.getVal()).getValue(); int val = charset == null ? FontCharset.ANSI.getValue() : FontCharset.valueOf(charset.getVal()).getValue();
return (byte)val; return (byte)val;
} }
@ -107,7 +107,7 @@ public class XSSFFont implements Font {
* @see IndexedColors * @see IndexedColors
*/ */
public short getColor() { public short getColor() {
CTColor color = ctFont.sizeOfColorArray() == 0 ? null : ctFont.getColorArray(0); CTColor color = _ctFont.sizeOfColorArray() == 0 ? null : _ctFont.getColorArray(0);
if (color == null) return IndexedColors.BLACK.getIndex(); if (color == null) return IndexedColors.BLACK.getIndex();
long index = color.getIndexed(); long index = color.getIndexed();
@ -128,7 +128,7 @@ public class XSSFFont implements Font {
* @return XSSFColor - rgb color to use * @return XSSFColor - rgb color to use
*/ */
public XSSFColor getXSSFColor() { public XSSFColor getXSSFColor() {
CTColor ctColor = ctFont.sizeOfColorArray() == 0 ? null : ctFont.getColorArray(0); CTColor ctColor = _ctFont.sizeOfColorArray() == 0 ? null : _ctFont.getColorArray(0);
return ctColor == null ? null : new XSSFColor(ctColor); return ctColor == null ? null : new XSSFColor(ctColor);
} }
@ -140,7 +140,7 @@ public class XSSFFont implements Font {
* @return short - theme defined to use * @return short - theme defined to use
*/ */
public short getThemeColor() { public short getThemeColor() {
CTColor color = ctFont.sizeOfColorArray() == 0 ? null : ctFont.getColorArray(0); CTColor color = _ctFont.sizeOfColorArray() == 0 ? null : _ctFont.getColorArray(0);
long index = color == null ? 0 : color.getTheme(); long index = color == null ? 0 : color.getTheme();
return (short) index; return (short) index;
} }
@ -151,12 +151,12 @@ public class XSSFFont implements Font {
* @return short - height in point * @return short - height in point
*/ */
public short getFontHeight() { public short getFontHeight() {
CTFontSize size = ctFont.sizeOfSzArray() == 0 ? null : ctFont.getSzArray(0); CTFontSize size = _ctFont.sizeOfSzArray() == 0 ? null : _ctFont.getSzArray(0);
if (size != null) { if (size != null) {
double fontHeight = size.getVal(); double fontHeight = size.getVal();
return (short)(fontHeight*20); return (short)(fontHeight*20);
} else }
return (short)(DEFAULT_FONT_SIZE*20); return (short)(DEFAULT_FONT_SIZE*20);
} }
/** /**
@ -172,7 +172,7 @@ public class XSSFFont implements Font {
* @return String - a string representing the name of the font to use * @return String - a string representing the name of the font to use
*/ */
public String getFontName() { public String getFontName() {
CTFontName name = ctFont.sizeOfNameArray() == 0 ? null : ctFont.getNameArray(0); CTFontName name = _ctFont.sizeOfNameArray() == 0 ? null : _ctFont.getNameArray(0);
return name == null ? DEFAULT_FONT_NAME : name.getVal(); return name == null ? DEFAULT_FONT_NAME : name.getVal();
} }
@ -182,7 +182,7 @@ public class XSSFFont implements Font {
* @return boolean - value for italic * @return boolean - value for italic
*/ */
public boolean getItalic() { public boolean getItalic() {
CTBooleanProperty italic = ctFont.sizeOfIArray() == 0 ? null : ctFont.getIArray(0); CTBooleanProperty italic = _ctFont.sizeOfIArray() == 0 ? null : _ctFont.getIArray(0);
return italic != null && italic.getVal(); return italic != null && italic.getVal();
} }
@ -192,7 +192,7 @@ public class XSSFFont implements Font {
* @return boolean - value for strikeout * @return boolean - value for strikeout
*/ */
public boolean getStrikeout() { public boolean getStrikeout() {
CTBooleanProperty strike = ctFont.sizeOfStrikeArray() == 0 ? null : ctFont.getStrikeArray(0); CTBooleanProperty strike = _ctFont.sizeOfStrikeArray() == 0 ? null : _ctFont.getStrikeArray(0);
return strike != null && strike.getVal(); return strike != null && strike.getVal();
} }
@ -205,21 +205,21 @@ public class XSSFFont implements Font {
* @see Font#SS_SUB * @see Font#SS_SUB
*/ */
public short getTypeOffset() { public short getTypeOffset() {
CTVerticalAlignFontProperty vAlign = ctFont.sizeOfVertAlignArray() == 0 ? null : ctFont.getVertAlignArray(0); CTVerticalAlignFontProperty vAlign = _ctFont.sizeOfVertAlignArray() == 0 ? null : _ctFont.getVertAlignArray(0);
if (vAlign != null) { if (vAlign == null) {
int val = vAlign.getVal().intValue();
switch (val) {
case STVerticalAlignRun.INT_BASELINE:
return Font.SS_NONE;
case STVerticalAlignRun.INT_SUBSCRIPT:
return Font.SS_SUB;
case STVerticalAlignRun.INT_SUPERSCRIPT:
return Font.SS_SUPER;
default:
throw new POIXMLException("Wrong offset value " + val);
}
} else
return Font.SS_NONE; return Font.SS_NONE;
}
int val = vAlign.getVal().intValue();
switch (val) {
case STVerticalAlignRun.INT_BASELINE:
return Font.SS_NONE;
case STVerticalAlignRun.INT_SUBSCRIPT:
return Font.SS_SUB;
case STVerticalAlignRun.INT_SUPERSCRIPT:
return Font.SS_SUPER;
default:
throw new POIXMLException("Wrong offset value " + val);
}
} }
/** /**
@ -229,7 +229,7 @@ public class XSSFFont implements Font {
* @see org.apache.poi.ss.usermodel.FontUnderline * @see org.apache.poi.ss.usermodel.FontUnderline
*/ */
public byte getUnderline() { public byte getUnderline() {
CTUnderlineProperty underline = ctFont.sizeOfUArray() == 0 ? null : ctFont.getUArray(0); CTUnderlineProperty underline = _ctFont.sizeOfUArray() == 0 ? null : _ctFont.getUArray(0);
if (underline != null) { if (underline != null) {
FontUnderline val = FontUnderline.valueOf(underline.getVal().intValue()); FontUnderline val = FontUnderline.valueOf(underline.getVal().intValue());
return val.getByteValue(); return val.getByteValue();
@ -244,10 +244,10 @@ public class XSSFFont implements Font {
*/ */
public void setBold(boolean bold) { public void setBold(boolean bold) {
if(bold){ if(bold){
CTBooleanProperty ctBold = ctFont.sizeOfBArray() == 0 ? ctFont.addNewB() : ctFont.getBArray(0); CTBooleanProperty ctBold = _ctFont.sizeOfBArray() == 0 ? _ctFont.addNewB() : _ctFont.getBArray(0);
ctBold.setVal(bold); ctBold.setVal(bold);
} else { } else {
ctFont.setBArray(null); _ctFont.setBArray(null);
} }
} }
@ -275,7 +275,7 @@ public class XSSFFont implements Font {
* @see FontCharset * @see FontCharset
*/ */
public void setCharSet(byte charset) { public void setCharSet(byte charset) {
CTIntProperty charsetProperty = ctFont.sizeOfCharsetArray() == 0 ? ctFont.addNewCharset() : ctFont.getCharsetArray(0); CTIntProperty charsetProperty = _ctFont.sizeOfCharsetArray() == 0 ? _ctFont.addNewCharset() : _ctFont.getCharsetArray(0);
switch (charset) { switch (charset) {
case Font.ANSI_CHARSET: case Font.ANSI_CHARSET:
charsetProperty.setVal(FontCharset.ANSI.getValue()); charsetProperty.setVal(FontCharset.ANSI.getValue());
@ -308,7 +308,7 @@ public class XSSFFont implements Font {
* @see IndexedColors * @see IndexedColors
*/ */
public void setColor(short color) { public void setColor(short color) {
CTColor ctColor = ctFont.sizeOfColorArray() == 0 ? ctFont.addNewColor() : ctFont.getColorArray(0); CTColor ctColor = _ctFont.sizeOfColorArray() == 0 ? _ctFont.addNewColor() : _ctFont.getColorArray(0);
switch (color) { switch (color) {
case Font.COLOR_NORMAL: { case Font.COLOR_NORMAL: {
ctColor.setIndexed(XSSFFont.DEFAULT_FONT_COLOR); ctColor.setIndexed(XSSFFont.DEFAULT_FONT_COLOR);
@ -329,9 +329,9 @@ public class XSSFFont implements Font {
* @param color - color to use * @param color - color to use
*/ */
public void setColor(XSSFColor color) { public void setColor(XSSFColor color) {
if(color == null) ctFont.setColorArray(null); if(color == null) _ctFont.setColorArray(null);
else { else {
CTColor ctColor = ctFont.sizeOfColorArray() == 0 ? ctFont.addNewColor() : ctFont.getColorArray(0); CTColor ctColor = _ctFont.sizeOfColorArray() == 0 ? _ctFont.addNewColor() : _ctFont.getColorArray(0);
ctColor.setRgb(color.getRgb()); ctColor.setRgb(color.getRgb());
} }
} }
@ -351,7 +351,7 @@ public class XSSFFont implements Font {
* @param height - height in points * @param height - height in points
*/ */
public void setFontHeight(double height) { public void setFontHeight(double height) {
CTFontSize fontSize = ctFont.sizeOfSzArray() == 0 ? ctFont.addNewSz() : ctFont.getSzArray(0); CTFontSize fontSize = _ctFont.sizeOfSzArray() == 0 ? _ctFont.addNewSz() : _ctFont.getSzArray(0);
fontSize.setVal(height); fontSize.setVal(height);
} }
@ -370,7 +370,7 @@ public class XSSFFont implements Font {
* @param theme - theme color to use * @param theme - theme color to use
*/ */
public void setThemeColor(short theme) { public void setThemeColor(short theme) {
CTColor ctColor = ctFont.sizeOfColorArray() == 0 ? ctFont.addNewColor() : ctFont.getColorArray(0); CTColor ctColor = _ctFont.sizeOfColorArray() == 0 ? _ctFont.addNewColor() : _ctFont.getColorArray(0);
ctColor.setTheme(theme); ctColor.setTheme(theme);
} }
@ -386,7 +386,7 @@ public class XSSFFont implements Font {
* @see #DEFAULT_FONT_NAME * @see #DEFAULT_FONT_NAME
*/ */
public void setFontName(String name) { public void setFontName(String name) {
CTFontName fontName = ctFont.sizeOfNameArray() == 0 ? ctFont.addNewName() : ctFont.getNameArray(0); CTFontName fontName = _ctFont.sizeOfNameArray() == 0 ? _ctFont.addNewName() : _ctFont.getNameArray(0);
fontName.setVal(name == null ? DEFAULT_FONT_NAME : name); fontName.setVal(name == null ? DEFAULT_FONT_NAME : name);
} }
@ -399,10 +399,10 @@ public class XSSFFont implements Font {
*/ */
public void setItalic(boolean italic) { public void setItalic(boolean italic) {
if(italic){ if(italic){
CTBooleanProperty bool = ctFont.sizeOfIArray() == 0 ? ctFont.addNewI() : ctFont.getIArray(0); CTBooleanProperty bool = _ctFont.sizeOfIArray() == 0 ? _ctFont.addNewI() : _ctFont.getIArray(0);
bool.setVal(italic); bool.setVal(italic);
} else { } else {
ctFont.setIArray(null); _ctFont.setIArray(null);
} }
} }
@ -414,9 +414,9 @@ public class XSSFFont implements Font {
* @param strikeout - value for strikeout or not * @param strikeout - value for strikeout or not
*/ */
public void setStrikeout(boolean strikeout) { public void setStrikeout(boolean strikeout) {
if(!strikeout) ctFont.setStrikeArray(null); if(!strikeout) _ctFont.setStrikeArray(null);
else { else {
CTBooleanProperty strike = ctFont.sizeOfStrikeArray() == 0 ? ctFont.addNewStrike() : ctFont.getStrikeArray(0); CTBooleanProperty strike = _ctFont.sizeOfStrikeArray() == 0 ? _ctFont.addNewStrike() : _ctFont.getStrikeArray(0);
strike.setVal(strikeout); strike.setVal(strikeout);
} }
} }
@ -433,9 +433,9 @@ public class XSSFFont implements Font {
*/ */
public void setTypeOffset(short offset) { public void setTypeOffset(short offset) {
if(offset == Font.SS_NONE){ if(offset == Font.SS_NONE){
ctFont.setVertAlignArray(null); _ctFont.setVertAlignArray(null);
} else { } else {
CTVerticalAlignFontProperty offsetProperty = ctFont.sizeOfVertAlignArray() == 0 ? ctFont.addNewVertAlign() : ctFont.getVertAlignArray(0); CTVerticalAlignFontProperty offsetProperty = _ctFont.sizeOfVertAlignArray() == 0 ? _ctFont.addNewVertAlign() : _ctFont.getVertAlignArray(0);
switch (offset) { switch (offset) {
case Font.SS_NONE: case Font.SS_NONE:
offsetProperty.setVal(STVerticalAlignRun.BASELINE); offsetProperty.setVal(STVerticalAlignRun.BASELINE);
@ -469,10 +469,10 @@ public class XSSFFont implements Font {
* @param underline - FontUnderline enum value * @param underline - FontUnderline enum value
*/ */
public void setUnderline(FontUnderline underline) { public void setUnderline(FontUnderline underline) {
if(underline == FontUnderline.NONE && ctFont.sizeOfUArray() > 0){ if(underline == FontUnderline.NONE && _ctFont.sizeOfUArray() > 0){
ctFont.setUArray(null); _ctFont.setUArray(null);
} else { } else {
CTUnderlineProperty ctUnderline = ctFont.sizeOfUArray() == 0 ? ctFont.addNewU() : ctFont.getUArray(0); CTUnderlineProperty ctUnderline = _ctFont.sizeOfUArray() == 0 ? _ctFont.addNewU() : _ctFont.getUArray(0);
STUnderlineValues.Enum val = STUnderlineValues.Enum.forInt(underline.getValue()); STUnderlineValues.Enum val = STUnderlineValues.Enum.forInt(underline.getValue());
ctUnderline.setVal(val); ctUnderline.setVal(val);
} }
@ -480,7 +480,7 @@ public class XSSFFont implements Font {
public String toString() { public String toString() {
return ctFont.toString(); return _ctFont.toString();
} }
@ -489,7 +489,7 @@ public class XSSFFont implements Font {
*/ */
public long putFont(StylesTable styles) { public long putFont(StylesTable styles) {
short idx = (short)styles.putFont(this); short idx = (short)styles.putFont(this);
this.index = idx; this._index = idx;
return idx; return idx;
} }
@ -501,7 +501,7 @@ public class XSSFFont implements Font {
* @see org.apache.poi.xssf.model.StylesTable#createDefaultFont() * @see org.apache.poi.xssf.model.StylesTable#createDefaultFont()
*/ */
public FontScheme getScheme() { public FontScheme getScheme() {
CTFontScheme scheme = ctFont.sizeOfSchemeArray() == 0 ? null : ctFont.getSchemeArray(0); CTFontScheme scheme = _ctFont.sizeOfSchemeArray() == 0 ? null : _ctFont.getSchemeArray(0);
return scheme == null ? FontScheme.NONE : FontScheme.valueOf(scheme.getVal().intValue()); return scheme == null ? FontScheme.NONE : FontScheme.valueOf(scheme.getVal().intValue());
} }
@ -512,7 +512,7 @@ public class XSSFFont implements Font {
* @see FontScheme * @see FontScheme
*/ */
public void setScheme(FontScheme scheme) { public void setScheme(FontScheme scheme) {
CTFontScheme ctFontScheme = ctFont.sizeOfSchemeArray() == 0 ? ctFont.addNewScheme() : ctFont.getSchemeArray(0); CTFontScheme ctFontScheme = _ctFont.sizeOfSchemeArray() == 0 ? _ctFont.addNewScheme() : _ctFont.getSchemeArray(0);
STFontScheme.Enum val = STFontScheme.Enum.forInt(scheme.getValue()); STFontScheme.Enum val = STFontScheme.Enum.forInt(scheme.getValue());
ctFontScheme.setVal(val); ctFontScheme.setVal(val);
} }
@ -524,7 +524,7 @@ public class XSSFFont implements Font {
* @see org.apache.poi.ss.usermodel.FontFamily * @see org.apache.poi.ss.usermodel.FontFamily
*/ */
public int getFamily() { public int getFamily() {
CTIntProperty family = ctFont.sizeOfFamilyArray() == 0 ? ctFont.addNewFamily() : ctFont.getFamilyArray(0); CTIntProperty family = _ctFont.sizeOfFamilyArray() == 0 ? _ctFont.addNewFamily() : _ctFont.getFamilyArray(0);
return family == null ? FontFamily.NOT_APPLICABLE.getValue() : FontFamily.valueOf(family.getVal()).getValue(); return family == null ? FontFamily.NOT_APPLICABLE.getValue() : FontFamily.valueOf(family.getVal()).getValue();
} }
@ -537,7 +537,7 @@ public class XSSFFont implements Font {
* @see FontFamily * @see FontFamily
*/ */
public void setFamily(int value) { public void setFamily(int value) {
CTIntProperty family = ctFont.sizeOfFamilyArray() == 0 ? ctFont.addNewFamily() : ctFont.getFamilyArray(0); CTIntProperty family = _ctFont.sizeOfFamilyArray() == 0 ? _ctFont.addNewFamily() : _ctFont.getFamilyArray(0);
family.setVal(value); family.setVal(value);
} }
@ -560,18 +560,18 @@ public class XSSFFont implements Font {
public short getIndex() public short getIndex()
{ {
return index; return _index;
} }
public int hashCode(){ public int hashCode(){
return ctFont.toString().hashCode(); return _ctFont.toString().hashCode();
} }
public boolean equals(Object o){ public boolean equals(Object o){
if(!(o instanceof XSSFFont)) return false; if(!(o instanceof XSSFFont)) return false;
XSSFFont cf = (XSSFFont)o; XSSFFont cf = (XSSFFont)o;
return ctFont.toString().equals(cf.getCTFont().toString()); return _ctFont.toString().equals(cf.getCTFont().toString());
} }
} }

View File

@ -32,10 +32,10 @@ import org.apache.poi.openxml4j.opc.PackageRelationship;
* are largely stored as relations of the sheet * are largely stored as relations of the sheet
*/ */
public class XSSFHyperlink implements Hyperlink { public class XSSFHyperlink implements Hyperlink {
private int type; private int _type;
private PackageRelationship externalRel; private PackageRelationship _externalRel;
private CTHyperlink ctHyperlink; private CTHyperlink _ctHyperlink;
private String location; private String _location;
/** /**
* Create a new XSSFHyperlink. This method is protected to be used only by XSSFCreationHelper * Create a new XSSFHyperlink. This method is protected to be used only by XSSFCreationHelper
@ -43,8 +43,8 @@ public class XSSFHyperlink implements Hyperlink {
* @param type - the type of hyperlink to create * @param type - the type of hyperlink to create
*/ */
protected XSSFHyperlink(int type) { protected XSSFHyperlink(int type) {
this.type = type; _type = type;
this.ctHyperlink = CTHyperlink.Factory.newInstance(); _ctHyperlink = CTHyperlink.Factory.newInstance();
} }
/** /**
@ -54,37 +54,36 @@ public class XSSFHyperlink implements Hyperlink {
* @param hyperlinkRel the relationship in the underlying OPC package which stores the actual link's address * @param hyperlinkRel the relationship in the underlying OPC package which stores the actual link's address
*/ */
protected XSSFHyperlink(CTHyperlink ctHyperlink, PackageRelationship hyperlinkRel) { protected XSSFHyperlink(CTHyperlink ctHyperlink, PackageRelationship hyperlinkRel) {
this.ctHyperlink = ctHyperlink; _ctHyperlink = ctHyperlink;
this.externalRel = hyperlinkRel; _externalRel = hyperlinkRel;
// Figure out the Hyperlink type and distination // Figure out the Hyperlink type and distination
// If it has a location, it's internal // If it has a location, it's internal
if (ctHyperlink.getLocation() != null) { if (ctHyperlink.getLocation() != null) {
type = Hyperlink.LINK_DOCUMENT; _type = Hyperlink.LINK_DOCUMENT;
location = ctHyperlink.getLocation(); _location = ctHyperlink.getLocation();
} else { } else {
// Otherwise it's somehow external, check // Otherwise it's somehow external, check
// the relation to see how // the relation to see how
if (externalRel == null) { if (_externalRel == null) {
if (ctHyperlink.getId() != null) { if (ctHyperlink.getId() != null) {
throw new IllegalStateException("The hyperlink for cell " + ctHyperlink.getRef() + " references relation " + ctHyperlink.getId() + ", but that didn't exist!"); throw new IllegalStateException("The hyperlink for cell " + ctHyperlink.getRef() + " references relation " + ctHyperlink.getId() + ", but that didn't exist!");
} else {
throw new IllegalStateException("A sheet hyperlink must either have a location, or a relationship. Found:\n" + ctHyperlink);
} }
throw new IllegalStateException("A sheet hyperlink must either have a location, or a relationship. Found:\n" + ctHyperlink);
} }
URI target = externalRel.getTargetURI(); URI target = _externalRel.getTargetURI();
location = target.toString(); _location = target.toString();
// Try to figure out the type // Try to figure out the type
if (location.startsWith("http://") || location.startsWith("https://") if (_location.startsWith("http://") || _location.startsWith("https://")
|| location.startsWith("ftp://")) { || _location.startsWith("ftp://")) {
type = Hyperlink.LINK_URL; _type = Hyperlink.LINK_URL;
} else if (location.startsWith("mailto:")) { } else if (_location.startsWith("mailto:")) {
type = Hyperlink.LINK_EMAIL; _type = Hyperlink.LINK_EMAIL;
} else { } else {
type = Hyperlink.LINK_FILE; _type = Hyperlink.LINK_FILE;
} }
} }
} }
@ -93,7 +92,7 @@ public class XSSFHyperlink implements Hyperlink {
* Returns the underlying hyperlink object * Returns the underlying hyperlink object
*/ */
protected CTHyperlink getCTHyperlink() { protected CTHyperlink getCTHyperlink() {
return ctHyperlink; return _ctHyperlink;
} }
/** /**
@ -101,7 +100,7 @@ public class XSSFHyperlink implements Hyperlink {
* this hyperlink? * this hyperlink?
*/ */
public boolean needsRelationToo() { public boolean needsRelationToo() {
return (type != Hyperlink.LINK_DOCUMENT); return (_type != Hyperlink.LINK_DOCUMENT);
} }
/** /**
@ -111,10 +110,10 @@ public class XSSFHyperlink implements Hyperlink {
if (needsRelationToo()) { if (needsRelationToo()) {
// Generate the relation // Generate the relation
PackageRelationship rel = PackageRelationship rel =
sheetPart.addExternalRelationship(location, XSSFRelation.SHEET_HYPERLINKS.getRelation()); sheetPart.addExternalRelationship(_location, XSSFRelation.SHEET_HYPERLINKS.getRelation());
// Update the r:id // Update the r:id
ctHyperlink.setId(rel.getId()); _ctHyperlink.setId(rel.getId());
} }
} }
@ -124,7 +123,7 @@ public class XSSFHyperlink implements Hyperlink {
* @return the type of this hyperlink * @return the type of this hyperlink
*/ */
public int getType() { public int getType() {
return type; return _type;
} }
/** /**
@ -132,7 +131,7 @@ public class XSSFHyperlink implements Hyperlink {
* es A55 * es A55
*/ */
public String getCellRef() { public String getCellRef() {
return ctHyperlink.getRef(); return _ctHyperlink.getRef();
} }
/** /**
@ -141,7 +140,7 @@ public class XSSFHyperlink implements Hyperlink {
* @return the address of this hyperlink * @return the address of this hyperlink
*/ */
public String getAddress() { public String getAddress() {
return location; return _location;
} }
/** /**
@ -150,7 +149,7 @@ public class XSSFHyperlink implements Hyperlink {
* @return text to display * @return text to display
*/ */
public String getLabel() { public String getLabel() {
return ctHyperlink.getDisplay(); return _ctHyperlink.getDisplay();
} }
/** /**
@ -160,7 +159,7 @@ public class XSSFHyperlink implements Hyperlink {
* @return location * @return location
*/ */
public String getLocation() { public String getLocation() {
return ctHyperlink.getLocation(); return _ctHyperlink.getLocation();
} }
/** /**
@ -169,7 +168,7 @@ public class XSSFHyperlink implements Hyperlink {
* @param label text label for this hyperlink * @param label text label for this hyperlink
*/ */
public void setLabel(String label) { public void setLabel(String label) {
ctHyperlink.setDisplay(label); _ctHyperlink.setDisplay(label);
} }
/** /**
@ -179,7 +178,7 @@ public class XSSFHyperlink implements Hyperlink {
* @param location - string representing a location of this hyperlink * @param location - string representing a location of this hyperlink
*/ */
public void setLocation(String location) { public void setLocation(String location) {
ctHyperlink.setLocation(location); _ctHyperlink.setLocation(location);
} }
/** /**
@ -188,9 +187,9 @@ public class XSSFHyperlink implements Hyperlink {
* @param address - the address of this hyperlink * @param address - the address of this hyperlink
*/ */
public void setAddress(String address) { public void setAddress(String address) {
location = address; _location = address;
//we must set location for internal hyperlinks //we must set location for internal hyperlinks
if (type == Hyperlink.LINK_DOCUMENT) { if (_type == Hyperlink.LINK_DOCUMENT) {
setLocation(address); setLocation(address);
} }
} }
@ -199,11 +198,11 @@ public class XSSFHyperlink implements Hyperlink {
* Assigns this hyperlink to the given cell reference * Assigns this hyperlink to the given cell reference
*/ */
protected void setCellReference(String ref) { protected void setCellReference(String ref) {
ctHyperlink.setRef(ref); _ctHyperlink.setRef(ref);
} }
private CellReference buildCellReference() { private CellReference buildCellReference() {
return new CellReference(ctHyperlink.getRef()); return new CellReference(_ctHyperlink.getRef());
} }
@ -251,7 +250,7 @@ public class XSSFHyperlink implements Hyperlink {
* @param col the 0-based column of the first cell that contains the hyperlink * @param col the 0-based column of the first cell that contains the hyperlink
*/ */
public void setFirstColumn(int col) { public void setFirstColumn(int col) {
ctHyperlink.setRef( _ctHyperlink.setRef(
new CellReference( new CellReference(
getFirstRow(), col getFirstRow(), col
).formatAsString() ).formatAsString()
@ -273,7 +272,7 @@ public class XSSFHyperlink implements Hyperlink {
* @param row the 0-based row of the first cell that contains the hyperlink * @param row the 0-based row of the first cell that contains the hyperlink
*/ */
public void setFirstRow(int row) { public void setFirstRow(int row) {
ctHyperlink.setRef( _ctHyperlink.setRef(
new CellReference( new CellReference(
row, getFirstColumn() row, getFirstColumn()
).formatAsString() ).formatAsString()

View File

@ -102,8 +102,8 @@ public final class XSSFName implements Name {
*/ */
public final static String BUILTIN_SHEET_TITLE = "_xlnm.Sheet_Title"; public final static String BUILTIN_SHEET_TITLE = "_xlnm.Sheet_Title";
private XSSFWorkbook workbook; private XSSFWorkbook _workbook;
private CTDefinedName ctName; private CTDefinedName _ctName;
/** /**
* Creates an XSSFName object - called internally by XSSFWorkbook. * Creates an XSSFName object - called internally by XSSFWorkbook.
@ -113,15 +113,15 @@ public final class XSSFName implements Name {
* @see org.apache.poi.xssf.usermodel.XSSFWorkbook#createName() * @see org.apache.poi.xssf.usermodel.XSSFWorkbook#createName()
*/ */
protected XSSFName(CTDefinedName name, XSSFWorkbook workbook) { protected XSSFName(CTDefinedName name, XSSFWorkbook workbook) {
this.workbook = workbook; _workbook = workbook;
this.ctName = name; _ctName = name;
} }
/** /**
* Returns the underlying named range object * Returns the underlying named range object
*/ */
protected CTDefinedName getCTName() { protected CTDefinedName getCTName() {
return ctName; return _ctName;
} }
/** /**
@ -130,7 +130,7 @@ public final class XSSFName implements Name {
* @return text name of this defined name * @return text name of this defined name
*/ */
public String getNameName() { public String getNameName() {
return ctName.getName(); return _ctName.getName();
} }
/** /**
@ -169,8 +169,8 @@ public final class XSSFName implements Name {
int sheetIndex = getSheetIndex(); int sheetIndex = getSheetIndex();
//Check to ensure no other names have the same case-insensitive name //Check to ensure no other names have the same case-insensitive name
for (int i = 0; i < workbook.getNumberOfNames(); i++) { for (int i = 0; i < _workbook.getNumberOfNames(); i++) {
XSSFName nm = workbook.getNameAt(i); XSSFName nm = _workbook.getNameAt(i);
if (nm != this) { if (nm != this) {
if(name.equalsIgnoreCase(nm.getNameName()) && sheetIndex == nm.getSheetIndex()){ if(name.equalsIgnoreCase(nm.getNameName()) && sheetIndex == nm.getSheetIndex()){
String msg = "The "+(sheetIndex == -1 ? "workbook" : "sheet")+" already contains this name: " + name; String msg = "The "+(sheetIndex == -1 ? "workbook" : "sheet")+" already contains this name: " + name;
@ -178,11 +178,11 @@ public final class XSSFName implements Name {
} }
} }
} }
ctName.setName(name); _ctName.setName(name);
} }
public String getRefersToFormula() { public String getRefersToFormula() {
String result = ctName.getStringValue(); String result = _ctName.getStringValue();
if (result == null || result.length() < 1) { if (result == null || result.length() < 1) {
return null; return null;
} }
@ -190,11 +190,11 @@ public final class XSSFName implements Name {
} }
public void setRefersToFormula(String formulaText) { public void setRefersToFormula(String formulaText) {
XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(workbook); XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(_workbook);
//validate through the FormulaParser //validate through the FormulaParser
FormulaParser.parse(formulaText, fpb, FormulaType.NAMEDRANGE, getSheetIndex()); FormulaParser.parse(formulaText, fpb, FormulaType.NAMEDRANGE, getSheetIndex());
ctName.setStringValue(formulaText); _ctName.setStringValue(formulaText);
} }
public boolean isDeleted(){ public boolean isDeleted(){
@ -202,7 +202,7 @@ public final class XSSFName implements Name {
if (formulaText == null) { if (formulaText == null) {
return false; return false;
} }
XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(workbook); XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(_workbook);
Ptg[] ptgs = FormulaParser.parse(formulaText, fpb, FormulaType.NAMEDRANGE, getSheetIndex()); Ptg[] ptgs = FormulaParser.parse(formulaText, fpb, FormulaType.NAMEDRANGE, getSheetIndex());
return Ptg.doesFormulaReferToDeletedCell(ptgs); return Ptg.doesFormulaReferToDeletedCell(ptgs);
} }
@ -213,16 +213,16 @@ public final class XSSFName implements Name {
* @param index the sheet index this name applies to, -1 unsets this property making the name workbook-global * @param index the sheet index this name applies to, -1 unsets this property making the name workbook-global
*/ */
public void setSheetIndex(int index) { public void setSheetIndex(int index) {
int lastSheetIx = workbook.getNumberOfSheets() - 1; int lastSheetIx = _workbook.getNumberOfSheets() - 1;
if (index < -1 || index > lastSheetIx) { if (index < -1 || index > lastSheetIx) {
throw new IllegalArgumentException("Sheet index (" + index +") is out of range" + throw new IllegalArgumentException("Sheet index (" + index +") is out of range" +
(lastSheetIx == -1 ? "" : (" (0.." + lastSheetIx + ")"))); (lastSheetIx == -1 ? "" : (" (0.." + lastSheetIx + ")")));
} }
if(index == -1) { if(index == -1) {
if(ctName.isSetLocalSheetId()) ctName.unsetLocalSheetId(); if(_ctName.isSetLocalSheetId()) _ctName.unsetLocalSheetId();
} else { } else {
ctName.setLocalSheetId(index); _ctName.setLocalSheetId(index);
} }
} }
@ -232,7 +232,7 @@ public final class XSSFName implements Name {
* @return the sheet index this name applies to, -1 if this name applies to the entire workbook * @return the sheet index this name applies to, -1 if this name applies to the entire workbook
*/ */
public int getSheetIndex() { public int getSheetIndex() {
return ctName.isSetLocalSheetId() ? (int) ctName.getLocalSheetId() : -1; return _ctName.isSetLocalSheetId() ? (int) _ctName.getLocalSheetId() : -1;
} }
/** /**
@ -242,7 +242,7 @@ public final class XSSFName implements Name {
* @param value <code>true</code> indicates the name refers to a function. * @param value <code>true</code> indicates the name refers to a function.
*/ */
public void setFunction(boolean value) { public void setFunction(boolean value) {
ctName.setFunction(value); _ctName.setFunction(value);
} }
/** /**
@ -252,7 +252,7 @@ public final class XSSFName implements Name {
* @return <code>true</code> indicates the name refers to a function. * @return <code>true</code> indicates the name refers to a function.
*/ */
public boolean getFunction() { public boolean getFunction() {
return ctName.getFunction(); return _ctName.getFunction();
} }
/** /**
@ -263,7 +263,7 @@ public final class XSSFName implements Name {
* @param functionGroupId the function group index that defines the general category for the function * @param functionGroupId the function group index that defines the general category for the function
*/ */
public void setFunctionGroupId(int functionGroupId) { public void setFunctionGroupId(int functionGroupId) {
ctName.setFunctionGroupId(functionGroupId); _ctName.setFunctionGroupId(functionGroupId);
} }
/** /**
@ -274,7 +274,7 @@ public final class XSSFName implements Name {
* @return the function group index that defines the general category for the function * @return the function group index that defines the general category for the function
*/ */
public int getFunctionGroupId() { public int getFunctionGroupId() {
return (int) ctName.getFunctionGroupId(); return (int) _ctName.getFunctionGroupId();
} }
/** /**
@ -284,15 +284,14 @@ public final class XSSFName implements Name {
* Empty string if the referenced sheet name weas not found. * Empty string if the referenced sheet name weas not found.
*/ */
public String getSheetName() { public String getSheetName() {
if (ctName.isSetLocalSheetId()) { if (_ctName.isSetLocalSheetId()) {
// Given as explicit sheet id // Given as explicit sheet id
int sheetId = (int)ctName.getLocalSheetId(); int sheetId = (int)_ctName.getLocalSheetId();
return workbook.getSheetName(sheetId); return _workbook.getSheetName(sheetId);
} else {
String ref = getRefersToFormula();
AreaReference areaRef = new AreaReference(ref);
return areaRef.getFirstCell().getSheetName();
} }
String ref = getRefersToFormula();
AreaReference areaRef = new AreaReference(ref);
return areaRef.getFirstCell().getSheetName();
} }
/** /**
@ -310,7 +309,7 @@ public final class XSSFName implements Name {
* @return the user comment for this named range * @return the user comment for this named range
*/ */
public String getComment() { public String getComment() {
return ctName.getComment(); return _ctName.getComment();
} }
/** /**
@ -319,12 +318,12 @@ public final class XSSFName implements Name {
* @param comment the user comment for this named range * @param comment the user comment for this named range
*/ */
public void setComment(String comment) { public void setComment(String comment) {
ctName.setComment(comment); _ctName.setComment(comment);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return ctName.toString().hashCode(); return _ctName.toString().hashCode();
} }
/** /**
@ -343,7 +342,7 @@ public final class XSSFName implements Name {
if (!(o instanceof XSSFName)) return false; if (!(o instanceof XSSFName)) return false;
XSSFName cf = (XSSFName) o; XSSFName cf = (XSSFName) o;
return ctName.toString().equals(cf.getCTName().toString()); return _ctName.toString().equals(cf.getCTName().toString());
} }
private static void validateName(String name){ private static void validateName(String name){

View File

@ -42,7 +42,7 @@ import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.openxml4j.opc.PackagingURIHelper;
/** /**
* *
*/ */
public final class XSSFRelation extends POIXMLRelation { public final class XSSFRelation extends POIXMLRelation {
@ -114,28 +114,28 @@ public final class XSSFRelation extends POIXMLRelation {
"/xl/drawings/vmlDrawing#.vml", "/xl/drawings/vmlDrawing#.vml",
null null
); );
public static final XSSFRelation CUSTOM_XML_MAPPINGS = new XSSFRelation( public static final XSSFRelation CUSTOM_XML_MAPPINGS = new XSSFRelation(
"application/xml", "application/xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/xmlMaps", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/xmlMaps",
"/xl/xmlMaps.xml", "/xl/xmlMaps.xml",
MapInfo.class MapInfo.class
); );
public static final XSSFRelation SINGLE_XML_CELLS = new XSSFRelation( public static final XSSFRelation SINGLE_XML_CELLS = new XSSFRelation(
"application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableSingleCells", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableSingleCells",
"/tables/tableSingleCells#.xml", "/tables/tableSingleCells#.xml",
SingleXmlCells.class SingleXmlCells.class
); );
public static final XSSFRelation TABLE = new XSSFRelation( public static final XSSFRelation TABLE = new XSSFRelation(
"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/table", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/table",
"/tables/table#.xml", "/tables/table#.xml",
Table.class Table.class
); );
public static final XSSFRelation IMAGES = new XSSFRelation( public static final XSSFRelation IMAGES = new XSSFRelation(
null, null,
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
@ -234,7 +234,7 @@ public final class XSSFRelation extends POIXMLRelation {
"/xl/calcChain.xml", "/xl/calcChain.xml",
CalculationChain.class CalculationChain.class
); );
private XSSFRelation(String type, String rel, String defaultName, Class<? extends POIXMLDocumentPart> cls) { private XSSFRelation(String type, String rel, String defaultName, Class<? extends POIXMLDocumentPart> cls) {
super(type, rel, defaultName, cls); super(type, rel, defaultName, cls);
@ -256,10 +256,9 @@ public final class XSSFRelation extends POIXMLRelation {
PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI()); PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI());
PackagePart part = corePart.getPackage().getPart(relName); PackagePart part = corePart.getPackage().getPart(relName);
return part.getInputStream(); return part.getInputStream();
} else {
log.log(POILogger.WARN, "No part " + _defaultName + " found");
return null;
} }
log.log(POILogger.WARN, "No part " + _defaultName + " found");
return null;
} }

View File

@ -324,14 +324,14 @@ public class XSSFRichTextString implements RichTextString {
* Returns the plain string representation. * Returns the plain string representation.
*/ */
public String getString() { public String getString() {
if(st.sizeOfRArray() == 0) return st.getT(); if(st.sizeOfRArray() == 0) {
else { return st.getT();
StringBuffer buf = new StringBuffer();
for(CTRElt r : st.getRArray()){
buf.append(r.getT());
}
return buf.toString();
} }
StringBuffer buf = new StringBuffer();
for(CTRElt r : st.getRArray()){
buf.append(r.getT());
}
return buf.toString();
} }
/** /**

View File

@ -38,18 +38,18 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
/** /**
* the xml bean containing all cell definitions for this row * the xml bean containing all cell definitions for this row
*/ */
private final CTRow row; private final CTRow _row;
/** /**
* Cells of this row keyed by their column indexes. * Cells of this row keyed by their column indexes.
* The TreeMap ensures that the cells are ordered by columnIndex in the ascending order. * The TreeMap ensures that the cells are ordered by columnIndex in the ascending order.
*/ */
private final TreeMap<Integer, Cell> cells; private final TreeMap<Integer, Cell> _cells;
/** /**
* the parent sheet * the parent sheet
*/ */
private final XSSFSheet sheet; private final XSSFSheet _sheet;
/** /**
* Construct a XSSFRow. * Construct a XSSFRow.
@ -58,12 +58,12 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @param sheet the parent sheet. * @param sheet the parent sheet.
*/ */
protected XSSFRow(CTRow row, XSSFSheet sheet) { protected XSSFRow(CTRow row, XSSFSheet sheet) {
this.row = row; _row = row;
this.sheet = sheet; _sheet = sheet;
this.cells = new TreeMap<Integer, Cell>(); _cells = new TreeMap<Integer, Cell>();
for (CTCell c : row.getCArray()) { for (CTCell c : row.getCArray()) {
XSSFCell cell = new XSSFCell(this, c); XSSFCell cell = new XSSFCell(this, c);
cells.put(cell.getColumnIndex(), cell); _cells.put(cell.getColumnIndex(), cell);
sheet.onReadCell(cell); sheet.onReadCell(cell);
} }
} }
@ -74,7 +74,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @return the XSSFSheet that owns this row * @return the XSSFSheet that owns this row
*/ */
public XSSFSheet getSheet() { public XSSFSheet getSheet() {
return this.sheet; return this._sheet;
} }
/** /**
@ -89,7 +89,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @return an iterator over cells in this row. * @return an iterator over cells in this row.
*/ */
public Iterator<Cell> cellIterator() { public Iterator<Cell> cellIterator() {
return cells.values().iterator(); return _cells.values().iterator();
} }
/** /**
@ -164,7 +164,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
if (type != Cell.CELL_TYPE_BLANK) { if (type != Cell.CELL_TYPE_BLANK) {
xcell.setCellType(type); xcell.setCellType(type);
} }
cells.put(columnIndex, xcell); _cells.put(columnIndex, xcell);
return xcell; return xcell;
} }
@ -175,7 +175,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @return the cell at the given (0 based) index * @return the cell at the given (0 based) index
*/ */
public XSSFCell getCell(int cellnum) { public XSSFCell getCell(int cellnum) {
return getCell(cellnum, sheet.getWorkbook().getMissingCellPolicy()); return getCell(cellnum, _sheet.getWorkbook().getMissingCellPolicy());
} }
/** /**
@ -190,7 +190,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
public XSSFCell getCell(int cellnum, MissingCellPolicy policy) { public XSSFCell getCell(int cellnum, MissingCellPolicy policy) {
if(cellnum < 0) throw new IllegalArgumentException("Cell index must be >= 0"); if(cellnum < 0) throw new IllegalArgumentException("Cell index must be >= 0");
XSSFCell cell = (XSSFCell)cells.get(cellnum); XSSFCell cell = (XSSFCell)_cells.get(cellnum);
if(policy == RETURN_NULL_AND_BLANK) { if(policy == RETURN_NULL_AND_BLANK) {
return cell; return cell;
} }
@ -217,7 +217,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* or -1 if the row does not contain any cells. * or -1 if the row does not contain any cells.
*/ */
public short getFirstCellNum() { public short getFirstCellNum() {
return (short)(cells.size() == 0 ? -1 : cells.firstKey()); return (short)(_cells.size() == 0 ? -1 : _cells.firstKey());
} }
/** /**
@ -240,7 +240,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* or -1 if the row does not contain any cells. * or -1 if the row does not contain any cells.
*/ */
public short getLastCellNum() { public short getLastCellNum() {
return (short)(cells.size() == 0 ? -1 : (cells.lastKey() + 1)); return (short)(_cells.size() == 0 ? -1 : (_cells.lastKey() + 1));
} }
/** /**
@ -261,11 +261,10 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @see org.apache.poi.xssf.usermodel.XSSFSheet#getDefaultRowHeightInPoints() * @see org.apache.poi.xssf.usermodel.XSSFSheet#getDefaultRowHeightInPoints()
*/ */
public float getHeightInPoints() { public float getHeightInPoints() {
if (this.row.isSetHt()) { if (this._row.isSetHt()) {
return (float) this.row.getHt(); return (float) this._row.getHt();
} else {
return sheet.getDefaultRowHeightInPoints();
} }
return _sheet.getDefaultRowHeightInPoints();
} }
/** /**
@ -275,11 +274,11 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
*/ */
public void setHeight(short height) { public void setHeight(short height) {
if (height == -1) { if (height == -1) {
if (row.isSetHt()) row.unsetHt(); if (_row.isSetHt()) _row.unsetHt();
if (row.isSetCustomHeight()) row.unsetCustomHeight(); if (_row.isSetCustomHeight()) _row.unsetCustomHeight();
} else { } else {
row.setHt((double) height / 20); _row.setHt((double) height / 20);
row.setCustomHeight(true); _row.setCustomHeight(true);
} }
} }
@ -300,7 +299,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @return int representing the number of defined cells in the row. * @return int representing the number of defined cells in the row.
*/ */
public int getPhysicalNumberOfCells() { public int getPhysicalNumberOfCells() {
return cells.size(); return _cells.size();
} }
/** /**
@ -309,7 +308,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @return the row number (0 based) * @return the row number (0 based)
*/ */
public int getRowNum() { public int getRowNum() {
return (int) (row.getR() - 1); return (int) (_row.getR() - 1);
} }
/** /**
@ -321,10 +320,10 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
public void setRowNum(int rowIndex) { public void setRowNum(int rowIndex) {
int maxrow = SpreadsheetVersion.EXCEL2007.getLastRowIndex(); int maxrow = SpreadsheetVersion.EXCEL2007.getLastRowIndex();
if (rowIndex < 0 || rowIndex > maxrow) { if (rowIndex < 0 || rowIndex > maxrow) {
throw new IllegalArgumentException("Invalid row number (" + rowIndex throw new IllegalArgumentException("Invalid row number (" + rowIndex
+ ") outside allowable range (0.." + maxrow + ")"); + ") outside allowable range (0.." + maxrow + ")");
} }
row.setR(rowIndex + 1); _row.setR(rowIndex + 1);
} }
/** /**
@ -333,7 +332,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @return - height is zero or not. * @return - height is zero or not.
*/ */
public boolean getZeroHeight() { public boolean getZeroHeight() {
return this.row.getHidden(); return this._row.getHidden();
} }
/** /**
@ -342,7 +341,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @param height height is zero or not. * @param height height is zero or not.
*/ */
public void setZeroHeight(boolean height) { public void setZeroHeight(boolean height) {
this.row.setHidden(height); this._row.setHidden(height);
} }
@ -352,7 +351,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @param cell the cell to remove * @param cell the cell to remove
*/ */
public void removeCell(Cell cell) { public void removeCell(Cell cell) {
cells.remove(cell.getColumnIndex()); _cells.remove(cell.getColumnIndex());
} }
/** /**
@ -361,7 +360,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @return the underlying CTRow xml bean * @return the underlying CTRow xml bean
*/ */
public CTRow getCTRow(){ public CTRow getCTRow(){
return row; return _row;
} }
/** /**
@ -372,14 +371,14 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
* @see org.apache.poi.xssf.usermodel.XSSFSheet#commit() * @see org.apache.poi.xssf.usermodel.XSSFSheet#commit()
*/ */
protected void onDocumentWrite(){ protected void onDocumentWrite(){
ArrayList<CTCell> cArray = new ArrayList<CTCell>(cells.size()); ArrayList<CTCell> cArray = new ArrayList<CTCell>(_cells.size());
//create array of CTCell objects. //create array of CTCell objects.
//TreeMap's value iterator ensures that the cells are ordered by columnIndex in the ascending order //TreeMap's value iterator ensures that the cells are ordered by columnIndex in the ascending order
for (Cell cell : cells.values()) { for (Cell cell : _cells.values()) {
XSSFCell c = (XSSFCell)cell; XSSFCell c = (XSSFCell)cell;
cArray.add(c.getCTCell()); cArray.add(c.getCTCell());
} }
row.setCArray(cArray.toArray(new CTCell[cArray.size()])); _row.setCArray(cArray.toArray(new CTCell[cArray.size()]));
} }
/** /**
@ -387,7 +386,7 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
*/ */
@Override @Override
public String toString(){ public String toString(){
return row.toString(); return _row.toString();
} }
/** /**
@ -397,8 +396,8 @@ public class XSSFRow implements Row, Comparable<XSSFRow> {
*/ */
protected void shift(int n) { protected void shift(int n) {
int rownum = getRowNum() + n; int rownum = getRowNum() + n;
CalculationChain calcChain = sheet.getWorkbook().getCalculationChain(); CalculationChain calcChain = _sheet.getWorkbook().getCalculationChain();
int sheetId = (int)sheet.sheet.getSheetId(); int sheetId = (int)_sheet.sheet.getSheetId();
for(Cell c : this){ for(Cell c : this){
XSSFCell cell = (XSSFCell)c; XSSFCell cell = (XSSFCell)c;

View File

@ -434,8 +434,10 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
} }
public XSSFComment getCellComment(int row, int column) { public XSSFComment getCellComment(int row, int column) {
if (sheetComments == null) return null; if (sheetComments == null) {
else return sheetComments.findCellComment(row, column); return null;
}
return sheetComments.findCellComment(row, column);
} }
public XSSFHyperlink getHyperlink(int row, int column) { public XSSFHyperlink getHyperlink(int row, int column) {
@ -1915,9 +1917,8 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
} }
if (endLevel > startLevel) { if (endLevel > startLevel) {
return endHidden; return endHidden;
} else {
return startHidden;
} }
return startHidden;
} }
/** /**
@ -1925,10 +1926,10 @@ public class XSSFSheet extends POIXMLDocumentPart implements Sheet {
*/ */
private boolean isRowGroupCollapsed(int row) { private boolean isRowGroupCollapsed(int row) {
int collapseRow = findEndOfRowOutlineGroup(row) + 1; int collapseRow = findEndOfRowOutlineGroup(row) + 1;
if (getRow(collapseRow) == null) if (getRow(collapseRow) == null) {
return false; return false;
else }
return getRow(collapseRow).getCTRow().getCollapsed(); return getRow(collapseRow).getCTRow().getCollapsed();
} }
/** /**

View File

@ -89,7 +89,7 @@ public class XWPFParagraph {
if (o instanceof CTFtnEdnRef) { if (o instanceof CTFtnEdnRef) {
CTFtnEdnRef ftn = (CTFtnEdnRef) o; CTFtnEdnRef ftn = (CTFtnEdnRef) o;
footnoteText.append("[").append(ftn.getId()).append(": "); footnoteText.append("[").append(ftn.getId()).append(": ");
XWPFFootnote footnote = XWPFFootnote footnote =
ftn.getDomNode().getLocalName().equals("footnoteReference") ? ftn.getDomNode().getLocalName().equals("footnoteReference") ?
document.getFootnoteByID(ftn.getId().intValue()) : document.getFootnoteByID(ftn.getId().intValue()) :
document.getEndnoteByID(ftn.getId().intValue()); document.getEndnoteByID(ftn.getId().intValue());
@ -582,10 +582,10 @@ public class XWPFParagraph {
CTOnOff ct_pageBreak = ppr.isSetPageBreakBefore() ? ppr CTOnOff ct_pageBreak = ppr.isSetPageBreakBefore() ? ppr
.getPageBreakBefore() : null; .getPageBreakBefore() : null;
if (ct_pageBreak != null if (ct_pageBreak != null
&& ct_pageBreak.getVal().intValue() == STOnOff.INT_TRUE) && ct_pageBreak.getVal().intValue() == STOnOff.INT_TRUE) {
return true; return true;
else }
return false; return false;
} }
/** /**
@ -934,8 +934,8 @@ public class XWPFParagraph {
return (wordWrap.getVal() == STOnOff.ON return (wordWrap.getVal() == STOnOff.ON
|| wordWrap.getVal() == STOnOff.TRUE || wordWrap.getVal() == STOnOff.X_1) ? true || wordWrap.getVal() == STOnOff.TRUE || wordWrap.getVal() == STOnOff.X_1) ? true
: false; : false;
} else }
return false; return false;
} }
/** /**

View File

@ -155,10 +155,10 @@ public class XWPFTable {
* @return the row at the position specified or null if no rows is defined or if the position is greather than the max size of rows array * @return the row at the position specified or null if no rows is defined or if the position is greather than the max size of rows array
*/ */
public XWPFTableRow getRow(int pos) { public XWPFTableRow getRow(int pos) {
if (pos >= 0 && pos < ctTbl.sizeOfTrArray()) if (pos >= 0 && pos < ctTbl.sizeOfTrArray()) {
return new XWPFTableRow(ctTbl.getTrArray(pos)); return new XWPFTableRow(ctTbl.getTrArray(pos));
else }
return null; return null;
} }

View File

@ -44,10 +44,10 @@ public class XWPFTableRow {
} }
public XWPFTableCell getCell(int pos) { public XWPFTableCell getCell(int pos) {
if (pos >= 0 && pos < ctRow.sizeOfTcArray()) if (pos >= 0 && pos < ctRow.sizeOfTcArray()) {
return new XWPFTableCell(ctRow.getTcArray(pos)); return new XWPFTableCell(ctRow.getTcArray(pos));
else }
return null; return null;
} }
/** /**

View File

@ -52,14 +52,6 @@ public final class HeaderFooter
} }
public boolean isEmpty() public boolean isEmpty()
{ {
if(_start - _end == 0) return _start - _end == 0;
{
return true;
}
else
{
return false;
}
} }
} }

View File

@ -1279,13 +1279,6 @@ public final class StyleSheet {
} }
public static boolean getFlag(int x) public static boolean getFlag(int x)
{ {
if(x != 0) return x != 0;
{
return true;
}
else
{
return false;
}
} }
} }

View File

@ -314,34 +314,29 @@ public final class WordDocument {
{ {
throw new IOException("corrupted Word file"); throw new IOException("corrupted Word file");
} }
else //parse out the text pieces
int pieceTableSize = LittleEndian.getInt(tableStream, ++pos);
pos += 4;
int pieces = (pieceTableSize - 4) / 12;
for (int x = 0; x < pieces; x++)
{ {
//parse out the text pieces int filePos = LittleEndian.getInt(tableStream, pos + ((pieces + 1) * 4) + (x * 8) + 2);
int pieceTableSize = LittleEndian.getInt(tableStream, ++pos); boolean unicode = false;
pos += 4; if ((filePos & 0x40000000) == 0)
int pieces = (pieceTableSize - 4) / 12;
for (int x = 0; x < pieces; x++)
{ {
int filePos = LittleEndian.getInt(tableStream, pos + ((pieces + 1) * 4) + (x * 8) + 2); unicode = true;
boolean unicode = false;
if ((filePos & 0x40000000) == 0)
{
unicode = true;
}
else
{
unicode = false;
filePos &= ~(0x40000000);//gives me FC in doc stream
filePos /= 2;
}
int totLength = LittleEndian.getInt(tableStream, pos + (x + 1) * 4) -
LittleEndian.getInt(tableStream, pos + (x * 4));
TextPiece piece = new TextPiece(filePos, totLength, unicode);
_text.add(piece);
} }
else
{
unicode = false;
filePos &= ~(0x40000000);//gives me FC in doc stream
filePos /= 2;
}
int totLength = LittleEndian.getInt(tableStream, pos + (x + 1) * 4) -
LittleEndian.getInt(tableStream, pos + (x * 4));
TextPiece piece = new TextPiece(filePos, totLength, unicode);
_text.add(piece);
} }
} }
@ -355,8 +350,7 @@ public final class WordDocument {
* @param size of the paragraph bin table. * @param size of the paragraph bin table.
*/ */
private void findFormatting(byte[] tableStream, int charOffset, private void findFormatting(byte[] tableStream, int charOffset,
int charPlcSize, int parOffset, int parPlcSize) throws IOException int charPlcSize, int parOffset, int parPlcSize) {
{
openDoc(); openDoc();
createStyleSheet(tableStream); createStyleSheet(tableStream);
createListTables(tableStream); createListTables(tableStream);
@ -1287,7 +1281,7 @@ public final class WordDocument {
private ArrayList findProperties(int start, int end, BTreeSet.BTreeNode root) private ArrayList findProperties(int start, int end, BTreeSet.BTreeNode root)
{ {
ArrayList results = new ArrayList(); ArrayList results = new ArrayList();
BTreeSet.Entry[] entries = root.entries; BTreeSet.Entry[] entries = root._entries;
for(int x = 0; x < entries.length; x++) for(int x = 0; x < entries.length; x++)
{ {
@ -1366,7 +1360,7 @@ public final class WordDocument {
private ArrayList findPAPProperties(int start, int end, BTreeSet.BTreeNode root) private ArrayList findPAPProperties(int start, int end, BTreeSet.BTreeNode root)
{ {
ArrayList results = new ArrayList(); ArrayList results = new ArrayList();
BTreeSet.Entry[] entries = root.entries; BTreeSet.Entry[] entries = root._entries;
for(int x = 0; x < entries.length; x++) for(int x = 0; x < entries.length; x++)
{ {

View File

@ -42,8 +42,8 @@ public final class BTreeSet extends AbstractSet implements Set {
*/ */
public BTreeNode root; public BTreeNode root;
private Comparator comparator = null; private Comparator comparator = null;
private int order; int order;
private int size = 0; int size = 0;
/* /*
* Constructors * Constructors
@ -99,14 +99,14 @@ public final class BTreeSet extends AbstractSet implements Set {
} }
public java.util.Iterator iterator() { public java.util.Iterator iterator() {
return new Iterator(); return new BTIterator();
} }
/* /*
* Private methods * Private methods
*/ */
private int compare(Object x, Object y) { int compare(Object x, Object y) {
return (comparator == null ? ((Comparable)x).compareTo(y) : comparator.compare(x, y)); return (comparator == null ? ((Comparable)x).compareTo(y) : comparator.compare(x, y));
} }
@ -125,14 +125,14 @@ public final class BTreeSet extends AbstractSet implements Set {
* chance of receiving a NullPointerException. The Iterator.delete method is supported. * chance of receiving a NullPointerException. The Iterator.delete method is supported.
*/ */
private class Iterator implements java.util.Iterator { private final class BTIterator implements java.util.Iterator {
private int index = 0; private int index = 0;
private Stack parentIndex = new Stack(); // Contains all parentIndicies for currentNode Stack parentIndex = new Stack(); // Contains all parentIndicies for currentNode
private Object lastReturned = null; private Object lastReturned = null;
private Object next; private Object next;
private BTreeNode currentNode; BTreeNode currentNode;
Iterator() { BTIterator() {
currentNode = firstNode(); currentNode = firstNode();
next = nextElement(); next = nextElement();
} }
@ -159,8 +159,8 @@ public final class BTreeSet extends AbstractSet implements Set {
private BTreeNode firstNode() { private BTreeNode firstNode() {
BTreeNode temp = BTreeSet.this.root; BTreeNode temp = BTreeSet.this.root;
while (temp.entries[0].child != null) { while (temp._entries[0].child != null) {
temp = temp.entries[0].child; temp = temp._entries[0].child;
parentIndex.push(new Integer(0)); parentIndex.push(new Integer(0));
} }
@ -169,40 +169,39 @@ public final class BTreeSet extends AbstractSet implements Set {
private Object nextElement() { private Object nextElement() {
if (currentNode.isLeaf()) { if (currentNode.isLeaf()) {
if (index < currentNode.nrElements) return currentNode.entries[index++].element; if (index < currentNode._nrElements) return currentNode._entries[index++].element;
else if (!parentIndex.empty()) { //All elements have been returned, return successor of lastReturned if it exists else if (!parentIndex.empty()) { //All elements have been returned, return successor of lastReturned if it exists
currentNode = currentNode.parent; currentNode = currentNode._parent;
index = ((Integer)parentIndex.pop()).intValue(); index = ((Integer)parentIndex.pop()).intValue();
while (index == currentNode.nrElements) { while (index == currentNode._nrElements) {
if (parentIndex.empty()) break; if (parentIndex.empty()) break;
currentNode = currentNode.parent; currentNode = currentNode._parent;
index = ((Integer)parentIndex.pop()).intValue(); index = ((Integer)parentIndex.pop()).intValue();
} }
if (index == currentNode.nrElements) return null; //Reached root and he has no more children if (index == currentNode._nrElements) return null; //Reached root and he has no more children
return currentNode.entries[index++].element; return currentNode._entries[index++].element;
} }
else { //Your a leaf and the root else { //Your a leaf and the root
if (index == currentNode.nrElements) return null; if (index == currentNode._nrElements) return null;
return currentNode.entries[index++].element; return currentNode._entries[index++].element;
} }
} }
else { //Your not a leaf so simply find and return the successor of lastReturned // else - You're not a leaf so simply find and return the successor of lastReturned
currentNode = currentNode.entries[index].child; currentNode = currentNode._entries[index].child;
parentIndex.push(new Integer(index)); parentIndex.push(new Integer(index));
while (currentNode.entries[0].child != null) { while (currentNode._entries[0].child != null) {
currentNode = currentNode.entries[0].child; currentNode = currentNode._entries[0].child;
parentIndex.push(new Integer(0)); parentIndex.push(new Integer(0));
}
index = 1;
return currentNode.entries[0].element;
} }
index = 1;
return currentNode._entries[0].element;
} }
} }
@ -216,49 +215,51 @@ public final class BTreeSet extends AbstractSet implements Set {
public class BTreeNode { public class BTreeNode {
public Entry[] entries; public Entry[] _entries;
public BTreeNode parent; public BTreeNode _parent;
private int nrElements = 0; int _nrElements = 0;
private final int MIN = (BTreeSet.this.order - 1) / 2; private final int MIN = (BTreeSet.this.order - 1) / 2;
BTreeNode(BTreeNode parent) { BTreeNode(BTreeNode parent) {
this.parent = parent; _parent = parent;
entries = new Entry[BTreeSet.this.order]; _entries = new Entry[BTreeSet.this.order];
entries[0] = new Entry(); _entries[0] = new Entry();
} }
boolean insert(Object x, int parentIndex) { boolean insert(Object x, int parentIndex) {
if (isFull()) { // If full, you must split and promote splitNode before inserting if (isFull()) { // If full, you must split and promote splitNode before inserting
Object splitNode = entries[nrElements / 2].element; Object splitNode = _entries[_nrElements / 2].element;
BTreeNode rightSibling = split(); BTreeNode rightSibling = split();
if (isRoot()) { // Grow a level if (isRoot()) { // Grow a level
splitRoot(splitNode, this, rightSibling); splitRoot(splitNode, this, rightSibling);
// Determine where to insert // Determine where to insert
if (BTreeSet.this.compare(x, BTreeSet.this.root.entries[0].element) < 0) insert(x, 0); if (BTreeSet.this.compare(x, BTreeSet.this.root._entries[0].element) < 0) insert(x, 0);
else rightSibling.insert(x, 1); else rightSibling.insert(x, 1);
} }
else { // Promote splitNode else { // Promote splitNode
parent.insertSplitNode(splitNode, this, rightSibling, parentIndex); _parent.insertSplitNode(splitNode, this, rightSibling, parentIndex);
if (BTreeSet.this.compare(x, parent.entries[parentIndex].element) < 0) return insert(x, parentIndex); if (BTreeSet.this.compare(x, _parent._entries[parentIndex].element) < 0) {
else return rightSibling.insert(x, parentIndex + 1); return insert(x, parentIndex);
}
return rightSibling.insert(x, parentIndex + 1);
} }
} }
else if (isLeaf()) { // If leaf, simply insert the non-duplicate element else if (isLeaf()) { // If leaf, simply insert the non-duplicate element
int insertAt = childToInsertAt(x, true); int insertAt = childToInsertAt(x, true);
if (insertAt == -1) return false; // Determine if the element already exists if (insertAt == -1) {
else { return false; // Determine if the element already exists
insertNewElement(x, insertAt);
BTreeSet.this.size++;
return true;
} }
insertNewElement(x, insertAt);
BTreeSet.this.size++;
return true;
} }
else { // If not full and not leaf recursively find correct node to insert at else { // If not full and not leaf recursively find correct node to insert at
int insertAt = childToInsertAt(x, true); int insertAt = childToInsertAt(x, true);
return (insertAt == -1 ? false : entries[insertAt].child.insert(x, insertAt)); return (insertAt == -1 ? false : _entries[insertAt].child.insert(x, insertAt));
} }
return false; return false;
} }
@ -266,8 +267,8 @@ public final class BTreeSet extends AbstractSet implements Set {
boolean includes(Object x) { boolean includes(Object x) {
int index = childToInsertAt(x, true); int index = childToInsertAt(x, true);
if (index == -1) return true; if (index == -1) return true;
if (entries[index] == null || entries[index].child == null) return false; if (_entries[index] == null || _entries[index].child == null) return false;
return entries[index].child.includes(x); return _entries[index].child.includes(x);
} }
boolean delete(Object x, int parentIndex) { boolean delete(Object x, int parentIndex) {
@ -276,8 +277,8 @@ public final class BTreeSet extends AbstractSet implements Set {
BTreeNode temp = this; BTreeNode temp = this;
if (i != -1) { if (i != -1) {
do { do {
if (temp.entries[i] == null || temp.entries[i].child == null) return false; if (temp._entries[i] == null || temp._entries[i].child == null) return false;
temp = temp.entries[i].child; temp = temp._entries[i].child;
priorParentIndex = parentIndex; priorParentIndex = parentIndex;
parentIndex = i; parentIndex = i;
i = temp.childToInsertAt(x, true); i = temp.childToInsertAt(x, true);
@ -285,54 +286,52 @@ public final class BTreeSet extends AbstractSet implements Set {
} // Now temp contains element to delete and temp's parentIndex is parentIndex } // Now temp contains element to delete and temp's parentIndex is parentIndex
if (temp.isLeaf()) { // If leaf and have more than MIN elements, simply delete if (temp.isLeaf()) { // If leaf and have more than MIN elements, simply delete
if (temp.nrElements > MIN) { if (temp._nrElements > MIN) {
temp.deleteElement(x); temp.deleteElement(x);
BTreeSet.this.size--; BTreeSet.this.size--;
return true; return true;
} }
else { // If leaf and have less than MIN elements, than prepare the BTreeSet for deletion // else If leaf and have less than MIN elements, than prepare the BTreeSet for deletion
temp.prepareForDeletion(parentIndex); temp.prepareForDeletion(parentIndex);
temp.deleteElement(x); temp.deleteElement(x);
BTreeSet.this.size--; BTreeSet.this.size--;
temp.fixAfterDeletion(priorParentIndex); temp.fixAfterDeletion(priorParentIndex);
return true; return true;
}
} }
else { // Only delete at leaf so first switch with successor than delete // else Only delete at leaf so first switch with successor than delete
temp.switchWithSuccessor(x); temp.switchWithSuccessor(x);
parentIndex = temp.childToInsertAt(x, false) + 1; parentIndex = temp.childToInsertAt(x, false) + 1;
return temp.entries[parentIndex].child.delete(x, parentIndex); return temp._entries[parentIndex].child.delete(x, parentIndex);
}
} }
private boolean isFull() { return nrElements == (BTreeSet.this.order - 1); } private boolean isFull() { return _nrElements == (BTreeSet.this.order - 1); }
private boolean isLeaf() { return entries[0].child == null; } boolean isLeaf() { return _entries[0].child == null; }
private boolean isRoot() { return parent == null; } private boolean isRoot() { return _parent == null; }
/* /*
* Splits a BTreeNode into two BTreeNodes, removing the splitNode from the * Splits a BTreeNode into two BTreeNodes, removing the splitNode from the
* calling BTreeNode. * calling BTreeNode.
*/ */
private BTreeNode split() { private BTreeNode split() {
BTreeNode rightSibling = new BTreeNode(parent); BTreeNode rightSibling = new BTreeNode(_parent);
int index = nrElements / 2; int index = _nrElements / 2;
entries[index++].element = null; _entries[index++].element = null;
for (int i = 0, nr = nrElements; index <= nr; i++, index++) { for (int i = 0, nr = _nrElements; index <= nr; i++, index++) {
rightSibling.entries[i] = entries[index]; rightSibling._entries[i] = _entries[index];
if (rightSibling.entries[i] != null && rightSibling.entries[i].child != null) if (rightSibling._entries[i] != null && rightSibling._entries[i].child != null)
rightSibling.entries[i].child.parent = rightSibling; rightSibling._entries[i].child._parent = rightSibling;
entries[index] = null; _entries[index] = null;
nrElements--; _nrElements--;
rightSibling.nrElements++; rightSibling._nrElements++;
} }
rightSibling.nrElements--; // Need to correct for copying the last Entry which has a null element and a child rightSibling._nrElements--; // Need to correct for copying the last Entry which has a null element and a child
return rightSibling; return rightSibling;
} }
@ -342,34 +341,34 @@ public final class BTreeSet extends AbstractSet implements Set {
*/ */
private void splitRoot(Object splitNode, BTreeNode left, BTreeNode right) { private void splitRoot(Object splitNode, BTreeNode left, BTreeNode right) {
BTreeNode newRoot = new BTreeNode(null); BTreeNode newRoot = new BTreeNode(null);
newRoot.entries[0].element = splitNode; newRoot._entries[0].element = splitNode;
newRoot.entries[0].child = left; newRoot._entries[0].child = left;
newRoot.entries[1] = new Entry(); newRoot._entries[1] = new Entry();
newRoot.entries[1].child = right; newRoot._entries[1].child = right;
newRoot.nrElements = 1; newRoot._nrElements = 1;
left.parent = right.parent = newRoot; left._parent = right._parent = newRoot;
BTreeSet.this.root = newRoot; BTreeSet.this.root = newRoot;
} }
private void insertSplitNode(Object splitNode, BTreeNode left, BTreeNode right, int insertAt) { private void insertSplitNode(Object splitNode, BTreeNode left, BTreeNode right, int insertAt) {
for (int i = nrElements; i >= insertAt; i--) entries[i + 1] = entries[i]; for (int i = _nrElements; i >= insertAt; i--) _entries[i + 1] = _entries[i];
entries[insertAt] = new Entry(); _entries[insertAt] = new Entry();
entries[insertAt].element = splitNode; _entries[insertAt].element = splitNode;
entries[insertAt].child = left; _entries[insertAt].child = left;
entries[insertAt + 1].child = right; _entries[insertAt + 1].child = right;
nrElements++; _nrElements++;
} }
private void insertNewElement(Object x, int insertAt) { private void insertNewElement(Object x, int insertAt) {
for (int i = nrElements; i > insertAt; i--) entries[i] = entries[i - 1]; for (int i = _nrElements; i > insertAt; i--) _entries[i] = _entries[i - 1];
entries[insertAt] = new Entry(); _entries[insertAt] = new Entry();
entries[insertAt].element = x; _entries[insertAt].element = x;
nrElements++; _nrElements++;
} }
/* /*
@ -382,13 +381,13 @@ public final class BTreeSet extends AbstractSet implements Set {
* in entries[] is returned. * in entries[] is returned.
*/ */
private int childToInsertAt(Object x, boolean position) { private int childToInsertAt(Object x, boolean position) {
int index = nrElements / 2; int index = _nrElements / 2;
if (entries[index] == null || entries[index].element == null) return index; if (_entries[index] == null || _entries[index].element == null) return index;
int lo = 0, hi = nrElements - 1; int lo = 0, hi = _nrElements - 1;
while (lo <= hi) { while (lo <= hi) {
if (BTreeSet.this.compare(x, entries[index].element) > 0) { if (BTreeSet.this.compare(x, _entries[index].element) > 0) {
lo = index + 1; lo = index + 1;
index = (hi + lo) / 2; index = (hi + lo) / 2;
} }
@ -399,32 +398,32 @@ public final class BTreeSet extends AbstractSet implements Set {
} }
hi++; hi++;
if (entries[hi] == null || entries[hi].element == null) return hi; if (_entries[hi] == null || _entries[hi].element == null) return hi;
return (!position ? hi : BTreeSet.this.compare(x, entries[hi].element) == 0 ? -1 : hi); return (!position ? hi : BTreeSet.this.compare(x, _entries[hi].element) == 0 ? -1 : hi);
} }
private void deleteElement(Object x) { private void deleteElement(Object x) {
int index = childToInsertAt(x, false); int index = childToInsertAt(x, false);
for (; index < (nrElements - 1); index++) entries[index] = entries[index + 1]; for (; index < (_nrElements - 1); index++) _entries[index] = _entries[index + 1];
if (nrElements == 1) entries[index] = new Entry(); // This is root and it is empty if (_nrElements == 1) _entries[index] = new Entry(); // This is root and it is empty
else entries[index] = null; else _entries[index] = null;
nrElements--; _nrElements--;
} }
private void prepareForDeletion(int parentIndex) { private void prepareForDeletion(int parentIndex) {
if (isRoot()) return; // Don't attempt to steal or merge if your the root if (isRoot()) return; // Don't attempt to steal or merge if your the root
// If not root then try to steal left // If not root then try to steal left
else if (parentIndex != 0 && parent.entries[parentIndex - 1].child.nrElements > MIN) { else if (parentIndex != 0 && _parent._entries[parentIndex - 1].child._nrElements > MIN) {
stealLeft(parentIndex); stealLeft(parentIndex);
return; return;
} }
// If not root and can't steal left try to steal right // If not root and can't steal left try to steal right
else if (parentIndex < entries.length && parent.entries[parentIndex + 1] != null && parent.entries[parentIndex + 1].child != null && parent.entries[parentIndex + 1].child.nrElements > MIN) { else if (parentIndex < _entries.length && _parent._entries[parentIndex + 1] != null && _parent._entries[parentIndex + 1].child != null && _parent._entries[parentIndex + 1].child._nrElements > MIN) {
stealRight(parentIndex); stealRight(parentIndex);
return; return;
} }
@ -440,29 +439,29 @@ public final class BTreeSet extends AbstractSet implements Set {
} }
private void fixAfterDeletion(int parentIndex) { private void fixAfterDeletion(int parentIndex) {
if (isRoot() || parent.isRoot()) return; // No fixing needed if (isRoot() || _parent.isRoot()) return; // No fixing needed
if (parent.nrElements < MIN) { // If parent lost it's n/2 element repair it if (_parent._nrElements < MIN) { // If parent lost it's n/2 element repair it
BTreeNode temp = parent; BTreeNode temp = _parent;
temp.prepareForDeletion(parentIndex); temp.prepareForDeletion(parentIndex);
if (temp.parent == null) return; // Root changed if (temp._parent == null) return; // Root changed
if (!temp.parent.isRoot() && temp.parent.nrElements < MIN) { // If need be recurse if (!temp._parent.isRoot() && temp._parent._nrElements < MIN) { // If need be recurse
BTreeNode x = temp.parent.parent; BTreeNode x = temp._parent._parent;
int i = 0; int i = 0;
// Find parent's parentIndex // Find parent's parentIndex
for (; i < entries.length; i++) if (x.entries[i].child == temp.parent) break; for (; i < _entries.length; i++) if (x._entries[i].child == temp._parent) break;
temp.parent.fixAfterDeletion(i); temp._parent.fixAfterDeletion(i);
} }
} }
} }
private void switchWithSuccessor(Object x) { private void switchWithSuccessor(Object x) {
int index = childToInsertAt(x, false); int index = childToInsertAt(x, false);
BTreeNode temp = entries[index + 1].child; BTreeNode temp = _entries[index + 1].child;
while (temp.entries[0] != null && temp.entries[0].child != null) temp = temp.entries[0].child; while (temp._entries[0] != null && temp._entries[0].child != null) temp = temp._entries[0].child;
Object successor = temp.entries[0].element; Object successor = temp._entries[0].element;
temp.entries[0].element = entries[index].element; temp._entries[0].element = _entries[index].element;
entries[index].element = successor; _entries[index].element = successor;
} }
/* /*
@ -470,26 +469,26 @@ public final class BTreeSet extends AbstractSet implements Set {
* has a leftSibling, and the leftSibling has more than the minimum number of elements. * has a leftSibling, and the leftSibling has more than the minimum number of elements.
*/ */
private void stealLeft(int parentIndex) { private void stealLeft(int parentIndex) {
BTreeNode p = parent; BTreeNode p = _parent;
BTreeNode ls = parent.entries[parentIndex - 1].child; BTreeNode ls = _parent._entries[parentIndex - 1].child;
if (isLeaf()) { // When stealing from leaf to leaf don't worry about children if (isLeaf()) { // When stealing from leaf to leaf don't worry about children
int add = childToInsertAt(p.entries[parentIndex - 1].element, true); int add = childToInsertAt(p._entries[parentIndex - 1].element, true);
insertNewElement(p.entries[parentIndex - 1].element, add); insertNewElement(p._entries[parentIndex - 1].element, add);
p.entries[parentIndex - 1].element = ls.entries[ls.nrElements - 1].element; p._entries[parentIndex - 1].element = ls._entries[ls._nrElements - 1].element;
ls.entries[ls.nrElements - 1] = null; ls._entries[ls._nrElements - 1] = null;
ls.nrElements--; ls._nrElements--;
} }
else { // Was called recursively to fix an undermanned parent else { // Was called recursively to fix an undermanned parent
entries[0].element = p.entries[parentIndex - 1].element; _entries[0].element = p._entries[parentIndex - 1].element;
p.entries[parentIndex - 1].element = ls.entries[ls.nrElements - 1].element; p._entries[parentIndex - 1].element = ls._entries[ls._nrElements - 1].element;
entries[0].child = ls.entries[ls.nrElements].child; _entries[0].child = ls._entries[ls._nrElements].child;
entries[0].child.parent = this; _entries[0].child._parent = this;
ls.entries[ls.nrElements] = null; ls._entries[ls._nrElements] = null;
ls.entries[ls.nrElements - 1].element = null; ls._entries[ls._nrElements - 1].element = null;
nrElements++; _nrElements++;
ls.nrElements--; ls._nrElements--;
} }
} }
@ -499,30 +498,30 @@ public final class BTreeSet extends AbstractSet implements Set {
* has more than the minimum number of elements. * has more than the minimum number of elements.
*/ */
private void stealRight(int parentIndex) { private void stealRight(int parentIndex) {
BTreeNode p = parent; BTreeNode p = _parent;
BTreeNode rs = p.entries[parentIndex + 1].child; BTreeNode rs = p._entries[parentIndex + 1].child;
if (isLeaf()) { // When stealing from leaf to leaf don't worry about children if (isLeaf()) { // When stealing from leaf to leaf don't worry about children
entries[nrElements] = new Entry(); _entries[_nrElements] = new Entry();
entries[nrElements].element = p.entries[parentIndex].element; _entries[_nrElements].element = p._entries[parentIndex].element;
p.entries[parentIndex].element = rs.entries[0].element; p._entries[parentIndex].element = rs._entries[0].element;
for (int i = 0; i < rs.nrElements; i++) rs.entries[i] = rs.entries[i + 1]; for (int i = 0; i < rs._nrElements; i++) rs._entries[i] = rs._entries[i + 1];
rs.entries[rs.nrElements - 1] = null; rs._entries[rs._nrElements - 1] = null;
nrElements++; _nrElements++;
rs.nrElements--; rs._nrElements--;
} }
else { // Was called recursively to fix an undermanned parent else { // Was called recursively to fix an undermanned parent
for (int i = 0; i <= nrElements; i++) entries[i] = entries[i + 1]; for (int i = 0; i <= _nrElements; i++) _entries[i] = _entries[i + 1];
entries[nrElements].element = p.entries[parentIndex].element; _entries[_nrElements].element = p._entries[parentIndex].element;
p.entries[parentIndex].element = rs.entries[0].element; p._entries[parentIndex].element = rs._entries[0].element;
entries[nrElements + 1] = new Entry(); _entries[_nrElements + 1] = new Entry();
entries[nrElements + 1].child = rs.entries[0].child; _entries[_nrElements + 1].child = rs._entries[0].child;
entries[nrElements + 1].child.parent = this; _entries[_nrElements + 1].child._parent = this;
for (int i = 0; i <= rs.nrElements; i++) rs.entries[i] = rs.entries[i + 1]; for (int i = 0; i <= rs._nrElements; i++) rs._entries[i] = rs._entries[i + 1];
rs.entries[rs.nrElements] = null; rs._entries[rs._nrElements] = null;
nrElements++; _nrElements++;
rs.nrElements--; rs._nrElements--;
} }
} }
@ -536,77 +535,77 @@ public final class BTreeSet extends AbstractSet implements Set {
* expect the parent to be in such a condition. * expect the parent to be in such a condition.
*/ */
private void mergeLeft(int parentIndex) { private void mergeLeft(int parentIndex) {
BTreeNode p = parent; BTreeNode p = _parent;
BTreeNode ls = p.entries[parentIndex - 1].child; BTreeNode ls = p._entries[parentIndex - 1].child;
if (isLeaf()) { // Don't worry about children if (isLeaf()) { // Don't worry about children
int add = childToInsertAt(p.entries[parentIndex - 1].element, true); int add = childToInsertAt(p._entries[parentIndex - 1].element, true);
insertNewElement(p.entries[parentIndex - 1].element, add); // Could have been a successor switch insertNewElement(p._entries[parentIndex - 1].element, add); // Could have been a successor switch
p.entries[parentIndex - 1].element = null; p._entries[parentIndex - 1].element = null;
for (int i = nrElements - 1, nr = ls.nrElements; i >= 0; i--) for (int i = _nrElements - 1, nr = ls._nrElements; i >= 0; i--)
entries[i + nr] = entries[i]; _entries[i + nr] = _entries[i];
for (int i = ls.nrElements - 1; i >= 0; i--) { for (int i = ls._nrElements - 1; i >= 0; i--) {
entries[i] = ls.entries[i]; _entries[i] = ls._entries[i];
nrElements++; _nrElements++;
} }
if (p.nrElements == MIN && p != BTreeSet.this.root) { if (p._nrElements == MIN && p != BTreeSet.this.root) {
for (int x = parentIndex - 1, y = parentIndex - 2; y >= 0; x--, y--) for (int x = parentIndex - 1, y = parentIndex - 2; y >= 0; x--, y--)
p.entries[x] = p.entries[y]; p._entries[x] = p._entries[y];
p.entries[0] = new Entry(); p._entries[0] = new Entry();
p.entries[0].child = ls; //So p doesn't think it's a leaf this will be deleted in the next recursive call p._entries[0].child = ls; //So p doesn't think it's a leaf this will be deleted in the next recursive call
} }
else { else {
for (int x = parentIndex - 1, y = parentIndex; y <= p.nrElements; x++, y++) for (int x = parentIndex - 1, y = parentIndex; y <= p._nrElements; x++, y++)
p.entries[x] = p.entries[y]; p._entries[x] = p._entries[y];
p.entries[p.nrElements] = null; p._entries[p._nrElements] = null;
} }
p.nrElements--; p._nrElements--;
if (p.isRoot() && p.nrElements == 0) { // It's the root and it's empty if (p.isRoot() && p._nrElements == 0) { // It's the root and it's empty
BTreeSet.this.root = this; BTreeSet.this.root = this;
parent = null; _parent = null;
} }
} }
else { // I'm not a leaf but fixing the tree structure else { // I'm not a leaf but fixing the tree structure
entries[0].element = p.entries[parentIndex - 1].element; _entries[0].element = p._entries[parentIndex - 1].element;
entries[0].child = ls.entries[ls.nrElements].child; _entries[0].child = ls._entries[ls._nrElements].child;
nrElements++; _nrElements++;
for (int x = nrElements, nr = ls.nrElements; x >= 0; x--) for (int x = _nrElements, nr = ls._nrElements; x >= 0; x--)
entries[x + nr] = entries[x]; _entries[x + nr] = _entries[x];
for (int x = ls.nrElements - 1; x >= 0; x--) { for (int x = ls._nrElements - 1; x >= 0; x--) {
entries[x] = ls.entries[x]; _entries[x] = ls._entries[x];
entries[x].child.parent = this; _entries[x].child._parent = this;
nrElements++; _nrElements++;
} }
if (p.nrElements == MIN && p != BTreeSet.this.root) { // Push everything to the right if (p._nrElements == MIN && p != BTreeSet.this.root) { // Push everything to the right
for (int x = parentIndex - 1, y = parentIndex - 2; y >= 0; x++, y++){ for (int x = parentIndex - 1, y = parentIndex - 2; y >= 0; x++, y++){
System.out.println(x + " " + y); System.out.println(x + " " + y);
p.entries[x] = p.entries[y];} p._entries[x] = p._entries[y];}
p.entries[0] = new Entry(); p._entries[0] = new Entry();
} }
else { // Either p.nrElements > MIN or p == BTreeSet.this.root so push everything to the left else { // Either p.nrElements > MIN or p == BTreeSet.this.root so push everything to the left
for (int x = parentIndex - 1, y = parentIndex; y <= p.nrElements; x++, y++) for (int x = parentIndex - 1, y = parentIndex; y <= p._nrElements; x++, y++)
p.entries[x] = p.entries[y]; p._entries[x] = p._entries[y];
p.entries[p.nrElements] = null; p._entries[p._nrElements] = null;
} }
p.nrElements--; p._nrElements--;
if (p.isRoot() && p.nrElements == 0) { // p == BTreeSet.this.root and it's empty if (p.isRoot() && p._nrElements == 0) { // p == BTreeSet.this.root and it's empty
BTreeSet.this.root = this; BTreeSet.this.root = this;
parent = null; _parent = null;
} }
} }
} }
@ -621,69 +620,69 @@ public final class BTreeSet extends AbstractSet implements Set {
* expect the parent to be in such a condition. * expect the parent to be in such a condition.
*/ */
private void mergeRight(int parentIndex) { private void mergeRight(int parentIndex) {
BTreeNode p = parent; BTreeNode p = _parent;
BTreeNode rs = p.entries[parentIndex + 1].child; BTreeNode rs = p._entries[parentIndex + 1].child;
if (isLeaf()) { // Don't worry about children if (isLeaf()) { // Don't worry about children
entries[nrElements] = new Entry(); _entries[_nrElements] = new Entry();
entries[nrElements].element = p.entries[parentIndex].element; _entries[_nrElements].element = p._entries[parentIndex].element;
nrElements++; _nrElements++;
for (int i = 0, nr = nrElements; i < rs.nrElements; i++, nr++) { for (int i = 0, nr = _nrElements; i < rs._nrElements; i++, nr++) {
entries[nr] = rs.entries[i]; _entries[nr] = rs._entries[i];
nrElements++; _nrElements++;
} }
p.entries[parentIndex].element = p.entries[parentIndex + 1].element; p._entries[parentIndex].element = p._entries[parentIndex + 1].element;
if (p.nrElements == MIN && p != BTreeSet.this.root) { if (p._nrElements == MIN && p != BTreeSet.this.root) {
for (int x = parentIndex + 1, y = parentIndex; y >= 0; x--, y--) for (int x = parentIndex + 1, y = parentIndex; y >= 0; x--, y--)
p.entries[x] = p.entries[y]; p._entries[x] = p._entries[y];
p.entries[0] = new Entry(); p._entries[0] = new Entry();
p.entries[0].child = rs; // So it doesn't think it's a leaf, this child will be deleted in the next recursive call p._entries[0].child = rs; // So it doesn't think it's a leaf, this child will be deleted in the next recursive call
} }
else { else {
for (int x = parentIndex + 1, y = parentIndex + 2; y <= p.nrElements; x++, y++) for (int x = parentIndex + 1, y = parentIndex + 2; y <= p._nrElements; x++, y++)
p.entries[x] = p.entries[y]; p._entries[x] = p._entries[y];
p.entries[p.nrElements] = null; p._entries[p._nrElements] = null;
} }
p.nrElements--; p._nrElements--;
if (p.isRoot() && p.nrElements == 0) { // It's the root and it's empty if (p.isRoot() && p._nrElements == 0) { // It's the root and it's empty
BTreeSet.this.root = this; BTreeSet.this.root = this;
parent = null; _parent = null;
} }
} }
else { // It's not a leaf else { // It's not a leaf
entries[nrElements].element = p.entries[parentIndex].element; _entries[_nrElements].element = p._entries[parentIndex].element;
nrElements++; _nrElements++;
for (int x = nrElements + 1, y = 0; y <= rs.nrElements; x++, y++) { for (int x = _nrElements + 1, y = 0; y <= rs._nrElements; x++, y++) {
entries[x] = rs.entries[y]; _entries[x] = rs._entries[y];
rs.entries[y].child.parent = this; rs._entries[y].child._parent = this;
nrElements++; _nrElements++;
} }
nrElements--; _nrElements--;
p.entries[++parentIndex].child = this; p._entries[++parentIndex].child = this;
if (p.nrElements == MIN && p != BTreeSet.this.root) { if (p._nrElements == MIN && p != BTreeSet.this.root) {
for (int x = parentIndex - 1, y = parentIndex - 2; y >= 0; x--, y--) for (int x = parentIndex - 1, y = parentIndex - 2; y >= 0; x--, y--)
p.entries[x] = p.entries[y]; p._entries[x] = p._entries[y];
p.entries[0] = new Entry(); p._entries[0] = new Entry();
} }
else { else {
for (int x = parentIndex - 1, y = parentIndex; y <= p.nrElements; x++, y++) for (int x = parentIndex - 1, y = parentIndex; y <= p._nrElements; x++, y++)
p.entries[x] = p.entries[y]; p._entries[x] = p._entries[y];
p.entries[p.nrElements] = null; p._entries[p._nrElements] = null;
} }
p.nrElements--; p._nrElements--;
if (p.isRoot() && p.nrElements == 0) { // It's the root and it's empty if (p.isRoot() && p._nrElements == 0) { // It's the root and it's empty
BTreeSet.this.root = this; BTreeSet.this.root = this;
parent = null; _parent = null;
} }
} }
} }

View File

@ -52,14 +52,6 @@ public final class HeaderFooter
} }
public boolean isEmpty() public boolean isEmpty()
{ {
if(_start - _end == 0) return _start - _end == 0;
{
return true;
}
else
{
return false;
}
} }
} }

View File

@ -1466,13 +1466,6 @@ public final class StyleSheet implements HDFType {
*/ */
public static boolean getFlag(int x) public static boolean getFlag(int x)
{ {
if(x != 0) return x != 0;
{
return true;
}
else
{
return false;
}
} }
} }

View File

@ -45,7 +45,7 @@ public final class BTreeSet extends AbstractSet
public BTreeNode root; public BTreeNode root;
private Comparator comparator = null; private Comparator comparator = null;
private int order; private int order;
private int size = 0; int size = 0;
/* /*
* Constructors * Constructors
@ -172,7 +172,7 @@ public final class BTreeSet extends AbstractSet
/* /*
* Private methods * Private methods
*/ */
private int compare(Object x, Object y) int compare(Object x, Object y)
{ {
return (comparator == null ? ((Comparable)x).compareTo(y) : comparator.compare(x, y)); return (comparator == null ? ((Comparable)x).compareTo(y) : comparator.compare(x, y));
} }
@ -270,20 +270,18 @@ public final class BTreeSet extends AbstractSet
} }
} }
else // else - You're not a leaf so simply find and return the successor of lastReturned
{ //Your not a leaf so simply find and return the successor of lastReturned currentNode = currentNode.entries[index].child;
currentNode = currentNode.entries[index].child; parentIndex.push(new Integer(index));
parentIndex.push(new Integer(index));
while (currentNode.entries[0].child != null) while (currentNode.entries[0].child != null)
{ {
currentNode = currentNode.entries[0].child; currentNode = currentNode.entries[0].child;
parentIndex.push(new Integer(0)); parentIndex.push(new Integer(0));
}
index = 1;
return currentNode.entries[0].element;
} }
index = 1;
return currentNode.entries[0].element;
} }
} }
@ -329,21 +327,23 @@ public final class BTreeSet extends AbstractSet
else else
{ // Promote splitNode { // Promote splitNode
parent.insertSplitNode(splitNode, this, rightSibling, parentIndex); parent.insertSplitNode(splitNode, this, rightSibling, parentIndex);
if (BTreeSet.this.compare(x, parent.entries[parentIndex].element) < 0) return insert(x, parentIndex); if (BTreeSet.this.compare(x, parent.entries[parentIndex].element) < 0) {
else return rightSibling.insert(x, parentIndex + 1); return insert(x, parentIndex);
}
return rightSibling.insert(x, parentIndex + 1);
} }
} }
else if (isLeaf()) else if (isLeaf())
{ // If leaf, simply insert the non-duplicate element { // If leaf, simply insert the non-duplicate element
int insertAt = childToInsertAt(x, true); int insertAt = childToInsertAt(x, true);
if (insertAt == -1) return false; // Determine if the element already exists // Determine if the element already exists
else if (insertAt == -1) {
{ return false;
insertNewElement(x, insertAt);
BTreeSet.this.size++;
return true;
} }
insertNewElement(x, insertAt);
BTreeSet.this.size++;
return true;
} }
else else
@ -388,22 +388,19 @@ public final class BTreeSet extends AbstractSet
return true; return true;
} }
else // else - If leaf and have less than MIN elements, than prepare the BTreeSet for deletion
{ // If leaf and have less than MIN elements, than prepare the BTreeSet for deletion temp.prepareForDeletion(parentIndex);
temp.prepareForDeletion(parentIndex); temp.deleteElement(x);
temp.deleteElement(x); BTreeSet.this.size--;
BTreeSet.this.size--; temp.fixAfterDeletion(priorParentIndex);
temp.fixAfterDeletion(priorParentIndex); return true;
return true;
}
} }
else // else - Only delete at leaf so first switch with successor than delete
{ // Only delete at leaf so first switch with successor than delete temp.switchWithSuccessor(x);
temp.switchWithSuccessor(x); parentIndex = temp.childToInsertAt(x, false) + 1;
parentIndex = temp.childToInsertAt(x, false) + 1; return temp.entries[parentIndex].child.delete(x, parentIndex);
return temp.entries[parentIndex].child.delete(x, parentIndex);
}
} }

View File

@ -311,7 +311,7 @@ private void output8Codes(OutputStream res) throws IOException {
/** /**
* Does the compression * Does the compression
*/ */
private void compress(InputStream src, OutputStream res) throws IOException { public void compress(InputStream src, OutputStream res) throws IOException {
// Have we hit the end of the file yet? // Have we hit the end of the file yet?
boolean going = true; boolean going = true;
@ -375,11 +375,10 @@ private void compress(InputStream src, OutputStream res) throws IOException {
if(findRawCodeInBuffer() > -1) { if(findRawCodeInBuffer() > -1) {
// Fits in, wait for next byte // Fits in, wait for next byte
continue; continue;
} else {
// Doesn't fit, output
outputUncompressed(dataB,res);
rawCodeLen = 0;
} }
// Doesn't fit, output
outputUncompressed(dataB,res);
rawCodeLen = 0;
} else { } else {
// Nothing in rawCode before, so this byte // Nothing in rawCode before, so this byte
// isn't in the buffer dictionary // isn't in the buffer dictionary

View File

@ -112,10 +112,9 @@ public class AutoShape extends TextShape {
if(outline == null){ if(outline == null){
logger.log(POILogger.WARN, "Outline not found for " + ShapeTypes.typeName(getShapeType())); logger.log(POILogger.WARN, "Outline not found for " + ShapeTypes.typeName(getShapeType()));
return anchor; return anchor;
} else {
java.awt.Shape shape = outline.getOutline(this);
return AutoShapes.transform(shape, anchor);
} }
java.awt.Shape shape = outline.getOutline(this);
return AutoShapes.transform(shape, anchor);
} }
} }

View File

@ -43,15 +43,15 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
protected POILogger log = POILogFactory.getLogger(this.getClass()); protected POILogger log = POILogFactory.getLogger(this.getClass());
//The ppt object to write into. //The ppt object to write into.
private ShapeGroup group; private ShapeGroup _group;
private AffineTransform transform; private AffineTransform _transform;
private Stroke stroke; private Stroke _stroke;
private Paint paint; private Paint _paint;
private Font font; private Font _font;
private Color foreground; private Color _foreground;
private Color background; private Color _background;
private RenderingHints hints; private RenderingHints _hints;
/** /**
* Construct Java Graphics object which translates graphic calls in ppt drawing layer. * Construct Java Graphics object which translates graphic calls in ppt drawing layer.
@ -59,22 +59,22 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @param group The shape group to write the graphics calls into. * @param group The shape group to write the graphics calls into.
*/ */
public PPGraphics2D(ShapeGroup group){ public PPGraphics2D(ShapeGroup group){
this.group = group; this._group = group;
transform = new AffineTransform(); _transform = new AffineTransform();
stroke = new BasicStroke(); _stroke = new BasicStroke();
paint = Color.black; _paint = Color.black;
font = new Font("Arial", Font.PLAIN, 12); _font = new Font("Arial", Font.PLAIN, 12);
background = Color.black; _background = Color.black;
foreground = Color.white; _foreground = Color.white;
hints = new RenderingHints(null); _hints = new RenderingHints(null);
} }
/** /**
* @return the shape group being used for drawing * @return the shape group being used for drawing
*/ */
public ShapeGroup getShapeGroup(){ public ShapeGroup getShapeGroup(){
return group; return _group;
} }
/** /**
@ -84,7 +84,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see java.awt.Graphics#setFont(Font) * @see java.awt.Graphics#setFont(Font)
*/ */
public Font getFont(){ public Font getFont(){
return font; return _font;
} }
/** /**
@ -98,7 +98,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see java.awt.Graphics#drawChars(char[], int, int, int, int) * @see java.awt.Graphics#drawChars(char[], int, int, int, int)
*/ */
public void setFont(Font font){ public void setFont(Font font){
this.font = font; this._font = font;
} }
/** /**
@ -108,7 +108,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see java.awt.Graphics#setColor * @see java.awt.Graphics#setColor
*/ */
public Color getColor(){ public Color getColor(){
return foreground; return _foreground;
} }
/** /**
@ -131,7 +131,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see #setStroke * @see #setStroke
*/ */
public Stroke getStroke(){ public Stroke getStroke(){
return stroke; return _stroke;
} }
/** /**
@ -140,7 +140,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* <code>Shape</code> during the rendering process * <code>Shape</code> during the rendering process
*/ */
public void setStroke(Stroke s){ public void setStroke(Stroke s){
this.stroke = s; this._stroke = s;
} }
/** /**
@ -152,7 +152,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see java.awt.Graphics#setColor * @see java.awt.Graphics#setColor
*/ */
public Paint getPaint(){ public Paint getPaint(){
return paint; return _paint;
} }
/** /**
@ -168,8 +168,8 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
public void setPaint(Paint paint){ public void setPaint(Paint paint){
if(paint == null) return; if(paint == null) return;
this.paint = paint; this._paint = paint;
if (paint instanceof Color) foreground = (Color)paint; if (paint instanceof Color) _foreground = (Color)paint;
} }
/** /**
@ -177,11 +177,11 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* <code>Graphics2D</code> context. * <code>Graphics2D</code> context.
* @return the current <code>AffineTransform</code> in the * @return the current <code>AffineTransform</code> in the
* <code>Graphics2D</code> context. * <code>Graphics2D</code> context.
* @see #transform * @see #_transform
* @see #setTransform * @see #setTransform
*/ */
public AffineTransform getTransform(){ public AffineTransform getTransform(){
return new AffineTransform(transform); return new AffineTransform(_transform);
} }
/** /**
@ -189,11 +189,11 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* context. * context.
* @param Tx the <code>AffineTransform</code> object to be used in the * @param Tx the <code>AffineTransform</code> object to be used in the
* rendering process * rendering process
* @see #transform * @see #_transform
* @see AffineTransform * @see AffineTransform
*/ */
public void setTransform(AffineTransform Tx) { public void setTransform(AffineTransform Tx) {
transform = new AffineTransform(Tx); _transform = new AffineTransform(Tx);
} }
/** /**
@ -206,19 +206,19 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see #setStroke * @see #setStroke
* @see #setPaint * @see #setPaint
* @see java.awt.Graphics#setColor * @see java.awt.Graphics#setColor
* @see #transform * @see #_transform
* @see #setTransform * @see #setTransform
* @see #clip * @see #clip
* @see #setClip * @see #setClip
* @see #setComposite * @see #setComposite
*/ */
public void draw(Shape shape){ public void draw(Shape shape){
GeneralPath path = new GeneralPath(transform.createTransformedShape(shape)); GeneralPath path = new GeneralPath(_transform.createTransformedShape(shape));
Freeform p = new Freeform(group); Freeform p = new Freeform(_group);
p.setPath(path); p.setPath(path);
p.getFill().setForegroundColor(null); p.getFill().setForegroundColor(null);
applyStroke(p); applyStroke(p);
group.addShape(p); _group.addShape(p);
} }
/** /**
@ -247,18 +247,18 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see #setClip * @see #setClip
*/ */
public void drawString(String s, float x, float y) { public void drawString(String s, float x, float y) {
TextBox txt = new TextBox(group); TextBox txt = new TextBox(_group);
txt.getTextRun().supplySlideShow(group.getSheet().getSlideShow()); txt.getTextRun().supplySlideShow(_group.getSheet().getSlideShow());
txt.getTextRun().setSheet(group.getSheet()); txt.getTextRun().setSheet(_group.getSheet());
txt.setText(s); txt.setText(s);
RichTextRun rt = txt.getTextRun().getRichTextRuns()[0]; RichTextRun rt = txt.getTextRun().getRichTextRuns()[0];
rt.setFontSize(font.getSize()); rt.setFontSize(_font.getSize());
rt.setFontName(font.getFamily()); rt.setFontName(_font.getFamily());
if (getColor() != null) rt.setFontColor(getColor()); if (getColor() != null) rt.setFontColor(getColor());
if (font.isBold()) rt.setBold(true); if (_font.isBold()) rt.setBold(true);
if (font.isItalic()) rt.setItalic(true); if (_font.isItalic()) rt.setItalic(true);
txt.setMarginBottom(0); txt.setMarginBottom(0);
txt.setMarginTop(0); txt.setMarginTop(0);
@ -269,7 +269,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
txt.setVerticalAlignment(TextBox.AnchorMiddle); txt.setVerticalAlignment(TextBox.AnchorMiddle);
TextLayout layout = new TextLayout(s, font, getFontRenderContext()); TextLayout layout = new TextLayout(s, _font, getFontRenderContext());
float ascent = layout.getAscent(); float ascent = layout.getAscent();
float width = (float) Math.floor(layout.getAdvance()); float width = (float) Math.floor(layout.getAdvance());
@ -295,7 +295,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
*/ */
txt.setAnchor(new Rectangle2D.Float(x, y, width, height)); txt.setAnchor(new Rectangle2D.Float(x, y, width, height));
group.addShape(txt); _group.addShape(txt);
} }
/** /**
@ -306,19 +306,19 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @param shape the <code>Shape</code> to be filled * @param shape the <code>Shape</code> to be filled
* @see #setPaint * @see #setPaint
* @see java.awt.Graphics#setColor * @see java.awt.Graphics#setColor
* @see #transform * @see #_transform
* @see #setTransform * @see #setTransform
* @see #setComposite * @see #setComposite
* @see #clip * @see #clip
* @see #setClip * @see #setClip
*/ */
public void fill(Shape shape){ public void fill(Shape shape){
GeneralPath path = new GeneralPath(transform.createTransformedShape(shape)); GeneralPath path = new GeneralPath(_transform.createTransformedShape(shape));
Freeform p = new Freeform(group); Freeform p = new Freeform(_group);
p.setPath(path); p.setPath(path);
applyPaint(p); applyPaint(p);
p.setLineColor(null); //Fills must be "No Line" p.setLineColor(null); //Fills must be "No Line"
group.addShape(p); _group.addShape(p);
} }
/** /**
@ -333,7 +333,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @param y the <i>y</i> coordinate. * @param y the <i>y</i> coordinate.
*/ */
public void translate(int x, int y){ public void translate(int x, int y){
transform.translate(x, y); _transform.translate(x, y);
} }
/** /**
@ -400,7 +400,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* rendering operations. * rendering operations.
*/ */
public void scale(double sx, double sy){ public void scale(double sx, double sy){
transform.scale(sx, sy); _transform.scale(sx, sy);
} }
/** /**
@ -1055,10 +1055,10 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
*/ */
public Rectangle getClipBounds(){ public Rectangle getClipBounds(){
Shape c = getClip(); Shape c = getClip();
if(c==null) if (c==null) {
return null; return null;
else }
return c.getBounds(); return c.getBounds();
} }
/** /**
@ -1143,7 +1143,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @param theta the angle of rotation in radians * @param theta the angle of rotation in radians
*/ */
public void rotate(double theta){ public void rotate(double theta){
transform.rotate(theta); _transform.rotate(theta);
} }
/** /**
@ -1166,7 +1166,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @param y y coordinate of the origin of the rotation * @param y y coordinate of the origin of the rotation
*/ */
public void rotate(double theta, double x, double y){ public void rotate(double theta, double x, double y){
transform.rotate(theta, x, y); _transform.rotate(theta, x, y);
} }
/** /**
@ -1188,7 +1188,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* the positive Y axis direction as a function of their X coordinate * the positive Y axis direction as a function of their X coordinate
*/ */
public void shear(double shx, double shy){ public void shear(double shx, double shy){
transform.shear(shx, shy); _transform.shear(shx, shy);
} }
/** /**
@ -1240,7 +1240,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see AffineTransform * @see AffineTransform
*/ */
public void transform(AffineTransform Tx) { public void transform(AffineTransform Tx) {
transform.concatenate(Tx); _transform.concatenate(Tx);
} }
/** /**
@ -1258,7 +1258,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @param op the filter to be applied to the image before rendering * @param op the filter to be applied to the image before rendering
* @param x the x coordinate in user space where the image is rendered * @param x the x coordinate in user space where the image is rendered
* @param y the y coordinate in user space where the image is rendered * @param y the y coordinate in user space where the image is rendered
* @see #transform * @see #_transform
* @see #setTransform * @see #setTransform
* @see #setComposite * @see #setComposite
* @see #clip * @see #clip
@ -1292,7 +1292,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
if(color == null) if(color == null)
return; return;
background = color; _background = color;
} }
/** /**
@ -1302,7 +1302,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see #setBackground * @see #setBackground
*/ */
public Color getBackground(){ public Color getBackground(){
return background; return _background;
} }
/** /**
@ -1359,7 +1359,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see RenderingHints * @see RenderingHints
*/ */
public Object getRenderingHint(RenderingHints.Key hintKey){ public Object getRenderingHint(RenderingHints.Key hintKey){
return hints.get(hintKey); return _hints.get(hintKey);
} }
/** /**
@ -1374,7 +1374,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see RenderingHints * @see RenderingHints
*/ */
public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue){ public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue){
hints.put(hintKey, hintValue); _hints.put(hintKey, hintValue);
} }
@ -1434,7 +1434,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see RenderingHints * @see RenderingHints
*/ */
public void addRenderingHints(Map hints){ public void addRenderingHints(Map hints){
this.hints.putAll(hints); this._hints.putAll(hints);
} }
/** /**
@ -1454,7 +1454,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @param ty the distance to translate along the y-axis * @param ty the distance to translate along the y-axis
*/ */
public void translate(double tx, double ty){ public void translate(double tx, double ty){
transform.translate(tx, ty); _transform.translate(tx, ty);
} }
/** /**
@ -1510,7 +1510,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see #setStroke * @see #setStroke
* @see #fill(Shape) * @see #fill(Shape)
* @see #draw(Shape) * @see #draw(Shape)
* @see #transform * @see #_transform
* @see #setTransform * @see #setTransform
* @see #clip * @see #clip
* @see #setClip(Shape) * @see #setClip(Shape)
@ -1540,7 +1540,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see RenderingHints * @see RenderingHints
*/ */
public RenderingHints getRenderingHints(){ public RenderingHints getRenderingHints(){
return hints; return _hints;
} }
/** /**
@ -1557,7 +1557,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @see RenderingHints * @see RenderingHints
*/ */
public void setRenderingHints(Map hints){ public void setRenderingHints(Map hints){
this.hints = new RenderingHints(hints); this._hints = new RenderingHints(hints);
} }
/** /**
@ -1579,7 +1579,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @return <code>true</code> if the <code>Image</code> is * @return <code>true</code> if the <code>Image</code> is
* fully loaded and completely rendered; * fully loaded and completely rendered;
* <code>false</code> if the <code>Image</code> is still being loaded. * <code>false</code> if the <code>Image</code> is still being loaded.
* @see #transform * @see #_transform
* @see #setTransform * @see #setTransform
* @see #setComposite * @see #setComposite
* @see #clip * @see #clip
@ -1713,7 +1713,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @param img the image to be rendered. This method does * @param img the image to be rendered. This method does
* nothing if <code>img</code> is null. * nothing if <code>img</code> is null.
* @param xform the transformation from image space into user space * @param xform the transformation from image space into user space
* @see #transform * @see #_transform
* @see #setTransform * @see #setTransform
* @see #setComposite * @see #setComposite
* @see #clip * @see #clip
@ -1739,7 +1739,7 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
* @param img the image to be rendered. This method does * @param img the image to be rendered. This method does
* nothing if <code>img</code> is null. * nothing if <code>img</code> is null.
* @param xform the transformation from image space into user space * @param xform the transformation from image space into user space
* @see #transform * @see #_transform
* @see #setTransform * @see #setTransform
* @see #setComposite * @see #setComposite
* @see #clip * @see #clip
@ -1750,8 +1750,8 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
} }
protected void applyStroke(SimpleShape shape) { protected void applyStroke(SimpleShape shape) {
if (stroke instanceof BasicStroke){ if (_stroke instanceof BasicStroke){
BasicStroke bs = (BasicStroke)stroke; BasicStroke bs = (BasicStroke)_stroke;
shape.setLineWidth(bs.getLineWidth()); shape.setLineWidth(bs.getLineWidth());
float[] dash = bs.getDashArray(); float[] dash = bs.getDashArray();
if (dash != null) { if (dash != null) {
@ -1762,8 +1762,8 @@ public final class PPGraphics2D extends Graphics2D implements Cloneable {
} }
protected void applyPaint(SimpleShape shape) { protected void applyPaint(SimpleShape shape) {
if (paint instanceof Color) { if (_paint instanceof Color) {
shape.getFill().setForegroundColor((Color)paint); shape.getFill().setForegroundColor((Color)_paint);
} }
} }
} }

View File

@ -152,14 +152,14 @@ public class Picture extends SimpleShape {
img = ImageIO.read(new ByteArrayInputStream(pict.getData())); img = ImageIO.read(new ByteArrayInputStream(pict.getData()));
} }
catch (IOException e){} catch (IOException e){}
catch (NegativeArraySizeException ne) {} catch (NegativeArraySizeException ne) {}
if(img != null) { if(img != null) {
// Valid image, set anchor from it // Valid image, set anchor from it
setAnchor(new java.awt.Rectangle(0, 0, img.getWidth()*POINT_DPI/PIXEL_DPI, img.getHeight()*POINT_DPI/PIXEL_DPI)); setAnchor(new java.awt.Rectangle(0, 0, img.getWidth()*POINT_DPI/PIXEL_DPI, img.getHeight()*POINT_DPI/PIXEL_DPI));
} else { } else {
// Invalid image, go with the default metafile size // Invalid image, go with the default metafile size
setAnchor(new java.awt.Rectangle(0, 0, 200, 200)); setAnchor(new java.awt.Rectangle(0, 0, 200, 200));
} }
} else { } else {
//default size of a metafile picture is 200x200 //default size of a metafile picture is 200x200
@ -204,9 +204,8 @@ public class Picture extends SimpleShape {
if (idx == 0){ if (idx == 0){
logger.log(POILogger.DEBUG, "picture index was not found, returning "); logger.log(POILogger.DEBUG, "picture index was not found, returning ");
return null; return null;
} else {
return (EscherBSERecord)lst.get(idx-1);
} }
return (EscherBSERecord)lst.get(idx-1);
} }
/** /**

View File

@ -40,10 +40,8 @@ public final class ShapeFactory {
public static Shape createShape(EscherContainerRecord spContainer, Shape parent){ public static Shape createShape(EscherContainerRecord spContainer, Shape parent){
if (spContainer.getRecordId() == EscherContainerRecord.SPGR_CONTAINER){ if (spContainer.getRecordId() == EscherContainerRecord.SPGR_CONTAINER){
return createShapeGroup(spContainer, parent); return createShapeGroup(spContainer, parent);
} else {
return createSimpeShape(spContainer, parent);
} }
return createSimpeShape(spContainer, parent);
} }
public static ShapeGroup createShapeGroup(EscherContainerRecord spContainer, Shape parent){ public static ShapeGroup createShapeGroup(EscherContainerRecord spContainer, Shape parent){

View File

@ -17,16 +17,22 @@
package org.apache.poi.hslf.model; package org.apache.poi.hslf.model;
import java.awt.Graphics2D;
import java.util.Vector; import java.util.Vector;
import java.util.Iterator;
import java.awt.*;
import org.apache.poi.hslf.record.*;
import org.apache.poi.hslf.record.SlideListWithText.SlideAtomsSet;
import org.apache.poi.ddf.EscherDggRecord;
import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherContainerRecord;
import org.apache.poi.ddf.EscherDgRecord; import org.apache.poi.ddf.EscherDgRecord;
import org.apache.poi.ddf.EscherDggRecord;
import org.apache.poi.ddf.EscherSpRecord; import org.apache.poi.ddf.EscherSpRecord;
import org.apache.poi.hslf.record.ColorSchemeAtom;
import org.apache.poi.hslf.record.Comment2000;
import org.apache.poi.hslf.record.HeadersFootersContainer;
import org.apache.poi.hslf.record.Record;
import org.apache.poi.hslf.record.RecordContainer;
import org.apache.poi.hslf.record.RecordTypes;
import org.apache.poi.hslf.record.SlideAtom;
import org.apache.poi.hslf.record.TextHeaderAtom;
import org.apache.poi.hslf.record.SlideListWithText.SlideAtomsSet;
/** /**
* This class represents a slide in a PowerPoint Document. It allows * This class represents a slide in a PowerPoint Document. It allows
@ -144,8 +150,7 @@ public final class Slide extends Sheet
dgg.setDrawingsSaved(dgg.getDrawingsSaved() + 1); dgg.setDrawingsSaved(dgg.getDrawingsSaved() + 1);
dgg.setMaxDrawingGroupId(dgId); dgg.setMaxDrawingGroupId(dgId);
for (Iterator it = dgContainer.getChildContainers().iterator(); it.hasNext(); ) { for (EscherContainerRecord c : dgContainer.getChildContainers()) {
EscherContainerRecord c = (EscherContainerRecord)it.next();
EscherSpRecord spr = null; EscherSpRecord spr = null;
switch(c.getRecordId()){ switch(c.getRecordId()){
case EscherContainerRecord.SPGR_CONTAINER: case EscherContainerRecord.SPGR_CONTAINER:
@ -343,10 +348,10 @@ public final class Slide extends Sheet
* Background for this slide. * Background for this slide.
*/ */
public Background getBackground() { public Background getBackground() {
if(getFollowMasterBackground()) if(getFollowMasterBackground()) {
return getMasterSheet().getBackground(); return getMasterSheet().getBackground();
else }
return super.getBackground(); return super.getBackground();
} }
/** /**
@ -449,13 +454,11 @@ public final class Slide extends Sheet
if(hdd == null && !ppt2007) { if(hdd == null && !ppt2007) {
return getSlideShow().getSlideHeadersFooters(); return getSlideShow().getSlideHeadersFooters();
} }
else { if(hdd == null) {
if(hdd == null) { hdd = new HeadersFootersContainer(HeadersFootersContainer.SlideHeadersFootersContainer);
hdd = new HeadersFootersContainer(HeadersFootersContainer.SlideHeadersFootersContainer); newRecord = true;
newRecord = true;
}
return new HeadersFooters(hdd, this, newRecord, ppt2007);
} }
return new HeadersFooters(hdd, this, newRecord, ppt2007);
} }
protected void onAddTextShape(TextShape shape) { protected void onAddTextShape(TextShape shape) {

View File

@ -46,7 +46,7 @@ public final class TextRun
protected boolean _isUnicode; protected boolean _isUnicode;
protected RichTextRun[] _rtRuns; protected RichTextRun[] _rtRuns;
private SlideShow slideShow; private SlideShow slideShow;
private Sheet sheet; private Sheet _sheet;
private int shapeId; private int shapeId;
private int slwtIndex; //position in the owning SlideListWithText private int slwtIndex; //position in the owning SlideListWithText
/** /**
@ -564,9 +564,8 @@ public final class TextRun
public String getRawText() { public String getRawText() {
if(_isUnicode) { if(_isUnicode) {
return _charAtom.getText(); return _charAtom.getText();
} else {
return _byteAtom.getText();
} }
return _byteAtom.getText();
} }
/** /**
@ -610,11 +609,11 @@ public final class TextRun
} }
public void setSheet(Sheet sheet){ public void setSheet(Sheet sheet){
this.sheet = sheet; this._sheet = sheet;
} }
public Sheet getSheet(){ public Sheet getSheet(){
return this.sheet; return this._sheet;
} }
/** /**

View File

@ -171,26 +171,26 @@ public final class TxMasterStyleAtom extends RecordAtom {
protected TextProp[] getParagraphProps(int type, int level){ protected TextProp[] getParagraphProps(int type, int level){
if (level != 0 || type >= MAX_INDENT){ if (level != 0 || type >= MAX_INDENT){
return StyleTextPropAtom.paragraphTextPropTypes; return StyleTextPropAtom.paragraphTextPropTypes;
} else {
return new TextProp[] {
new ParagraphFlagsTextProp(),
new TextProp(2, 0x80, "bullet.char"),
new TextProp(2, 0x10, "bullet.font"),
new TextProp(2, 0x40, "bullet.size"),
new TextProp(4, 0x20, "bullet.color"),
new TextProp(2, 0xD00, "alignment"),
new TextProp(2, 0x1000, "linespacing"),
new TextProp(2, 0x2000, "spacebefore"),
new TextProp(2, 0x4000, "spaceafter"),
new TextProp(2, 0x8000, "text.offset"),
new TextProp(2, 0x10000, "bullet.offset"),
new TextProp(2, 0x20000, "defaulttab"),
new TextProp(2, 0x40000, "para_unknown_2"),
new TextProp(2, 0x80000, "para_unknown_3"),
new TextProp(2, 0x100000, "para_unknown_4"),
new TextProp(2, 0x200000, "para_unknown_5")
};
} }
return new TextProp[] {
new ParagraphFlagsTextProp(),
new TextProp(2, 0x80, "bullet.char"),
new TextProp(2, 0x10, "bullet.font"),
new TextProp(2, 0x40, "bullet.size"),
new TextProp(4, 0x20, "bullet.color"),
new TextProp(2, 0xD00, "alignment"),
new TextProp(2, 0x1000, "linespacing"),
new TextProp(2, 0x2000, "spacebefore"),
new TextProp(2, 0x4000, "spaceafter"),
new TextProp(2, 0x8000, "text.offset"),
new TextProp(2, 0x10000, "bullet.offset"),
new TextProp(2, 0x20000, "defaulttab"),
new TextProp(2, 0x40000, "para_unknown_2"),
new TextProp(2, 0x80000, "para_unknown_3"),
new TextProp(2, 0x100000, "para_unknown_4"),
new TextProp(2, 0x200000, "para_unknown_5")
};
} }
/** /**
@ -202,16 +202,16 @@ public final class TxMasterStyleAtom extends RecordAtom {
protected TextProp[] getCharacterProps(int type, int level){ protected TextProp[] getCharacterProps(int type, int level){
if (level != 0 || type >= MAX_INDENT){ if (level != 0 || type >= MAX_INDENT){
return StyleTextPropAtom.characterTextPropTypes; return StyleTextPropAtom.characterTextPropTypes;
} else }
return new TextProp[] { return new TextProp[] {
new CharFlagsTextProp(), new CharFlagsTextProp(),
new TextProp(2, 0x10000, "font.index"), new TextProp(2, 0x10000, "font.index"),
new TextProp(2, 0x20000, "char_unknown_1"), new TextProp(2, 0x20000, "char_unknown_1"),
new TextProp(4, 0x40000, "char_unknown_2"), new TextProp(4, 0x40000, "char_unknown_2"),
new TextProp(2, 0x80000, "font.size"), new TextProp(2, 0x80000, "font.size"),
new TextProp(2, 0x100000, "char_unknown_3"), new TextProp(2, 0x100000, "char_unknown_3"),
new TextProp(4, 0x200000, "font.color"), new TextProp(4, 0x200000, "font.color"),
new TextProp(2, 0x800000, "char_unknown_4") new TextProp(2, 0x800000, "char_unknown_4")
}; };
} }
} }

View File

@ -262,12 +262,11 @@ public final class SlideShow {
if (coreRecordId != null) { if (coreRecordId != null) {
Record r = _mostRecentCoreRecords[coreRecordId.intValue()]; Record r = _mostRecentCoreRecords[coreRecordId.intValue()];
return r; return r;
} else {
logger.log(POILogger.ERROR,
"We tried to look up a reference to a core record, but there was no core ID for reference ID "
+ refID);
return null;
} }
logger.log(POILogger.ERROR,
"We tried to look up a reference to a core record, but there was no core ID for reference ID "
+ refID);
return null;
} }
/** /**
@ -989,9 +988,8 @@ public final class SlideShow {
} }
if (ppt2007 && _notes.length > 0) { if (ppt2007 && _notes.length > 0) {
return new HeadersFooters(hdd, _notes[0], newRecord, ppt2007); return new HeadersFooters(hdd, _notes[0], newRecord, ppt2007);
} else {
return new HeadersFooters(hdd, this, newRecord, ppt2007);
} }
return new HeadersFooters(hdd, this, newRecord, ppt2007);
} }
/** /**

View File

@ -49,12 +49,9 @@ public final class ComplexFileTable
{ {
throw new IOException("The text piece table is corrupted"); throw new IOException("The text piece table is corrupted");
} }
else int pieceTableSize = LittleEndian.getInt(tableStream, ++offset);
{ offset += LittleEndian.INT_SIZE;
int pieceTableSize = LittleEndian.getInt(tableStream, ++offset); _tpt = new TextPieceTable(documentStream, tableStream, offset, pieceTableSize, fcMin);
offset += LittleEndian.INT_SIZE;
_tpt = new TextPieceTable(documentStream, tableStream, offset, pieceTableSize, fcMin);
}
} }
public TextPieceTable getTextPieceTable() public TextPieceTable getTextPieceTable()

View File

@ -194,10 +194,9 @@ public final class ListTables
if(level < lst.numLevels()) { if(level < lst.numLevels()) {
ListLevel lvl = lst.getLevels()[level]; ListLevel lvl = lst.getLevels()[level];
return lvl; return lvl;
} else {
log.log(POILogger.WARN, "Requested level " + level + " which was greater than the maximum defined (" + lst.numLevels() + ")");
return null;
} }
log.log(POILogger.WARN, "Requested level " + level + " which was greater than the maximum defined (" + lst.numLevels() + ")");
return null;
} }
public ListData getListData(int listID) public ListData getListData(int listID)

View File

@ -226,13 +226,12 @@ public final class PAPFormattedDiskPage extends FormattedDiskPage {
throw new UnsupportedOperationException( throw new UnsupportedOperationException(
"This Paragraph has no dataStream storage."); "This Paragraph has no dataStream storage.");
} }
else // we have some storage... // we have some storage...
{
// get the size of the existing storage
int maxHugeGrpprlSize = LittleEndian.getUShort(_dataStream,
hugeGrpprlOffset);
if (maxHugeGrpprlSize < grpprl.length-2) // grpprl.length-2 because we don't store the istd // get the size of the existing storage
int maxHugeGrpprlSize = LittleEndian.getUShort(_dataStream, hugeGrpprlOffset);
if (maxHugeGrpprlSize < grpprl.length-2) { // grpprl.length-2 because we don't store the istd
throw new UnsupportedOperationException( throw new UnsupportedOperationException(
"This Paragraph's dataStream storage is too small."); "This Paragraph's dataStream storage is too small.");
} }

View File

@ -112,10 +112,7 @@ public final class PAPX extends BytePropertyNode {
{ {
return 0; return 0;
} }
else
{
return LittleEndian.getShort(buf); return LittleEndian.getShort(buf);
}
} }
public SprmBuffer getSprmBuf() public SprmBuffer getSprmBuf()

View File

@ -67,7 +67,7 @@ public final class SprmBuffer
_buf[grpprlOffset] = operand; _buf[grpprlOffset] = operand;
return; return;
} }
else addSprm(opcode, operand); addSprm(opcode, operand);
} }
public void updateSprm(short opcode, short operand) public void updateSprm(short opcode, short operand)
@ -78,7 +78,7 @@ public final class SprmBuffer
LittleEndian.putShort(_buf, grpprlOffset, operand); LittleEndian.putShort(_buf, grpprlOffset, operand);
return; return;
} }
else addSprm(opcode, operand); addSprm(opcode, operand);
} }
public void updateSprm(short opcode, int operand) public void updateSprm(short opcode, int operand)
@ -89,7 +89,7 @@ public final class SprmBuffer
LittleEndian.putInt(_buf, grpprlOffset, operand); LittleEndian.putInt(_buf, grpprlOffset, operand);
return; return;
} }
else addSprm(opcode, operand); addSprm(opcode, operand);
} }
public void addSprm(short opcode, byte operand) public void addSprm(short opcode, byte operand)

View File

@ -152,10 +152,7 @@ public final class SprmOperation
_gOffset += 2; _gOffset += 2;
return retVal; return retVal;
} }
else return (0x000000ff & _grpprl[_gOffset++]) + 3;
{
return (0x000000ff & _grpprl[_gOffset++]) + 3;
}
case 7: case 7:
return 5; return 5;
default: default:

View File

@ -15,7 +15,7 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
==================================================================== */ ==================================================================== */
package org.apache.poi.hssf.usermodel; package org.apache.poi.hssf.usermodel;
@ -93,10 +93,7 @@ public class SanityChecker
{ {
return matchRequired( firstRecord, records, recordIdx ); return matchRequired( firstRecord, records, recordIdx );
} }
else return matchOptional( firstRecord, records, recordIdx );
{
return matchOptional( firstRecord, records, recordIdx );
}
} }
private int matchOptional( int firstRecord, List records, int recordIdx ) private int matchOptional( int firstRecord, List records, int recordIdx )