/* The class has no renderer, try the superclass, if any. */
final Class superclass = c.getSuperclass();
- if (superclass != null)
+ if (superclass != null) {
return findRenderer(superclass);
- else
- return null;
+ }
+ return null;
}
}
* <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
* 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
* a POI filesystem it calls this class' {@link #processPOIFSReaderEvent} for
* each document it has been registered for. This method appends the document it
}
return n;
}
- else
- {
- /* The path is somewhere down in the POI filesystem's
- * hierarchy. We need the tree node of this path's parent
- * and attach our new node to it. */
- final String name = path.getComponent(path.length() - 1);
- final POIFSDocumentPath parentPath = path.getParent();
- final MutableTreeNode parentNode =
- getNode(parentPath, fsName, root);
- n = new DefaultMutableTreeNode(name);
- pathToNode.put(path, n);
- parentNode.insert(n, 0);
- return n;
- }
+ /* else - The path is somewhere down in the POI filesystem's
+ * hierarchy. We need the tree node of this path's parent
+ * and attach our new node to it. */
+ final String name = path.getComponent(path.length() - 1);
+ final POIFSDocumentPath parentPath = path.getParent();
+ final MutableTreeNode parentNode =
+ getNode(parentPath, fsName, root);
+ n = new DefaultMutableTreeNode(name);
+ pathToNode.put(path, n);
+ parentNode.insert(n, 0);
+ return n;
}
-
}
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.hssf.contrib.view;
toAppendTo.append(format(((Number)obj).doubleValue()));
return toAppendTo;
}
- else throw new IllegalArgumentException("Can only handle Numbers");
+ throw new IllegalArgumentException("Can only handle Numbers");
}
public Object parseObject(String source,
/**
* <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
* mutable counterparts in the new <code>MutablePropertySet</code>.</p>
- *
+ *
* @param ps The property set to copy
*/
public MutablePropertySet(final PropertySet ps)
/**
* <p>Writes the property set to an output stream.</p>
- *
+ *
* @param out the output stream to write the section to
* @exception IOException if an error when writing to the output stream
* occurs
catch (HPSFRuntimeException ex)
{
final Throwable cause = ex.getReason();
- if (cause instanceof UnsupportedEncodingException)
+ if (cause instanceof UnsupportedEncodingException) {
throw new IllegalPropertySetDataException(cause);
- else
- throw ex;
+ }
+ throw ex;
}
}
* the {@link MutablePropertySet} only.</p>
*
* @return the contents of this property set stream
- *
+ *
* @throws WritingNotSupportedException if HPSF does not yet support writing
* of a property's variant type.
* @throws IOException if an I/O exception occurs.
* @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
* same name in the directory the latter will be overwritten.
- *
+ *
* @throws WritingNotSupportedException
* @throws IOException
*/
* 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
* reports or patches for the types you need.</p>
- *
+ *
* <p>Microsoft documentation: <a
* href="http://msdn.microsoft.com/library/en-us/stg/stg/property_set_display_name_dictionary.asp?frame=true">
* Property Set Display Name Dictionary</a>.
/**
* <p>Creates a property.</p>
- *
+ *
* @param id the property's ID.
* @param type the property's type, see {@link Variant}.
* @param value the property's value. Only certain types are allowed, see
/**
* <p>Reads a dictionary.</p>
- *
+ *
* @param src The byte array containing the bytes making out the dictionary.
* @param offset At this offset within <var>src </var> the dictionary
* starts.
* 4.</p>
*
* @return the property's size in bytes
- *
+ *
* @exception WritingNotSupportedException if HPSF does not yet support the
* property's variant type.
*/
* 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
* may have the different types Variant.VT_LPSTR and Variant.VT_LPWSTR;</p>
- *
+ *
* @see Object#equals(java.lang.Object)
*/
public boolean equals(final Object o)
{
- if (!(o instanceof Property))
+ if (!(o instanceof Property)) {
return false;
+ }
final Property p = (Property) o;
final Object pValue = p.getValue();
final long pId = p.getID();
return false;
/* It's clear now that both values are non-null. */
- final Class valueClass = value.getClass();
- final Class pValueClass = pValue.getClass();
+ final Class<?> valueClass = value.getClass();
+ final Class<?> pValueClass = pValue.getClass();
if (!(valueClass.isAssignableFrom(pValueClass)) &&
!(pValueClass.isAssignableFrom(valueClass)))
return false;
{
if (t1 == t2 ||
(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;
- else
- return false;
+ }
+ return false;
}
* @param src Contains the complete property set stream.
* @param offset The position in the stream that points to the
* section's format ID.
- *
+ *
* @exception UnsupportedEncodingException if the section's codepage is not
* supported.
*/
/*
* Read the properties. The offset is positioned at the first
* entry of the property list. There are two problems:
- *
+ *
* 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
* to the section's beginning. Unfortunately the properties in the
* possible to calculate the length as
* (offset of property(i+1) - offset of property(i)). Before we can
* 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.
* The reason is that property 1 specifies the codepage. If it is
* 1200, all strings are in Unicode. In other words: Before we can
* seconds pass reads the other properties.
*/
properties = new Property[propertyCount];
-
+
/* Pass 1: Read the property list. */
int pass1Offset = o1;
- final List propertyList = new ArrayList(propertyCount);
+ final List<PropertyListEntry> propertyList = new ArrayList<PropertyListEntry>(propertyCount);
PropertyListEntry ple;
for (int i = 0; i < properties.length; i++)
{
/* Calculate the properties' lengths. */
for (int i = 0; i < propertyCount - 1; i++)
{
- final PropertyListEntry ple1 =
- (PropertyListEntry) propertyList.get(i);
- final PropertyListEntry ple2 =
- (PropertyListEntry) propertyList.get(i + 1);
+ PropertyListEntry ple1 = propertyList.get(i);
+ PropertyListEntry ple2 = propertyList.get(i + 1);
ple1.length = ple2.offset - ple1.offset;
}
if (propertyCount > 0)
{
- ple = (PropertyListEntry) propertyList.get(propertyCount - 1);
+ ple = propertyList.get(propertyCount - 1);
ple.length = size - ple.offset;
if (ple.length <= 0)
{
protected boolean getPropertyBooleanValue(final int id)
{
final Boolean b = (Boolean) getProperty(id);
- if (b != null)
- return b.booleanValue();
- else
+ if (b == null) {
return false;
}
+ return b.booleanValue();
+ }
/**
* <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>
- *
+ *
* <ul>
- *
+ *
* <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 sections have a different number of properties. However,
* 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 properties have different values. The order of the properties
* is irrelevant.</p></li>
- *
+ *
* </ul>
- *
+ *
* @param o The object to compare this section with
* @return <code>true</code> if the objects are equal, <code>false</code> if
* not
if (!s.getFormatID().equals(getFormatID()))
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. */
Property[] pa1 = new Property[getProperties().length];
Property[] pa2 = new Property[s.getProperties().length];
dictionaryEqual = p10.getValue().equals(p20.getValue());
else if (p10 != null || p20 != null)
dictionaryEqual = false;
- if (!dictionaryEqual)
- return false;
- else
+ if (dictionaryEqual) {
return Util.equals(pa1, pa2);
+ }
+ return false;
}
* <p>Removes a field from a property array. The resulting array is
* compactified and returned.</p>
*
- * @param pa The property array.
+ * @param pa The property array.
* @param i The index of the field to be removed.
* @return the compactified array.
*/
/**
* <p>Convenience class representing a Summary Information stream in a
* Microsoft Office document.</p>
- *
+ *
* @author Rainer Klute <a
* href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
* @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>Creates a {@link SummaryInformation} from a given {@link
* PropertySet}.</p>
- *
+ *
* @param ps A property set which should be created from a summary
* information stream.
* @throws UnexpectedPropertySetTypeException if <var>ps</var> does not
/**
* <p>Returns the title (or <code>null</code>).</p>
- *
+ *
* @return The title or <code>null</code>
*/
public String getTitle()
/**
* <p>Sets the title.</p>
- *
+ *
* @param title The title to set.
*/
public void setTitle(final String title)
/**
* <p>Returns the subject (or <code>null</code>).</p>
- *
+ *
* @return The subject or <code>null</code>
*/
public String getSubject()
/**
* <p>Sets the subject.</p>
- *
+ *
* @param subject The subject to set.
*/
public void setSubject(final String subject)
/**
* <p>Returns the author (or <code>null</code>).</p>
- *
+ *
* @return The author or <code>null</code>
*/
public String getAuthor()
/**
* <p>Sets the author.</p>
- *
+ *
* @param author The author to set.
*/
public void setAuthor(final String author)
/**
* <p>Returns the keywords (or <code>null</code>).</p>
- *
+ *
* @return The keywords or <code>null</code>
*/
public String getKeywords()
/**
* <p>Sets the keywords.</p>
- *
+ *
* @param keywords The keywords to set.
*/
public void setKeywords(final String keywords)
/**
* <p>Returns the comments (or <code>null</code>).</p>
- *
+ *
* @return The comments or <code>null</code>
*/
public String getComments()
/**
* <p>Sets the comments.</p>
- *
+ *
* @param comments The comments to set.
*/
public void setComments(final String comments)
/**
* <p>Returns the template (or <code>null</code>).</p>
- *
+ *
* @return The template or <code>null</code>
*/
public String getTemplate()
/**
* <p>Sets the template.</p>
- *
+ *
* @param template The template to set.
*/
public void setTemplate(final String template)
/**
* <p>Returns the last author (or <code>null</code>).</p>
- *
+ *
* @return The last author or <code>null</code>
*/
public String getLastAuthor()
/**
* <p>Sets the last author.</p>
- *
+ *
* @param lastAuthor The last author to set.
*/
public void setLastAuthor(final String lastAuthor)
/**
* <p>Returns the revision number (or <code>null</code>). </p>
- *
+ *
* @return The revision number or <code>null</code>
*/
public String getRevNumber()
/**
* <p>Sets the revision number.</p>
- *
+ *
* @param revNumber The revision number to set.
*/
public void setRevNumber(final String revNumber)
/**
* <p>Returns the total time spent in editing the document (or
* <code>0</code>).</p>
- *
+ *
* @return The total time spent in editing the document or 0 if the {@link
* SummaryInformation} does not contain this information.
*/
public long getEditTime()
{
final Date d = (Date) getProperty(PropertyIDMap.PID_EDITTIME);
- if (d == null)
+ if (d == null) {
return 0;
- else
- return Util.dateToFileTime(d);
+ }
+ return Util.dateToFileTime(d);
}
/**
* <p>Sets the total time spent in editing the document.</p>
- *
+ *
* @param time The time to set.
*/
public void setEditTime(final long time)
/**
* <p>Returns the last printed time (or <code>null</code>).</p>
- *
+ *
* @return The last printed time or <code>null</code>
*/
public Date getLastPrinted()
/**
* <p>Sets the lastPrinted.</p>
- *
+ *
* @param lastPrinted The lastPrinted to set.
*/
public void setLastPrinted(final Date lastPrinted)
/**
* <p>Returns the creation time (or <code>null</code>).</p>
- *
+ *
* @return The creation time or <code>null</code>
*/
public Date getCreateDateTime()
/**
* <p>Sets the creation time.</p>
- *
+ *
* @param createDateTime The creation time to set.
*/
public void setCreateDateTime(final Date createDateTime)
/**
* <p>Returns the last save time (or <code>null</code>).</p>
- *
+ *
* @return The last save time or <code>null</code>
*/
public Date getLastSaveDateTime()
/**
* <p>Sets the total time spent in editing the document.</p>
- *
+ *
* @param time The time to set.
*/
public void setLastSaveDateTime(final Date time)
/**
* <p>Returns the page count or 0 if the {@link SummaryInformation} does
* not contain a page count.</p>
- *
+ *
* @return The page count or 0 if the {@link SummaryInformation} does not
* contain a page count.
*/
/**
* <p>Sets the page count.</p>
- *
+ *
* @param pageCount The page count to set.
*/
public void setPageCount(final int pageCount)
/**
* <p>Returns the word count or 0 if the {@link SummaryInformation} does
* not contain a word count.</p>
- *
+ *
* @return The word count or <code>null</code>
*/
public int getWordCount()
/**
* <p>Sets the word count.</p>
- *
+ *
* @param wordCount The word count to set.
*/
public void setWordCount(final int wordCount)
/**
* <p>Returns the character count or 0 if the {@link SummaryInformation}
* does not contain a char count.</p>
- *
+ *
* @return The character count or <code>null</code>
*/
public int getCharCount()
/**
* <p>Sets the character count.</p>
- *
+ *
* @param charCount The character count to set.
*/
public void setCharCount(final int charCount)
* <p>Returns the thumbnail (or <code>null</code>) <strong>when this
* method is implemented. Please note that the return type is likely to
* change!</strong></p>
- *
+ *
* <p><strong>Hint to developers:</strong> Drew Varner <Drew.Varner
* -at- sc.edu> said that this is an image in WMF or Clipboard (BMP?)
* format. However, we won't do any conversion into any image type but
* instead just return a byte array.</p>
- *
+ *
* @return The thumbnail or <code>null</code>
*/
public byte[] getThumbnail()
/**
* <p>Sets the thumbnail.</p>
- *
+ *
* @param thumbnail The thumbnail to set.
*/
public void setThumbnail(final byte[] thumbnail)
/**
* <p>Returns the application name (or <code>null</code>).</p>
- *
+ *
* @return The application name or <code>null</code>
*/
public String getApplicationName()
/**
* <p>Sets the application name.</p>
- *
+ *
* @param applicationName The application name to set.
*/
public void setApplicationName(final String applicationName)
/**
* <p>Returns a security code which is one of the following values:</p>
- *
+ *
* <ul>
- *
+ *
* <li><p>0 if the {@link SummaryInformation} does not contain a
* security field or if there is no security on the document. Use
* {@link PropertySet#wasNull()} to distinguish between the two
* cases!</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>4 if the document is read-only enforced</p></li>
- *
+ *
* <li><p>8 if the document is locked for annotations</p></li>
- *
+ *
* </ul>
- *
+ *
* @return The security code or <code>null</code>
*/
public int getSecurity()
/**
* <p>Sets the security code.</p>
- *
+ *
* @param security The security code to set.
*/
public void setSecurity(final int security)
* @author Drew Varner (Drew.Varner inOrAround sc.edu)
* @see SummaryInformation#getThumbnail()
*/
-public class Thumbnail
-{
+public final class Thumbnail {
/**
* <p>Offset in bytes where the Clipboard Format Tag starts in the
* <p>A <code>byte[]</code> to hold a thumbnail image in ({@link
* Variant#VT_CF VT_CF}) format.</p>
*/
- private byte[] thumbnailData = null;
+ private byte[] _thumbnailData = null;
*/
public Thumbnail(final byte[] thumbnailData)
{
- this.thumbnailData = thumbnailData;
+ this._thumbnailData = thumbnailData;
}
*/
public byte[] getThumbnail()
{
- return thumbnailData;
+ return _thumbnailData;
}
*/
public void setThumbnail(final byte[] thumbnail)
{
- this.thumbnailData = thumbnail;
+ this._thumbnailData = thumbnail;
}
if (!(getClipboardFormatTag() == CFTAG_WINDOWS))
throw new HPSFException("Clipboard Format Tag of Thumbnail must " +
"be CFTAG_WINDOWS.");
- if (!(getClipboardFormat() == CF_METAFILEPICT))
+ if (!(getClipboardFormat() == CF_METAFILEPICT)) {
throw new HPSFException("Clipboard Format of Thumbnail must " +
"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;
}
-
}
};
/**
- * <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]";
final long pid)
{
final PropertyIDMap m = getInstance().get(sectionFormatID);
- if (m == null)
+ if (m == null) {
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;
}
/**
* <p>Returns the {@link PropertyIDMap} for a given section format
* ID.</p>
- *
+ *
* @param sectionFormatID the section format ID
* @return the property ID map
*/
/**
* <p>Associates a section format ID with a {@link
* PropertyIDMap}.</p>
- *
+ *
* @param sectionFormatID the section format ID
* @param propertyIDMap the property ID map
* @return as defined by {@link java.util.Map#put}
* @deprecated Use {@link #put(byte[], PropertyIDMap)} instead!
*
* @see #put(byte[], PropertyIDMap)
- *
+ *
* @param key This parameter remains undocumented since the method is
* deprecated.
* @param value This parameter remains undocumented since the method is
}
//ERFListener
- public boolean processRecord(Record rec)
- {
- if (rec.getSid() == BOFRecord.sid) {
- if (lastEOF != true) {
- throw new RuntimeException("Not yet handled embedded models");
- } else {
- BOFRecord bof = (BOFRecord)rec;
- switch (bof.getType()) {
- case BOFRecord.TYPE_WORKBOOK:
- currentmodel = new Workbook();
- break;
- case BOFRecord.TYPE_WORKSHEET:
- currentmodel = Sheet.createSheet();
- break;
- default:
+ public boolean processRecord(Record rec) {
+ if (rec.getSid() == BOFRecord.sid) {
+ if (lastEOF != true) {
+ throw new RuntimeException("Not yet handled embedded models");
+ }
+ BOFRecord bof = (BOFRecord)rec;
+ switch (bof.getType()) {
+ case BOFRecord.TYPE_WORKBOOK:
+ currentmodel = new Workbook();
+ break;
+ case BOFRecord.TYPE_WORKSHEET:
+ currentmodel = Sheet.createSheet();
+ break;
+ default:
throw new RuntimeException("Unsupported model type "+bof.getType());
- }
-
- }
+ }
}
if (rec.getSid() == EOFRecord.sid) {
} else {
lastEOF = false;
}
-
-
return true;
}
mfl.process(model);
}
}
-
-
}
import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
/**
- * A proxy HSSFListener that keeps track of the document
- * formatting records, and provides an easy way to look
- * up the format strings used by cells from their ids.
+ * A proxy HSSFListener that keeps track of the document formatting records, and
+ * provides an easy way to look up the format strings used by cells from their
+ * ids.
*/
public class FormatTrackingHSSFListener implements HSSFListener {
- private HSSFListener childListener;
- private HSSFDataFormatter formatter = new HSSFDataFormatter();
- private Map customFormatRecords = new Hashtable();
- private List xfRecords = new ArrayList();
+ private final HSSFListener _childListener;
+ private HSSFDataFormatter _formatter = new HSSFDataFormatter();
+ private final Map<Integer, FormatRecord> _customFormatRecords = new Hashtable<Integer, FormatRecord>();
+ private final List<ExtendedFormatRecord> _xfRecords = new ArrayList<ExtendedFormatRecord>();
public FormatTrackingHSSFListener(HSSFListener childListener) {
- this.childListener = childListener;
+ _childListener = childListener;
}
-
+
protected int getNumberOfCustomFormats() {
- return customFormatRecords.size();
+ return _customFormatRecords.size();
}
+
protected int getNumberOfExtendedFormats() {
- return xfRecords.size();
+ return _xfRecords.size();
}
-
+
/**
- * Process this record ourselves, and then
- * pass it on to our child listener
+ * Process this record ourselves, and then pass it on to our child listener
*/
public void processRecord(Record record) {
// Handle it ourselves
processRecordInternally(record);
-
+
// Now pass on to our child
- childListener.processRecord(record);
+ _childListener.processRecord(record);
}
-
+
/**
- * Process the record ourselves, but do not
- * pass it on to the child Listener.
+ * Process the record ourselves, but do not pass it on to the child
+ * Listener.
+ *
* @param record
*/
public void processRecordInternally(Record record) {
- if(record instanceof FormatRecord) {
+ if (record instanceof FormatRecord) {
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;
- xfRecords.add(xr);
+ _xfRecords.add(xr);
}
}
-
+
/**
- * Formats the given numeric of date Cell's contents
- * as a String, in as close as we can to the way
- * that Excel would do so.
- * Uses the various format records to manage this.
- *
- * TODO - move this to a central class in such a
- * way that hssf.usermodel can make use of it too
+ * Formats the given numeric of date Cell's contents as a String, in as
+ * close as we can to the way that Excel would do so. Uses the various
+ * format records to manage this.
+ *
+ * TODO - move this to a central class in such a way that hssf.usermodel can
+ * make use of it too
*/
public String formatNumberDateCell(CellValueRecordInterface cell) {
double value;
- if(cell instanceof NumberRecord) {
- value = ((NumberRecord)cell).getValue();
- } else if(cell instanceof FormulaRecord) {
- value = ((FormulaRecord)cell).getValue();
+ if (cell instanceof NumberRecord) {
+ value = ((NumberRecord) cell).getValue();
+ } else if (cell instanceof FormulaRecord) {
+ value = ((FormulaRecord) cell).getValue();
} else {
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);
String formatString = getFormatString(cell);
-
- if(formatString == null) {
- return Double.toString(value);
- } else {
- // Format, using the nice new
- // HSSFDataFormatter to do the work for us
- return formatter.formatRawCellContents(value, formatIndex, formatString);
- }
+
+ if (formatString == null) {
+ return Double.toString(value);
+ }
+ // Format, using the nice new
+ // HSSFDataFormatter to do the work for us
+ return _formatter.formatRawCellContents(value, formatIndex, formatString);
}
-
+
/**
- * Returns the format string, eg $##.##, for the
- * given number format index.
+ * Returns the format string, eg $##.##, for the given number format index.
*/
public String getFormatString(int formatIndex) {
- String format = null;
- if(formatIndex >= HSSFDataFormat.getNumberOfBuiltinBuiltinFormats()) {
- FormatRecord tfr = (FormatRecord)customFormatRecords.get(new Integer(formatIndex));
- if(tfr == null) {
- System.err.println("Requested format at index " + formatIndex + ", but it wasn't found");
- } else {
- format = tfr.getFormatString();
- }
- } else {
- format = HSSFDataFormat.getBuiltinFormat((short)formatIndex);
- }
+ String format = null;
+ if (formatIndex >= HSSFDataFormat.getNumberOfBuiltinBuiltinFormats()) {
+ FormatRecord tfr = _customFormatRecords.get(new Integer(formatIndex));
+ if (tfr == null) {
+ System.err.println("Requested format at index " + formatIndex
+ + ", but it wasn't found");
+ } else {
+ format = tfr.getFormatString();
+ }
+ } else {
+ format = HSSFDataFormat.getBuiltinFormat((short) formatIndex);
+ }
return format;
}
-
+
/**
- * Returns the format string, eg $##.##, used
- * by your cell
+ * Returns the format string, eg $##.##, used by your cell
*/
public String getFormatString(CellValueRecordInterface cell) {
int formatIndex = getFormatIndex(cell);
- if(formatIndex == -1) {
- // Not found
- return null;
- }
- return getFormatString(formatIndex);
+ if (formatIndex == -1) {
+ // Not found
+ return null;
+ }
+ return getFormatString(formatIndex);
}
-
+
/**
- * Returns the index of the format string, used by your cell,
- * or -1 if none found
+ * Returns the index of the format string, used by your cell, or -1 if none
+ * found
*/
public int getFormatIndex(CellValueRecordInterface cell) {
- ExtendedFormatRecord xfr = (ExtendedFormatRecord)
- xfRecords.get(cell.getXFIndex());
- if(xfr == null) {
- System.err.println("Cell " + cell.getRow() + "," + cell.getColumn() + " uses XF with index " + cell.getXFIndex() + ", but we don't have that");
- return -1;
- }
- return xfr.getFormatIndex();
+ ExtendedFormatRecord xfr = _xfRecords.get(cell.getXFIndex());
+ if (xfr == null) {
+ System.err.println("Cell " + cell.getRow() + "," + cell.getColumn()
+ + " uses XF with index " + cell.getXFIndex() + ", but we don't have that");
+ return -1;
+ }
+ return xfr.getFormatIndex();
}
}
* 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 {
- private POIFSFileSystem fs;
- private boolean includeSheetNames = true;
- private boolean formulasNotResults = false;
+ private POIFSFileSystem _fs;
+ boolean _includeSheetNames = true;
+ boolean _formulasNotResults = false;
public EventBasedExcelExtractor(POIFSFileSystem fs) {
super(null);
- this.fs = fs;
+ _fs = fs;
}
/**
* Should sheet names be included? Default is true
*/
public void setIncludeSheetNames(boolean includeSheetNames) {
- this.includeSheetNames = includeSheetNames;
+ _includeSheetNames = includeSheetNames;
}
/**
* Should we return the formula itself, and not
* the result it produces? Default is false
*/
public void setFormulasNotResults(boolean formulasNotResults) {
- this.formulasNotResults = formulasNotResults;
+ _formulasNotResults = formulasNotResults;
}
try {
TextListener tl = triggerExtraction();
- text = tl.text.toString();
+ text = tl._text.toString();
if(! text.endsWith("\n")) {
text = text + "\n";
}
private TextListener triggerExtraction() throws IOException {
TextListener tl = new TextListener();
FormatTrackingHSSFListener ft = new FormatTrackingHSSFListener(tl);
- tl.ft = ft;
+ tl._ft = ft;
// Register and process
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
request.addListenerForAllRecords(ft);
- factory.processWorkbookEvents(request, fs);
+ factory.processWorkbookEvents(request, _fs);
return tl;
}
private class TextListener implements HSSFListener {
- private FormatTrackingHSSFListener ft;
+ FormatTrackingHSSFListener _ft;
private SSTRecord sstRecord;
- private List sheetNames = new ArrayList();
- private StringBuffer text = new StringBuffer();
+ private final List<String> sheetNames;
+ final StringBuffer _text = new StringBuffer();
private int sheetNum = -1;
private int rowNum;
private boolean outputNextStringValue = false;
private int nextRow = -1;
+ public TextListener() {
+ sheetNames = new ArrayList<String>();
+ }
public void processRecord(Record record) {
String thisText = null;
int thisRow = -1;
sheetNum++;
rowNum = -1;
- if(includeSheetNames) {
- if(text.length() > 0) text.append("\n");
- text.append(sheetNames.get(sheetNum));
+ if(_includeSheetNames) {
+ if(_text.length() > 0) _text.append("\n");
+ _text.append(sheetNames.get(sheetNum));
}
}
break;
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
- if(formulasNotResults) {
+ if(_formulasNotResults) {
thisText = HSSFFormulaParser.toFormulaString((HSSFWorkbook)null, frec.getParsedExpression());
} else {
if(frec.hasCachedResultString()) {
if(thisText != null) {
if(thisRow != rowNum) {
rowNum = thisRow;
- if(text.length() > 0)
- text.append("\n");
+ if(_text.length() > 0)
+ _text.append("\n");
} else {
- text.append("\t");
+ _text.append("\t");
}
- text.append(thisText);
+ _text.append(thisText);
}
}
*/
private String formatNumberDateCell(CellValueRecordInterface cell, double value) {
// Get the built in format, if there is one
- int formatIndex = ft.getFormatIndex(cell);
- String formatString = ft.getFormatString(cell);
+ int formatIndex = _ft.getFormatIndex(cell);
+ String formatString = _ft.getFormatString(cell);
if(formatString == null) {
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);
- }
+ }
+ // 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 number
- DecimalFormat df = new DecimalFormat(formatString);
- return df.format(value);
- }
+ // 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);
}
}
}
anchor.setDy2( (short) a.getDy2() );
return anchor;
}
- else
- {
- HSSFChildAnchor a = (HSSFChildAnchor) userAnchor;
- EscherChildAnchorRecord anchor = new EscherChildAnchorRecord();
- anchor.setRecordId( EscherChildAnchorRecord.RECORD_ID );
- anchor.setOptions( (short) 0x0000 );
- anchor.setDx1( (short) Math.min(a.getDx1(), a.getDx2()) );
- anchor.setDy1( (short) Math.min(a.getDy1(), a.getDy2()) );
- anchor.setDx2( (short) Math.max(a.getDx2(), a.getDx1()) );
- anchor.setDy2( (short) Math.max(a.getDy2(), a.getDy1()) );
- return anchor;
- }
+ HSSFChildAnchor a = (HSSFChildAnchor) userAnchor;
+ EscherChildAnchorRecord anchor = new EscherChildAnchorRecord();
+ anchor.setRecordId( EscherChildAnchorRecord.RECORD_ID );
+ anchor.setOptions( (short) 0x0000 );
+ anchor.setDx1( (short) Math.min(a.getDx1(), a.getDx2()) );
+ anchor.setDy1( (short) Math.min(a.getDy1(), a.getDy2()) );
+ anchor.setDx2( (short) Math.max(a.getDx2(), a.getDx1()) );
+ anchor.setDy2( (short) Math.max(a.getDy2(), a.getDy1()) );
+ return anchor;
}
-
}
System.arraycopy( rawData, 0, data, 4 + offset, rawData.length);
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;
- for ( Iterator iterator = escherRecords.iterator(); iterator.hasNext(); )
- {
- EscherRecord r = (EscherRecord) iterator.next();
- pos += r.serialize( pos, data, new NullEscherSerializationListener() );
- }
+ int pos = offset + 4;
+ for ( Iterator iterator = escherRecords.iterator(); iterator.hasNext(); )
+ {
+ EscherRecord r = (EscherRecord) iterator.next();
+ pos += r.serialize( pos, data, new NullEscherSerializationListener() );
}
return getRecordSize();
}
{
escherRecords.clear();
}
-
+
/**
* If we have a EscherContainerRecord as one of our
* children (and most top level escher holders do),
return r;
}
}
-
+
// Then check our children in turn
for(Iterator<EscherRecord> it = records.iterator(); it.hasNext();) {
EscherRecord r = it.next();
}
}
}
-
+
// Not found in this lot
return null;
}
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_18_formula2;
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
- fontFormatting=null;
- borderFormatting=null;
- patternFormatting=null;
+ _fontFormatting=null;
+ _borderFormatting=null;
+ _patternFormatting=null;
field_17_formula1=Formula.create(Ptg.EMPTY_PTG_ARRAY);
field_18_formula2=Formula.create(Ptg.EMPTY_PTG_ARRAY);
}
field_6_not_used = in.readShort();
if (containsFontFormattingBlock()) {
- fontFormatting = new FontFormatting(in);
+ _fontFormatting = new FontFormatting(in);
}
if (containsBorderFormattingBlock()) {
- borderFormatting = new BorderFormatting(in);
+ _borderFormatting = new BorderFormatting(in);
}
if (containsPatternFormattingBlock()) {
- patternFormatting = new PatternFormatting(in);
+ _patternFormatting = new PatternFormatting(in);
}
// "You may not use unions, intersections or array constants in Conditional Formatting criteria"
}
public void setFontFormatting(FontFormatting fontFormatting)
{
- this.fontFormatting = fontFormatting;
+ _fontFormatting = fontFormatting;
setOptionFlag(fontFormatting != null, font);
}
public FontFormatting getFontFormatting()
{
if( containsFontFormattingBlock())
{
- return fontFormatting;
- }
- else
- {
- return null;
+ return _fontFormatting;
}
+ return null;
}
public boolean containsAlignFormattingBlock()
}
public void setBorderFormatting(BorderFormatting borderFormatting)
{
- this.borderFormatting = borderFormatting;
+ _borderFormatting = borderFormatting;
setOptionFlag(borderFormatting != null, bord);
}
public BorderFormatting getBorderFormatting()
{
if( containsBorderFormattingBlock())
{
- return borderFormatting;
- }
- else
- {
- return null;
+ return _borderFormatting;
}
+ return null;
}
public boolean containsPatternFormattingBlock()
}
public void setPatternFormatting(PatternFormatting patternFormatting)
{
- this.patternFormatting = patternFormatting;
+ _patternFormatting = patternFormatting;
setOptionFlag(patternFormatting!=null, patt);
}
public PatternFormatting getPatternFormatting()
{
if( containsPatternFormattingBlock())
{
- return patternFormatting;
- }
- else
- {
- return null;
+ return _patternFormatting;
}
+ return null;
}
public boolean containsProtectionFormattingBlock()
out.writeShort(field_6_not_used);
if (containsFontFormattingBlock()) {
- byte[] fontFormattingRawRecord = fontFormatting.getRawRecord();
+ byte[] fontFormattingRawRecord = _fontFormatting.getRawRecord();
out.write(fontFormattingRawRecord);
}
if (containsBorderFormattingBlock()) {
- borderFormatting.serialize(out);
+ _borderFormatting.serialize(out);
}
if (containsPatternFormattingBlock()) {
- patternFormatting.serialize(out);
+ _patternFormatting.serialize(out);
}
field_17_formula1.serializeTokens(out);
protected int getDataSize() {
return 12 +
- (containsFontFormattingBlock()?fontFormatting.getRawRecord().length:0)+
+ (containsFontFormattingBlock()?_fontFormatting.getRawRecord().length:0)+
(containsBorderFormattingBlock()?8:0)+
(containsPatternFormattingBlock()?4:0)+
getFormulaSize(field_17_formula1)+
buffer.append(" OPTION FLAGS=0x"+Integer.toHexString(getOptions()));
if (false) {
if (containsFontFormattingBlock()) {
- buffer.append(fontFormatting.toString());
+ buffer.append(_fontFormatting.toString());
}
if (containsBorderFormattingBlock()) {
- buffer.append(borderFormatting.toString());
+ buffer.append(_borderFormatting.toString());
}
if (containsPatternFormattingBlock()) {
- buffer.append(patternFormatting.toString());
+ buffer.append(_patternFormatting.toString());
}
buffer.append("[/CFRULE]\n");
}
rec.field_5_options = field_5_options;
rec.field_6_not_used = field_6_not_used;
if (containsFontFormattingBlock()) {
- rec.fontFormatting = (FontFormatting) fontFormatting.clone();
+ rec._fontFormatting = (FontFormatting) _fontFormatting.clone();
}
if (containsBorderFormattingBlock()) {
- rec.borderFormatting = (BorderFormatting) borderFormatting.clone();
+ rec._borderFormatting = (BorderFormatting) _borderFormatting.clone();
}
if (containsPatternFormattingBlock()) {
- rec.patternFormatting = (PatternFormatting) patternFormatting.clone();
+ rec._patternFormatting = (PatternFormatting) _patternFormatting.clone();
}
rec.field_17_formula1 = field_17_formula1.copy();
rec.field_18_formula2 = field_17_formula1.copy();
{
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()];
- int pos = 0;
- for ( Iterator iterator = getEscherRecords().iterator(); iterator.hasNext(); )
- {
- EscherRecord r = (EscherRecord) iterator.next();
- pos += r.serialize(pos, buffer, new NullEscherSerializationListener() );
- }
-
- return writeData( offset, data, buffer );
+ EscherRecord r = (EscherRecord) iterator.next();
+ pos += r.serialize(pos, buffer, new NullEscherSerializationListener() );
}
+
+ return writeData( offset, data, buffer );
}
-
+
/**
* Process the bytes into escher records.
* (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)
*/
public void processChildRecords() {
LittleEndian.putShort(data, 0 + offset, ContinueRecord.sid);
LittleEndian.putShort(data, 2 + offset, (short) sizeExcludingHeader);
}
-
}
* @author Marc Johnson (mjohnson at apache dot 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 byte field_2_optionflags;
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 static final BitField highByte = BitFieldFactory.getInstance(0x1);
private static final BitField extBit = BitFieldFactory.getInstance(0x4);
private static final BitField richText = BitFieldFactory.getInstance(0x8);
- public static class FormatRun implements Comparable {
- short character;
- short fontIndex;
+ public static class FormatRun implements Comparable<FormatRun> {
+ final short _character;
+ short _fontIndex;
public FormatRun(short character, short fontIndex) {
- this.character = character;
- this.fontIndex = fontIndex;
+ this._character = character;
+ this._fontIndex = fontIndex;
}
public FormatRun(LittleEndianInput in) {
}
public short getCharacterPos() {
- return character;
+ return _character;
}
public short getFontIndex() {
- return fontIndex;
+ return _fontIndex;
}
public boolean equals(Object o) {
}
FormatRun other = ( FormatRun ) o;
- return character == other.character && fontIndex == other.fontIndex;
+ return _character == other._character && _fontIndex == other._fontIndex;
}
- public int compareTo(Object obj) {
- FormatRun r = (FormatRun)obj;
- if ((character == r.character) && (fontIndex == r.fontIndex))
+ public int compareTo(FormatRun r) {
+ if (_character == r._character && _fontIndex == r._fontIndex) {
return 0;
- if (character == r.character)
- return fontIndex - r.fontIndex;
- else return character - r.character;
+ }
+ if (_character == r._character) {
+ return _fontIndex - r._fontIndex;
+ }
+ return _character - r._character;
}
public String toString() {
- return "character="+character+",fontIndex="+fontIndex;
+ return "character="+_character+",fontIndex="+_fontIndex;
}
public void serialize(LittleEndianOutput out) {
- out.writeShort(character);
- out.writeShort(fontIndex);
+ out.writeShort(_character);
+ out.writeShort(_fontIndex);
}
}
return false;
for (int i=0;i<size;i++) {
- FormatRun run1 = (FormatRun)field_4_format_runs.get(i);
- FormatRun run2 = (FormatRun)other.field_4_format_runs.get(i);
+ FormatRun run1 = field_4_format_runs.get(i);
+ FormatRun run2 = other.field_4_format_runs.get(i);
if (!run1.equals(run2))
return false;
} else {
field_3_string = in.readUnicodeLEString(getCharCount());
}
-
+
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++) {
field_4_format_runs.add(new FormatRun(in));
}
}
public FormatRun getFormatRun(int index) {
- if (field_4_format_runs == null)
- return null;
- if ((index < 0) || (index >= field_4_format_runs.size()))
- return null;
- return (FormatRun)field_4_format_runs.get(index);
+ if (field_4_format_runs == null) {
+ return null;
+ }
+ if (index < 0 || index >= field_4_format_runs.size()) {
+ return null;
+ }
+ return field_4_format_runs.get(index);
}
private int findFormatRunAt(int characterPos) {
int size = field_4_format_runs.size();
for (int i=0;i<size;i++) {
- FormatRun r = (FormatRun)field_4_format_runs.get(i);
- if (r.character == characterPos)
+ FormatRun r = field_4_format_runs.get(i);
+ if (r._character == characterPos)
return i;
- else if (r.character > characterPos)
+ else if (r._character > characterPos)
return -1;
}
return -1;
* replaced with the font run to be added.
*/
public void addFormatRun(FormatRun r) {
- if (field_4_format_runs == null)
- field_4_format_runs = new ArrayList();
+ if (field_4_format_runs == null) {
+ field_4_format_runs = new ArrayList<FormatRun>();
+ }
- int index = findFormatRunAt(r.character);
+ int index = findFormatRunAt(r._character);
if (index != -1)
field_4_format_runs.remove(index);
field_2_optionflags = richText.setByte(field_2_optionflags);
}
- public Iterator formatIterator() {
- if (field_4_format_runs != null)
+ public Iterator<FormatRun> formatIterator() {
+ if (field_4_format_runs != null) {
return field_4_format_runs.iterator();
+ }
return null;
}
/**
- * 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.
* Normally only called when fonts have been
* removed / re-ordered
*/
public void swapFontUse(short oldFontIndex, short newFontIndex) {
- Iterator i = field_4_format_runs.iterator();
- while(i.hasNext()) {
- FormatRun run = (FormatRun)i.next();
- if(run.fontIndex == oldFontIndex) {
- run.fontIndex = newFontIndex;
+ for (FormatRun run : field_4_format_runs) {
+ if(run._fontIndex == oldFontIndex) {
+ run._fontIndex = newFontIndex;
}
}
}
-
+
/**
* unlike the real records we return the same as "getString()" rather than debug info
* @see #getDebugInfo()
* @return String of output for biffviewer etc.
*
*/
-
public String getDebugInfo()
{
StringBuffer buffer = new StringBuffer();
buffer.append(" .string = ").append(getString()).append("\n");
if (field_4_format_runs != null) {
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");
}
}
if (isExtendedText() && field_5_ext_rst != null) {
extendedDataSize = field_5_ext_rst.length;
}
-
+
out.writeString(field_3_string, numberOfRichTextRuns, extendedDataSize);
if (numberOfRichTextRuns > 0) {
if (out.getAvailableSpace() < 4) {
out.writeContinue();
}
- FormatRun r = (FormatRun)field_4_format_runs.get(i);
+ FormatRun r = field_4_format_runs.get(i);
r.serialize(out);
}
}
}
}
- public int compareTo(Object obj)
- {
- UnicodeString str = ( UnicodeString ) obj;
+ public int compareTo(UnicodeString str) {
int result = getString().compareTo(str.getString());
return size - str.field_4_format_runs.size();
for (int i=0;i<size;i++) {
- FormatRun run1 = (FormatRun)field_4_format_runs.get(i);
- FormatRun run2 = (FormatRun)str.field_4_format_runs.get(i);
+ FormatRun run1 = field_4_format_runs.get(i);
+ FormatRun run2 = str.field_4_format_runs.get(i);
result = run1.compareTo(run2);
if (result != 0)
str.field_2_optionflags = field_2_optionflags;
str.field_3_string = field_3_string;
if (field_4_format_runs != null) {
- str.field_4_format_runs = new ArrayList();
- int size = field_4_format_runs.size();
- for (int i = 0; i < size; i++) {
- FormatRun r = (FormatRun) field_4_format_runs.get(i);
- str.field_4_format_runs.add(new FormatRun(r.character, r.fontIndex));
+ str.field_4_format_runs = new ArrayList<FormatRun>();
+ for (FormatRun r : field_4_format_runs) {
+ str.field_4_format_runs.add(new FormatRun(r._character, r._fontIndex));
}
}
if (field_5_ext_rst != null) {
*/
public class FontDetails
{
- private String fontName;
- private int height;
- private Map charWidths = new HashMap();
+ private String _fontName;
+ private int _height;
+ private final Map<Character, Integer> charWidths = new HashMap<Character, Integer>();
/**
* Construct the font details with the given name and height.
*/
public FontDetails( String fontName, int height )
{
- this.fontName = fontName;
- this.height = height;
+ _fontName = fontName;
+ _height = height;
}
public String getFontName()
{
- return fontName;
+ return _fontName;
}
public int getHeight()
{
- return height;
+ return _height;
}
public void addChar( char c, int width )
public int getCharWidth( char c )
{
Integer widthInteger = (Integer)(charWidths.get(new Character(c)));
- if (widthInteger == null && c != 'W')
+ if (widthInteger == null && c != 'W') {
return getCharWidth('W');
- else
- return widthInteger.intValue();
+ }
+ return widthInteger.intValue();
}
public void addChars( char[] characters, int[] widths )
}
}
- protected static String buildFontHeightProperty(String fontName) {
- return "font." + fontName + ".height";
- }
- protected static String buildFontWidthsProperty(String fontName) {
- return "font." + fontName + ".widths";
- }
- protected static String buildFontCharactersProperty(String fontName) {
- return "font." + fontName + ".characters";
- }
+ protected static String buildFontHeightProperty(String fontName) {
+ return "font." + fontName + ".height";
+ }
+ protected static String buildFontWidthsProperty(String fontName) {
+ return "font." + fontName + ".widths";
+ }
+ protected static String buildFontCharactersProperty(String fontName) {
+ return "font." + fontName + ".characters";
+ }
/**
* Create an instance of <code>FontDetails</code> by loading them from the
return list;
}
-
-
}
/**
* 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 Jason Height (jheight at chariot dot net dot au)
* @see org.apache.poi.hssf.usermodel.HSSFWorkbook#createCellStyle()
* @see org.apache.poi.hssf.usermodel.HSSFWorkbook#getCellStyleAt(short)
* @see org.apache.poi.hssf.usermodel.HSSFCell#setCellStyle(HSSFCellStyle)
*/
-
-public class HSSFCellStyle implements CellStyle
-{
- private ExtendedFormatRecord format = null;
- private short index = 0;
- private Workbook workbook = null;
+public final class HSSFCellStyle implements CellStyle {
+ private ExtendedFormatRecord _format = null;
+ private short _index = 0;
+ private Workbook _workbook = null;
/** Creates new HSSFCellStyle why would you want to do this?? */
}
protected HSSFCellStyle(short index, ExtendedFormatRecord rec, Workbook workbook)
{
- this.workbook = workbook;
- this.index = index;
- format = rec;
+ _workbook = workbook;
+ _index = index;
+ _format = rec;
}
/**
* @return unique index number of the underlying record this style represents (probably you don't care
* unless you're comparing which one is which)
*/
-
public short getIndex()
{
- return index;
+ return _index;
}
-
+
/**
* Return the parent style for this cell style.
* In most cases this will be null, but in a few
* cases there'll be a fully defined parent.
*/
public HSSFCellStyle getParentStyle() {
- if(format.getParentIndex() == 0) {
+ if(_format.getParentIndex() == 0) {
return null;
}
return new HSSFCellStyle(
- format.getParentIndex(),
- workbook.getExFormatAt(format.getParentIndex()),
- workbook
+ _format.getParentIndex(),
+ _workbook.getExFormatAt(_format.getParentIndex()),
+ _workbook
);
}
* set the data format (must be a valid format)
* @see org.apache.poi.hssf.usermodel.HSSFDataFormat
*/
-
public void setDataFormat(short fmt)
{
- format.setFormatIndex(fmt);
+ _format.setFormatIndex(fmt);
}
/**
public short getDataFormat()
{
- return format.getFormatIndex();
+ return _format.getFormatIndex();
}
-
+
/**
* Get the contents of the format string, by looking up
* the DataFormat against the bound workbook
* @return the format string or "General" if not found
*/
public String getDataFormatString() {
- return getDataFormatString(workbook);
+ return getDataFormatString(_workbook);
}
/**
* Get the contents of the format string, by looking up
*/
public String getDataFormatString(org.apache.poi.ss.usermodel.Workbook workbook) {
HSSFDataFormat format = new HSSFDataFormat( ((HSSFWorkbook)workbook).getWorkbook() );
-
+
int idx = getDataFormat();
return idx == -1 ? "General" : format.getFormat(getDataFormat());
}
*/
public String getDataFormatString(org.apache.poi.hssf.model.Workbook workbook) {
HSSFDataFormat format = new HSSFDataFormat( workbook );
-
+
return format.getFormat(getDataFormat());
}
setFont((HSSFFont)font);
}
public void setFont(HSSFFont font) {
- format.setIndentNotParentFont(true);
+ _format.setIndentNotParentFont(true);
short fontindex = font.getIndex();
- format.setFontIndex(fontindex);
+ _format.setFontIndex(fontindex);
}
/**
*/
public short getFontIndex()
{
- return format.getFontIndex();
+ return _format.getFontIndex();
}
-
+
/**
* gets the font for this style
* @param parentWorkbook The HSSFWorkbook that this style belongs to
* set the cell's using this style to be hidden
* @param hidden - whether the cell using this style should be hidden
*/
-
public void setHidden(boolean hidden)
{
- format.setIndentNotParentCellOptions(true);
- format.setHidden(hidden);
+ _format.setIndentNotParentCellOptions(true);
+ _format.setHidden(hidden);
}
/**
* get whether the cell's using this style are to be hidden
* @return hidden - whether the cell using this style should be hidden
*/
-
public boolean getHidden()
{
- return format.isHidden();
+ return _format.isHidden();
}
/**
* set the cell's using this style to be locked
* @param locked - whether the cell using this style should be locked
*/
-
public void setLocked(boolean locked)
{
- format.setIndentNotParentCellOptions(true);
- format.setLocked(locked);
+ _format.setIndentNotParentCellOptions(true);
+ _format.setLocked(locked);
}
/**
* get whether the cell's using this style are to be locked
* @return hidden - whether the cell using this style should be locked
*/
-
public boolean getLocked()
{
- return format.isLocked();
+ return _format.isLocked();
}
/**
* @see #ALIGN_JUSTIFY
* @see #ALIGN_CENTER_SELECTION
*/
-
public void setAlignment(short align)
{
- format.setIndentNotParentAlignment(true);
- format.setAlignment(align);
+ _format.setIndentNotParentAlignment(true);
+ _format.setAlignment(align);
}
/**
* @see #ALIGN_JUSTIFY
* @see #ALIGN_CENTER_SELECTION
*/
-
public short getAlignment()
{
- return format.getAlignment();
+ return _format.getAlignment();
}
/**
* set whether the text should be wrapped
* @param wrapped wrap text or not
*/
-
public void setWrapText(boolean wrapped)
{
- format.setIndentNotParentAlignment(true);
- format.setWrapText(wrapped);
+ _format.setIndentNotParentAlignment(true);
+ _format.setWrapText(wrapped);
}
/**
* get whether the text should be wrapped
* @return wrap text or not
*/
-
public boolean getWrapText()
{
- return format.getWrapText();
+ return _format.getWrapText();
}
/**
* @see #VERTICAL_BOTTOM
* @see #VERTICAL_JUSTIFY
*/
-
public void setVerticalAlignment(short align)
{
- format.setVerticalAlignment(align);
+ _format.setVerticalAlignment(align);
}
/**
* @see #VERTICAL_BOTTOM
* @see #VERTICAL_JUSTIFY
*/
-
public short getVerticalAlignment()
{
- return format.getVerticalAlignment();
+ return _format.getVerticalAlignment();
}
/**
* set the degree of rotation for the text in the cell
* @param rotation degrees (between -90 and 90 degrees)
*/
-
public void setRotation(short rotation)
{
if ((rotation < 0)&&(rotation >= -90)) {
else if ((rotation < -90) ||(rotation > 90))
//Do not allow an incorrect rotation to be set
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
* @return rotation degrees (between -90 and 90 degrees)
*/
-
public short getRotation()
{
- short rotation = format.getRotation();
+ short rotation = _format.getRotation();
if (rotation > 90)
//This is actually the 4th quadrant
rotation = (short)(90-rotation);
* set the number of spaces to indent the text in the cell
* @param indent - number of spaces
*/
-
public void setIndention(short indent)
{
- format.setIndent(indent);
+ _format.setIndent(indent);
}
/**
* get the number of spaces to indent the text in the cell
* @return indent - number of spaces
*/
-
public short getIndention()
{
- return format.getIndent();
+ return _format.getIndent();
}
/**
* @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT
*/
-
public void setBorderLeft(short border)
{
- format.setIndentNotParentBorder(true);
- format.setBorderLeft(border);
+ _format.setIndentNotParentBorder(true);
+ _format.setBorderLeft(border);
}
/**
* @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT
*/
-
public short getBorderLeft()
{
- return format.getBorderLeft();
+ return _format.getBorderLeft();
}
/**
* @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT
*/
-
public void setBorderRight(short border)
{
- format.setIndentNotParentBorder(true);
- format.setBorderRight(border);
+ _format.setIndentNotParentBorder(true);
+ _format.setBorderRight(border);
}
/**
* @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT
*/
-
public short getBorderRight()
{
- return format.getBorderRight();
+ return _format.getBorderRight();
}
/**
* @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT
*/
-
public void setBorderTop(short border)
{
- format.setIndentNotParentBorder(true);
- format.setBorderTop(border);
+ _format.setIndentNotParentBorder(true);
+ _format.setBorderTop(border);
}
/**
* @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT
*/
-
public short getBorderTop()
{
- return format.getBorderTop();
+ return _format.getBorderTop();
}
/**
* @see #BORDER_MEDIUM_DASH_DOT_DOT
* @see #BORDER_SLANTED_DASH_DOT
*/
-
public void setBorderBottom(short border)
{
- format.setIndentNotParentBorder(true);
- format.setBorderBottom(border);
+ _format.setIndentNotParentBorder(true);
+ _format.setBorderBottom(border);
}
/**
*/
public short getBorderBottom()
{
- return format.getBorderBottom();
+ return _format.getBorderBottom();
}
/**
*/
public void setLeftBorderColor(short color)
{
- format.setLeftBorderPaletteIdx(color);
+ _format.setLeftBorderPaletteIdx(color);
}
/**
*/
public short getLeftBorderColor()
{
- return format.getLeftBorderPaletteIdx();
+ return _format.getLeftBorderPaletteIdx();
}
/**
*/
public void setRightBorderColor(short color)
{
- format.setRightBorderPaletteIdx(color);
+ _format.setRightBorderPaletteIdx(color);
}
/**
*/
public short getRightBorderColor()
{
- return format.getRightBorderPaletteIdx();
+ return _format.getRightBorderPaletteIdx();
}
/**
*/
public void setTopBorderColor(short color)
{
- format.setTopBorderPaletteIdx(color);
+ _format.setTopBorderPaletteIdx(color);
}
/**
*/
public short getTopBorderColor()
{
- return format.getTopBorderPaletteIdx();
+ return _format.getTopBorderPaletteIdx();
}
/**
*/
public void setBottomBorderColor(short color)
{
- format.setBottomBorderPaletteIdx(color);
+ _format.setBottomBorderPaletteIdx(color);
}
/**
*/
public short getBottomBorderColor()
{
- return format.getBottomBorderPaletteIdx();
+ return _format.getBottomBorderPaletteIdx();
}
/**
*/
public void setFillPattern(short fp)
{
- format.setAdtlFillPattern(fp);
+ _format.setAdtlFillPattern(fp);
}
/**
* get the fill pattern (??) - set to 1 to fill with foreground color
* @return fill pattern
*/
-
public short getFillPattern()
{
- return format.getAdtlFillPattern();
+ return _format.getAdtlFillPattern();
}
-
+
/**
* Checks if the background and foreground fills are set correctly when one
* or the other is set to the default color.
* <p>NONE AUTOMATIC</p>
* <p>0x41 0x40</p>
* <p>NONE RED/ANYTHING</p>
- * <p>0x40 0xSOMETHING</p>
+ * <p>0x40 0xSOMETHING</p>
*/
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
//to me now.... But experience has shown that when the fore is set to AUTOMATIC then the
//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));
- } 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!!!
- 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);
}
* For example:
* <pre>
* cs.setFillPattern(HSSFCellStyle.FINE_DOTS );
- * cs.setFillBackgroundColor(new HSSFColor.RED().getIndex());
+ * cs.setFillBackgroundColor(new HSSFColor.RED().getIndex());
* </pre>
* optionally a Foreground and background fill can be applied:
* <i>Note: Ensure Foreground color is set prior to background</i>
* <pre>
* cs.setFillPattern(HSSFCellStyle.FINE_DOTS );
* cs.setFillForegroundColor(new HSSFColor.BLUE().getIndex());
- * cs.setFillBackgroundColor(new HSSFColor.RED().getIndex());
+ * cs.setFillBackgroundColor(new HSSFColor.RED().getIndex());
* </pre>
* or, for the special case of SOLID_FILL:
* <pre>
*
* @param bg color
*/
-
public void setFillBackgroundColor(short bg)
- {
- format.setFillBackground(bg);
+ {
+ _format.setFillBackground(bg);
checkDefaultBackgroundFills();
}
*/
public short getFillBackgroundColor()
{
- short result = format.getFillBackground();
+ short result = _format.getFillBackground();
//JMH: Do this ridiculous conversion, and let HSSFCellStyle
//internally migrate back and forth
- if (result == (HSSFColor.AUTOMATIC.index+1))
- return HSSFColor.AUTOMATIC.index;
- else return result;
+ if (result == (HSSFColor.AUTOMATIC.index+1)) {
+ return HSSFColor.AUTOMATIC.index;
+ }
+ return result;
}
/**
*/
public void setFillForegroundColor(short bg)
{
- format.setFillForeground(bg);
+ _format.setFillForeground(bg);
checkDefaultBackgroundFills();
}
/**
* 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()})
* @see org.apache.poi.hssf.usermodel.HSSFPalette#getColor(short)
* @return fill color
*/
public short getFillForegroundColor()
{
- return format.getFillForeground();
+ return _format.getFillForeground();
}
-
+
/**
* Gets the name of the user defined style.
* Returns null for built in styles, and
* styles where no name has been defined
*/
public String getUserStyleName() {
- StyleRecord sr = workbook.getStyleRecord(index);
+ StyleRecord sr = _workbook.getStyleRecord(_index);
if(sr == null) {
return null;
}
}
return sr.getName();
}
-
+
/**
* Sets the name of the user defined style.
* Will complain if you try this on a built in style.
*/
public void setUserStyleName(String styleName) {
- StyleRecord sr = workbook.getStyleRecord(index);
+ StyleRecord sr = _workbook.getStyleRecord(_index);
if(sr == null) {
- sr = workbook.createStyleRecord(index);
+ sr = _workbook.createStyleRecord(_index);
}
if(sr.isBuiltin()) {
throw new IllegalArgumentException("Unable to set user specified style names for built in styles!");
* @throws IllegalArgumentException if there's a workbook mis-match
*/
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?");
}
}
-
+
/**
* Clones all the style information from another
- * HSSFCellStyle, onto this one. This
+ * HSSFCellStyle, onto this one. This
* HSSFCellStyle will then have all the same
* properties as the source, but the two may
* 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
* HSSFWorkbook if you like. This allows you to
* copy styles from one HSSFWorkbook to another.
public void cloneStyleFrom(HSSFCellStyle source) {
// First we need to clone the extended format
// record
- format.cloneStyleFrom(source.format);
-
+ _format.cloneStyleFrom(source._format);
+
// Handle matching things if we cross workbooks
- if(workbook != source.workbook) {
+ if(_workbook != source._workbook) {
// Then we need to clone the format string,
// and update the format record for this
- short fmt = (short)workbook.createFormat(source.getDataFormatString() );
+ short fmt = (short)_workbook.createFormat(source.getDataFormatString() );
setDataFormat(fmt);
-
+
// Finally we need to clone the font,
// and update the format record for this
- FontRecord fr = workbook.createNewFont();
+ FontRecord fr = _workbook.createNewFont();
fr.cloneStyleFrom(
- source.workbook.getFontRecordAt(
+ source._workbook.getFontRecordAt(
source.getFontIndex()
)
);
-
+
HSSFFont font = new HSSFFont(
- (short)workbook.getFontIndex(fr), fr
+ (short)_workbook.getFontIndex(fr), fr
);
setFont(font);
- }
+ }
}
-
+
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result + ((format == null) ? 0 : format.hashCode());
- result = prime * result + index;
+ result = prime * result + ((_format == null) ? 0 : _format.hashCode());
+ result = prime * result + _index;
return result;
}
if (obj == null) return false;
if (obj instanceof HSSFCellStyle) {
final HSSFCellStyle other = (HSSFCellStyle) obj;
- if (format == null) {
- if (other.format != null)
+ if (_format == null) {
+ if (other._format != null)
return false;
- } else if (!format.equals(other.format))
+ } else if (!_format.equals(other._format))
return false;
- if (index != other.index)
+ if (_index != other._index)
return false;
return true;
}
*
* @author Glen Stampoultzis (glens at apache.org)
*/
-public class HSSFClientAnchor
- extends HSSFAnchor implements ClientAnchor
-{
+public final class HSSFClientAnchor extends HSSFAnchor implements ClientAnchor {
short col1;
int row1;
short col2;
private float getRowHeightInPoints(HSSFSheet sheet, int rowNum)
{
HSSFRow row = sheet.getRow(rowNum);
- if (row == null)
+ if (row == null) {
return sheet.getDefaultRowHeightInPoints();
- else
- return row.getHeightInPoints();
+ }
+ return row.getHeightInPoints();
}
public short getCol1()
*/
public boolean isHorizontallyFlipped()
{
- if (col1 == col2)
+ if (col1 == col2) {
return dx1 > dx2;
- else
- return col1 > col2;
+ }
+ return col1 > col2;
}
/**
*/
public boolean isVerticallyFlipped()
{
- if (row1 == row2)
+ if (row1 == row2) {
return dy1 > dy2;
- else
- return row1 > row2;
+ }
+ return row1 > row2;
}
/**
import org.apache.poi.hssf.record.EmbeddedObjectRefSubRecord;
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.Entry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
*
* @author Daniel Noll
*/
-public final class HSSFObjectData
-{
+public final class HSSFObjectData {
/**
* 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.
*/
- private POIFSFileSystem poifs;
+ private final POIFSFileSystem _poifs;
/**
* Constructs object data by wrapping a lower level object record.
*/
public HSSFObjectData(ObjRecord record, POIFSFileSystem poifs)
{
- this.record = record;
- this.poifs = poifs;
+ _record = record;
+ _poifs = poifs;
}
-
+
/**
* Returns the OLE2 Class Name of the object
*/
int streamId = subRecord.getStreamId().intValue();
String streamName = "MBD" + HexDump.toHex(streamId);
- Entry entry = poifs.getRoot().getEntry(streamName);
+ Entry entry = _poifs.getRoot().getEntry(streamName);
if (entry instanceof DirectoryEntry) {
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
* that doesn't have an associated POIFS Directory
public byte[] getObjectData() {
return findObjectRecord().getObjectData();
}
-
+
/**
- * Does this ObjectData have an associated POIFS
+ * Does this ObjectData have an associated POIFS
* Directory Entry?
* (Not all do, those that don't have a data portion)
*/
public boolean hasDirectoryEntry() {
EmbeddedObjectRefSubRecord subRecord = findObjectRecord();
-
+
// 'stream id' field tells you
Integer streamId = subRecord.getStreamId();
return streamId != null && streamId.intValue() != 0;
}
-
+
/**
- * Finds the EmbeddedObjectRefSubRecord, or throws an
+ * Finds the EmbeddedObjectRefSubRecord, or throws an
* Exception if there wasn't one
*/
protected EmbeddedObjectRefSubRecord findObjectRecord() {
- Iterator subRecordIter = record.getSubRecords().iterator();
-
+ Iterator<SubRecord> subRecordIter = _record.getSubRecords().iterator();
+
while (subRecordIter.hasNext()) {
Object subRecord = subRecordIter.next();
if (subRecord instanceof EmbeddedObjectRefSubRecord) {
return (EmbeddedObjectRefSubRecord)subRecord;
}
}
-
+
throw new IllegalStateException("Object data does not contain a reference to an embedded object OLE2 directory");
}
}
* @author Glen Stampoultzis (glens at apache.org)
* @author Jason Height (jheight at apache.org)
*/
-public class HSSFRichTextString
- implements Comparable, RichTextString
-{
+public final class HSSFRichTextString implements Comparable<HSSFRichTextString>, RichTextString {
/** Place holder for indicating that NO_FONT has been applied here */
public static final short NO_FONT = 0;
- private UnicodeString string;
- private Workbook book;
- private LabelSSTRecord record;
+ private UnicodeString _string;
+ private Workbook _book;
+ private LabelSSTRecord _record;
public HSSFRichTextString()
{
this("");
}
- public HSSFRichTextString( String string )
- {
- if (string == null)
- string = "";
- this.string = new UnicodeString(string);
+ public HSSFRichTextString(String string) {
+ if (string == null) {
+ _string = new UnicodeString("");
+ } else {
+ _string = new UnicodeString(string);
+ }
}
HSSFRichTextString(Workbook book, LabelSSTRecord 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
* a RichTextString is added to a cell
- */
+ */
void setWorkbookReferences(Workbook book, LabelSSTRecord record) {
- this.book = book;
- this.record = record;
+ _book = book;
+ _record = record;
}
-
+
/** 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
* be affected by changes that we make to this string.
*/
private UnicodeString cloneStringIfRequired() {
- if (book == null)
- return string;
- UnicodeString s = (UnicodeString)string.clone();
+ if (_book == null)
+ return _string;
+ UnicodeString s = (UnicodeString)_string.clone();
return s;
}
private void addToSSTIfRequired() {
- if (book != null) {
- int index = book.addSSTString(string);
- record.setSSTIndex(index);
+ if (_book != null) {
+ int index = _book.addSSTString(_string);
+ _record.setSSTIndex(index);
//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
- string = book.getSSTString(index);
+ //an existing string was returned for the index, so update our local version
+ _string = _book.getSSTString(index);
}
}
}
//Need to clear the current formatting between the startIndex and endIndex
- string = cloneStringIfRequired();
- Iterator formatting = string.formatIterator();
+ _string = cloneStringIfRequired();
+ Iterator formatting = _string.formatIterator();
if (formatting != null) {
while (formatting.hasNext()) {
UnicodeString.FormatRun r = (UnicodeString.FormatRun)formatting.next();
}
- string.addFormatRun(new UnicodeString.FormatRun((short)startIndex, fontIndex));
+ _string.addFormatRun(new UnicodeString.FormatRun((short)startIndex, fontIndex));
if (endIndex != length())
- string.addFormatRun(new UnicodeString.FormatRun((short)endIndex, currentFont));
-
+ _string.addFormatRun(new UnicodeString.FormatRun((short)endIndex, currentFont));
+
addToSSTIfRequired();
}
*/
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.
*/
public void clearFormatting() {
- string = cloneStringIfRequired();
- string.clearFormatting();
+ _string = cloneStringIfRequired();
+ _string.clearFormatting();
addToSSTIfRequired();
}
*/
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.
* Will ensure the string is not shared
*/
UnicodeString getUnicodeString() {
return cloneStringIfRequired();
}
-
+
/**
- * Returns the raw, probably shared Unicode String.
- * Used when tweaking the styles, eg updating font
+ * Returns the raw, probably shared Unicode String.
+ * Used when tweaking the styles, eg updating font
* positions.
* Changes to this string may well effect
- * other RichTextStrings too!
+ * other RichTextStrings too!
*/
UnicodeString getRawUnicodeString() {
- return string;
+ return _string;
}
/** Used internally by the HSSFCell to set the internal string value*/
void setUnicodeString(UnicodeString str) {
- this.string = str;
+ this._string = str;
}
-
+
/**
* @return the number of characters in the text.
*/
public int length() {
- return string.getCharCount();
+ return _string.getCharCount();
}
/**
*/
public short getFontAtIndex( int index )
{
- int size = string.getFormatRunCount();
+ int size = _string.getFormatRunCount();
UnicodeString.FormatRun currentRun = null;
for (int i=0;i<size;i++) {
- UnicodeString.FormatRun r = string.getFormatRun(i);
- if (r.getCharacterPos() > index)
- break;
- else currentRun = r;
+ UnicodeString.FormatRun r = _string.getFormatRun(i);
+ if (r.getCharacterPos() > index) {
+ break;
+ }
+ currentRun = r;
}
- if (currentRun == null)
- return NO_FONT;
- else return currentRun.getFontIndex();
+ if (currentRun == null) {
+ return NO_FONT;
+ }
+ return currentRun.getFontIndex();
}
/**
*/
public int numFormattingRuns()
{
- return string.getFormatRunCount();
+ return _string.getFormatRunCount();
}
/**
*/
public int getIndexOfFormattingRun(int index)
{
- UnicodeString.FormatRun r = string.getFormatRun(index);
+ UnicodeString.FormatRun r = _string.getFormatRun(index);
return r.getCharacterPos();
}
*/
public short getFontOfFormattingRun(int index)
{
- UnicodeString.FormatRun r = string.getFormatRun(index);
+ UnicodeString.FormatRun r = _string.getFormatRun(index);
return r.getFontIndex();
}
/**
* Compares one rich text string to another.
*/
- public int compareTo( Object o )
- {
- HSSFRichTextString r = (HSSFRichTextString)o;
- return string.compareTo(r.string);
+ public int compareTo(HSSFRichTextString r) {
+ return _string.compareTo(r._string);
}
public boolean equals(Object o) {
if (o instanceof HSSFRichTextString) {
- return string.equals(((HSSFRichTextString)o).string);
+ return _string.equals(((HSSFRichTextString)o)._string);
}
return false;
-
+
}
/**
*/
public String toString()
{
- return string.toString();
+ return _string.toString();
}
/**
*/
public void applyFont( short fontIndex )
{
- applyFont(0, string.getCharCount(), fontIndex);
+ applyFont(0, _string.getCharCount(), fontIndex);
}
}
package org.apache.poi.hssf.usermodel;
-import java.util.*;
-import java.awt.*;
-import java.io.*;
+import java.awt.Font;
+import java.io.File;
+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
- * actually having the font on the system. The font details are loaded
- * as a resource from the POI jar file (or classpath) and should be contained
- * in path "/font_metrics.properties". The font widths are for a 10 point
- * version of the font. Use a multiplier for other sizes.
+ * actually having the font on the system. The font details are loaded as a
+ * resource from the POI jar file (or classpath) and should be contained in path
+ * "/font_metrics.properties". The font widths are for a 10 point version of the
+ * font. Use a multiplier for other sizes.
*
* @author Glen Stampoultzis (glens at apache.org)
*/
-class StaticFontMetrics
-{
+final class StaticFontMetrics {
/** 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 */
- 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.
- * @param font the font to lookup.
- * @return the fake font.
- */
- public static FontDetails getFontDetails(Font font)
- {
+ /**
+ * Retrieves the fake font details for a given font.
+ *
+ * @param font
+ * the font to lookup.
+ * @return the fake font.
+ */
+ public static FontDetails getFontDetails(Font font) {
// If we haven't already identified out font metrics file,
- // figure out which one to use and load it
- if (fontMetricsProps == null)
- {
- InputStream metricsIn = null;
- try
- {
- fontMetricsProps = new Properties();
+ // figure out which one to use and load it
+ if (fontMetricsProps == null) {
+ InputStream metricsIn = null;
+ try {
+ fontMetricsProps = new Properties();
- // Check to see if the font metric file was specified
- // as a system property
- String propFileName = null;
- try {
- propFileName = System.getProperty("font.metrics.filename");
- } catch(SecurityException e) {}
+ // Check to see if the font metric file was specified
+ // as a system property
+ String propFileName = null;
+ try {
+ propFileName = System.getProperty("font.metrics.filename");
+ } catch (SecurityException e) {
+ }
- if (propFileName != null) {
- File file = new File(propFileName);
- if (!file.exists())
- throw new FileNotFoundException("font_metrics.properties not found at path " + file.getAbsolutePath());
- metricsIn = new FileInputStream(file);
- }
- else {
- // Use the built-in font metrics file off the classpath
- metricsIn = FontDetails.class.getResourceAsStream("/font_metrics.properties");
- if (metricsIn == null)
- throw new FileNotFoundException("font_metrics.properties not found in classpath");
- }
- fontMetricsProps.load(metricsIn);
- }
- catch ( IOException e )
- {
- throw new RuntimeException("Could not load font metrics: " + e.getMessage());
- }
- finally
- {
- if (metricsIn != null)
- {
- try
- {
- metricsIn.close();
- }
- catch ( IOException ignore ) { }
- }
- }
- }
+ if (propFileName != null) {
+ File file = new File(propFileName);
+ if (!file.exists())
+ throw new FileNotFoundException(
+ "font_metrics.properties not found at path "
+ + file.getAbsolutePath());
+ metricsIn = new FileInputStream(file);
+ } else {
+ // Use the built-in font metrics file off the classpath
+ metricsIn = FontDetails.class.getResourceAsStream("/font_metrics.properties");
+ if (metricsIn == null)
+ throw new FileNotFoundException(
+ "font_metrics.properties not found in classpath");
+ }
+ fontMetricsProps.load(metricsIn);
+ } catch (IOException e) {
+ throw new RuntimeException("Could not load font metrics: " + e.getMessage());
+ } finally {
+ if (metricsIn != null) {
+ try {
+ metricsIn.close();
+ } catch (IOException ignore) {
+ }
+ }
+ }
+ }
// 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
// Others have different font instances for bold etc
// (eg font.dialog.plain.* vs font.Californian FB Bold.*)
String fontStyle = "";
- if(font.isPlain()) fontStyle += "plain";
- if(font.isBold()) fontStyle += "bold";
- if(font.isItalic()) fontStyle += "italic";
+ if (font.isPlain())
+ fontStyle += "plain";
+ if (font.isBold())
+ fontStyle += "bold";
+ if (font.isItalic())
+ fontStyle += "italic";
// Do we have a definition for this font with just the name?
// If not, check with the font style added
- if(fontMetricsProps.get(FontDetails.buildFontHeightProperty(fontName)) == null &&
- fontMetricsProps.get(FontDetails.buildFontHeightProperty(fontName+"."+fontStyle)) != null) {
+ if (fontMetricsProps.get(FontDetails.buildFontHeightProperty(fontName)) == null
+ && fontMetricsProps.get(FontDetails.buildFontHeightProperty(fontName + "."
+ + fontStyle)) != null) {
// Need to add on the style to the font name
fontName += "." + fontStyle;
}
// Get the details on this font
- if (fontDetailsMap.get(fontName) == null) {
- FontDetails fontDetails = FontDetails.create(fontName, fontMetricsProps);
- fontDetailsMap.put( fontName, fontDetails );
- return fontDetails;
- } else {
- return (FontDetails) fontDetailsMap.get(fontName);
- }
-
- }
+ if (fontDetailsMap.get(fontName) == null) {
+ FontDetails fontDetails = FontDetails.create(fontName, fontMetricsProps);
+ fontDetailsMap.put(fontName, fontDetails);
+ return fontDetails;
+ }
+ return fontDetailsMap.get(fontName);
+ }
}
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.poifs.filesystem;
{
private static final POILogger _logger =
POILogFactory.getLogger(POIFSFileSystem.class);
-
+
private static final class CloseIgnoringInputStream extends InputStream {
private final InputStream _is;
// do nothing
}
}
-
+
/**
* Convenience method for clients that want to avoid the auto-close behaviour of the constructor.
*/
public static InputStream createNonClosingInputStream(InputStream is) {
return new CloseIgnoringInputStream(is);
}
-
+
private PropertyTable _property_table;
private List _documents;
private DirectoryNode _root;
-
+
/**
* What big block size the file uses. Most files
* use 512 bytes, but a few use 4096
/**
* Create a POIFSFileSystem from an <tt>InputStream</tt>. Normally the stream is read until
* EOF. The stream is always closed.<p/>
- *
- * 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
+ *
+ * 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
* <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 (
* <tt>createNonClosingInputStream()</tt>) has been provided for this purpose:
* <pre>
* InputStream wrappedStream = POIFSFileSystem.createNonClosingInputStream(is);
* HSSFWorkbook wb = new HSSFWorkbook(wrappedStream);
- * is.reset();
- * doSomethingElse(is);
+ * is.reset();
+ * doSomethingElse(is);
* </pre>
* Note also the special case of <tt>ByteArrayInputStream</tt> for which the <tt>close()</tt>
- * method does nothing.
+ * method does nothing.
* <pre>
* ByteArrayInputStream bais = ...
* HSSFWorkbook wb = new HSSFWorkbook(bais); // calls bais.close() !
// read the header block from the stream
header_block_reader = new HeaderBlockReader(stream);
bigBlockSize = header_block_reader.getBigBlockSize();
-
+
// read the rest of the stream into blocks
data_blocks = new RawDataBlockList(stream, bigBlockSize);
success = true;
} finally {
closeInputStream(stream, success);
}
-
+
// set up the block allocation table (necessary for the
// data_blocks to be manageable
// init documents
processProperties(
SmallBlockTableReader.getSmallDocumentBlocks(
- data_blocks, properties.getRoot(),
+ data_blocks, properties.getRoot(),
header_block_reader.getSBATStart()
- ),
- data_blocks,
- properties.getRoot().getChildren(),
+ ),
+ data_blocks,
+ properties.getRoot().getChildren(),
null,
header_block_reader.getPropertyStart()
);
* @param success <code>false</code> if an exception is currently being thrown in the calling method
*/
private void closeInputStream(InputStream stream, boolean success) {
-
+
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. "
+ "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(success) {
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
e.printStackTrace();
}
/**
* 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.
* If your InputStream does not support mark / reset,
* then wrap it in a PushBackInputStream, then be
* 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 {
- // We want to peek at the first 8 bytes
+ // We want to peek at the first 8 bytes
inp.mark(8);
byte[] header = new byte[8];
} else {
inp.reset();
}
-
+
// Did it match the signature?
return (signature.get() == HeaderBlockConstants._signature);
}
{
return getRoot().createDirectory(name);
}
-
+
/**
* Write the filesystem out
*
processProperties(
small_blocks, big_blocks,
- (( DirectoryProperty ) property).getChildren(),
+ (( DirectoryProperty ) property).getChildren(),
new_dir, headerPropertiesStartAt);
}
else
if (property.shouldUseSmallBlocks())
{
document =
- new POIFSDocument(name,
- small_blocks.fetchBlocks(startBlock, headerPropertiesStartAt),
+ new POIFSDocument(name,
+ small_blocks.fetchBlocks(startBlock, headerPropertiesStartAt),
size);
}
else
{
return (( POIFSViewable ) getRoot()).getViewableArray();
}
- else
- {
- return new Object[ 0 ];
- }
+ return new Object[ 0 ];
}
/**
{
return (( POIFSViewable ) getRoot()).getViewableIterator();
}
- else
- {
- return Collections.EMPTY_LIST.iterator();
- }
+ return Collections.EMPTY_LIST.iterator();
}
/**
public int getBigBlockSize() {
return bigBlockSize;
}
-
+
/* ********** END begin implementation of POIFSViewable ********** */
} // end public class POIFSFileSystem
* outside the data array's bounds
* @return output string
*/
-
+
public static String dump(final byte [] data, final long offset,
final int index) {
StringBuffer buffer;
}
buffer.append(EOL);
display_offset += chars_read;
- }
+ }
return buffer.toString();
}
-
+
private static String dump(final long value)
{
while (bytesRemaining-- > 0)
{
int c = in.read();
- if (c == -1)
+ if (c == -1) {
break;
- else
- buf.write(c);
+ }
+ buf.write(c);
}
}
// 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;
char[] result = new char[charPos];
-
+
long value = pValue;
do {
result[--charPos] = _hexcodes[(int) (value & 0x0F)];
value >>>= 4;
} while (charPos > 1);
-
+
// Prefix added to avoid ambiguity
result[0] = '0';
result[1] = 'x';
public static void main(String[] args) throws Exception {
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()];
in.read(b);
System.out.println(HexDump.dump(b, 0, 0));
-
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
package org.apache.poi.util;
import java.io.InputStream;
import java.io.OutputStream;
-public class IOUtils
-{
- private IOUtils()
- {
- }
+public final class IOUtils {
+ private IOUtils() {
+ // no instances of this class
+ }
+
+ /**
+ * Reads all the data from the input stream, and returns the bytes read.
+ */
+ public static byte[] toByteArray(InputStream stream) throws IOException {
+ 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);
+ }
+ }
- /**
- * Reads all the data from the input stream, and returns
- * the bytes read.
- */
- public static byte[] toByteArray(InputStream stream) throws IOException {
- 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();
- }
+ return baos.toByteArray();
+ }
- /**
- * Helper method, just calls <tt>readFully(in, b, 0, b.length)</tt>
- */
- public static int readFully(InputStream in, byte[] b)
- throws IOException
- {
- return readFully(in, b, 0, b.length);
- }
+ /**
+ * Helper method, just calls <tt>readFully(in, b, 0, b.length)</tt>
+ */
+ 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;
- 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;
- }
- }
- }
+ /**
+ * 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.
- */
+ /**
+ * 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 {
byte[] buff = new byte[4096];
int count;
- while( (count = inp.read(buff)) != -1 ) {
- if(count > 0) {
+ while ((count = inp.read(buff)) != -1) {
+ if (count > 0) {
out.write(buff, 0, count);
}
}
}
-}
\ No newline at end of file
+}
-
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
package org.apache.poi.util;
*/
public class SystemOutLogger extends POILogger
{
- private String cat;
+ private String _cat;
public void initialize(final String cat)
{
- this.cat=cat;
+ this._cat=cat;
}
/**
{
log(level, obj1, null);
}
-
+
/**
* Log a message
*
public void log(final int level, final Object obj1,
final Throwable exception) {
if (check(level)) {
- System.out.println("["+cat+"] "+obj1);
+ System.out.println("["+_cat+"] "+obj1);
if(exception != null) {
exception.printStackTrace(System.out);
}
currentLevel = POILogger.DEBUG;
}
- if (level >= currentLevel)
+ if (level >= currentLevel) {
return true;
- else
- return false;
+ }
+ return false;
}
/**
* Represents the core properties part of a package.
- *
+ *
* @author Julien Chable
- * @version 1.0
*/
-public class PackagePropertiesPart extends PackagePart implements
+public final class PackagePropertiesPart extends PackagePart implements
PackageProperties {
public final static String NAMESPACE_DC_URI = "http://purl.org/dc/elements/1.1/";
/**
* Constructor.
- *
+ *
* @param pack
* Container package.
* @param partName
/**
* A categorization of the content of this package.
- *
+ *
* [Example: Example values for this property might include: Resume, Letter,
* Financial Forecast, Proposal, Technical Presentation, and so on. This
* value might be used by an application's user interface to facilitate
/**
* The status of the content.
- *
+ *
* [Example: Values might include "Draft", "Reviewed", and "Final". end
* example]
*/
/**
* The type of content represented, generally defined by a specific use and
* intended audience.
- *
+ *
* [Example: Values might include "Whitepaper", "Security Bulletin", and
* "Exam". end example] [Note: This property is distinct from MIME content
* types as defined in RFC 2616. end note]
/**
* An explanation of the content of the resource.
- *
+ *
* [Example: Values might include an abstract, table of contents, reference
* to a graphical representation of content, and a free-text account of the
* content. end example]
/**
* The language of the intellectual content of the resource.
- *
+ *
* [Note: IETF RFC 3066 provides guidance on encoding to represent
* languages. end note]
*/
/**
* The user who performed the last modification. The identification is
* environment-specific.
- *
+ *
* [Example: A name, email address, or employee ID. end example] It is
* recommended that this value be as concise as possible.
*/
/**
* The revision number.
- *
+ *
* [Example: This value might indicate the number of saves or revisions,
* provided the application updates it after each revision. end example]
*/
/**
* Get the category property.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getCategoryProperty()
*/
public Nullable<String> getCategoryProperty() {
/**
* Get content status.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getContentStatusProperty()
*/
public Nullable<String> getContentStatusProperty() {
/**
* Get content type.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getContentTypeProperty()
*/
public Nullable<String> getContentTypeProperty() {
/**
* Get created date.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getCreatedProperty()
*/
public Nullable<Date> getCreatedProperty() {
/**
* Get created date formated into a String.
- *
+ *
* @return A string representation of the created date.
*/
public String getCreatedPropertyString() {
/**
* Get creator.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getCreatorProperty()
*/
public Nullable<String> getCreatorProperty() {
/**
* Get description.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getDescriptionProperty()
*/
public Nullable<String> getDescriptionProperty() {
/**
* Get identifier.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getIdentifierProperty()
*/
public Nullable<String> getIdentifierProperty() {
/**
* Get keywords.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getKeywordsProperty()
*/
public Nullable<String> getKeywordsProperty() {
/**
* Get the language.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getLanguageProperty()
*/
public Nullable<String> getLanguageProperty() {
/**
* Get the author of last modifications.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getLastModifiedByProperty()
*/
public Nullable<String> getLastModifiedByProperty() {
/**
* Get last printed date.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getLastPrintedProperty()
*/
public Nullable<Date> getLastPrintedProperty() {
/**
* Get last printed date formated into a String.
- *
+ *
* @return A string representation of the last printed date.
*/
public String getLastPrintedPropertyString() {
/**
* Get modified date.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getModifiedProperty()
*/
public Nullable<Date> getModifiedProperty() {
/**
* Get modified date formated into a String.
- *
+ *
* @return A string representation of the modified date.
*/
public String getModifiedPropertyString() {
- if (!modified.hasValue())
- return getDateValue(new Nullable<Date>(new Date()));
- else
+ if (modified.hasValue()) {
return getDateValue(modified);
+ }
+ return getDateValue(new Nullable<Date>(new Date()));
}
/**
* Get revision.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getRevisionProperty()
*/
public Nullable<String> getRevisionProperty() {
/**
* Get subject.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getSubjectProperty()
*/
public Nullable<String> getSubjectProperty() {
/**
* Get title.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getTitleProperty()
*/
public Nullable<String> getTitleProperty() {
/**
* Get version.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#getVersionProperty()
*/
public Nullable<String> getVersionProperty() {
/**
* Set the category.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setCategoryProperty(java.lang.String)
*/
public void setCategoryProperty(String category) {
/**
* Set the content status.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setContentStatusProperty(java.lang.String)
*/
public void setContentStatusProperty(String contentStatus) {
/**
* Set the content type.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setContentTypeProperty(java.lang.String)
*/
public void setContentTypeProperty(String contentType) {
/**
* Set the created date.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatedProperty(org.apache.poi.openxml4j.util.Nullable)
*/
public void setCreatedProperty(String created) {
/**
* Set the created date.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatedProperty(org.apache.poi.openxml4j.util.Nullable)
*/
public void setCreatedProperty(Nullable<Date> created) {
/**
* Set the creator.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatorProperty(java.lang.String)
*/
public void setCreatorProperty(String creator) {
/**
* Set the description.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setDescriptionProperty(java.lang.String)
*/
public void setDescriptionProperty(String description) {
/**
* Set identifier.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setIdentifierProperty(java.lang.String)
*/
public void setIdentifierProperty(String identifier) {
/**
* Set keywords.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setKeywordsProperty(java.lang.String)
*/
public void setKeywordsProperty(String keywords) {
/**
* Set language.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setLanguageProperty(java.lang.String)
*/
public void setLanguageProperty(String language) {
/**
* Set last modifications author.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setLastModifiedByProperty(java.lang.String)
*/
public void setLastModifiedByProperty(String lastModifiedBy) {
/**
* Set last printed date.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setLastPrintedProperty(org.apache.poi.openxml4j.util.Nullable)
*/
public void setLastPrintedProperty(String lastPrinted) {
/**
* Set last printed date.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setLastPrintedProperty(org.apache.poi.openxml4j.util.Nullable)
*/
public void setLastPrintedProperty(Nullable<Date> lastPrinted) {
/**
* Set last modification date.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setModifiedProperty(org.apache.poi.openxml4j.util.Nullable)
*/
public void setModifiedProperty(String modified) {
/**
* Set last modification date.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setModifiedProperty(org.apache.poi.openxml4j.util.Nullable)
*/
public void setModifiedProperty(Nullable<Date> modified) {
/**
* Set revision.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setRevisionProperty(java.lang.String)
*/
public void setRevisionProperty(String revision) {
/**
* Set subject.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setSubjectProperty(java.lang.String)
*/
public void setSubjectProperty(String subject) {
/**
* Set title.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setTitleProperty(java.lang.String)
*/
public void setTitleProperty(String title) {
/**
* Set version.
- *
+ *
* @see org.apache.poi.openxml4j.opc.PackageProperties#setVersionProperty(java.lang.String)
*/
public void setVersionProperty(String version) {
* Convert a strig value into a Nullable<String>
*/
private Nullable<String> setStringValue(String s) {
- if (s == null || s.equals(""))
+ if (s == null || s.equals("")) {
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>.
- *
+ *
* @throws InvalidFormatException
* Throws if the date format isnot valid.
*/
private Nullable<Date> setDateValue(String s) throws InvalidFormatException {
- if (s == null || s.equals(""))
+ if (s == null || s.equals("")) {
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.
- *
+ *
* @param d
* The Date to convert.
* @return The formated date or null.
* @see java.util.SimpleDateFormat
*/
private String getDateValue(Nullable<Date> d) {
- if (d == null || d.equals(""))
+ if (d == null || d.equals("")) {
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
- public boolean save(OutputStream zos) throws OpenXML4JException {
+ public boolean save(OutputStream zos) {
throw new InvalidOperationException("Operation not authorized");
}
@Override
- public boolean load(InputStream ios) throws InvalidFormatException {
+ public boolean load(InputStream ios) {
throw new InvalidOperationException("Operation not authorized");
}
/**
* Zip implementation of the ContentTypeManager.
- *
+ *
* @author Julien Chable
* @version 1.0
* @see ContentTypeManager
/**
* Delegate constructor to the super constructor.
- *
+ *
* @param in
* The input stream to parse to fill internal content type
* collections.
if (resultRead == -1) {
// end of file reached
break;
- } else {
- zos.write(buff, 0, resultRead);
}
+ zos.write(buff, 0, resultRead);
}
zos.closeEntry();
} catch (IOException ioe) {
* @throws OpenXML4JException
* Throws if internal error occurs.
*/
- public static ZipEntry getCorePropertiesZipEntry(ZipPackage pkg)
- throws OpenXML4JException {
+ public static ZipEntry getCorePropertiesZipEntry(ZipPackage pkg) {
PackageRelationship corePropsRel = pkg.getRelationshipsByType(
PackageRelationshipTypes.CORE_PROPERTIES).getRelationship(0);
public static String getOPCNameFromZipItemName(String zipItemName) {
if (zipItemName == null)
throw new IllegalArgumentException("zipItemName");
- if (zipItemName.startsWith(FORWARD_SLASH))
+ if (zipItemName.startsWith(FORWARD_SLASH)) {
return zipItemName;
- else
- return FORWARD_SLASH + zipItemName;
+ }
+ return FORWARD_SLASH + zipItemName;
}
/**
import org.dom4j.QName;
import org.dom4j.io.SAXReader;
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.PackagePart;
import org.apache.poi.openxml4j.opc.PackageProperties;
* Package properties unmarshaller.
*
* @author Julien Chable
- * @version 1.0
*/
public final class PackagePropertiesUnmarshaller implements PartUnmarshaller {
.getInputStream(context.getZipEntry());
} else if (context.getPackage() != null) {
// Try to retrieve the part inputstream from the URI
- ZipEntry zipEntry;
- try {
- zipEntry = ZipHelper
- .getCorePropertiesZipEntry((ZipPackage) context
- .getPackage());
- } catch (OpenXML4JException e) {
- throw new IOException(
- "Error while trying to get the part input stream.");
- }
+ ZipEntry zipEntry = ZipHelper
+ .getCorePropertiesZipEntry((ZipPackage) context
+ .getPackage());
in = ((ZipPackage) context.getPackage()).getZipArchive()
.getInputStream(zipEntry);
} else
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
+
package org.apache.poi.util;
import org.apache.poi.openxml4j.opc.*;
*
* @author Yegor Kozlov
*/
-public class PackageHelper {
+public final class PackageHelper {
/**
* Clone the specified package.
if (rel.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) {
copyProperties(pkg.getPackageProperties(), dest.getPackageProperties());
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();
IOUtils.copy(part.getInputStream(), out);
}
/**
- * 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 {
File file = TempFile.createTempFile("poi-ooxml-", ".tmp");
part_tgt.addExternalRelationship(rel.getTargetURI().toString(), rel.getRelationshipType(), rel.getId());
//external relations don't have associated package parts
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;
}
protected CTDxf getDxf(int idx) {
- if(dxfs.size()==0)
- return CTDxf.Factory.newInstance();
- else
+ if (dxfs.size()==0) {
+ return CTDxf.Factory.newInstance();
+ }
return dxfs.get(idx);
}
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.xssf.model.StylesTable;
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.CTCellFormula;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;
* </p>
*/
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 TRUE_AS_STRING = "1";
* the xml bean containing information about the cell's location, value,
* data type, formatting, and formula
*/
- private final CTCell cell;
+ private final CTCell _cell;
/**
* the XSSFRow this cell belongs to
*/
- private final XSSFRow row;
+ private final XSSFRow _row;
/**
* 0-based column index
*/
- private int cellNum;
+ private int _cellNum;
/**
* Table of strings shared across this workbook.
* 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.
*/
- private StylesTable stylesSource;
+ private StylesTable _stylesSource;
/**
* Construct a XSSFCell.
* @param cell the xml bean containing information about the cell.
*/
protected XSSFCell(XSSFRow row, CTCell cell) {
- this.cell = cell;
- this.row = row;
+ _cell = cell;
+ _row = row;
if (cell.getR() != null) {
- this.cellNum = new CellReference(cell.getR()).getCol();
+ _cellNum = new CellReference(cell.getR()).getCol();
}
- this.sharedStringSource = row.getSheet().getWorkbook().getSharedStringSource();
- this.stylesSource = row.getSheet().getWorkbook().getStylesSource();
+ _sharedStringSource = row.getSheet().getWorkbook().getSharedStringSource();
+ _stylesSource = row.getSheet().getWorkbook().getStylesSource();
}
/**
* @return table of strings shared across this workbook
*/
protected SharedStringsTable getSharedStringSource() {
- return sharedStringSource;
+ return _sharedStringSource;
}
/**
* @return table of cell styles shared across this workbook
*/
protected StylesTable getStylesSource() {
- return stylesSource;
+ return _stylesSource;
}
/**
* @return the row this cell belongs to
*/
public XSSFRow getRow() {
- return row;
+ return _row;
}
/**
case CELL_TYPE_BLANK:
return false;
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:
//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:
throw typeMismatch(CELL_TYPE_BOOLEAN, cellType, false);
}
* will change the cell to a boolean cell and set its value.
*/
public void setCellValue(boolean value) {
- cell.setT(STCellType.B);
- cell.setV(value ? TRUE_AS_STRING : FALSE_AS_STRING);
+ _cell.setT(STCellType.B);
+ _cell.setV(value ? TRUE_AS_STRING : FALSE_AS_STRING);
}
/**
return 0.0;
case CELL_TYPE_FORMULA:
case CELL_TYPE_NUMERIC:
- return cell.isSetV() ? Double.parseDouble(cell.getV()) : 0.0;
+ return _cell.isSetV() ? Double.parseDouble(_cell.getV()) : 0.0;
default:
throw typeMismatch(CELL_TYPE_NUMERIC, cellType, false);
}
*/
public void setCellValue(double value) {
if(Double.isInfinite(value) || Double.isNaN(value)) {
- cell.setT(STCellType.E);
- cell.setV(FormulaError.NUM.getString());
+ _cell.setT(STCellType.E);
+ _cell.setV(FormulaError.NUM.getString());
} else {
- cell.setT(STCellType.N);
- cell.setV(String.valueOf(value));
+ _cell.setT(STCellType.N);
+ _cell.setV(String.valueOf(value));
}
}
rt = new XSSFRichTextString("");
break;
case CELL_TYPE_STRING:
- if (cell.getT() == STCellType.INLINE_STR) {
- if(cell.isSetIs()) {
+ if (_cell.getT() == STCellType.INLINE_STR) {
+ if(_cell.isSetIs()) {
//string is expressed directly in the cell definition instead of implementing the shared string table.
- rt = new XSSFRichTextString(cell.getIs());
- } else if (cell.isSetV()) {
+ rt = new XSSFRichTextString(_cell.getIs());
+ } else if (_cell.isSetV()) {
//cached result of a formula
- rt = new XSSFRichTextString(cell.getV());
+ rt = new XSSFRichTextString(_cell.getV());
} else {
rt = new XSSFRichTextString("");
}
} else {
- if (cell.isSetV()) {
- int idx = Integer.parseInt(cell.getV());
- rt = new XSSFRichTextString(sharedStringSource.getEntryAt(idx));
+ if (_cell.isSetV()) {
+ int idx = Integer.parseInt(_cell.getV());
+ rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(idx));
}
else {
rt = new XSSFRichTextString("");
}
break;
case CELL_TYPE_FORMULA:
- rt = new XSSFRichTextString(cell.isSetV() ? cell.getV() : "");
+ rt = new XSSFRichTextString(_cell.isSetV() ? _cell.getV() : "");
break;
default:
throw typeMismatch(CELL_TYPE_STRING, cellType, false);
}
- rt.setStylesTableReference(stylesSource);
+ rt.setStylesTableReference(_stylesSource);
return rt;
}
int cellType = getCellType();
switch(cellType){
case Cell.CELL_TYPE_FORMULA:
- cell.setV(str.getString());
- cell.setT(STCellType.STR);
+ _cell.setV(str.getString());
+ _cell.setT(STCellType.STR);
break;
default:
- if(cell.getT() == STCellType.INLINE_STR) {
+ if(_cell.getT() == STCellType.INLINE_STR) {
//set the 'pre-evaluated result
- cell.setV(str.getString());
+ _cell.setV(str.getString());
} else {
- cell.setT(STCellType.S);
+ _cell.setT(STCellType.S);
XSSFRichTextString rt = (XSSFRichTextString)str;
- rt.setStylesTableReference(stylesSource);
- int sRef = sharedStringSource.addEntry(rt.getCTRst());
- cell.setV(Integer.toString(sRef));
+ rt.setStylesTableReference(_stylesSource);
+ int sRef = _sharedStringSource.addEntry(rt.getCTRst());
+ _cell.setV(Integer.toString(sRef));
}
break;
}
int cellType = getCellType();
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){
return convertSharedFormula((int)f.getSi());
- } else {
- return f.getStringValue();
}
+ return f.getStringValue();
}
/**
* @throws IllegalArgumentException if the formula is invalid
*/
public void setCellFormula(String formula) {
- XSSFWorkbook wb = row.getSheet().getWorkbook();
+ XSSFWorkbook wb = _row.getSheet().getWorkbook();
if (formula == null) {
wb.onDeleteFormula(this);
- if(cell.isSetF()) cell.unsetF();
+ if(_cell.isSetF()) _cell.unsetF();
return;
}
CTCellFormula f = CTCellFormula.Factory.newInstance();
f.setStringValue(formula);
- cell.setF(f);
- if(cell.isSetV()) cell.unsetV();
+ _cell.setF(f);
+ if(_cell.isSetV()) _cell.unsetV();
}
/**
* @return zero-based column index of a column in a sheet.
*/
public int getColumnIndex() {
- return this.cellNum;
+ return this._cellNum;
}
/**
* @return zero-based row index of a row in the sheet that contains this cell
*/
public int getRowIndex() {
- return row.getRowNum();
+ return _row.getRowNum();
}
/**
* @return A1 style reference to the location of this cell
*/
public String getReference() {
- return cell.getR();
+ return _cell.getR();
}
/**
* <code>workbook.getCellStyleAt(0)</code>
*/
public XSSFCellStyle getCellStyle() {
- long idx = cell.isSetS() ? cell.getS() : 0;
- return stylesSource.getStyleAt((int)idx);
+ long idx = _cell.isSetS() ? _cell.getS() : 0;
+ return _stylesSource.getStyleAt((int)idx);
}
/**
*/
public void setCellStyle(CellStyle style) {
if(style == null) {
- if(cell.isSetS()) cell.unsetS();
+ if(_cell.isSetS()) _cell.unsetS();
} else {
XSSFCellStyle xStyle = (XSSFCellStyle)style;
- xStyle.verifyBelongsToStylesSource(stylesSource);
+ xStyle.verifyBelongsToStylesSource(_stylesSource);
- long idx = stylesSource.putStyle(xStyle);
- cell.setS(idx);
+ long idx = _stylesSource.putStyle(xStyle);
+ _cell.setS(idx);
}
}
*/
public int getCellType() {
- if (cell.getF() != null) {
+ if (_cell.getF() != null) {
return CELL_TYPE_FORMULA;
}
* on the cached value of the formula
*/
public int getCachedFormulaResultType() {
- if (cell.getF() == null) {
+ if (_cell.getF() == null) {
throw new IllegalStateException("Only formula cells have cached results");
}
* Detect cell type based on the "t" attribute of the CTCell bean
*/
private int getBaseCellType(boolean blankCells) {
- switch (cell.getT().intValue()) {
+ switch (_cell.getT().intValue()) {
case STCellType.INT_B:
return CELL_TYPE_BOOLEAN;
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
// (either not present or) a numeric cell with no value set.
// The formula evaluator (and perhaps other clients of this interface) needs to
case STCellType.INT_STR:
return CELL_TYPE_STRING;
default:
- throw new IllegalStateException("Illegal cell type: " + this.cell.getT());
+ throw new IllegalStateException("Illegal cell type: " + this._cell.getT());
}
}
int cellType = getCellType();
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.
* cell and set its value.
*/
public void setCellErrorValue(FormulaError error) {
- cell.setT(STCellType.E);
- cell.setV(error.getString());
+ _cell.setT(STCellType.E);
+ _cell.setV(error.getString());
}
/**
* Sets this cell as the active cell for the worksheet.
*/
public void setAsActiveCell() {
- getSheet().setActiveCell(cell.getR());
+ getSheet().setActiveCell(_cell.getR());
}
/**
*/
private void setBlank(){
CTCell blank = CTCell.Factory.newInstance();
- blank.setR(cell.getR());
- blank.setS(cell.getS());
- cell.set(blank);
+ blank.setR(_cell.getR());
+ blank.setS(_cell.getS());
+ _cell.set(blank);
}
/**
*/
protected void setCellNum(int num) {
checkBounds(num);
- cellNum = num;
+ _cellNum = num;
String ref = new CellReference(getRowIndex(), getColumnIndex()).formatAsString();
- cell.setR(ref);
+ _cell.setR(ref);
}
/**
break;
case CELL_TYPE_BOOLEAN:
String newVal = convertCellValueToBoolean() ? TRUE_AS_STRING : FALSE_AS_STRING;
- cell.setT(STCellType.B);
- cell.setV(newVal);
+ _cell.setT(STCellType.B);
+ _cell.setV(newVal);
break;
case CELL_TYPE_NUMERIC:
- cell.setT(STCellType.N);
+ _cell.setT(STCellType.N);
break;
case CELL_TYPE_ERROR:
- cell.setT(STCellType.E);
+ _cell.setT(STCellType.E);
break;
case CELL_TYPE_STRING:
if(prevType != CELL_TYPE_STRING){
String str = convertCellValueToString();
XSSFRichTextString rt = new XSSFRichTextString(str);
- rt.setStylesTableReference(stylesSource);
- int sRef = sharedStringSource.addEntry(rt.getCTRst());
- cell.setV(Integer.toString(sRef));
+ rt.setStylesTableReference(_stylesSource);
+ int sRef = _sharedStringSource.addEntry(rt.getCTRst());
+ _cell.setV(Integer.toString(sRef));
}
- cell.setT(STCellType.S);
+ _cell.setT(STCellType.S);
break;
case CELL_TYPE_FORMULA:
- if(!cell.isSetF()){
+ if(!_cell.isSetF()){
CTCellFormula f = CTCellFormula.Factory.newInstance();
f.setStringValue("0");
- cell.setF(f);
- if(cell.isSetT()) cell.unsetT();
+ _cell.setF(f);
+ if(_cell.isSetT()) _cell.unsetT();
}
break;
default:
if (DateUtil.isCellDateFormatted(this)) {
DateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
return sdf.format(getDateCellValue());
- } else {
- return getNumericCellValue() + "";
}
+ return getNumericCellValue() + "";
case CELL_TYPE_STRING:
return getRichStringCellValue().toString();
default:
* <code>null</code> for blank cells.
*/
public String getRawValue() {
- return cell.getV();
+ return _cell.getV();
}
/**
* @return the cell comment associated with this cell or <code>null</code>
*/
public XSSFComment getCellComment() {
- return getSheet().getCellComment(row.getRowNum(), getColumnIndex());
+ return getSheet().getCellComment(_row.getRowNum(), getColumnIndex());
}
/**
* @param comment comment associated with this cell
*/
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);
}
* @return hyperlink associated with this cell or <code>null</code> if not found
*/
public XSSFHyperlink getHyperlink() {
- return getSheet().getHyperlink(row.getRowNum(), cellNum);
+ return getSheet().getHyperlink(_row.getRowNum(), _cellNum);
}
/**
XSSFHyperlink link = (XSSFHyperlink)hyperlink;
// Assign to us
- link.setCellReference( new CellReference(row.getRowNum(), cellNum).formatAsString() );
+ link.setCellReference( new CellReference(_row.getRowNum(), _cellNum).formatAsString() );
// Add to the lists
getSheet().setCellHyperlink(link);
* @return the xml bean containing information about this cell
*/
public CTCell getCTCell(){
- return cell;
+ return _cell;
}
/**
switch (cellType) {
case CELL_TYPE_BOOLEAN:
- return TRUE_AS_STRING.equals(cell.getV());
+ return TRUE_AS_STRING.equals(_cell.getV());
case CELL_TYPE_STRING:
- int sstIndex = Integer.parseInt(cell.getV());
- XSSFRichTextString rt = new XSSFRichTextString(sharedStringSource.getEntryAt(sstIndex));
+ int sstIndex = Integer.parseInt(_cell.getV());
+ XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(sstIndex));
String text = rt.getString();
- return Boolean.valueOf(text);
+ return Boolean.valueOf(text).booleanValue();
case CELL_TYPE_NUMERIC:
- return Double.parseDouble(cell.getV()) != 0;
+ return Double.parseDouble(_cell.getV()) != 0;
case CELL_TYPE_ERROR:
case CELL_TYPE_BLANK:
case CELL_TYPE_BLANK:
return "";
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:
- int sstIndex = Integer.parseInt(cell.getV());
- XSSFRichTextString rt = new XSSFRichTextString(sharedStringSource.getEntryAt(sstIndex));
+ int sstIndex = Integer.parseInt(_cell.getV());
+ XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(sstIndex));
return rt.getString();
case CELL_TYPE_NUMERIC:
- return String.valueOf(Double.parseDouble(cell.getV()));
+ return String.valueOf(Double.parseDouble(_cell.getV()));
case CELL_TYPE_ERROR:
- return cell.getV();
+ return _cell.getV();
case CELL_TYPE_FORMULA:
// should really evaluate, but HSSFCell can't call HSSFFormulaEvaluator
return "";
*/
public class XSSFCellStyle implements CellStyle {
- private int cellXfId;
- private StylesTable stylesSource;
- private CTXf cellXf;
- private CTXf cellStyleXf;
- private XSSFFont font;
- private XSSFCellAlignment cellAlignment;
+ private int _cellXfId;
+ private StylesTable _stylesSource;
+ private CTXf _cellXf;
+ private CTXf _cellStyleXf;
+ private XSSFFont _font;
+ private XSSFCellAlignment _cellAlignment;
/**
* Creates a Cell Style from the supplied parts
* @param stylesSource Styles Source to work off
*/
public XSSFCellStyle(int cellXfId, int cellStyleXfId, StylesTable stylesSource) {
- this.cellXfId = cellXfId;
- this.stylesSource = stylesSource;
- this.cellXf = stylesSource.getCellXfAt(this.cellXfId);
- this.cellStyleXf = stylesSource.getCellStyleXfAt(cellStyleXfId);
+ _cellXfId = cellXfId;
+ _stylesSource = stylesSource;
+ _cellXf = stylesSource.getCellXfAt(this._cellXfId);
+ _cellStyleXf = stylesSource.getCellStyleXfAt(cellStyleXfId);
}
/**
* Used so that StylesSource can figure out our location
*/
public CTXf getCoreXf() {
- return cellXf;
+ return _cellXf;
}
/**
* Used so that StylesSource can figure out our location
*/
public CTXf getStyleXf() {
- return cellStyleXf;
+ return _cellStyleXf;
}
/**
* Creates an empty Cell Style
*/
public XSSFCellStyle(StylesTable stylesSource) {
- this.stylesSource = stylesSource;
+ _stylesSource = stylesSource;
// We need a new CTXf for the main styles
// TODO decide on a style ctxf
- cellXf = CTXf.Factory.newInstance();
- cellStyleXf = null;
+ _cellXf = CTXf.Factory.newInstance();
+ _cellStyleXf = null;
}
/**
* @throws IllegalArgumentException if there's a workbook mis-match
*/
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?");
}
}
public void cloneStyleFrom(CellStyle source) {
if(source instanceof XSSFCellStyle) {
XSSFCellStyle src = (XSSFCellStyle)source;
- cellXf.set(src.getCoreXf());
- cellStyleXf.set(src.getStyleXf());
+ _cellXf.set(src.getCoreXf());
+ _cellStyleXf.set(src.getStyleXf());
} else {
throw new IllegalArgumentException("Can only clone from one XSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle");
}
* @see org.apache.poi.ss.usermodel.HorizontalAlignment
*/
public HorizontalAlignment getAlignmentEnum() {
- CTCellAlignment align = cellXf.getAlignment();
+ CTCellAlignment align = _cellXf.getAlignment();
if(align != null && align.isSetHorizontal()) {
return HorizontalAlignment.values()[align.getHorizontal().intValue()-1];
}
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/
public short getBorderBottom() {
- if(!cellXf.getApplyBorder()) return BORDER_NONE;
+ if(!_cellXf.getApplyBorder()) return BORDER_NONE;
- int idx = (int)cellXf.getBorderId();
- CTBorder ct = stylesSource.getBorderAt(idx).getCTBorder();
+ int idx = (int)_cellXf.getBorderId();
+ CTBorder ct = _stylesSource.getBorderAt(idx).getCTBorder();
STBorderStyle.Enum ptrn = ct.isSetBottom() ? ct.getBottom().getStyle() : null;
return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1);
}
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/
public short getBorderLeft() {
- if(!cellXf.getApplyBorder()) return BORDER_NONE;
+ if(!_cellXf.getApplyBorder()) return BORDER_NONE;
- int idx = (int)cellXf.getBorderId();
- CTBorder ct = stylesSource.getBorderAt(idx).getCTBorder();
+ int idx = (int)_cellXf.getBorderId();
+ CTBorder ct = _stylesSource.getBorderAt(idx).getCTBorder();
STBorderStyle.Enum ptrn = ct.isSetLeft() ? ct.getLeft().getStyle() : null;
return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1);
}
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/
public short getBorderRight() {
- if(!cellXf.getApplyBorder()) return BORDER_NONE;
+ if(!_cellXf.getApplyBorder()) return BORDER_NONE;
- int idx = (int)cellXf.getBorderId();
- CTBorder ct = stylesSource.getBorderAt(idx).getCTBorder();
+ int idx = (int)_cellXf.getBorderId();
+ CTBorder ct = _stylesSource.getBorderAt(idx).getCTBorder();
STBorderStyle.Enum ptrn = ct.isSetRight() ? ct.getRight().getStyle() : null;
return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1);
}
* @see org.apache.poi.ss.usermodel.CellStyle#BORDER_SLANTED_DASH_DOT
*/
public short getBorderTop() {
- if(!cellXf.getApplyBorder()) return BORDER_NONE;
+ if(!_cellXf.getApplyBorder()) return BORDER_NONE;
- int idx = (int)cellXf.getBorderId();
- CTBorder ct = stylesSource.getBorderAt(idx).getCTBorder();
+ int idx = (int)_cellXf.getBorderId();
+ CTBorder ct = _stylesSource.getBorderAt(idx).getCTBorder();
STBorderStyle.Enum ptrn = ct.isSetTop() ? ct.getTop().getStyle() : null;
return ptrn == null ? BORDER_NONE : (short)(ptrn.intValue() - 1);
}
* @return the used color or <code>null</code> if not set
*/
public XSSFColor getBottomBorderXSSFColor() {
- if(!cellXf.getApplyBorder()) return null;
+ if(!_cellXf.getApplyBorder()) return null;
- int idx = (int)cellXf.getBorderId();
- XSSFCellBorder border = stylesSource.getBorderAt(idx);
+ int idx = (int)_cellXf.getBorderId();
+ XSSFCellBorder border = _stylesSource.getBorderAt(idx);
return border.getBorderColor(BorderSide.BOTTOM);
}
* @return the index of the number format
*/
public short getDataFormat() {
- return (short)cellXf.getNumFmtId();
+ return (short)_cellXf.getNumFmtId();
}
/**
*/
public String getDataFormatString() {
int idx = getDataFormat();
- return new XSSFDataFormat(stylesSource).getFormat((short)idx);
+ return new XSSFDataFormat(_stylesSource).getFormat((short)idx);
}
/**
* @return XSSFColor - fill color or <code>null</code> if not set
*/
public XSSFColor getFillBackgroundXSSFColor() {
- if(!cellXf.getApplyFill()) return null;
+ if(!_cellXf.getApplyFill()) return null;
- int fillIndex = (int)cellXf.getFillId();
- XSSFCellFill fg = stylesSource.getFillAt(fillIndex);
+ int fillIndex = (int)_cellXf.getFillId();
+ XSSFCellFill fg = _stylesSource.getFillAt(fillIndex);
return fg.getFillBackgroundColor();
}
* @return XSSFColor - fill color or <code>null</code> if not set
*/
public XSSFColor getFillForegroundXSSFColor() {
- if(!cellXf.getApplyFill()) return null;
+ if(!_cellXf.getApplyFill()) return null;
- int fillIndex = (int)cellXf.getFillId();
- XSSFCellFill fg = stylesSource.getFillAt(fillIndex);
+ int fillIndex = (int)_cellXf.getFillId();
+ XSSFCellFill fg = _stylesSource.getFillAt(fillIndex);
return fg.getFillForegroundColor();
}
* @see org.apache.poi.ss.usermodel.CellStyle#DIAMONDS
*/
public short getFillPattern() {
- if(!cellXf.getApplyFill()) return 0;
+ if(!_cellXf.getApplyFill()) return 0;
- int fillIndex = (int)cellXf.getFillId();
- XSSFCellFill fill = stylesSource.getFillAt(fillIndex);
+ int fillIndex = (int)_cellXf.getFillId();
+ XSSFCellFill fill = _stylesSource.getFillAt(fillIndex);
STPatternType.Enum ptrn = fill.getPatternType();
if(ptrn == null) return CellStyle.NO_FILL;
* @return Font - font
*/
public XSSFFont getFont() {
- if (font == null) {
- font = stylesSource.getFontAt(getFontId());
+ if (_font == null) {
+ _font = _stylesSource.getFontAt(getFontId());
}
- return font;
+ return _font;
}
/**
* @return indent - number of spaces
*/
public short getIndention() {
- CTCellAlignment align = cellXf.getAlignment();
+ CTCellAlignment align = _cellXf.getAlignment();
return (short)(align == null ? 0 : align.getIndent());
}
* @return unique index number of the underlying record this style represents
*/
public short getIndex() {
- return (short)this.cellXfId;
+ return (short)this._cellXfId;
}
/**
* @see org.apache.poi.ss.usermodel.IndexedColors
*/
public XSSFColor getLeftBorderXSSFColor() {
- if(!cellXf.getApplyBorder()) return null;
+ if(!_cellXf.getApplyBorder()) return null;
- int idx = (int)cellXf.getBorderId();
- XSSFCellBorder border = stylesSource.getBorderAt(idx);
+ int idx = (int)_cellXf.getBorderId();
+ XSSFCellBorder border = _stylesSource.getBorderAt(idx);
return border.getBorderColor(BorderSide.LEFT);
}
* @return the used color or <code>null</code> if not set
*/
public XSSFColor getRightBorderXSSFColor() {
- if(!cellXf.getApplyBorder()) return null;
+ if(!_cellXf.getApplyBorder()) return null;
- int idx = (int)cellXf.getBorderId();
- XSSFCellBorder border = stylesSource.getBorderAt(idx);
+ int idx = (int)_cellXf.getBorderId();
+ XSSFCellBorder border = _stylesSource.getBorderAt(idx);
return border.getBorderColor(BorderSide.RIGHT);
}
* @return rotation degrees (between 0 and 180 degrees)
*/
public short getRotation() {
- CTCellAlignment align = cellXf.getAlignment();
+ CTCellAlignment align = _cellXf.getAlignment();
return (short)(align == null ? 0 : align.getTextRotation());
}
* @return the used color or <code>null</code> if not set
*/
public XSSFColor getTopBorderXSSFColor() {
- if(!cellXf.getApplyBorder()) return null;
+ if(!_cellXf.getApplyBorder()) return null;
- int idx = (int)cellXf.getBorderId();
- XSSFCellBorder border = stylesSource.getBorderAt(idx);
+ int idx = (int)_cellXf.getBorderId();
+ XSSFCellBorder border = _stylesSource.getBorderAt(idx);
return border.getBorderColor(BorderSide.TOP);
}
* @see org.apache.poi.ss.usermodel.VerticalAlignment
*/
public VerticalAlignment getVerticalAlignmentEnum() {
- CTCellAlignment align = cellXf.getAlignment();
+ CTCellAlignment align = _cellXf.getAlignment();
if(align != null && align.isSetVertical()) {
return VerticalAlignment.values()[align.getVertical().intValue()-1];
- } else {
- return VerticalAlignment.BOTTOM;
}
+ return VerticalAlignment.BOTTOM;
}
/**
* @return a boolean value indicating if the text in a cell should be line-wrapped within the cell.
*/
public boolean getWrapText() {
- CTCellAlignment align = cellXf.getAlignment();
+ CTCellAlignment align = _cellXf.getAlignment();
return align != null && align.getWrapText();
}
if(border == BORDER_NONE) ct.unsetBottom();
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.setApplyBorder(true);
+ _cellXf.setBorderId(idx);
+ _cellXf.setApplyBorder(true);
}
/**
if(border == BORDER_NONE) ct.unsetLeft();
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.setApplyBorder(true);
+ _cellXf.setBorderId(idx);
+ _cellXf.setApplyBorder(true);
}
/**
if(border == BORDER_NONE) ct.unsetRight();
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.setApplyBorder(true);
+ _cellXf.setBorderId(idx);
+ _cellXf.setApplyBorder(true);
}
/**
if(border == BORDER_NONE) ct.unsetTop();
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.setApplyBorder(true);
+ _cellXf.setBorderId(idx);
+ _cellXf.setApplyBorder(true);
}
/**
if(color != null) pr.setColor(color.getCTColor());
else pr.unsetColor();
- int idx = stylesSource.putBorder(new XSSFCellBorder(ct));
+ int idx = _stylesSource.putBorder(new XSSFCellBorder(ct));
- cellXf.setBorderId(idx);
- cellXf.setApplyBorder(true);
+ _cellXf.setBorderId(idx);
+ _cellXf.setApplyBorder(true);
}
/**
* @param fmt the index of a data format
*/
public void setDataFormat(short fmt) {
- cellXf.setApplyNumberFormat(true);
- cellXf.setNumFmtId(fmt);
+ _cellXf.setApplyNumberFormat(true);
+ _cellXf.setNumFmtId(fmt);
}
/**
ptrn.setBgColor(color.getCTColor());
}
- int idx = stylesSource.putFill(new XSSFCellFill(ct));
+ int idx = _stylesSource.putFill(new XSSFCellFill(ct));
- cellXf.setFillId(idx);
- cellXf.setApplyFill(true);
+ _cellXf.setFillId(idx);
+ _cellXf.setApplyFill(true);
}
/**
ptrn.setFgColor(color.getCTColor());
}
- int idx = stylesSource.putFill(new XSSFCellFill(ct));
+ int idx = _stylesSource.putFill(new XSSFCellFill(ct));
- cellXf.setFillId(idx);
- cellXf.setApplyFill(true);
+ _cellXf.setFillId(idx);
+ _cellXf.setApplyFill(true);
}
/**
*/
private CTFill getCTFill(){
CTFill ct;
- if(cellXf.getApplyFill()) {
- int fillIndex = (int)cellXf.getFillId();
- XSSFCellFill cf = stylesSource.getFillAt(fillIndex);
+ if(_cellXf.getApplyFill()) {
+ int fillIndex = (int)_cellXf.getFillId();
+ XSSFCellFill cf = _stylesSource.getFillAt(fillIndex);
ct = (CTFill)cf.getCTFill().copy();
} else {
*/
private CTBorder getCTBorder(){
CTBorder ct;
- if(cellXf.getApplyBorder()) {
- int idx = (int)cellXf.getBorderId();
- XSSFCellBorder cf = stylesSource.getBorderAt(idx);
+ if(_cellXf.getApplyBorder()) {
+ int idx = (int)_cellXf.getBorderId();
+ XSSFCellBorder cf = _stylesSource.getBorderAt(idx);
ct = (CTBorder)cf.getCTBorder().copy();
} else {
if(fp == NO_FILL && ptrn.isSetPatternType()) ptrn.unsetPatternType();
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.setApplyFill(true);
+ _cellXf.setFillId(idx);
+ _cellXf.setApplyFill(true);
}
/**
public void setFont(Font font) {
if(font != null){
long index = font.getIndex();
- this.cellXf.setFontId(index);
- this.cellXf.setApplyFont(true);
+ this._cellXf.setFontId(index);
+ this._cellXf.setApplyFont(true);
} else {
- this.cellXf.setApplyFont(false);
+ this._cellXf.setApplyFont(false);
}
}
if(color != null) pr.setColor(color.getCTColor());
else pr.unsetColor();
- int idx = stylesSource.putBorder(new XSSFCellBorder(ct));
+ int idx = _stylesSource.putBorder(new XSSFCellBorder(ct));
- cellXf.setBorderId(idx);
- cellXf.setApplyBorder(true);
+ _cellXf.setBorderId(idx);
+ _cellXf.setApplyBorder(true);
}
/**
if(color != null) pr.setColor(color.getCTColor());
else pr.unsetColor();
- int idx = stylesSource.putBorder(new XSSFCellBorder(ct));
+ int idx = _stylesSource.putBorder(new XSSFCellBorder(ct));
- cellXf.setBorderId(idx);
- cellXf.setApplyBorder(true);
+ _cellXf.setBorderId(idx);
+ _cellXf.setApplyBorder(true);
}
/**
if(color != null) pr.setColor(color.getCTColor());
else pr.unsetColor();
- int idx = stylesSource.putBorder(new XSSFCellBorder(ct));
+ int idx = _stylesSource.putBorder(new XSSFCellBorder(ct));
- cellXf.setBorderId(idx);
- cellXf.setApplyBorder(true);
+ _cellXf.setBorderId(idx);
+ _cellXf.setApplyBorder(true);
}
/**
}
}
private int getFontId() {
- if (cellXf.isSetFontId()) {
- return (int) cellXf.getFontId();
+ if (_cellXf.isSetFontId()) {
+ return (int) _cellXf.getFontId();
}
- return (int) cellStyleXf.getFontId();
+ return (int) _cellStyleXf.getFontId();
}
/**
* @return CTCellProtection
*/
private CTCellProtection getCellProtection() {
- if (cellXf.getProtection() == null) {
- cellXf.addNewProtection();
+ if (_cellXf.getProtection() == null) {
+ _cellXf.addNewProtection();
}
- return cellXf.getProtection();
+ return _cellXf.getProtection();
}
/**
* @return XSSFCellAlignment - cell alignment
*/
protected XSSFCellAlignment getCellAlignment() {
- if (this.cellAlignment == null) {
- this.cellAlignment = new XSSFCellAlignment(getCTCellAlignment());
+ if (this._cellAlignment == null) {
+ this._cellAlignment = new XSSFCellAlignment(getCTCellAlignment());
}
- return this.cellAlignment;
+ return this._cellAlignment;
}
/**
* @return CTCellAlignment
*/
private CTCellAlignment getCTCellAlignment() {
- if (cellXf.getAlignment() == null) {
- cellXf.setAlignment(CTCellAlignment.Factory.newInstance());
+ if (_cellXf.getAlignment() == null) {
+ _cellXf.setAlignment(CTCellAlignment.Factory.newInstance());
}
- return cellXf.getAlignment();
+ return _cellXf.getAlignment();
}
/**
* @return the hash code value for this style
*/
public int hashCode(){
- return cellXf.toString().hashCode();
+ return _cellXf.toString().hashCode();
}
/**
if(o == null || !(o instanceof XSSFCellStyle)) return false;
XSSFCellStyle cf = (XSSFCellStyle)o;
- return cellXf.toString().equals(cf.getCoreXf().toString());
+ return _cellXf.toString().equals(cf.getCoreXf().toString());
}
/**
* @return a copy of this style
*/
public Object clone(){
- CTXf xf = (CTXf)cellXf.copy();
+ CTXf xf = (CTXf)_cellXf.copy();
- int xfSize = stylesSource._getStyleXfsSize();
- int indexXf = stylesSource.putCellXf(xf);
- return new XSSFCellStyle(indexXf-1, xfSize-1, stylesSource);
+ int xfSize = _stylesSource._getStyleXfsSize();
+ int indexXf = _stylesSource.putCellXf(xf);
+ return new XSSFCellStyle(indexXf-1, xfSize-1, _stylesSource);
}
}
*/
public static final short DEFAULT_FONT_COLOR = IndexedColors.BLACK.getIndex();
- private CTFont ctFont;
- private short index;
+ private CTFont _ctFont;
+ private short _index;
/**
* Create a new XSSFFont
* @param font the underlying CTFont bean
*/
public XSSFFont(CTFont font) {
- this.ctFont = font;
- this.index = 0;
+ _ctFont = font;
+ _index = 0;
}
public XSSFFont(CTFont font, int index) {
- this.ctFont = font;
- this.index = (short)index;
+ _ctFont = font;
+ _index = (short)index;
}
/**
* Create a new XSSFont. This method is protected to be used only by XSSFWorkbook
*/
protected XSSFFont() {
- this.ctFont = CTFont.Factory.newInstance();
+ this._ctFont = CTFont.Factory.newInstance();
setFontName(DEFAULT_FONT_NAME);
setFontHeight((double)DEFAULT_FONT_SIZE);
}
* get the underlying CTFont font
*/
public CTFont getCTFont() {
- return ctFont;
+ return _ctFont;
}
/**
* @return boolean - bold
*/
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());
}
* @see org.apache.poi.ss.usermodel.FontCharset
*/
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();
return (byte)val;
}
* @see IndexedColors
*/
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();
long index = color.getIndexed();
* @return XSSFColor - rgb color to use
*/
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 short - theme defined to use
*/
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();
return (short) index;
}
* @return short - height in point
*/
public short getFontHeight() {
- CTFontSize size = ctFont.sizeOfSzArray() == 0 ? null : ctFont.getSzArray(0);
+ CTFontSize size = _ctFont.sizeOfSzArray() == 0 ? null : _ctFont.getSzArray(0);
if (size != null) {
double fontHeight = size.getVal();
return (short)(fontHeight*20);
- } else
- return (short)(DEFAULT_FONT_SIZE*20);
+ }
+ return (short)(DEFAULT_FONT_SIZE*20);
}
/**
* @return String - a string representing the name of the font to use
*/
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 boolean - value for italic
*/
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 boolean - value for strikeout
*/
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();
}
* @see Font#SS_SUB
*/
public short getTypeOffset() {
- CTVerticalAlignFontProperty vAlign = ctFont.sizeOfVertAlignArray() == 0 ? null : ctFont.getVertAlignArray(0);
- 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
+ CTVerticalAlignFontProperty vAlign = _ctFont.sizeOfVertAlignArray() == 0 ? null : _ctFont.getVertAlignArray(0);
+ if (vAlign == null) {
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);
+ }
}
/**
* @see org.apache.poi.ss.usermodel.FontUnderline
*/
public byte getUnderline() {
- CTUnderlineProperty underline = ctFont.sizeOfUArray() == 0 ? null : ctFont.getUArray(0);
+ CTUnderlineProperty underline = _ctFont.sizeOfUArray() == 0 ? null : _ctFont.getUArray(0);
if (underline != null) {
FontUnderline val = FontUnderline.valueOf(underline.getVal().intValue());
return val.getByteValue();
*/
public void setBold(boolean 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);
} else {
- ctFont.setBArray(null);
+ _ctFont.setBArray(null);
}
}
* @see FontCharset
*/
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) {
case Font.ANSI_CHARSET:
charsetProperty.setVal(FontCharset.ANSI.getValue());
* @see IndexedColors
*/
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) {
case Font.COLOR_NORMAL: {
ctColor.setIndexed(XSSFFont.DEFAULT_FONT_COLOR);
* @param color - color to use
*/
public void setColor(XSSFColor color) {
- if(color == null) ctFont.setColorArray(null);
+ if(color == null) _ctFont.setColorArray(null);
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());
}
}
* @param height - height in points
*/
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);
}
* @param theme - theme color to use
*/
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);
}
* @see #DEFAULT_FONT_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);
}
*/
public void setItalic(boolean 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);
} else {
- ctFont.setIArray(null);
+ _ctFont.setIArray(null);
}
}
* @param strikeout - value for strikeout or not
*/
public void setStrikeout(boolean strikeout) {
- if(!strikeout) ctFont.setStrikeArray(null);
+ if(!strikeout) _ctFont.setStrikeArray(null);
else {
- CTBooleanProperty strike = ctFont.sizeOfStrikeArray() == 0 ? ctFont.addNewStrike() : ctFont.getStrikeArray(0);
+ CTBooleanProperty strike = _ctFont.sizeOfStrikeArray() == 0 ? _ctFont.addNewStrike() : _ctFont.getStrikeArray(0);
strike.setVal(strikeout);
}
}
*/
public void setTypeOffset(short offset) {
if(offset == Font.SS_NONE){
- ctFont.setVertAlignArray(null);
+ _ctFont.setVertAlignArray(null);
} else {
- CTVerticalAlignFontProperty offsetProperty = ctFont.sizeOfVertAlignArray() == 0 ? ctFont.addNewVertAlign() : ctFont.getVertAlignArray(0);
+ CTVerticalAlignFontProperty offsetProperty = _ctFont.sizeOfVertAlignArray() == 0 ? _ctFont.addNewVertAlign() : _ctFont.getVertAlignArray(0);
switch (offset) {
case Font.SS_NONE:
offsetProperty.setVal(STVerticalAlignRun.BASELINE);
* @param underline - FontUnderline enum value
*/
public void setUnderline(FontUnderline underline) {
- if(underline == FontUnderline.NONE && ctFont.sizeOfUArray() > 0){
- ctFont.setUArray(null);
+ if(underline == FontUnderline.NONE && _ctFont.sizeOfUArray() > 0){
+ _ctFont.setUArray(null);
} 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());
ctUnderline.setVal(val);
}
public String toString() {
- return ctFont.toString();
+ return _ctFont.toString();
}
*/
public long putFont(StylesTable styles) {
short idx = (short)styles.putFont(this);
- this.index = idx;
+ this._index = idx;
return idx;
}
* @see org.apache.poi.xssf.model.StylesTable#createDefaultFont()
*/
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());
}
* @see FontScheme
*/
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());
ctFontScheme.setVal(val);
}
* @see org.apache.poi.ss.usermodel.FontFamily
*/
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();
}
* @see FontFamily
*/
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);
}
public short getIndex()
{
- return index;
+ return _index;
}
public int hashCode(){
- return ctFont.toString().hashCode();
+ return _ctFont.toString().hashCode();
}
public boolean equals(Object o){
if(!(o instanceof XSSFFont)) return false;
XSSFFont cf = (XSSFFont)o;
- return ctFont.toString().equals(cf.getCTFont().toString());
+ return _ctFont.toString().equals(cf.getCTFont().toString());
}
}
* are largely stored as relations of the sheet
*/
public class XSSFHyperlink implements Hyperlink {
- private int type;
- private PackageRelationship externalRel;
- private CTHyperlink ctHyperlink;
- private String location;
+ private int _type;
+ private PackageRelationship _externalRel;
+ private CTHyperlink _ctHyperlink;
+ private String _location;
/**
* Create a new XSSFHyperlink. This method is protected to be used only by XSSFCreationHelper
* @param type - the type of hyperlink to create
*/
protected XSSFHyperlink(int type) {
- this.type = type;
- this.ctHyperlink = CTHyperlink.Factory.newInstance();
+ _type = type;
+ _ctHyperlink = CTHyperlink.Factory.newInstance();
}
/**
* @param hyperlinkRel the relationship in the underlying OPC package which stores the actual link's address
*/
protected XSSFHyperlink(CTHyperlink ctHyperlink, PackageRelationship hyperlinkRel) {
- this.ctHyperlink = ctHyperlink;
- this.externalRel = hyperlinkRel;
+ _ctHyperlink = ctHyperlink;
+ _externalRel = hyperlinkRel;
// Figure out the Hyperlink type and distination
// If it has a location, it's internal
if (ctHyperlink.getLocation() != null) {
- type = Hyperlink.LINK_DOCUMENT;
- location = ctHyperlink.getLocation();
+ _type = Hyperlink.LINK_DOCUMENT;
+ _location = ctHyperlink.getLocation();
} else {
// Otherwise it's somehow external, check
// the relation to see how
- if (externalRel == null) {
+ if (_externalRel == null) {
if (ctHyperlink.getId() != null) {
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();
- location = target.toString();
+ URI target = _externalRel.getTargetURI();
+ _location = target.toString();
// Try to figure out the type
- if (location.startsWith("http://") || location.startsWith("https://")
- || location.startsWith("ftp://")) {
- type = Hyperlink.LINK_URL;
- } else if (location.startsWith("mailto:")) {
- type = Hyperlink.LINK_EMAIL;
+ if (_location.startsWith("http://") || _location.startsWith("https://")
+ || _location.startsWith("ftp://")) {
+ _type = Hyperlink.LINK_URL;
+ } else if (_location.startsWith("mailto:")) {
+ _type = Hyperlink.LINK_EMAIL;
} else {
- type = Hyperlink.LINK_FILE;
+ _type = Hyperlink.LINK_FILE;
}
}
}
* Returns the underlying hyperlink object
*/
protected CTHyperlink getCTHyperlink() {
- return ctHyperlink;
+ return _ctHyperlink;
}
/**
* this hyperlink?
*/
public boolean needsRelationToo() {
- return (type != Hyperlink.LINK_DOCUMENT);
+ return (_type != Hyperlink.LINK_DOCUMENT);
}
/**
if (needsRelationToo()) {
// Generate the relation
PackageRelationship rel =
- sheetPart.addExternalRelationship(location, XSSFRelation.SHEET_HYPERLINKS.getRelation());
+ sheetPart.addExternalRelationship(_location, XSSFRelation.SHEET_HYPERLINKS.getRelation());
// Update the r:id
- ctHyperlink.setId(rel.getId());
+ _ctHyperlink.setId(rel.getId());
}
}
* @return the type of this hyperlink
*/
public int getType() {
- return type;
+ return _type;
}
/**
* es A55
*/
public String getCellRef() {
- return ctHyperlink.getRef();
+ return _ctHyperlink.getRef();
}
/**
* @return the address of this hyperlink
*/
public String getAddress() {
- return location;
+ return _location;
}
/**
* @return text to display
*/
public String getLabel() {
- return ctHyperlink.getDisplay();
+ return _ctHyperlink.getDisplay();
}
/**
* @return location
*/
public String getLocation() {
- return ctHyperlink.getLocation();
+ return _ctHyperlink.getLocation();
}
/**
* @param label text label for this hyperlink
*/
public void setLabel(String label) {
- ctHyperlink.setDisplay(label);
+ _ctHyperlink.setDisplay(label);
}
/**
* @param location - string representing a location of this hyperlink
*/
public void setLocation(String location) {
- ctHyperlink.setLocation(location);
+ _ctHyperlink.setLocation(location);
}
/**
* @param address - the address of this hyperlink
*/
public void setAddress(String address) {
- location = address;
- //we must set location for internal hyperlinks
- if (type == Hyperlink.LINK_DOCUMENT) {
+ _location = address;
+ //we must set location for internal hyperlinks
+ if (_type == Hyperlink.LINK_DOCUMENT) {
setLocation(address);
}
}
* Assigns this hyperlink to the given cell reference
*/
protected void setCellReference(String ref) {
- ctHyperlink.setRef(ref);
+ _ctHyperlink.setRef(ref);
}
private CellReference buildCellReference() {
- return new CellReference(ctHyperlink.getRef());
+ return new CellReference(_ctHyperlink.getRef());
}
* @param col the 0-based column of the first cell that contains the hyperlink
*/
public void setFirstColumn(int col) {
- ctHyperlink.setRef(
+ _ctHyperlink.setRef(
new CellReference(
getFirstRow(), col
).formatAsString()
* @param row the 0-based row of the first cell that contains the hyperlink
*/
public void setFirstRow(int row) {
- ctHyperlink.setRef(
+ _ctHyperlink.setRef(
new CellReference(
row, getFirstColumn()
).formatAsString()
*/
public final static String BUILTIN_SHEET_TITLE = "_xlnm.Sheet_Title";
- private XSSFWorkbook workbook;
- private CTDefinedName ctName;
+ private XSSFWorkbook _workbook;
+ private CTDefinedName _ctName;
/**
* Creates an XSSFName object - called internally by XSSFWorkbook.
* @see org.apache.poi.xssf.usermodel.XSSFWorkbook#createName()
*/
protected XSSFName(CTDefinedName name, XSSFWorkbook workbook) {
- this.workbook = workbook;
- this.ctName = name;
+ _workbook = workbook;
+ _ctName = name;
}
/**
* Returns the underlying named range object
*/
protected CTDefinedName getCTName() {
- return ctName;
+ return _ctName;
}
/**
* @return text name of this defined name
*/
public String getNameName() {
- return ctName.getName();
+ return _ctName.getName();
}
/**
int sheetIndex = getSheetIndex();
//Check to ensure no other names have the same case-insensitive name
- for (int i = 0; i < workbook.getNumberOfNames(); i++) {
- XSSFName nm = workbook.getNameAt(i);
+ for (int i = 0; i < _workbook.getNumberOfNames(); i++) {
+ XSSFName nm = _workbook.getNameAt(i);
if (nm != this) {
if(name.equalsIgnoreCase(nm.getNameName()) && sheetIndex == nm.getSheetIndex()){
String msg = "The "+(sheetIndex == -1 ? "workbook" : "sheet")+" already contains this name: " + name;
}
}
}
- ctName.setName(name);
+ _ctName.setName(name);
}
public String getRefersToFormula() {
- String result = ctName.getStringValue();
+ String result = _ctName.getStringValue();
if (result == null || result.length() < 1) {
return null;
}
}
public void setRefersToFormula(String formulaText) {
- XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(workbook);
+ XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(_workbook);
//validate through the FormulaParser
FormulaParser.parse(formulaText, fpb, FormulaType.NAMEDRANGE, getSheetIndex());
- ctName.setStringValue(formulaText);
+ _ctName.setStringValue(formulaText);
}
public boolean isDeleted(){
if (formulaText == null) {
return false;
}
- XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(workbook);
+ XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(_workbook);
Ptg[] ptgs = FormulaParser.parse(formulaText, fpb, FormulaType.NAMEDRANGE, getSheetIndex());
return Ptg.doesFormulaReferToDeletedCell(ptgs);
}
* @param index the sheet index this name applies to, -1 unsets this property making the name workbook-global
*/
public void setSheetIndex(int index) {
- int lastSheetIx = workbook.getNumberOfSheets() - 1;
+ int lastSheetIx = _workbook.getNumberOfSheets() - 1;
if (index < -1 || index > lastSheetIx) {
throw new IllegalArgumentException("Sheet index (" + index +") is out of range" +
(lastSheetIx == -1 ? "" : (" (0.." + lastSheetIx + ")")));
}
if(index == -1) {
- if(ctName.isSetLocalSheetId()) ctName.unsetLocalSheetId();
+ if(_ctName.isSetLocalSheetId()) _ctName.unsetLocalSheetId();
} else {
- ctName.setLocalSheetId(index);
+ _ctName.setLocalSheetId(index);
}
}
* @return the sheet index this name applies to, -1 if this name applies to the entire workbook
*/
public int getSheetIndex() {
- return ctName.isSetLocalSheetId() ? (int) ctName.getLocalSheetId() : -1;
+ return _ctName.isSetLocalSheetId() ? (int) _ctName.getLocalSheetId() : -1;
}
/**
* @param value <code>true</code> indicates the name refers to a function.
*/
public void setFunction(boolean value) {
- ctName.setFunction(value);
+ _ctName.setFunction(value);
}
/**
* @return <code>true</code> indicates the name refers to a function.
*/
public boolean getFunction() {
- return ctName.getFunction();
+ return _ctName.getFunction();
}
/**
* @param functionGroupId the function group index that defines the general category for the function
*/
public void setFunctionGroupId(int functionGroupId) {
- ctName.setFunctionGroupId(functionGroupId);
+ _ctName.setFunctionGroupId(functionGroupId);
}
/**
* @return the function group index that defines the general category for the function
*/
public int getFunctionGroupId() {
- return (int) ctName.getFunctionGroupId();
+ return (int) _ctName.getFunctionGroupId();
}
/**
* Empty string if the referenced sheet name weas not found.
*/
public String getSheetName() {
- if (ctName.isSetLocalSheetId()) {
+ if (_ctName.isSetLocalSheetId()) {
// Given as explicit sheet id
- int sheetId = (int)ctName.getLocalSheetId();
- return workbook.getSheetName(sheetId);
- } else {
- String ref = getRefersToFormula();
- AreaReference areaRef = new AreaReference(ref);
- return areaRef.getFirstCell().getSheetName();
+ int sheetId = (int)_ctName.getLocalSheetId();
+ return _workbook.getSheetName(sheetId);
}
+ String ref = getRefersToFormula();
+ AreaReference areaRef = new AreaReference(ref);
+ return areaRef.getFirstCell().getSheetName();
}
/**
* @return the user comment for this named range
*/
public String getComment() {
- return ctName.getComment();
+ return _ctName.getComment();
}
/**
* @param comment the user comment for this named range
*/
public void setComment(String comment) {
- ctName.setComment(comment);
+ _ctName.setComment(comment);
}
@Override
public int hashCode() {
- return ctName.toString().hashCode();
+ return _ctName.toString().hashCode();
}
/**
if (!(o instanceof XSSFName)) return false;
XSSFName cf = (XSSFName) o;
- return ctName.toString().equals(cf.getCTName().toString());
+ return _ctName.toString().equals(cf.getCTName().toString());
}
private static void validateName(String name){
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
/**
- *
+ *
*/
public final class XSSFRelation extends POIXMLRelation {
"/xl/drawings/vmlDrawing#.vml",
null
);
-
+
public static final XSSFRelation CUSTOM_XML_MAPPINGS = new XSSFRelation(
"application/xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/xmlMaps",
"/xl/xmlMaps.xml",
MapInfo.class
);
-
+
public static final XSSFRelation SINGLE_XML_CELLS = new XSSFRelation(
"application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableSingleCells",
"/tables/tableSingleCells#.xml",
SingleXmlCells.class
);
-
+
public static final XSSFRelation TABLE = new XSSFRelation(
"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/table",
"/tables/table#.xml",
Table.class
);
-
+
public static final XSSFRelation IMAGES = new XSSFRelation(
null,
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/xl/calcChain.xml",
CalculationChain.class
);
-
+
private XSSFRelation(String type, String rel, String defaultName, Class<? extends POIXMLDocumentPart> cls) {
super(type, rel, defaultName, cls);
PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI());
PackagePart part = corePart.getPackage().getPart(relName);
return part.getInputStream();
- } else {
- log.log(POILogger.WARN, "No part " + _defaultName + " found");
- return null;
}
+ log.log(POILogger.WARN, "No part " + _defaultName + " found");
+ return null;
}
* Returns the plain string representation.
*/
public String getString() {
- if(st.sizeOfRArray() == 0) return st.getT();
- else {
- StringBuffer buf = new StringBuffer();
- for(CTRElt r : st.getRArray()){
- buf.append(r.getT());
- }
- return buf.toString();
+ if(st.sizeOfRArray() == 0) {
+ return st.getT();
+ }
+ StringBuffer buf = new StringBuffer();
+ for(CTRElt r : st.getRArray()){
+ buf.append(r.getT());
}
+ return buf.toString();
}
/**
/**
* 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.
* 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
*/
- private final XSSFSheet sheet;
+ private final XSSFSheet _sheet;
/**
* Construct a XSSFRow.
* @param sheet the parent sheet.
*/
protected XSSFRow(CTRow row, XSSFSheet sheet) {
- this.row = row;
- this.sheet = sheet;
- this.cells = new TreeMap<Integer, Cell>();
+ _row = row;
+ _sheet = sheet;
+ _cells = new TreeMap<Integer, Cell>();
for (CTCell c : row.getCArray()) {
XSSFCell cell = new XSSFCell(this, c);
- cells.put(cell.getColumnIndex(), cell);
+ _cells.put(cell.getColumnIndex(), cell);
sheet.onReadCell(cell);
}
}
* @return the XSSFSheet that owns this row
*/
public XSSFSheet getSheet() {
- return this.sheet;
+ return this._sheet;
}
/**
* @return an iterator over cells in this row.
*/
public Iterator<Cell> cellIterator() {
- return cells.values().iterator();
+ return _cells.values().iterator();
}
/**
if (type != Cell.CELL_TYPE_BLANK) {
xcell.setCellType(type);
}
- cells.put(columnIndex, xcell);
+ _cells.put(columnIndex, xcell);
return xcell;
}
* @return the cell at the given (0 based) index
*/
public XSSFCell getCell(int cellnum) {
- return getCell(cellnum, sheet.getWorkbook().getMissingCellPolicy());
+ return getCell(cellnum, _sheet.getWorkbook().getMissingCellPolicy());
}
/**
public XSSFCell getCell(int cellnum, MissingCellPolicy policy) {
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) {
return cell;
}
* or -1 if the row does not contain any cells.
*/
public short getFirstCellNum() {
- return (short)(cells.size() == 0 ? -1 : cells.firstKey());
+ return (short)(_cells.size() == 0 ? -1 : _cells.firstKey());
}
/**
* or -1 if the row does not contain any cells.
*/
public short getLastCellNum() {
- return (short)(cells.size() == 0 ? -1 : (cells.lastKey() + 1));
+ return (short)(_cells.size() == 0 ? -1 : (_cells.lastKey() + 1));
}
/**
* @see org.apache.poi.xssf.usermodel.XSSFSheet#getDefaultRowHeightInPoints()
*/
public float getHeightInPoints() {
- if (this.row.isSetHt()) {
- return (float) this.row.getHt();
- } else {
- return sheet.getDefaultRowHeightInPoints();
+ if (this._row.isSetHt()) {
+ return (float) this._row.getHt();
}
+ return _sheet.getDefaultRowHeightInPoints();
}
/**
*/
public void setHeight(short height) {
if (height == -1) {
- if (row.isSetHt()) row.unsetHt();
- if (row.isSetCustomHeight()) row.unsetCustomHeight();
+ if (_row.isSetHt()) _row.unsetHt();
+ if (_row.isSetCustomHeight()) _row.unsetCustomHeight();
} else {
- row.setHt((double) height / 20);
- row.setCustomHeight(true);
+ _row.setHt((double) height / 20);
+ _row.setCustomHeight(true);
}
}
* @return int representing the number of defined cells in the row.
*/
public int getPhysicalNumberOfCells() {
- return cells.size();
+ return _cells.size();
}
/**
* @return the row number (0 based)
*/
public int getRowNum() {
- return (int) (row.getR() - 1);
+ return (int) (_row.getR() - 1);
}
/**
public void setRowNum(int rowIndex) {
int maxrow = SpreadsheetVersion.EXCEL2007.getLastRowIndex();
if (rowIndex < 0 || rowIndex > maxrow) {
- throw new IllegalArgumentException("Invalid row number (" + rowIndex
+ throw new IllegalArgumentException("Invalid row number (" + rowIndex
+ ") outside allowable range (0.." + maxrow + ")");
}
- row.setR(rowIndex + 1);
+ _row.setR(rowIndex + 1);
}
/**
* @return - height is zero or not.
*/
public boolean getZeroHeight() {
- return this.row.getHidden();
+ return this._row.getHidden();
}
/**
* @param height height is zero or not.
*/
public void setZeroHeight(boolean height) {
- this.row.setHidden(height);
+ this._row.setHidden(height);
}
* @param cell the cell to remove
*/
public void removeCell(Cell cell) {
- cells.remove(cell.getColumnIndex());
+ _cells.remove(cell.getColumnIndex());
}
/**
* @return the underlying CTRow xml bean
*/
public CTRow getCTRow(){
- return row;
+ return _row;
}
/**
* @see org.apache.poi.xssf.usermodel.XSSFSheet#commit()
*/
protected void onDocumentWrite(){
- ArrayList<CTCell> cArray = new ArrayList<CTCell>(cells.size());
+ ArrayList<CTCell> cArray = new ArrayList<CTCell>(_cells.size());
//create array of CTCell objects.
//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;
cArray.add(c.getCTCell());
}
- row.setCArray(cArray.toArray(new CTCell[cArray.size()]));
+ _row.setCArray(cArray.toArray(new CTCell[cArray.size()]));
}
/**
*/
@Override
public String toString(){
- return row.toString();
+ return _row.toString();
}
/**
*/
protected void shift(int n) {
int rownum = getRowNum() + n;
- CalculationChain calcChain = sheet.getWorkbook().getCalculationChain();
- int sheetId = (int)sheet.sheet.getSheetId();
+ CalculationChain calcChain = _sheet.getWorkbook().getCalculationChain();
+ int sheetId = (int)_sheet.sheet.getSheetId();
for(Cell c : this){
XSSFCell cell = (XSSFCell)c;
}
public XSSFComment getCellComment(int row, int column) {
- if (sheetComments == null) return null;
- else return sheetComments.findCellComment(row, column);
+ if (sheetComments == null) {
+ return null;
+ }
+ return sheetComments.findCellComment(row, column);
}
public XSSFHyperlink getHyperlink(int row, int column) {
}
if (endLevel > startLevel) {
return endHidden;
- } else {
- return startHidden;
}
+ return startHidden;
}
/**
*/
private boolean isRowGroupCollapsed(int row) {
int collapseRow = findEndOfRowOutlineGroup(row) + 1;
- if (getRow(collapseRow) == null)
- return false;
- else
- return getRow(collapseRow).getCTRow().getCollapsed();
+ if (getRow(collapseRow) == null) {
+ return false;
+ }
+ return getRow(collapseRow).getCTRow().getCollapsed();
}
/**
if (o instanceof CTFtnEdnRef) {
CTFtnEdnRef ftn = (CTFtnEdnRef) o;
footnoteText.append("[").append(ftn.getId()).append(": ");
- XWPFFootnote footnote =
+ XWPFFootnote footnote =
ftn.getDomNode().getLocalName().equals("footnoteReference") ?
document.getFootnoteByID(ftn.getId().intValue()) :
document.getEndnoteByID(ftn.getId().intValue());
CTOnOff ct_pageBreak = ppr.isSetPageBreakBefore() ? ppr
.getPageBreakBefore() : null;
if (ct_pageBreak != null
- && ct_pageBreak.getVal().intValue() == STOnOff.INT_TRUE)
+ && ct_pageBreak.getVal().intValue() == STOnOff.INT_TRUE) {
return true;
- else
- return false;
+ }
+ return false;
}
/**
return (wordWrap.getVal() == STOnOff.ON
|| wordWrap.getVal() == STOnOff.TRUE || wordWrap.getVal() == STOnOff.X_1) ? true
: false;
- } else
- return false;
+ }
+ return false;
}
/**
* @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) {
- if (pos >= 0 && pos < ctTbl.sizeOfTrArray())
+ if (pos >= 0 && pos < ctTbl.sizeOfTrArray()) {
return new XWPFTableRow(ctTbl.getTrArray(pos));
- else
- return null;
+ }
+ return null;
}
}
public XWPFTableCell getCell(int pos) {
- if (pos >= 0 && pos < ctRow.sizeOfTcArray())
+ if (pos >= 0 && pos < ctRow.sizeOfTcArray()) {
return new XWPFTableCell(ctRow.getTcArray(pos));
- else
- return null;
+ }
+ return null;
}
/**
}
public boolean isEmpty()
{
- if(_start - _end == 0)
- {
- return true;
- }
- else
- {
- return false;
- }
+ return _start - _end == 0;
}
-
}
}
public static boolean getFlag(int x)
{
- if(x != 0)
- {
- return true;
- }
- else
- {
- return false;
- }
+ return x != 0;
}
}
{
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 pieceTableSize = LittleEndian.getInt(tableStream, ++pos);
+ pos += 4;
+ int pieces = (pieceTableSize - 4) / 12;
+ for (int x = 0; x < pieces; x++)
+ {
+ int filePos = LittleEndian.getInt(tableStream, pos + ((pieces + 1) * 4) + (x * 8) + 2);
+ boolean unicode = false;
+ if ((filePos & 0x40000000) == 0)
{
- int filePos = LittleEndian.getInt(tableStream, pos + ((pieces + 1) * 4) + (x * 8) + 2);
- 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);
-
+ 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);
}
}
* @param size of the paragraph bin table.
*/
private void findFormatting(byte[] tableStream, int charOffset,
- int charPlcSize, int parOffset, int parPlcSize) throws IOException
- {
+ int charPlcSize, int parOffset, int parPlcSize) {
openDoc();
createStyleSheet(tableStream);
createListTables(tableStream);
private ArrayList findProperties(int start, int end, BTreeSet.BTreeNode root)
{
ArrayList results = new ArrayList();
- BTreeSet.Entry[] entries = root.entries;
+ BTreeSet.Entry[] entries = root._entries;
for(int x = 0; x < entries.length; x++)
{
private ArrayList findPAPProperties(int start, int end, BTreeSet.BTreeNode root)
{
ArrayList results = new ArrayList();
- BTreeSet.Entry[] entries = root.entries;
+ BTreeSet.Entry[] entries = root._entries;
for(int x = 0; x < entries.length; x++)
{
*/
public BTreeNode root;
private Comparator comparator = null;
- private int order;
- private int size = 0;
+ int order;
+ int size = 0;
/*
* Constructors
}
public java.util.Iterator iterator() {
- return new Iterator();
+ return new BTIterator();
}
/*
* 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));
}
* 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 Stack parentIndex = new Stack(); // Contains all parentIndicies for currentNode
+ Stack parentIndex = new Stack(); // Contains all parentIndicies for currentNode
private Object lastReturned = null;
private Object next;
- private BTreeNode currentNode;
+ BTreeNode currentNode;
- Iterator() {
+ BTIterator() {
currentNode = firstNode();
next = nextElement();
}
private BTreeNode firstNode() {
BTreeNode temp = BTreeSet.this.root;
- while (temp.entries[0].child != null) {
- temp = temp.entries[0].child;
+ while (temp._entries[0].child != null) {
+ temp = temp._entries[0].child;
parentIndex.push(new Integer(0));
}
private Object nextElement() {
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
- currentNode = currentNode.parent;
+ currentNode = currentNode._parent;
index = ((Integer)parentIndex.pop()).intValue();
- while (index == currentNode.nrElements) {
+ while (index == currentNode._nrElements) {
if (parentIndex.empty()) break;
- currentNode = currentNode.parent;
+ currentNode = currentNode._parent;
index = ((Integer)parentIndex.pop()).intValue();
}
- if (index == currentNode.nrElements) return null; //Reached root and he has no more children
- return currentNode.entries[index++].element;
+ if (index == currentNode._nrElements) return null; //Reached root and he has no more children
+ return currentNode._entries[index++].element;
}
else { //Your a leaf and the root
- if (index == currentNode.nrElements) return null;
- return currentNode.entries[index++].element;
+ if (index == currentNode._nrElements) return null;
+ return currentNode._entries[index++].element;
}
}
- else { //Your not a leaf so simply find and return the successor of lastReturned
- currentNode = currentNode.entries[index].child;
- parentIndex.push(new Integer(index));
+ // else - You're not a leaf so simply find and return the successor of lastReturned
+ currentNode = currentNode._entries[index].child;
+ parentIndex.push(new Integer(index));
- while (currentNode.entries[0].child != null) {
- currentNode = currentNode.entries[0].child;
- parentIndex.push(new Integer(0));
- }
-
- index = 1;
- return currentNode.entries[0].element;
+ while (currentNode._entries[0].child != null) {
+ currentNode = currentNode._entries[0].child;
+ parentIndex.push(new Integer(0));
}
+
+ index = 1;
+ return currentNode._entries[0].element;
}
}
public class BTreeNode {
- public Entry[] entries;
- public BTreeNode parent;
- private int nrElements = 0;
+ public Entry[] _entries;
+ public BTreeNode _parent;
+ int _nrElements = 0;
private final int MIN = (BTreeSet.this.order - 1) / 2;
BTreeNode(BTreeNode parent) {
- this.parent = parent;
- entries = new Entry[BTreeSet.this.order];
- entries[0] = new Entry();
+ _parent = parent;
+ _entries = new Entry[BTreeSet.this.order];
+ _entries[0] = new Entry();
}
boolean insert(Object x, int parentIndex) {
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();
if (isRoot()) { // Grow a level
splitRoot(splitNode, this, rightSibling);
// 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 { // Promote splitNode
- parent.insertSplitNode(splitNode, this, rightSibling, parentIndex);
- if (BTreeSet.this.compare(x, parent.entries[parentIndex].element) < 0) return insert(x, parentIndex);
- else return rightSibling.insert(x, parentIndex + 1);
+ _parent.insertSplitNode(splitNode, this, rightSibling, parentIndex);
+ if (BTreeSet.this.compare(x, _parent._entries[parentIndex].element) < 0) {
+ return insert(x, parentIndex);
+ }
+ return rightSibling.insert(x, parentIndex + 1);
}
}
else if (isLeaf()) { // If leaf, simply insert the non-duplicate element
int insertAt = childToInsertAt(x, true);
- if (insertAt == -1) return false; // Determine if the element already exists
- else {
- insertNewElement(x, insertAt);
- BTreeSet.this.size++;
- return true;
+ if (insertAt == -1) {
+ return false; // Determine if the element already exists
}
+ insertNewElement(x, insertAt);
+ BTreeSet.this.size++;
+ return true;
}
else { // If not full and not leaf recursively find correct node to insert at
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;
}
boolean includes(Object x) {
int index = childToInsertAt(x, true);
if (index == -1) return true;
- if (entries[index] == null || entries[index].child == null) return false;
- return entries[index].child.includes(x);
+ if (_entries[index] == null || _entries[index].child == null) return false;
+ return _entries[index].child.includes(x);
}
boolean delete(Object x, int parentIndex) {
BTreeNode temp = this;
if (i != -1) {
do {
- if (temp.entries[i] == null || temp.entries[i].child == null) return false;
- temp = temp.entries[i].child;
+ if (temp._entries[i] == null || temp._entries[i].child == null) return false;
+ temp = temp._entries[i].child;
priorParentIndex = parentIndex;
parentIndex = i;
i = temp.childToInsertAt(x, true);
} // 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.nrElements > MIN) {
+ if (temp._nrElements > MIN) {
temp.deleteElement(x);
BTreeSet.this.size--;
return true;
}
- else { // If leaf and have less than MIN elements, than prepare the BTreeSet for deletion
- temp.prepareForDeletion(parentIndex);
- temp.deleteElement(x);
- BTreeSet.this.size--;
- temp.fixAfterDeletion(priorParentIndex);
- return true;
- }
+ // else If leaf and have less than MIN elements, than prepare the BTreeSet for deletion
+ temp.prepareForDeletion(parentIndex);
+ temp.deleteElement(x);
+ BTreeSet.this.size--;
+ temp.fixAfterDeletion(priorParentIndex);
+ return true;
}
- else { // Only delete at leaf so first switch with successor than delete
- temp.switchWithSuccessor(x);
- parentIndex = temp.childToInsertAt(x, false) + 1;
- return temp.entries[parentIndex].child.delete(x, parentIndex);
- }
+ // else Only delete at leaf so first switch with successor than delete
+ temp.switchWithSuccessor(x);
+ parentIndex = temp.childToInsertAt(x, false) + 1;
+ 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
* calling BTreeNode.
*/
private BTreeNode split() {
- BTreeNode rightSibling = new BTreeNode(parent);
- int index = nrElements / 2;
- entries[index++].element = null;
-
- for (int i = 0, nr = nrElements; index <= nr; i++, index++) {
- rightSibling.entries[i] = entries[index];
- if (rightSibling.entries[i] != null && rightSibling.entries[i].child != null)
- rightSibling.entries[i].child.parent = rightSibling;
- entries[index] = null;
- nrElements--;
- rightSibling.nrElements++;
+ BTreeNode rightSibling = new BTreeNode(_parent);
+ int index = _nrElements / 2;
+ _entries[index++].element = null;
+
+ for (int i = 0, nr = _nrElements; index <= nr; i++, index++) {
+ rightSibling._entries[i] = _entries[index];
+ if (rightSibling._entries[i] != null && rightSibling._entries[i].child != null)
+ rightSibling._entries[i].child._parent = rightSibling;
+ _entries[index] = null;
+ _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;
}
*/
private void splitRoot(Object splitNode, BTreeNode left, BTreeNode right) {
BTreeNode newRoot = new BTreeNode(null);
- newRoot.entries[0].element = splitNode;
- newRoot.entries[0].child = left;
- newRoot.entries[1] = new Entry();
- newRoot.entries[1].child = right;
- newRoot.nrElements = 1;
- left.parent = right.parent = newRoot;
+ newRoot._entries[0].element = splitNode;
+ newRoot._entries[0].child = left;
+ newRoot._entries[1] = new Entry();
+ newRoot._entries[1].child = right;
+ newRoot._nrElements = 1;
+ left._parent = right._parent = newRoot;
BTreeSet.this.root = newRoot;
}
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].element = splitNode;
- entries[insertAt].child = left;
- entries[insertAt + 1].child = right;
+ _entries[insertAt] = new Entry();
+ _entries[insertAt].element = splitNode;
+ _entries[insertAt].child = left;
+ _entries[insertAt + 1].child = right;
- nrElements++;
+ _nrElements++;
}
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].element = x;
+ _entries[insertAt] = new Entry();
+ _entries[insertAt].element = x;
- nrElements++;
+ _nrElements++;
}
/*
* in entries[] is returned.
*/
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) {
- if (BTreeSet.this.compare(x, entries[index].element) > 0) {
+ if (BTreeSet.this.compare(x, _entries[index].element) > 0) {
lo = index + 1;
index = (hi + lo) / 2;
}
}
hi++;
- if (entries[hi] == null || entries[hi].element == null) return hi;
- return (!position ? hi : BTreeSet.this.compare(x, entries[hi].element) == 0 ? -1 : hi);
+ if (_entries[hi] == null || _entries[hi].element == null) return hi;
+ return (!position ? hi : BTreeSet.this.compare(x, _entries[hi].element) == 0 ? -1 : hi);
}
private void deleteElement(Object x) {
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
- else entries[index] = null;
+ if (_nrElements == 1) _entries[index] = new Entry(); // This is root and it is empty
+ else _entries[index] = null;
- nrElements--;
+ _nrElements--;
}
private void prepareForDeletion(int parentIndex) {
if (isRoot()) return; // Don't attempt to steal or merge if your the root
// 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);
return;
}
// 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);
return;
}
}
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
- BTreeNode temp = parent;
+ if (_parent._nrElements < MIN) { // If parent lost it's n/2 element repair it
+ BTreeNode temp = _parent;
temp.prepareForDeletion(parentIndex);
- if (temp.parent == null) return; // Root changed
- if (!temp.parent.isRoot() && temp.parent.nrElements < MIN) { // If need be recurse
- BTreeNode x = temp.parent.parent;
+ if (temp._parent == null) return; // Root changed
+ if (!temp._parent.isRoot() && temp._parent._nrElements < MIN) { // If need be recurse
+ BTreeNode x = temp._parent._parent;
int i = 0;
// Find parent's parentIndex
- for (; i < entries.length; i++) if (x.entries[i].child == temp.parent) break;
- temp.parent.fixAfterDeletion(i);
+ for (; i < _entries.length; i++) if (x._entries[i].child == temp._parent) break;
+ temp._parent.fixAfterDeletion(i);
}
}
}
private void switchWithSuccessor(Object x) {
int index = childToInsertAt(x, false);
- BTreeNode temp = entries[index + 1].child;
- while (temp.entries[0] != null && temp.entries[0].child != null) temp = temp.entries[0].child;
- Object successor = temp.entries[0].element;
- temp.entries[0].element = entries[index].element;
- entries[index].element = successor;
+ BTreeNode temp = _entries[index + 1].child;
+ while (temp._entries[0] != null && temp._entries[0].child != null) temp = temp._entries[0].child;
+ Object successor = temp._entries[0].element;
+ temp._entries[0].element = _entries[index].element;
+ _entries[index].element = successor;
}
/*
* has a leftSibling, and the leftSibling has more than the minimum number of elements.
*/
private void stealLeft(int parentIndex) {
- BTreeNode p = parent;
- BTreeNode ls = parent.entries[parentIndex - 1].child;
+ BTreeNode p = _parent;
+ BTreeNode ls = _parent._entries[parentIndex - 1].child;
if (isLeaf()) { // When stealing from leaf to leaf don't worry about children
- int add = childToInsertAt(p.entries[parentIndex - 1].element, true);
- insertNewElement(p.entries[parentIndex - 1].element, add);
- p.entries[parentIndex - 1].element = ls.entries[ls.nrElements - 1].element;
- ls.entries[ls.nrElements - 1] = null;
- ls.nrElements--;
+ int add = childToInsertAt(p._entries[parentIndex - 1].element, true);
+ insertNewElement(p._entries[parentIndex - 1].element, add);
+ p._entries[parentIndex - 1].element = ls._entries[ls._nrElements - 1].element;
+ ls._entries[ls._nrElements - 1] = null;
+ ls._nrElements--;
}
else { // Was called recursively to fix an undermanned parent
- entries[0].element = p.entries[parentIndex - 1].element;
- p.entries[parentIndex - 1].element = ls.entries[ls.nrElements - 1].element;
- entries[0].child = ls.entries[ls.nrElements].child;
- entries[0].child.parent = this;
- ls.entries[ls.nrElements] = null;
- ls.entries[ls.nrElements - 1].element = null;
- nrElements++;
- ls.nrElements--;
+ _entries[0].element = p._entries[parentIndex - 1].element;
+ p._entries[parentIndex - 1].element = ls._entries[ls._nrElements - 1].element;
+ _entries[0].child = ls._entries[ls._nrElements].child;
+ _entries[0].child._parent = this;
+ ls._entries[ls._nrElements] = null;
+ ls._entries[ls._nrElements - 1].element = null;
+ _nrElements++;
+ ls._nrElements--;
}
}
* has more than the minimum number of elements.
*/
private void stealRight(int parentIndex) {
- BTreeNode p = parent;
- BTreeNode rs = p.entries[parentIndex + 1].child;
+ BTreeNode p = _parent;
+ BTreeNode rs = p._entries[parentIndex + 1].child;
if (isLeaf()) { // When stealing from leaf to leaf don't worry about children
- entries[nrElements] = new Entry();
- entries[nrElements].element = p.entries[parentIndex].element;
- p.entries[parentIndex].element = rs.entries[0].element;
- for (int i = 0; i < rs.nrElements; i++) rs.entries[i] = rs.entries[i + 1];
- rs.entries[rs.nrElements - 1] = null;
- nrElements++;
- rs.nrElements--;
+ _entries[_nrElements] = new Entry();
+ _entries[_nrElements].element = p._entries[parentIndex].element;
+ p._entries[parentIndex].element = rs._entries[0].element;
+ for (int i = 0; i < rs._nrElements; i++) rs._entries[i] = rs._entries[i + 1];
+ rs._entries[rs._nrElements - 1] = null;
+ _nrElements++;
+ rs._nrElements--;
}
else { // Was called recursively to fix an undermanned parent
- for (int i = 0; i <= nrElements; i++) entries[i] = entries[i + 1];
- entries[nrElements].element = p.entries[parentIndex].element;
- p.entries[parentIndex].element = rs.entries[0].element;
- entries[nrElements + 1] = new Entry();
- entries[nrElements + 1].child = rs.entries[0].child;
- entries[nrElements + 1].child.parent = this;
- for (int i = 0; i <= rs.nrElements; i++) rs.entries[i] = rs.entries[i + 1];
- rs.entries[rs.nrElements] = null;
- nrElements++;
- rs.nrElements--;
+ for (int i = 0; i <= _nrElements; i++) _entries[i] = _entries[i + 1];
+ _entries[_nrElements].element = p._entries[parentIndex].element;
+ p._entries[parentIndex].element = rs._entries[0].element;
+ _entries[_nrElements + 1] = new Entry();
+ _entries[_nrElements + 1].child = rs._entries[0].child;
+ _entries[_nrElements + 1].child._parent = this;
+ for (int i = 0; i <= rs._nrElements; i++) rs._entries[i] = rs._entries[i + 1];
+ rs._entries[rs._nrElements] = null;
+ _nrElements++;
+ rs._nrElements--;
}
}
* expect the parent to be in such a condition.
*/
private void mergeLeft(int parentIndex) {
- BTreeNode p = parent;
- BTreeNode ls = p.entries[parentIndex - 1].child;
+ BTreeNode p = _parent;
+ BTreeNode ls = p._entries[parentIndex - 1].child;
if (isLeaf()) { // Don't worry about children
- int add = childToInsertAt(p.entries[parentIndex - 1].element, true);
- insertNewElement(p.entries[parentIndex - 1].element, add); // Could have been a successor switch
- p.entries[parentIndex - 1].element = null;
+ int add = childToInsertAt(p._entries[parentIndex - 1].element, true);
+ insertNewElement(p._entries[parentIndex - 1].element, add); // Could have been a successor switch
+ p._entries[parentIndex - 1].element = null;
- for (int i = nrElements - 1, nr = ls.nrElements; i >= 0; i--)
- entries[i + nr] = entries[i];
+ for (int i = _nrElements - 1, nr = ls._nrElements; i >= 0; i--)
+ _entries[i + nr] = _entries[i];
- for (int i = ls.nrElements - 1; i >= 0; i--) {
- entries[i] = ls.entries[i];
- nrElements++;
+ for (int i = ls._nrElements - 1; i >= 0; i--) {
+ _entries[i] = ls._entries[i];
+ _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--)
- p.entries[x] = p.entries[y];
- 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[x] = p._entries[y];
+ 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
}
else {
- for (int x = parentIndex - 1, y = parentIndex; y <= p.nrElements; x++, y++)
- p.entries[x] = p.entries[y];
- p.entries[p.nrElements] = null;
+ for (int x = parentIndex - 1, y = parentIndex; y <= p._nrElements; x++, y++)
+ p._entries[x] = p._entries[y];
+ 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;
- parent = null;
+ _parent = null;
}
}
else { // I'm not a leaf but fixing the tree structure
- entries[0].element = p.entries[parentIndex - 1].element;
- entries[0].child = ls.entries[ls.nrElements].child;
- nrElements++;
+ _entries[0].element = p._entries[parentIndex - 1].element;
+ _entries[0].child = ls._entries[ls._nrElements].child;
+ _nrElements++;
- for (int x = nrElements, nr = ls.nrElements; x >= 0; x--)
- entries[x + nr] = entries[x];
+ for (int x = _nrElements, nr = ls._nrElements; x >= 0; x--)
+ _entries[x + nr] = _entries[x];
- for (int x = ls.nrElements - 1; x >= 0; x--) {
- entries[x] = ls.entries[x];
- entries[x].child.parent = this;
- nrElements++;
+ for (int x = ls._nrElements - 1; x >= 0; x--) {
+ _entries[x] = ls._entries[x];
+ _entries[x].child._parent = this;
+ _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++){
System.out.println(x + " " + y);
- p.entries[x] = p.entries[y];}
- p.entries[0] = new Entry();
+ p._entries[x] = p._entries[y];}
+ p._entries[0] = new Entry();
}
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++)
- p.entries[x] = p.entries[y];
- p.entries[p.nrElements] = null;
+ for (int x = parentIndex - 1, y = parentIndex; y <= p._nrElements; x++, y++)
+ p._entries[x] = p._entries[y];
+ 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;
- parent = null;
+ _parent = null;
}
}
}
* expect the parent to be in such a condition.
*/
private void mergeRight(int parentIndex) {
- BTreeNode p = parent;
- BTreeNode rs = p.entries[parentIndex + 1].child;
+ BTreeNode p = _parent;
+ BTreeNode rs = p._entries[parentIndex + 1].child;
if (isLeaf()) { // Don't worry about children
- entries[nrElements] = new Entry();
- entries[nrElements].element = p.entries[parentIndex].element;
- nrElements++;
- for (int i = 0, nr = nrElements; i < rs.nrElements; i++, nr++) {
- entries[nr] = rs.entries[i];
- nrElements++;
+ _entries[_nrElements] = new Entry();
+ _entries[_nrElements].element = p._entries[parentIndex].element;
+ _nrElements++;
+ for (int i = 0, nr = _nrElements; i < rs._nrElements; i++, nr++) {
+ _entries[nr] = rs._entries[i];
+ _nrElements++;
}
- p.entries[parentIndex].element = p.entries[parentIndex + 1].element;
- if (p.nrElements == MIN && p != BTreeSet.this.root) {
+ p._entries[parentIndex].element = p._entries[parentIndex + 1].element;
+ if (p._nrElements == MIN && p != BTreeSet.this.root) {
for (int x = parentIndex + 1, y = parentIndex; y >= 0; x--, y--)
- p.entries[x] = p.entries[y];
- 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[x] = p._entries[y];
+ 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
}
else {
- for (int x = parentIndex + 1, y = parentIndex + 2; y <= p.nrElements; x++, y++)
- p.entries[x] = p.entries[y];
- p.entries[p.nrElements] = null;
+ for (int x = parentIndex + 1, y = parentIndex + 2; y <= p._nrElements; x++, y++)
+ p._entries[x] = p._entries[y];
+ p._entries[p._nrElements] = null;
}
- p.nrElements--;
- if (p.isRoot() && p.nrElements == 0) { // It's the root and it's empty
+ p._nrElements--;
+ if (p.isRoot() && p._nrElements == 0) { // It's the root and it's empty
BTreeSet.this.root = this;
- parent = null;
+ _parent = null;
}
}
else { // It's not a leaf
- entries[nrElements].element = p.entries[parentIndex].element;
- nrElements++;
+ _entries[_nrElements].element = p._entries[parentIndex].element;
+ _nrElements++;
- for (int x = nrElements + 1, y = 0; y <= rs.nrElements; x++, y++) {
- entries[x] = rs.entries[y];
- rs.entries[y].child.parent = this;
- nrElements++;
+ for (int x = _nrElements + 1, y = 0; y <= rs._nrElements; x++, y++) {
+ _entries[x] = rs._entries[y];
+ rs._entries[y].child._parent = this;
+ _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--)
- p.entries[x] = p.entries[y];
- p.entries[0] = new Entry();
+ p._entries[x] = p._entries[y];
+ p._entries[0] = new Entry();
}
else {
- for (int x = parentIndex - 1, y = parentIndex; y <= p.nrElements; x++, y++)
- p.entries[x] = p.entries[y];
- p.entries[p.nrElements] = null;
+ for (int x = parentIndex - 1, y = parentIndex; y <= p._nrElements; x++, y++)
+ p._entries[x] = p._entries[y];
+ 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;
- parent = null;
+ _parent = null;
}
}
}
}
public boolean isEmpty()
{
- if(_start - _end == 0)
- {
- return true;
- }
- else
- {
- return false;
- }
+ return _start - _end == 0;
}
-
}
*/
public static boolean getFlag(int x)
{
- if(x != 0)
- {
- return true;
- }
- else
- {
- return false;
- }
+ return x != 0;
}
}
public BTreeNode root;
private Comparator comparator = null;
private int order;
- private int size = 0;
+ int size = 0;
/*
* Constructors
/*
* 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));
}
}
}
- else
- { //Your not a leaf so simply find and return the successor of lastReturned
- currentNode = currentNode.entries[index].child;
- parentIndex.push(new Integer(index));
+ // else - You're not a leaf so simply find and return the successor of lastReturned
+ currentNode = currentNode.entries[index].child;
+ parentIndex.push(new Integer(index));
- while (currentNode.entries[0].child != null)
- {
- currentNode = currentNode.entries[0].child;
- parentIndex.push(new Integer(0));
- }
-
- index = 1;
- return currentNode.entries[0].element;
+ while (currentNode.entries[0].child != null)
+ {
+ currentNode = currentNode.entries[0].child;
+ parentIndex.push(new Integer(0));
}
+
+ index = 1;
+ return currentNode.entries[0].element;
}
}
else
{ // Promote splitNode
parent.insertSplitNode(splitNode, this, rightSibling, parentIndex);
- if (BTreeSet.this.compare(x, parent.entries[parentIndex].element) < 0) return insert(x, parentIndex);
- else return rightSibling.insert(x, parentIndex + 1);
+ if (BTreeSet.this.compare(x, parent.entries[parentIndex].element) < 0) {
+ return insert(x, parentIndex);
+ }
+ return rightSibling.insert(x, parentIndex + 1);
}
}
else if (isLeaf())
{ // If leaf, simply insert the non-duplicate element
int insertAt = childToInsertAt(x, true);
- if (insertAt == -1) return false; // Determine if the element already exists
- else
- {
- insertNewElement(x, insertAt);
- BTreeSet.this.size++;
- return true;
+ // Determine if the element already exists
+ if (insertAt == -1) {
+ return false;
}
+ insertNewElement(x, insertAt);
+ BTreeSet.this.size++;
+ return true;
}
else
return true;
}
- else
- { // If leaf and have less than MIN elements, than prepare the BTreeSet for deletion
- temp.prepareForDeletion(parentIndex);
- temp.deleteElement(x);
- BTreeSet.this.size--;
- temp.fixAfterDeletion(priorParentIndex);
- return true;
- }
+ // else - If leaf and have less than MIN elements, than prepare the BTreeSet for deletion
+ temp.prepareForDeletion(parentIndex);
+ temp.deleteElement(x);
+ BTreeSet.this.size--;
+ temp.fixAfterDeletion(priorParentIndex);
+ return true;
}
- else
- { // Only delete at leaf so first switch with successor than delete
- temp.switchWithSuccessor(x);
- parentIndex = temp.childToInsertAt(x, false) + 1;
- return temp.entries[parentIndex].child.delete(x, parentIndex);
- }
+ // else - Only delete at leaf so first switch with successor than delete
+ temp.switchWithSuccessor(x);
+ parentIndex = temp.childToInsertAt(x, false) + 1;
+ return temp.entries[parentIndex].child.delete(x, parentIndex);
+
}
/**
* 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?
boolean going = true;
if(findRawCodeInBuffer() > -1) {
// Fits in, wait for next byte
continue;
- } else {
- // Doesn't fit, output
- outputUncompressed(dataB,res);
- rawCodeLen = 0;
}
+ // Doesn't fit, output
+ outputUncompressed(dataB,res);
+ rawCodeLen = 0;
} else {
// Nothing in rawCode before, so this byte
// isn't in the buffer dictionary
if(outline == null){
logger.log(POILogger.WARN, "Outline not found for " + ShapeTypes.typeName(getShapeType()));
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);
}
}
protected POILogger log = POILogFactory.getLogger(this.getClass());
//The ppt object to write into.
- private ShapeGroup group;
+ private ShapeGroup _group;
- private AffineTransform transform;
- private Stroke stroke;
- private Paint paint;
- private Font font;
- private Color foreground;
- private Color background;
- private RenderingHints hints;
+ private AffineTransform _transform;
+ private Stroke _stroke;
+ private Paint _paint;
+ private Font _font;
+ private Color _foreground;
+ private Color _background;
+ private RenderingHints _hints;
/**
* Construct Java Graphics object which translates graphic calls in ppt drawing layer.
* @param group The shape group to write the graphics calls into.
*/
public PPGraphics2D(ShapeGroup group){
- this.group = group;
+ this._group = group;
- transform = new AffineTransform();
- stroke = new BasicStroke();
- paint = Color.black;
- font = new Font("Arial", Font.PLAIN, 12);
- background = Color.black;
- foreground = Color.white;
- hints = new RenderingHints(null);
+ _transform = new AffineTransform();
+ _stroke = new BasicStroke();
+ _paint = Color.black;
+ _font = new Font("Arial", Font.PLAIN, 12);
+ _background = Color.black;
+ _foreground = Color.white;
+ _hints = new RenderingHints(null);
}
/**
* @return the shape group being used for drawing
*/
public ShapeGroup getShapeGroup(){
- return group;
+ return _group;
}
/**
* @see java.awt.Graphics#setFont(Font)
*/
public Font getFont(){
- return font;
+ return _font;
}
/**
* @see java.awt.Graphics#drawChars(char[], int, int, int, int)
*/
public void setFont(Font font){
- this.font = font;
+ this._font = font;
}
/**
* @see java.awt.Graphics#setColor
*/
public Color getColor(){
- return foreground;
+ return _foreground;
}
/**
* @see #setStroke
*/
public Stroke getStroke(){
- return stroke;
+ return _stroke;
}
/**
* <code>Shape</code> during the rendering process
*/
public void setStroke(Stroke s){
- this.stroke = s;
+ this._stroke = s;
}
/**
* @see java.awt.Graphics#setColor
*/
public Paint getPaint(){
- return paint;
+ return _paint;
}
/**
public void setPaint(Paint paint){
if(paint == null) return;
- this.paint = paint;
- if (paint instanceof Color) foreground = (Color)paint;
+ this._paint = paint;
+ if (paint instanceof Color) _foreground = (Color)paint;
}
/**
* <code>Graphics2D</code> context.
* @return the current <code>AffineTransform</code> in the
* <code>Graphics2D</code> context.
- * @see #transform
+ * @see #_transform
* @see #setTransform
*/
public AffineTransform getTransform(){
- return new AffineTransform(transform);
+ return new AffineTransform(_transform);
}
/**
* context.
* @param Tx the <code>AffineTransform</code> object to be used in the
* rendering process
- * @see #transform
+ * @see #_transform
* @see AffineTransform
*/
public void setTransform(AffineTransform Tx) {
- transform = new AffineTransform(Tx);
+ _transform = new AffineTransform(Tx);
}
/**
* @see #setStroke
* @see #setPaint
* @see java.awt.Graphics#setColor
- * @see #transform
+ * @see #_transform
* @see #setTransform
* @see #clip
* @see #setClip
* @see #setComposite
*/
public void draw(Shape shape){
- GeneralPath path = new GeneralPath(transform.createTransformedShape(shape));
- Freeform p = new Freeform(group);
+ GeneralPath path = new GeneralPath(_transform.createTransformedShape(shape));
+ Freeform p = new Freeform(_group);
p.setPath(path);
p.getFill().setForegroundColor(null);
applyStroke(p);
- group.addShape(p);
+ _group.addShape(p);
}
/**
* @see #setClip
*/
public void drawString(String s, float x, float y) {
- TextBox txt = new TextBox(group);
- txt.getTextRun().supplySlideShow(group.getSheet().getSlideShow());
- txt.getTextRun().setSheet(group.getSheet());
+ TextBox txt = new TextBox(_group);
+ txt.getTextRun().supplySlideShow(_group.getSheet().getSlideShow());
+ txt.getTextRun().setSheet(_group.getSheet());
txt.setText(s);
RichTextRun rt = txt.getTextRun().getRichTextRuns()[0];
- rt.setFontSize(font.getSize());
- rt.setFontName(font.getFamily());
+ rt.setFontSize(_font.getSize());
+ rt.setFontName(_font.getFamily());
if (getColor() != null) rt.setFontColor(getColor());
- if (font.isBold()) rt.setBold(true);
- if (font.isItalic()) rt.setItalic(true);
+ if (_font.isBold()) rt.setBold(true);
+ if (_font.isItalic()) rt.setItalic(true);
txt.setMarginBottom(0);
txt.setMarginTop(0);
txt.setVerticalAlignment(TextBox.AnchorMiddle);
- TextLayout layout = new TextLayout(s, font, getFontRenderContext());
+ TextLayout layout = new TextLayout(s, _font, getFontRenderContext());
float ascent = layout.getAscent();
float width = (float) Math.floor(layout.getAdvance());
*/
txt.setAnchor(new Rectangle2D.Float(x, y, width, height));
- group.addShape(txt);
+ _group.addShape(txt);
}
/**
* @param shape the <code>Shape</code> to be filled
* @see #setPaint
* @see java.awt.Graphics#setColor
- * @see #transform
+ * @see #_transform
* @see #setTransform
* @see #setComposite
* @see #clip
* @see #setClip
*/
public void fill(Shape shape){
- GeneralPath path = new GeneralPath(transform.createTransformedShape(shape));
- Freeform p = new Freeform(group);
+ GeneralPath path = new GeneralPath(_transform.createTransformedShape(shape));
+ Freeform p = new Freeform(_group);
p.setPath(path);
applyPaint(p);
p.setLineColor(null); //Fills must be "No Line"
- group.addShape(p);
+ _group.addShape(p);
}
/**
* @param y the <i>y</i> coordinate.
*/
public void translate(int x, int y){
- transform.translate(x, y);
+ _transform.translate(x, y);
}
/**
* rendering operations.
*/
public void scale(double sx, double sy){
- transform.scale(sx, sy);
+ _transform.scale(sx, sy);
}
/**
*/
public Rectangle getClipBounds(){
Shape c = getClip();
- if(c==null)
+ if (c==null) {
return null;
- else
- return c.getBounds();
+ }
+ return c.getBounds();
}
/**
* @param theta the angle of rotation in radians
*/
public void rotate(double theta){
- transform.rotate(theta);
+ _transform.rotate(theta);
}
/**
* @param y y coordinate of the origin of the rotation
*/
public void rotate(double theta, double x, double y){
- transform.rotate(theta, x, y);
+ _transform.rotate(theta, x, y);
}
/**
* the positive Y axis direction as a function of their X coordinate
*/
public void shear(double shx, double shy){
- transform.shear(shx, shy);
+ _transform.shear(shx, shy);
}
/**
* @see AffineTransform
*/
public void transform(AffineTransform Tx) {
- transform.concatenate(Tx);
+ _transform.concatenate(Tx);
}
/**
* @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 y the y coordinate in user space where the image is rendered
- * @see #transform
+ * @see #_transform
* @see #setTransform
* @see #setComposite
* @see #clip
if(color == null)
return;
- background = color;
+ _background = color;
}
/**
* @see #setBackground
*/
public Color getBackground(){
- return background;
+ return _background;
}
/**
* @see RenderingHints
*/
public Object getRenderingHint(RenderingHints.Key hintKey){
- return hints.get(hintKey);
+ return _hints.get(hintKey);
}
/**
* @see RenderingHints
*/
public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue){
- hints.put(hintKey, hintValue);
+ _hints.put(hintKey, hintValue);
}
* @see RenderingHints
*/
public void addRenderingHints(Map hints){
- this.hints.putAll(hints);
+ this._hints.putAll(hints);
}
/**
* @param ty the distance to translate along the y-axis
*/
public void translate(double tx, double ty){
- transform.translate(tx, ty);
+ _transform.translate(tx, ty);
}
/**
* @see #setStroke
* @see #fill(Shape)
* @see #draw(Shape)
- * @see #transform
+ * @see #_transform
* @see #setTransform
* @see #clip
* @see #setClip(Shape)
* @see RenderingHints
*/
public RenderingHints getRenderingHints(){
- return hints;
+ return _hints;
}
/**
* @see RenderingHints
*/
public void setRenderingHints(Map hints){
- this.hints = new RenderingHints(hints);
+ this._hints = new RenderingHints(hints);
}
/**
* @return <code>true</code> if the <code>Image</code> is
* fully loaded and completely rendered;
* <code>false</code> if the <code>Image</code> is still being loaded.
- * @see #transform
+ * @see #_transform
* @see #setTransform
* @see #setComposite
* @see #clip
* @param img the image to be rendered. This method does
* nothing if <code>img</code> is null.
* @param xform the transformation from image space into user space
- * @see #transform
+ * @see #_transform
* @see #setTransform
* @see #setComposite
* @see #clip
* @param img the image to be rendered. This method does
* nothing if <code>img</code> is null.
* @param xform the transformation from image space into user space
- * @see #transform
+ * @see #_transform
* @see #setTransform
* @see #setComposite
* @see #clip
}
protected void applyStroke(SimpleShape shape) {
- if (stroke instanceof BasicStroke){
- BasicStroke bs = (BasicStroke)stroke;
+ if (_stroke instanceof BasicStroke){
+ BasicStroke bs = (BasicStroke)_stroke;
shape.setLineWidth(bs.getLineWidth());
float[] dash = bs.getDashArray();
if (dash != null) {
}
protected void applyPaint(SimpleShape shape) {
- if (paint instanceof Color) {
- shape.getFill().setForegroundColor((Color)paint);
+ if (_paint instanceof Color) {
+ shape.getFill().setForegroundColor((Color)_paint);
}
}
}
img = ImageIO.read(new ByteArrayInputStream(pict.getData()));
}
catch (IOException e){}
- catch (NegativeArraySizeException ne) {}
+ catch (NegativeArraySizeException ne) {}
if(img != null) {
- // 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));
+ // 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));
} else {
- // Invalid image, go with the default metafile size
- setAnchor(new java.awt.Rectangle(0, 0, 200, 200));
+ // Invalid image, go with the default metafile size
+ setAnchor(new java.awt.Rectangle(0, 0, 200, 200));
}
} else {
//default size of a metafile picture is 200x200
if (idx == 0){
logger.log(POILogger.DEBUG, "picture index was not found, returning ");
return null;
- } else {
- return (EscherBSERecord)lst.get(idx-1);
}
+ return (EscherBSERecord)lst.get(idx-1);
}
/**
public static Shape createShape(EscherContainerRecord spContainer, Shape parent){
if (spContainer.getRecordId() == EscherContainerRecord.SPGR_CONTAINER){
return createShapeGroup(spContainer, parent);
- } else {
- return createSimpeShape(spContainer, parent);
-
}
+ return createSimpeShape(spContainer, parent);
}
public static ShapeGroup createShapeGroup(EscherContainerRecord spContainer, Shape parent){
package org.apache.poi.hslf.model;
+import java.awt.Graphics2D;
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.EscherDgRecord;
+import org.apache.poi.ddf.EscherDggRecord;
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
dgg.setDrawingsSaved(dgg.getDrawingsSaved() + 1);
dgg.setMaxDrawingGroupId(dgId);
- for (Iterator it = dgContainer.getChildContainers().iterator(); it.hasNext(); ) {
- EscherContainerRecord c = (EscherContainerRecord)it.next();
+ for (EscherContainerRecord c : dgContainer.getChildContainers()) {
EscherSpRecord spr = null;
switch(c.getRecordId()){
case EscherContainerRecord.SPGR_CONTAINER:
* Background for this slide.
*/
public Background getBackground() {
- if(getFollowMasterBackground())
+ if(getFollowMasterBackground()) {
return getMasterSheet().getBackground();
- else
- return super.getBackground();
+ }
+ return super.getBackground();
}
/**
if(hdd == null && !ppt2007) {
return getSlideShow().getSlideHeadersFooters();
}
- else {
- if(hdd == null) {
- hdd = new HeadersFootersContainer(HeadersFootersContainer.SlideHeadersFootersContainer);
- newRecord = true;
- }
- return new HeadersFooters(hdd, this, newRecord, ppt2007);
+ if(hdd == null) {
+ hdd = new HeadersFootersContainer(HeadersFootersContainer.SlideHeadersFootersContainer);
+ newRecord = true;
}
+ return new HeadersFooters(hdd, this, newRecord, ppt2007);
}
protected void onAddTextShape(TextShape shape) {
protected boolean _isUnicode;
protected RichTextRun[] _rtRuns;
private SlideShow slideShow;
- private Sheet sheet;
+ private Sheet _sheet;
private int shapeId;
private int slwtIndex; //position in the owning SlideListWithText
/**
public String getRawText() {
if(_isUnicode) {
return _charAtom.getText();
- } else {
- return _byteAtom.getText();
}
+ return _byteAtom.getText();
}
/**
}
public void setSheet(Sheet sheet){
- this.sheet = sheet;
+ this._sheet = sheet;
}
public Sheet getSheet(){
- return this.sheet;
+ return this._sheet;
}
/**
protected TextProp[] getParagraphProps(int type, int level){
if (level != 0 || type >= MAX_INDENT){
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")
+ };
+
}
/**
protected TextProp[] getCharacterProps(int type, int level){
if (level != 0 || type >= MAX_INDENT){
return StyleTextPropAtom.characterTextPropTypes;
- } else
- return new TextProp[] {
- new CharFlagsTextProp(),
- new TextProp(2, 0x10000, "font.index"),
- new TextProp(2, 0x20000, "char_unknown_1"),
- new TextProp(4, 0x40000, "char_unknown_2"),
- new TextProp(2, 0x80000, "font.size"),
- new TextProp(2, 0x100000, "char_unknown_3"),
- new TextProp(4, 0x200000, "font.color"),
- new TextProp(2, 0x800000, "char_unknown_4")
- };
+ }
+ return new TextProp[] {
+ new CharFlagsTextProp(),
+ new TextProp(2, 0x10000, "font.index"),
+ new TextProp(2, 0x20000, "char_unknown_1"),
+ new TextProp(4, 0x40000, "char_unknown_2"),
+ new TextProp(2, 0x80000, "font.size"),
+ new TextProp(2, 0x100000, "char_unknown_3"),
+ new TextProp(4, 0x200000, "font.color"),
+ new TextProp(2, 0x800000, "char_unknown_4")
+ };
}
}
*
*/
public final class RichTextRun {
- protected POILogger logger = POILogFactory.getLogger(this.getClass());
+ protected POILogger logger = POILogFactory.getLogger(this.getClass());
/** The TextRun we belong to */
private TextRun parentRun;
/** How long a string (in the parent TextRun) we represent */
private int length;
- private String _fontname;
- /**
+ private String _fontname;
+ /**
* Our paragraph and character style.
* Note - we may share these styles with other RichTextRuns
*/
*/
public void supplySlideShow(SlideShow ss) {
slideShow = ss;
- if (_fontname != null) {
- setFontName(_fontname);
- _fontname = null;
- }
+ if (_fontname != null) {
+ setFontName(_fontname);
+ _fontname = null;
+ }
}
/**
return length;
}
- /**
- * The beginning index, inclusive.
- *
- * @return the beginning index, inclusive.
- */
- public int getStartIndex(){
- return startPos;
- }
+ /**
+ * The beginning index, inclusive.
+ *
+ * @return the beginning index, inclusive.
+ */
+ public int getStartIndex(){
+ return startPos;
+ }
- /**
- * The ending index, exclusive.
- *
- * @return the ending index, exclusive.
- */
- public int getEndIndex(){
- return startPos + length;
- }
+ /**
+ * The ending index, exclusive.
+ *
+ * @return the ending index, exclusive.
+ */
+ public int getEndIndex(){
+ return startPos + length;
+ }
/**
* Fetch the text, in output suitable form
* Change the text
*/
public void setText(String text) {
- String s = parentRun.normalize(text);
- setRawText(s);
+ String s = parentRun.normalize(text);
+ setRawText(s);
}
- /**
- * Change the text
- */
- public void setRawText(String text) {
- length = text.length();
- parentRun.changeTextInRichTextRun(this,text);
- }
+ /**
+ * Change the text
+ */
+ public void setRawText(String text) {
+ length = text.length();
+ parentRun.changeTextInRichTextRun(this,text);
+ }
/**
* Tells the RichTextRun its new position in the parent TextRun
return getFlag(true, index);
}
- private boolean getFlag(boolean isCharacter, int index) {
- TextPropCollection props;
- String propname;
- if (isCharacter){
- props = characterStyle;
- propname = CharFlagsTextProp.NAME;
- } else {
- props = paragraphStyle;
- propname = ParagraphFlagsTextProp.NAME;
- }
-
- BitMaskTextProp prop = null;
- if (props != null){
- prop = (BitMaskTextProp)props.findByName(propname);
- }
- if (prop == null){
- Sheet sheet = parentRun.getSheet();
- if(sheet != null){
- int txtype = parentRun.getRunType();
- MasterSheet master = sheet.getMasterSheet();
- if (master != null){
- prop = (BitMaskTextProp)master.getStyleAttribute(txtype, getIndentLevel(), propname, isCharacter);
- }
- } else {
- logger.log(POILogger.WARN, "MasterSheet is not available");
- }
- }
-
- return prop == null ? false : prop.getSubValue(index);
- }
+ private boolean getFlag(boolean isCharacter, int index) {
+ TextPropCollection props;
+ String propname;
+ if (isCharacter){
+ props = characterStyle;
+ propname = CharFlagsTextProp.NAME;
+ } else {
+ props = paragraphStyle;
+ propname = ParagraphFlagsTextProp.NAME;
+ }
+
+ BitMaskTextProp prop = null;
+ if (props != null){
+ prop = (BitMaskTextProp)props.findByName(propname);
+ }
+ if (prop == null){
+ Sheet sheet = parentRun.getSheet();
+ if(sheet != null){
+ int txtype = parentRun.getRunType();
+ MasterSheet master = sheet.getMasterSheet();
+ if (master != null){
+ prop = (BitMaskTextProp)master.getStyleAttribute(txtype, getIndentLevel(), propname, isCharacter);
+ }
+ } else {
+ logger.log(POILogger.WARN, "MasterSheet is not available");
+ }
+ }
+
+ return prop == null ? false : prop.getSubValue(index);
+ }
/**
* Set the value of the given flag in the CharFlagsTextProp, adding
* it if required.
*/
private void setCharFlagsTextPropVal(int index, boolean value) {
- if(getFlag(true, index) != value) setFlag(true, index, value);
- }
-
- public void setFlag(boolean isCharacter, int index, boolean value) {
- TextPropCollection props;
- String propname;
- if (isCharacter){
- props = characterStyle;
- propname = CharFlagsTextProp.NAME;
- } else {
- props = paragraphStyle;
- propname = ParagraphFlagsTextProp.NAME;
- }
+ if(getFlag(true, index) != value) setFlag(true, index, value);
+ }
+
+ public void setFlag(boolean isCharacter, int index, boolean value) {
+ TextPropCollection props;
+ String propname;
+ if (isCharacter){
+ props = characterStyle;
+ propname = CharFlagsTextProp.NAME;
+ } else {
+ props = paragraphStyle;
+ propname = ParagraphFlagsTextProp.NAME;
+ }
// Ensure we have the StyleTextProp atom we're going to need
if(props == null) {
parentRun.ensureStyleAtomPresent();
- props = isCharacter ? characterStyle : paragraphStyle;
+ props = isCharacter ? characterStyle : paragraphStyle;
}
BitMaskTextProp prop = (BitMaskTextProp) fetchOrAddTextProp(props, propname);
prop.setSubValue(value,index);
- }
+ }
/**
* Returns the named TextProp, either by fetching it (if it exists) or adding it
* Master Sheet will apply.
*/
private int getCharTextPropVal(String propName) {
- TextProp prop = null;
- if (characterStyle != null){
- prop = characterStyle.findByName(propName);
- }
-
- if (prop == null){
- Sheet sheet = parentRun.getSheet();
- int txtype = parentRun.getRunType();
- MasterSheet master = sheet.getMasterSheet();
- if (master != null)
- prop = master.getStyleAttribute(txtype, getIndentLevel(), propName, true);
- }
+ TextProp prop = null;
+ if (characterStyle != null){
+ prop = characterStyle.findByName(propName);
+ }
+
+ if (prop == null){
+ Sheet sheet = parentRun.getSheet();
+ int txtype = parentRun.getRunType();
+ MasterSheet master = sheet.getMasterSheet();
+ if (master != null)
+ prop = master.getStyleAttribute(txtype, getIndentLevel(), propName, true);
+ }
return prop == null ? -1 : prop.getValue();
}
/**
* Master Sheet will apply.
*/
private int getParaTextPropVal(String propName) {
- TextProp prop = null;
- boolean hardAttribute = false;
- if (paragraphStyle != null){
- prop = paragraphStyle.findByName(propName);
-
- BitMaskTextProp maskProp = (BitMaskTextProp)paragraphStyle.findByName(ParagraphFlagsTextProp.NAME);
- hardAttribute = maskProp != null && maskProp.getValue() == 0;
- }
- if (prop == null && !hardAttribute){
- Sheet sheet = parentRun.getSheet();
- int txtype = parentRun.getRunType();
- MasterSheet master = sheet.getMasterSheet();
- if (master != null)
- prop = master.getStyleAttribute(txtype, getIndentLevel(), propName, false);
- }
+ TextProp prop = null;
+ boolean hardAttribute = false;
+ if (paragraphStyle != null){
+ prop = paragraphStyle.findByName(propName);
+
+ BitMaskTextProp maskProp = (BitMaskTextProp)paragraphStyle.findByName(ParagraphFlagsTextProp.NAME);
+ hardAttribute = maskProp != null && maskProp.getValue() == 0;
+ }
+ if (prop == null && !hardAttribute){
+ Sheet sheet = parentRun.getSheet();
+ int txtype = parentRun.getRunType();
+ MasterSheet master = sheet.getMasterSheet();
+ if (master != null)
+ prop = master.getStyleAttribute(txtype, getIndentLevel(), propName, false);
+ }
return prop == null ? -1 : prop.getValue();
}
// --------------- Friendly getters / setters on rich text properties -------
- /**
- * Is the text bold?
- */
+ /**
+ * Is the text bold?
+ */
public boolean isBold() {
return isCharFlagsTextPropVal(CharFlagsTextProp.BOLD_IDX);
}
- /**
- * Is the text bold?
- */
+ /**
+ * Is the text bold?
+ */
public void setBold(boolean bold) {
setCharFlagsTextPropVal(CharFlagsTextProp.BOLD_IDX, bold);
}
- /**
- * Is the text italic?
- */
+ /**
+ * Is the text italic?
+ */
public boolean isItalic() {
return isCharFlagsTextPropVal(CharFlagsTextProp.ITALIC_IDX);
}
- /**
- * Is the text italic?
- */
+ /**
+ * Is the text italic?
+ */
public void setItalic(boolean italic) {
setCharFlagsTextPropVal(CharFlagsTextProp.ITALIC_IDX, italic);
}
- /**
- * Is the text underlined?
- */
+ /**
+ * Is the text underlined?
+ */
public boolean isUnderlined() {
return isCharFlagsTextPropVal(CharFlagsTextProp.UNDERLINE_IDX);
}
- /**
- * Is the text underlined?
- */
+ /**
+ * Is the text underlined?
+ */
public void setUnderlined(boolean underlined) {
setCharFlagsTextPropVal(CharFlagsTextProp.UNDERLINE_IDX, underlined);
}
- /**
- * Does the text have a shadow?
- */
- public boolean isShadowed() {
- return isCharFlagsTextPropVal(CharFlagsTextProp.SHADOW_IDX);
- }
-
- /**
- * Does the text have a shadow?
- */
- public void setShadowed(boolean flag) {
- setCharFlagsTextPropVal(CharFlagsTextProp.SHADOW_IDX, flag);
- }
-
- /**
- * Is this text embossed?
- */
- public boolean isEmbossed() {
- return isCharFlagsTextPropVal(CharFlagsTextProp.RELIEF_IDX);
- }
-
- /**
- * Is this text embossed?
- */
- public void setEmbossed(boolean flag) {
- setCharFlagsTextPropVal(CharFlagsTextProp.RELIEF_IDX, flag);
- }
-
- /**
- * Gets the strikethrough flag
- */
- public boolean isStrikethrough() {
- return isCharFlagsTextPropVal(CharFlagsTextProp.STRIKETHROUGH_IDX);
- }
-
- /**
- * Sets the strikethrough flag
- */
- public void setStrikethrough(boolean flag) {
- setCharFlagsTextPropVal(CharFlagsTextProp.STRIKETHROUGH_IDX, flag);
- }
-
- /**
- * Gets the subscript/superscript option
- *
- * @return the percentage of the font size. If the value is positive, it is superscript, otherwise it is subscript
- */
+ /**
+ * Does the text have a shadow?
+ */
+ public boolean isShadowed() {
+ return isCharFlagsTextPropVal(CharFlagsTextProp.SHADOW_IDX);
+ }
+
+ /**
+ * Does the text have a shadow?
+ */
+ public void setShadowed(boolean flag) {
+ setCharFlagsTextPropVal(CharFlagsTextProp.SHADOW_IDX, flag);
+ }
+
+ /**
+ * Is this text embossed?
+ */
+ public boolean isEmbossed() {
+ return isCharFlagsTextPropVal(CharFlagsTextProp.RELIEF_IDX);
+ }
+
+ /**
+ * Is this text embossed?
+ */
+ public void setEmbossed(boolean flag) {
+ setCharFlagsTextPropVal(CharFlagsTextProp.RELIEF_IDX, flag);
+ }
+
+ /**
+ * Gets the strikethrough flag
+ */
+ public boolean isStrikethrough() {
+ return isCharFlagsTextPropVal(CharFlagsTextProp.STRIKETHROUGH_IDX);
+ }
+
+ /**
+ * Sets the strikethrough flag
+ */
+ public void setStrikethrough(boolean flag) {
+ setCharFlagsTextPropVal(CharFlagsTextProp.STRIKETHROUGH_IDX, flag);
+ }
+
+ /**
+ * Gets the subscript/superscript option
+ *
+ * @return the percentage of the font size. If the value is positive, it is superscript, otherwise it is subscript
+ */
public int getSuperscript() {
- int val = getCharTextPropVal("superscript");
+ int val = getCharTextPropVal("superscript");
return val == -1 ? 0 : val;
}
- /**
- * Sets the subscript/superscript option
- *
- * @param val the percentage of the font size. If the value is positive, it is superscript, otherwise it is subscript
- */
+ /**
+ * Sets the subscript/superscript option
+ *
+ * @param val the percentage of the font size. If the value is positive, it is superscript, otherwise it is subscript
+ */
public void setSuperscript(int val) {
setCharTextPropVal("superscript", val);
}
- /**
- * Gets the font size
- */
+ /**
+ * Gets the font size
+ */
public int getFontSize() {
return getCharTextPropVal("font.size");
}
- /**
- * Sets the font size
- */
+ /**
+ * Sets the font size
+ */
public void setFontSize(int fontSize) {
setCharTextPropVal("font.size", fontSize);
}
- /**
- * Gets the font index
- */
+ /**
+ * Gets the font index
+ */
public int getFontIndex() {
return getCharTextPropVal("font.index");
}
- /**
- * Sets the font index
- */
+ /**
+ * Sets the font index
+ */
public void setFontIndex(int idx) {
setCharTextPropVal("font.index", idx);
}
- /**
- * Sets the font name to use
- */
+ /**
+ * Sets the font name to use
+ */
public void setFontName(String fontName) {
- if (slideShow == null) {
- //we can't set font since slideshow is not assigned yet
- _fontname = fontName;
- } else {
- // Get the index for this font (adding if needed)
- int fontIdx = slideShow.getFontCollection().addFont(fontName);
- setCharTextPropVal("font.index", fontIdx);
- }
- }
-
- /**
- * Gets the font name
- */
+ if (slideShow == null) {
+ //we can't set font since slideshow is not assigned yet
+ _fontname = fontName;
+ } else {
+ // Get the index for this font (adding if needed)
+ int fontIdx = slideShow.getFontCollection().addFont(fontName);
+ setCharTextPropVal("font.index", fontIdx);
+ }
+ }
+
+ /**
+ * Gets the font name
+ */
public String getFontName() {
- if (slideShow == null) {
- return _fontname;
- } else {
- int fontIdx = getCharTextPropVal("font.index");
- if(fontIdx == -1) { return null; }
- return slideShow.getFontCollection().getFontWithId(fontIdx);
- }
+ if (slideShow == null) {
+ return _fontname;
+ }
+ int fontIdx = getCharTextPropVal("font.index");
+ if(fontIdx == -1) { return null; }
+ return slideShow.getFontCollection().getFontWithId(fontIdx);
}
/**
* @see java.awt.Color
*/
public Color getFontColor() {
- int rgb = getCharTextPropVal("font.color");
+ int rgb = getCharTextPropVal("font.color");
- int cidx = rgb >> 24;
- if (rgb % 0x1000000 == 0){
- ColorSchemeAtom ca = parentRun.getSheet().getColorScheme();
- if(cidx >= 0 && cidx <= 7) rgb = ca.getColor(cidx);
- }
- Color tmp = new Color(rgb, true);
- return new Color(tmp.getBlue(), tmp.getGreen(), tmp.getRed());
+ int cidx = rgb >> 24;
+ if (rgb % 0x1000000 == 0){
+ ColorSchemeAtom ca = parentRun.getSheet().getColorScheme();
+ if(cidx >= 0 && cidx <= 7) rgb = ca.getColor(cidx);
+ }
+ Color tmp = new Color(rgb, true);
+ return new Color(tmp.getBlue(), tmp.getGreen(), tmp.getRed());
}
/**
setCharTextPropVal("font.color", bgr);
}
- /**
- * Sets color of the text, as a java.awt.Color
- */
- public void setFontColor(Color color) {
- // In PowerPont RGB bytes are swapped, as BGR
- int rgb = new Color(color.getBlue(), color.getGreen(), color.getRed(), 254).getRGB();
- setFontColor(rgb);
- }
-
- /**
- * Sets the type of horizontal alignment for the text.
- * One of the <code>Align*</code> constants defined in the <code>TextBox</code> class.
- *
- * @param align - the type of alignment
- */
- public void setAlignment(int align) {
- setParaTextPropVal("alignment", align);
- }
- /**
- * Returns the type of horizontal alignment for the text.
- * One of the <code>Align*</code> constants defined in the <code>TextBox</class> class.
- *
- * @return the type of alignment
- */
- public int getAlignment() {
- return getParaTextPropVal("alignment");
- }
-
- /**
- *
- * @return indentation level
- */
- public int getIndentLevel() {
- return paragraphStyle == null ? 0 : paragraphStyle.getReservedField();
- }
-
- /**
- * Sets indentation level
- *
- * @param level indentation level. Must be in the range [0, 4]
- */
- public void setIndentLevel(int level) {
- if(paragraphStyle != null ) paragraphStyle.setReservedField((short)level);
- }
-
- /**
- * Sets whether this rich text run has bullets
- */
- public void setBullet(boolean flag) {
- setFlag(false, ParagraphFlagsTextProp.BULLET_IDX, flag);
- }
-
- /**
- * Returns whether this rich text run has bullets
- */
- public boolean isBullet() {
- return getFlag(false, ParagraphFlagsTextProp.BULLET_IDX);
- }
-
- /**
- * Returns whether this rich text run has bullets
- */
- public boolean isBulletHard() {
- return getFlag(false, ParagraphFlagsTextProp.BULLET_IDX);
- }
-
- /**
- * Sets the bullet character
- */
- public void setBulletChar(char c) {
- setParaTextPropVal("bullet.char", c);
- }
-
- /**
- * Returns the bullet character
- */
- public char getBulletChar() {
- return (char)getParaTextPropVal("bullet.char");
- }
-
- /**
- * Sets the bullet offset
- */
- public void setBulletOffset(int offset) {
- setParaTextPropVal("bullet.offset", offset*Shape.MASTER_DPI/Shape.POINT_DPI);
- }
-
- /**
- * Returns the bullet offset
- */
- public int getBulletOffset() {
- return getParaTextPropVal("bullet.offset")*Shape.POINT_DPI/Shape.MASTER_DPI;
- }
-
- /**
- * Sets the text offset
- */
- public void setTextOffset(int offset) {
- setParaTextPropVal("text.offset", offset*Shape.MASTER_DPI/Shape.POINT_DPI);
- }
-
- /**
- * Returns the text offset
- */
- public int getTextOffset() {
- return getParaTextPropVal("text.offset")*Shape.POINT_DPI/Shape.MASTER_DPI;
- }
-
- /**
- * Sets the bullet size
- */
- public void setBulletSize(int size) {
- setParaTextPropVal("bullet.size", size);
- }
-
- /**
- * Returns the bullet size
- */
- public int getBulletSize() {
- return getParaTextPropVal("bullet.size");
- }
-
- /**
- * Sets the bullet color
- */
- public void setBulletColor(Color color) {
- int rgb = new Color(color.getBlue(), color.getGreen(), color.getRed(), 254).getRGB();
- setParaTextPropVal("bullet.color", rgb);
- }
-
- /**
- * Returns the bullet color
- */
- public Color getBulletColor() {
- int rgb = getParaTextPropVal("bullet.color");
- if(rgb == -1) return getFontColor();
-
- int cidx = rgb >> 24;
- if (rgb % 0x1000000 == 0){
- ColorSchemeAtom ca = parentRun.getSheet().getColorScheme();
- if(cidx >= 0 && cidx <= 7) rgb = ca.getColor(cidx);
- }
- Color tmp = new Color(rgb, true);
- return new Color(tmp.getBlue(), tmp.getGreen(), tmp.getRed());
- }
-
- /**
- * Sets the bullet font
- */
- public void setBulletFont(int idx) {
- setParaTextPropVal("bullet.font", idx);
- setFlag(false, ParagraphFlagsTextProp.BULLET_HARDFONT_IDX, true);
- }
-
- /**
- * Returns the bullet font
- */
- public int getBulletFont() {
- return getParaTextPropVal("bullet.font");
- }
-
- /**
- * Sets the line spacing.
- * <p>
- * If linespacing >= 0, then linespacing is a percentage of normal line height.
- * If linespacing < 0, the absolute value of linespacing is the spacing in master coordinates.
- * </p>
- */
- public void setLineSpacing(int val) {
- setParaTextPropVal("linespacing", val);
- }
-
- /**
- * Returns the line spacing
- * <p>
- * If linespacing >= 0, then linespacing is a percentage of normal line height.
- * If linespacing < 0, the absolute value of linespacing is the spacing in master coordinates.
- * </p>
- *
- * @return the spacing between lines
- */
- public int getLineSpacing() {
- int val = getParaTextPropVal("linespacing");
- return val == -1 ? 0 : val;
- }
-
- /**
- * Sets spacing before a paragraph.
- * <p>
- * If spacebefore >= 0, then spacebefore is a percentage of normal line height.
- * If spacebefore < 0, the absolute value of spacebefore is the spacing in master coordinates.
- * </p>
- */
- public void setSpaceBefore(int val) {
- setParaTextPropVal("spacebefore", val);
- }
-
- /**
- * Returns spacing before a paragraph
- * <p>
- * If spacebefore >= 0, then spacebefore is a percentage of normal line height.
- * If spacebefore < 0, the absolute value of spacebefore is the spacing in master coordinates.
- * </p>
- *
- * @return the spacing before a paragraph
- */
- public int getSpaceBefore() {
- int val = getParaTextPropVal("spacebefore");
- return val == -1 ? 0 : val;
- }
-
- /**
- * Sets spacing after a paragraph.
- * <p>
- * If spaceafter >= 0, then spaceafter is a percentage of normal line height.
- * If spaceafter < 0, the absolute value of spaceafter is the spacing in master coordinates.
- * </p>
- */
- public void setSpaceAfter(int val) {
- setParaTextPropVal("spaceafter", val);
- }
-
- /**
- * Returns spacing after a paragraph
- * <p>
- * If spaceafter >= 0, then spaceafter is a percentage of normal line height.
- * If spaceafter < 0, the absolute value of spaceafter is the spacing in master coordinates.
- * </p>
- *
- * @return the spacing before a paragraph
- */
- public int getSpaceAfter() {
- int val = getParaTextPropVal("spaceafter");
- return val == -1 ? 0 : val;
- }
+ /**
+ * Sets color of the text, as a java.awt.Color
+ */
+ public void setFontColor(Color color) {
+ // In PowerPont RGB bytes are swapped, as BGR
+ int rgb = new Color(color.getBlue(), color.getGreen(), color.getRed(), 254).getRGB();
+ setFontColor(rgb);
+ }
+
+ /**
+ * Sets the type of horizontal alignment for the text.
+ * One of the <code>Align*</code> constants defined in the <code>TextBox</code> class.
+ *
+ * @param align - the type of alignment
+ */
+ public void setAlignment(int align) {
+ setParaTextPropVal("alignment", align);
+ }
+ /**
+ * Returns the type of horizontal alignment for the text.
+ * One of the <code>Align*</code> constants defined in the <code>TextBox</class> class.
+ *
+ * @return the type of alignment
+ */
+ public int getAlignment() {
+ return getParaTextPropVal("alignment");
+ }
+
+ /**
+ *
+ * @return indentation level
+ */
+ public int getIndentLevel() {
+ return paragraphStyle == null ? 0 : paragraphStyle.getReservedField();
+ }
+
+ /**
+ * Sets indentation level
+ *
+ * @param level indentation level. Must be in the range [0, 4]
+ */
+ public void setIndentLevel(int level) {
+ if(paragraphStyle != null ) paragraphStyle.setReservedField((short)level);
+ }
+
+ /**
+ * Sets whether this rich text run has bullets
+ */
+ public void setBullet(boolean flag) {
+ setFlag(false, ParagraphFlagsTextProp.BULLET_IDX, flag);
+ }
+
+ /**
+ * Returns whether this rich text run has bullets
+ */
+ public boolean isBullet() {
+ return getFlag(false, ParagraphFlagsTextProp.BULLET_IDX);
+ }
+
+ /**
+ * Returns whether this rich text run has bullets
+ */
+ public boolean isBulletHard() {
+ return getFlag(false, ParagraphFlagsTextProp.BULLET_IDX);
+ }
+
+ /**
+ * Sets the bullet character
+ */
+ public void setBulletChar(char c) {
+ setParaTextPropVal("bullet.char", c);
+ }
+
+ /**
+ * Returns the bullet character
+ */
+ public char getBulletChar() {
+ return (char)getParaTextPropVal("bullet.char");
+ }
+
+ /**
+ * Sets the bullet offset
+ */
+ public void setBulletOffset(int offset) {
+ setParaTextPropVal("bullet.offset", offset*Shape.MASTER_DPI/Shape.POINT_DPI);
+ }
+
+ /**
+ * Returns the bullet offset
+ */
+ public int getBulletOffset() {
+ return getParaTextPropVal("bullet.offset")*Shape.POINT_DPI/Shape.MASTER_DPI;
+ }
+
+ /**
+ * Sets the text offset
+ */
+ public void setTextOffset(int offset) {
+ setParaTextPropVal("text.offset", offset*Shape.MASTER_DPI/Shape.POINT_DPI);
+ }
+
+ /**
+ * Returns the text offset
+ */
+ public int getTextOffset() {
+ return getParaTextPropVal("text.offset")*Shape.POINT_DPI/Shape.MASTER_DPI;
+ }
+
+ /**
+ * Sets the bullet size
+ */
+ public void setBulletSize(int size) {
+ setParaTextPropVal("bullet.size", size);
+ }
+
+ /**
+ * Returns the bullet size
+ */
+ public int getBulletSize() {
+ return getParaTextPropVal("bullet.size");
+ }
+
+ /**
+ * Sets the bullet color
+ */
+ public void setBulletColor(Color color) {
+ int rgb = new Color(color.getBlue(), color.getGreen(), color.getRed(), 254).getRGB();
+ setParaTextPropVal("bullet.color", rgb);
+ }
+
+ /**
+ * Returns the bullet color
+ */
+ public Color getBulletColor() {
+ int rgb = getParaTextPropVal("bullet.color");
+ if(rgb == -1) return getFontColor();
+
+ int cidx = rgb >> 24;
+ if (rgb % 0x1000000 == 0){
+ ColorSchemeAtom ca = parentRun.getSheet().getColorScheme();
+ if(cidx >= 0 && cidx <= 7) rgb = ca.getColor(cidx);
+ }
+ Color tmp = new Color(rgb, true);
+ return new Color(tmp.getBlue(), tmp.getGreen(), tmp.getRed());
+ }
+
+ /**
+ * Sets the bullet font
+ */
+ public void setBulletFont(int idx) {
+ setParaTextPropVal("bullet.font", idx);
+ setFlag(false, ParagraphFlagsTextProp.BULLET_HARDFONT_IDX, true);
+ }
+
+ /**
+ * Returns the bullet font
+ */
+ public int getBulletFont() {
+ return getParaTextPropVal("bullet.font");
+ }
+
+ /**
+ * Sets the line spacing.
+ * <p>
+ * If linespacing >= 0, then linespacing is a percentage of normal line height.
+ * If linespacing < 0, the absolute value of linespacing is the spacing in master coordinates.
+ * </p>
+ */
+ public void setLineSpacing(int val) {
+ setParaTextPropVal("linespacing", val);
+ }
+
+ /**
+ * Returns the line spacing
+ * <p>
+ * If linespacing >= 0, then linespacing is a percentage of normal line height.
+ * If linespacing < 0, the absolute value of linespacing is the spacing in master coordinates.
+ * </p>
+ *
+ * @return the spacing between lines
+ */
+ public int getLineSpacing() {
+ int val = getParaTextPropVal("linespacing");
+ return val == -1 ? 0 : val;
+ }
+
+ /**
+ * Sets spacing before a paragraph.
+ * <p>
+ * If spacebefore >= 0, then spacebefore is a percentage of normal line height.
+ * If spacebefore < 0, the absolute value of spacebefore is the spacing in master coordinates.
+ * </p>
+ */
+ public void setSpaceBefore(int val) {
+ setParaTextPropVal("spacebefore", val);
+ }
+
+ /**
+ * Returns spacing before a paragraph
+ * <p>
+ * If spacebefore >= 0, then spacebefore is a percentage of normal line height.
+ * If spacebefore < 0, the absolute value of spacebefore is the spacing in master coordinates.
+ * </p>
+ *
+ * @return the spacing before a paragraph
+ */
+ public int getSpaceBefore() {
+ int val = getParaTextPropVal("spacebefore");
+ return val == -1 ? 0 : val;
+ }
+
+ /**
+ * Sets spacing after a paragraph.
+ * <p>
+ * If spaceafter >= 0, then spaceafter is a percentage of normal line height.
+ * If spaceafter < 0, the absolute value of spaceafter is the spacing in master coordinates.
+ * </p>
+ */
+ public void setSpaceAfter(int val) {
+ setParaTextPropVal("spaceafter", val);
+ }
+
+ /**
+ * Returns spacing after a paragraph
+ * <p>
+ * If spaceafter >= 0, then spaceafter is a percentage of normal line height.
+ * If spaceafter < 0, the absolute value of spaceafter is the spacing in master coordinates.
+ * </p>
+ *
+ * @return the spacing before a paragraph
+ */
+ public int getSpaceAfter() {
+ int val = getParaTextPropVal("spaceafter");
+ return val == -1 ? 0 : val;
+ }
// --------------- Internal HSLF methods, not intended for end-user use! -------
/**
if (coreRecordId != null) {
Record r = _mostRecentCoreRecords[coreRecordId.intValue()];
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;
}
/**
}
if (ppt2007 && _notes.length > 0) {
return new HeadersFooters(hdd, _notes[0], newRecord, ppt2007);
- } else {
- return new HeadersFooters(hdd, this, newRecord, ppt2007);
}
+ return new HeadersFooters(hdd, this, newRecord, ppt2007);
}
/**
{
throw new IOException("The text piece table is corrupted");
}
- else
- {
- int pieceTableSize = LittleEndian.getInt(tableStream, ++offset);
- offset += LittleEndian.INT_SIZE;
- _tpt = new TextPieceTable(documentStream, tableStream, offset, pieceTableSize, fcMin);
- }
+ int pieceTableSize = LittleEndian.getInt(tableStream, ++offset);
+ offset += LittleEndian.INT_SIZE;
+ _tpt = new TextPieceTable(documentStream, tableStream, offset, pieceTableSize, fcMin);
}
public TextPieceTable getTextPieceTable()
if(level < lst.numLevels()) {
ListLevel lvl = lst.getLevels()[level];
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)
throw new UnsupportedOperationException(
"This Paragraph has no dataStream storage.");
}
- else // we have some storage...
- {
- // get the size of the existing storage
- int maxHugeGrpprlSize = LittleEndian.getUShort(_dataStream,
- hugeGrpprlOffset);
+ // 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
+ if (maxHugeGrpprlSize < grpprl.length-2) { // grpprl.length-2 because we don't store the istd
throw new UnsupportedOperationException(
"This Paragraph's dataStream storage is too small.");
}
{
return 0;
}
- else
- {
return LittleEndian.getShort(buf);
- }
}
public SprmBuffer getSprmBuf()
_buf[grpprlOffset] = operand;
return;
}
- else addSprm(opcode, operand);
+ addSprm(opcode, operand);
}
public void updateSprm(short opcode, short operand)
LittleEndian.putShort(_buf, grpprlOffset, operand);
return;
}
- else addSprm(opcode, operand);
+ addSprm(opcode, operand);
}
public void updateSprm(short opcode, int operand)
LittleEndian.putInt(_buf, grpprlOffset, operand);
return;
}
- else addSprm(opcode, operand);
+ addSprm(opcode, operand);
}
public void addSprm(short opcode, byte operand)
_gOffset += 2;
return retVal;
}
- else
- {
- return (0x000000ff & _grpprl[_gOffset++]) + 3;
- }
+ return (0x000000ff & _grpprl[_gOffset++]) + 3;
case 7:
return 5;
default:
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
-
+
package org.apache.poi.hssf.usermodel;
{
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 )