jcommon-1.0.16/0000755000175000017500000000000011351753320013177 5ustar twernertwernerjcommon-1.0.16/maven-jcommon-xml-project.xml0000644000175000017500000000504711172030703020731 0ustar twernertwerner 3 jcommon JCommon jfree @VERSION@ JFree.org http://www.jfree.org/ 2001 JCommon is a free general purpose Java class library that is used in several projects at www.jfree.org, including JFreeChart and JFreeReport. A free general purpose Java class library. http://www.jfree.org/jcommon/ http://sourceforge.net/tracker/?group_id=15494 scm:cvs:pserver:anonymous@cvs.sourceforge.net:/cvsroot/jfreechart:jcommon http://cvs.sourceforge.net/viewcvs.py/jfreechart/jcommon JFreeChart Developer List jfreechart-dev-request@lists.sourceforge.net?subject=subscribe jfreechart-dev-request@lists.sourceforge.net?subject=unsubscribe http://sourceforge.net/mailarchive/forum.php?forum=jfreechart-dev GNU Lesser General Public Licence http://www.gnu.org/licenses/lgpl.txt repo jfree jcommon @VERSION@ http://www.jfree.org/jcommon/ junit junit 3.7 http://www.junit.org/ xml-apis xml-apis 1.3.02 xml-apis-1.3.02.jar http://xml.apache.org/commons/#external jcommon-1.0.16/ant/0000755000175000017500000000000011351753320013761 5ustar twernertwernerjcommon-1.0.16/ant/build.properties0000644000175000017500000000254411172030703017175 0ustar twernertwerner########################################################### # # Global settings ... jcommon.name=jcommon jcommon.version=1.0.16 # # This defines the compiler settings. Optimizing would remove # the debug information, so we dont do that. This may be selfish, # but these settings guarantee better bug-reports :) build.debug=true build.optimize=false build.deprecation=true # # Make sure that JDK 1.2 compatible class files are generated build.target=1.2 build.source=1.2 # # All path settings are relative to the project root directory # (..) # libdir=lib junit-dir=lib # # If you specify a non-empty string, then dont forget the # trailing / here or your results wont fit your expectations... # targetdir= manifest-lib-prefix=lib/ ########################################################### # # Used libraries ... # Used by: core libraries # Used by: module-misc-beanshell jaxp-jar-file=gnujaxp.jar servlet-jar-file=servlet.jar junit-jar-file=junit.jar ############################################################## # # Generated files ... jcommon-jar-file=${jcommon.name}-${jcommon.version}.jar jcommon-bundle-file=${jcommon.name}-${jcommon.version}-bundle.jar jcommon-junit-jar-file=${jcommon.name}-${jcommon.version}-junit.jar jcommon-xml-jar-file=${jcommon.name}-xml-${jcommon.version}.jar jcommon-xml-bundle-file=${jcommon.name}-xml-${jcommon.version}-bundle.jar jcommon-1.0.16/ant/build.xml0000644000175000017500000002565211172030703015606 0ustar twernertwerner jcommon-1.0.16/checkstyle/0000755000175000017500000000000011351753320015335 5ustar twernertwernerjcommon-1.0.16/checkstyle/style.xml0000644000175000017500000001467011172030703017221 0ustar twernertwerner jcommon-1.0.16/checkstyle/lines.xml0000644000175000017500000000132211172030703017161 0ustar twernertwerner jcommon-1.0.16/checkstyle/whitespace.xml0000644000175000017500000000167411172030703020215 0ustar twernertwerner jcommon-1.0.16/checkstyle/javadocs.xml0000644000175000017500000000134111172030703017642 0ustar twernertwerner jcommon-1.0.16/checkstyle/properties.txt0000644000175000017500000000027211172030703020265 0ustar twernertwernercheckstyle.allow.tabs no checkstyle.maxlinelen 100 checkstyle.maxparameters 20 checkstyle.rcurly alone checkstyle.ignore.public.in.interface yes checkstyle.javadoc.checkUnusedThrows yes jcommon-1.0.16/lib/0000755000175000017500000000000011351753320013745 5ustar twernertwernerjcommon-1.0.16/source/0000755000175000017500000000000011351753320014477 5ustar twernertwernerjcommon-1.0.16/source/overview.html0000644000175000017500000000113211172030703017222 0ustar twernertwerner JCommon is a free general purpose library for Java that is shared by several other projects, including JFreeChart and Pentaho Reporting (formerly JFreeReport).

Please visit http://www.jfree.org/jcommon/index.html for the latest information about JCommon.

SPECIAL NOTICE: BOTH JFREECHART AND PENTAHO REPORTING ARE MOVING TOWARDS ELIMINATING THEIR DEPENDENCY ON JCOMMON. AFTER THIS HAPPENS, JCOMMON WILL MOST LIKELY BE "RETIRED". jcommon-1.0.16/source/org/0000755000175000017500000000000011172030703015260 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/0000755000175000017500000000000011351753320016361 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/resources/0000755000175000017500000000000011351753320020373 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/resources/package.html0000644000175000017500000000024111172030703022643 0ustar twernertwerner General localised resources for the JCommon class library. jcommon-1.0.16/source/org/jfree/resources/JCommonResources.java0000644000175000017500000000447211172030703024474 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * JCommonResources.java * --------------------- * (C) Copyright 2002-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: JCommonResources.java,v 1.22 2008/12/30 12:21:57 mungady Exp $ * */ package org.jfree.resources; import java.util.ListResourceBundle; /** * Localised resources for the JCommon Class Library. */ public class JCommonResources extends ListResourceBundle { /** * Default constructor. */ public JCommonResources() { } /** * Returns the array of strings in the resource bundle. * * @return The resources. */ public Object[][] getContents() { return CONTENTS; } /** The resources to be localised. */ private static final Object[][] CONTENTS = { {"project.name", "JCommon"}, {"project.version", "1.0.15"}, {"project.info", "http://www.jfree.org/jcommon/"}, {"project.copyright", "(C)opyright 2000-2008, by Object Refinery Limited and Contributors"} }; } jcommon-1.0.16/source/org/jfree/text/0000755000175000017500000000000011351753320017345 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/text/package.html0000644000175000017500000000021011172030703021611 0ustar twernertwerner Utility classes relating to text. jcommon-1.0.16/source/org/jfree/text/TextLine.java0000644000175000017500000002171011172030703021737 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------- * TextLine.java * ------------- * (C) Copyright 2003-2005, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextLine.java,v 1.13 2007/11/02 17:50:35 taqua Exp $ * * Changes * ------- * 07-Nov-2003 : Version 1 (DG); * 22-Dec-2003 : Added workaround for Java bug 4245442 (DG); * 29-Jan-2004 : Added new constructor (DG); * 22-Mar-2004 : Added equals() method and implemented Serializable (DG); * 01-Apr-2004 : Changed java.awt.geom.Dimension2D to org.jfree.ui.Size2D * because of JDK bug 4976448 which persists on JDK 1.3.1 (DG); * 03-Sep-2004 : Added a method to remove a fragment (DG); * 08-Jul-2005 : Fixed bug in calculateBaselineOffset() (DG); * */ package org.jfree.text; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.io.Serializable; import java.util.Iterator; import java.util.List; import org.jfree.ui.Size2D; import org.jfree.ui.TextAnchor; /** * A sequence of {@link TextFragment} objects that together form a line of * text. A sequence of text lines is managed by the {@link TextBlock} class. * * @author David Gilbert */ public class TextLine implements Serializable { /** For serialization. */ private static final long serialVersionUID = 7100085690160465444L; /** Storage for the text fragments that make up the line. */ private List fragments; /** * Creates a new empty line. */ public TextLine() { this.fragments = new java.util.ArrayList(); } /** * Creates a new text line using the default font. * * @param text the text (null not permitted). */ public TextLine(final String text) { this(text, TextFragment.DEFAULT_FONT); } /** * Creates a new text line. * * @param text the text (null not permitted). * @param font the text font (null not permitted). */ public TextLine(final String text, final Font font) { this.fragments = new java.util.ArrayList(); final TextFragment fragment = new TextFragment(text, font); this.fragments.add(fragment); } /** * Creates a new text line. * * @param text the text (null not permitted). * @param font the text font (null not permitted). * @param paint the text color (null not permitted). */ public TextLine(final String text, final Font font, final Paint paint) { if (text == null) { throw new IllegalArgumentException("Null 'text' argument."); } if (font == null) { throw new IllegalArgumentException("Null 'font' argument."); } if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.fragments = new java.util.ArrayList(); final TextFragment fragment = new TextFragment(text, font, paint); this.fragments.add(fragment); } /** * Adds a text fragment to the text line. * * @param fragment the text fragment (null not permitted). */ public void addFragment(final TextFragment fragment) { this.fragments.add(fragment); } /** * Removes a fragment from the line. * * @param fragment the fragment to remove. */ public void removeFragment(final TextFragment fragment) { this.fragments.remove(fragment); } /** * Draws the text line. * * @param g2 the graphics device. * @param anchorX the x-coordinate for the anchor point. * @param anchorY the y-coordinate for the anchor point. * @param anchor the point on the text line that is aligned to the anchor * point. * @param rotateX the x-coordinate for the rotation point. * @param rotateY the y-coordinate for the rotation point. * @param angle the rotation angle (in radians). */ public void draw(final Graphics2D g2, final float anchorX, final float anchorY, final TextAnchor anchor, final float rotateX, final float rotateY, final double angle) { float x = anchorX; final float yOffset = calculateBaselineOffset(g2, anchor); final Iterator iterator = this.fragments.iterator(); while (iterator.hasNext()) { final TextFragment fragment = (TextFragment) iterator.next(); final Size2D d = fragment.calculateDimensions(g2); fragment.draw( g2, x, anchorY + yOffset, TextAnchor.BASELINE_LEFT, rotateX, rotateY, angle ); x = x + (float) d.getWidth(); } } /** * Calculates the width and height of the text line. * * @param g2 the graphics device. * * @return The width and height. */ public Size2D calculateDimensions(final Graphics2D g2) { double width = 0.0; double height = 0.0; final Iterator iterator = this.fragments.iterator(); while (iterator.hasNext()) { final TextFragment fragment = (TextFragment) iterator.next(); final Size2D dimension = fragment.calculateDimensions(g2); width = width + dimension.getWidth(); height = Math.max(height, dimension.getHeight()); } return new Size2D(width, height); } /** * Returns the first text fragment in the line. * * @return The first text fragment in the line. */ public TextFragment getFirstTextFragment() { TextFragment result = null; if (this.fragments.size() > 0) { result = (TextFragment) this.fragments.get(0); } return result; } /** * Returns the last text fragment in the line. * * @return The last text fragment in the line. */ public TextFragment getLastTextFragment() { TextFragment result = null; if (this.fragments.size() > 0) { result = (TextFragment) this.fragments.get(this.fragments.size() - 1); } return result; } /** * Calculate the offsets required to translate from the specified anchor * position to the left baseline position. * * @param g2 the graphics device. * @param anchor the anchor position. * * @return The offsets. */ private float calculateBaselineOffset(final Graphics2D g2, final TextAnchor anchor) { float result = 0.0f; Iterator iterator = this.fragments.iterator(); while (iterator.hasNext()) { TextFragment fragment = (TextFragment) iterator.next(); result = Math.max(result, fragment.calculateBaselineOffset(g2, anchor)); } return result; } /** * Tests this object for equality with an arbitrary object. * * @param obj the object to test against (null permitted). * * @return A boolean. */ public boolean equals(final Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj instanceof TextLine) { final TextLine line = (TextLine) obj; return this.fragments.equals(line.fragments); } return false; } /** * Returns a hash code for this object. * * @return A hash code. */ public int hashCode() { return (this.fragments != null ? this.fragments.hashCode() : 0); } } jcommon-1.0.16/source/org/jfree/text/TextMeasurer.java0000644000175000017500000000421011172030703022627 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * TextMeasurer.java * ----------------- * (C) Copyright 2004, 2005, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextMeasurer.java,v 1.4 2005/10/18 13:17:16 mungady Exp $ * * Changes * ------- * 07-Jan-2004 : Version 1 (DG); * */ package org.jfree.text; /** * An object that can measure text. * * @author David Gilbert */ public interface TextMeasurer { /** * Calculates the width of a String in the current * Graphics context. * * @param text the text. * @param start the start position of the substring to be measured. * @param end the position of the last character to be measured. * * @return The width of the string in Java2D units. */ public float getStringWidth(String text, int start, int end); } jcommon-1.0.16/source/org/jfree/text/TextBlockAnchor.java0000644000175000017500000001315711172030703023243 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * TextBlockAnchor.java * -------------------- * (C) Copyright 2003-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextBlockAnchor.java,v 1.4 2005/10/18 13:17:16 mungady Exp $ * * Changes: * -------- * 06-Nov-2003 : Version 1 (DG); * 22-Mar-2004 : Added readResolve() method (DG); * */ package org.jfree.text; import java.io.ObjectStreamException; import java.io.Serializable; /** * Used to indicate the position of an anchor point for a text block. * * @author David Gilbert */ public final class TextBlockAnchor implements Serializable { /** For serialization. */ private static final long serialVersionUID = -3045058380983401544L; /** Top/left. */ public static final TextBlockAnchor TOP_LEFT = new TextBlockAnchor("TextBlockAnchor.TOP_LEFT"); /** Top/center. */ public static final TextBlockAnchor TOP_CENTER = new TextBlockAnchor( "TextBlockAnchor.TOP_CENTER" ); /** Top/right. */ public static final TextBlockAnchor TOP_RIGHT = new TextBlockAnchor( "TextBlockAnchor.TOP_RIGHT" ); /** Middle/left. */ public static final TextBlockAnchor CENTER_LEFT = new TextBlockAnchor( "TextBlockAnchor.CENTER_LEFT" ); /** Middle/center. */ public static final TextBlockAnchor CENTER = new TextBlockAnchor("TextBlockAnchor.CENTER"); /** Middle/right. */ public static final TextBlockAnchor CENTER_RIGHT = new TextBlockAnchor( "TextBlockAnchor.CENTER_RIGHT" ); /** Bottom/left. */ public static final TextBlockAnchor BOTTOM_LEFT = new TextBlockAnchor("TextBlockAnchor.BOTTOM_LEFT"); /** Bottom/center. */ public static final TextBlockAnchor BOTTOM_CENTER = new TextBlockAnchor("TextBlockAnchor.BOTTOM_CENTER"); /** Bottom/right. */ public static final TextBlockAnchor BOTTOM_RIGHT = new TextBlockAnchor("TextBlockAnchor.BOTTOM_RIGHT"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private TextBlockAnchor(final String name) { this.name = name; } /** * Returns a string representing the object. * * @return The string. */ public String toString() { return this.name; } /** * Returns true if this object is equal to the specified * object, and false otherwise. * * @param o the other object. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof TextBlockAnchor)) { return false; } final TextBlockAnchor other = (TextBlockAnchor) o; if (!this.name.equals(other.name)) { return false; } return true; } /** * Returns a hash code value for the object. * * @return the hashcode */ public int hashCode() { return this.name.hashCode(); } /** * Ensures that serialization returns the unique instances. * * @return The object. * * @throws ObjectStreamException if there is a problem. */ private Object readResolve() throws ObjectStreamException { if (this.equals(TextBlockAnchor.TOP_CENTER)) { return TextBlockAnchor.TOP_CENTER; } else if (this.equals(TextBlockAnchor.TOP_LEFT)) { return TextBlockAnchor.TOP_LEFT; } else if (this.equals(TextBlockAnchor.TOP_RIGHT)) { return TextBlockAnchor.TOP_RIGHT; } else if (this.equals(TextBlockAnchor.CENTER)) { return TextBlockAnchor.CENTER; } else if (this.equals(TextBlockAnchor.CENTER_LEFT)) { return TextBlockAnchor.CENTER_LEFT; } else if (this.equals(TextBlockAnchor.CENTER_RIGHT)) { return TextBlockAnchor.CENTER_RIGHT; } else if (this.equals(TextBlockAnchor.BOTTOM_CENTER)) { return TextBlockAnchor.BOTTOM_CENTER; } else if (this.equals(TextBlockAnchor.BOTTOM_LEFT)) { return TextBlockAnchor.BOTTOM_LEFT; } else if (this.equals(TextBlockAnchor.BOTTOM_RIGHT)) { return TextBlockAnchor.BOTTOM_RIGHT; } return null; } } jcommon-1.0.16/source/org/jfree/text/TextFragment.java0000644000175000017500000002471511172030703022623 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2007, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * TextFragment.java * ----------------- * (C) Copyright 2003-2007, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextFragment.java,v 1.13 2007/03/16 10:25:58 mungady Exp $ * * Changes * ------- * 07-Nov-2003 : Version 1 (DG); * 25-Nov-2003 : Fixed bug in the dimension calculation (DG); * 22-Dec-2003 : Added workaround for Java bug 4245442 (DG); * 29-Jan-2004 : Added paint attribute (DG); * 22-Mar-2004 : Added equals() method and implemented Serializable (DG); * 01-Apr-2004 : Changed java.awt.geom.Dimension2D to org.jfree.ui.Size2D * because of JDK bug 4976448 which persists on JDK 1.3.1 (DG); * 30-Sep-2004 : Moved drawRotatedString() from RefineryUtilities * --> TextUtilities (DG); * 16-Mar-2007 : Fixed serialization for GradientPaint (DG); * */ package org.jfree.text; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.font.LineMetrics; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.io.SerialUtilities; import org.jfree.ui.Size2D; import org.jfree.ui.TextAnchor; import org.jfree.util.Log; import org.jfree.util.LogContext; /** * A text item, with an associated font, that fits on a single line (see * {@link TextLine}). Instances of the class are immutable. */ public class TextFragment implements Serializable { /** For serialization. */ private static final long serialVersionUID = 4465945952903143262L; /** The default font. */ public static final Font DEFAULT_FONT = new Font("Serif", Font.PLAIN, 12); /** The default text color. */ public static final Paint DEFAULT_PAINT = Color.black; /** The text. */ private String text; /** The font. */ private Font font; /** The text color. */ private transient Paint paint; /** * The baseline offset (can be used to simulate subscripts and * superscripts). */ private float baselineOffset; /** Access to logging facilities. */ protected static final LogContext logger = Log.createContext( TextFragment.class); /** * Creates a new text fragment. * * @param text the text (null not permitted). */ public TextFragment(final String text) { this(text, DEFAULT_FONT, DEFAULT_PAINT); } /** * Creates a new text fragment. * * @param text the text (null not permitted). * @param font the font (null not permitted). */ public TextFragment(final String text, final Font font) { this(text, font, DEFAULT_PAINT); } /** * Creates a new text fragment. * * @param text the text (null not permitted). * @param font the font (null not permitted). * @param paint the text color (null not permitted). */ public TextFragment(final String text, final Font font, final Paint paint) { this(text, font, paint, 0.0f); } /** * Creates a new text fragment. * * @param text the text (null not permitted). * @param font the font (null not permitted). * @param paint the text color (null not permitted). * @param baselineOffset the baseline offset. */ public TextFragment(final String text, final Font font, final Paint paint, final float baselineOffset) { if (text == null) { throw new IllegalArgumentException("Null 'text' argument."); } if (font == null) { throw new IllegalArgumentException("Null 'font' argument."); } if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.text = text; this.font = font; this.paint = paint; this.baselineOffset = baselineOffset; } /** * Returns the text. * * @return The text (possibly null). */ public String getText() { return this.text; } /** * Returns the font. * * @return The font (never null). */ public Font getFont() { return this.font; } /** * Returns the text paint. * * @return The text paint (never null). */ public Paint getPaint() { return this.paint; } /** * Returns the baseline offset. * * @return The baseline offset. */ public float getBaselineOffset() { return this.baselineOffset; } /** * Draws the text fragment. * * @param g2 the graphics device. * @param anchorX the x-coordinate of the anchor point. * @param anchorY the y-coordinate of the anchor point. * @param anchor the location of the text that is aligned to the anchor * point. * @param rotateX the x-coordinate of the rotation point. * @param rotateY the y-coordinate of the rotation point. * @param angle the angle. */ public void draw(final Graphics2D g2, final float anchorX, final float anchorY, final TextAnchor anchor, final float rotateX, final float rotateY, final double angle) { g2.setFont(this.font); g2.setPaint(this.paint); TextUtilities.drawRotatedString(this.text, g2, anchorX, anchorY + this.baselineOffset, anchor, angle, rotateX, rotateY); } /** * Calculates the dimensions of the text fragment. * * @param g2 the graphics device. * * @return The width and height of the text. */ public Size2D calculateDimensions(final Graphics2D g2) { final FontMetrics fm = g2.getFontMetrics(this.font); final Rectangle2D bounds = TextUtilities.getTextBounds(this.text, g2, fm); final Size2D result = new Size2D(bounds.getWidth(), bounds.getHeight()); return result; } /** * Calculates the vertical offset between the baseline and the specified * text anchor. * * @param g2 the graphics device. * @param anchor the anchor. * * @return the offset. */ public float calculateBaselineOffset(final Graphics2D g2, final TextAnchor anchor) { float result = 0.0f; final FontMetrics fm = g2.getFontMetrics(this.font); final LineMetrics lm = fm.getLineMetrics("ABCxyz", g2); if (anchor == TextAnchor.TOP_LEFT || anchor == TextAnchor.TOP_CENTER || anchor == TextAnchor.TOP_RIGHT) { result = lm.getAscent(); } else if (anchor == TextAnchor.BOTTOM_LEFT || anchor == TextAnchor.BOTTOM_CENTER || anchor == TextAnchor.BOTTOM_RIGHT) { result = -lm.getDescent() - lm.getLeading(); } return result; } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object to test against (null permitted). * * @return A boolean. */ public boolean equals(final Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj instanceof TextFragment) { final TextFragment tf = (TextFragment) obj; if (!this.text.equals(tf.text)) { return false; } if (!this.font.equals(tf.font)) { return false; } if (!this.paint.equals(tf.paint)) { return false; } return true; } return false; } /** * Returns a hash code for this object. * * @return A hash code. */ public int hashCode() { int result; result = (this.text != null ? this.text.hashCode() : 0); result = 29 * result + (this.font != null ? this.font.hashCode() : 0); result = 29 * result + (this.paint != null ? this.paint.hashCode() : 0); return result; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(final ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.paint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.paint = SerialUtilities.readPaint(stream); } } jcommon-1.0.16/source/org/jfree/text/TextBox.java0000644000175000017500000003103011172030703021574 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------ * TextBox.java * ------------ * (C) Copyright 2004, 2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextBox.java,v 1.14 2008/09/01 16:00:42 mungady Exp $ * * Changes * ------- * 09-Mar-2004 : Version 1 (DG); * 22-Mar-2004 : Added equals() method and implemented Serializable (DG); * 09-Nov-2004 : Renamed getAdjustedHeight() --> calculateExtendedHeight() in * Spacer class (DG); * 22-Feb-2005 : Replaced Spacer with RectangleInsets (DG); * 14-Feb-2008 : Fixed alignment of text content with respect to insets (DG); * */ package org.jfree.text; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.io.SerialUtilities; import org.jfree.ui.RectangleAnchor; import org.jfree.ui.RectangleInsets; import org.jfree.ui.Size2D; import org.jfree.util.ObjectUtilities; /** * A box containing a text block. * * @author David Gilbert */ public class TextBox implements Serializable { /** For serialization. */ private static final long serialVersionUID = 3360220213180203706L; /** The outline paint. */ private transient Paint outlinePaint; /** The outline stroke. */ private transient Stroke outlineStroke; /** The interior space. */ private RectangleInsets interiorGap; /** The background paint. */ private transient Paint backgroundPaint; /** The shadow paint. */ private transient Paint shadowPaint; /** The shadow x-offset. */ private double shadowXOffset = 2.0; /** The shadow y-offset. */ private double shadowYOffset = 2.0; /** The text block. */ private TextBlock textBlock; /** * Creates an empty text box. */ public TextBox() { this((TextBlock) null); } /** * Creates a text box. * * @param text the text. */ public TextBox(final String text) { this((TextBlock) null); if (text != null) { this.textBlock = new TextBlock(); this.textBlock.addLine( text, new Font("SansSerif", Font.PLAIN, 10), Color.black ); } } /** * Creates a new text box. * * @param block the text block. */ public TextBox(final TextBlock block) { this.outlinePaint = Color.black; this.outlineStroke = new BasicStroke(1.0f); this.interiorGap = new RectangleInsets(1.0, 3.0, 1.0, 3.0); this.backgroundPaint = new Color(255, 255, 192); this.shadowPaint = Color.gray; this.shadowXOffset = 2.0; this.shadowYOffset = 2.0; this.textBlock = block; } /** * Returns the outline paint. * * @return The outline paint. */ public Paint getOutlinePaint() { return this.outlinePaint; } /** * Sets the outline paint. * * @param paint the paint. */ public void setOutlinePaint(final Paint paint) { this.outlinePaint = paint; } /** * Returns the outline stroke. * * @return The outline stroke. */ public Stroke getOutlineStroke() { return this.outlineStroke; } /** * Sets the outline stroke. * * @param stroke the stroke. */ public void setOutlineStroke(final Stroke stroke) { this.outlineStroke = stroke; } /** * Returns the interior gap. * * @return The interior gap. */ public RectangleInsets getInteriorGap() { return this.interiorGap; } /** * Sets the interior gap. * * @param gap the gap. */ public void setInteriorGap(final RectangleInsets gap) { this.interiorGap = gap; } /** * Returns the background paint. * * @return The background paint. */ public Paint getBackgroundPaint() { return this.backgroundPaint; } /** * Sets the background paint. * * @param paint the paint. */ public void setBackgroundPaint(final Paint paint) { this.backgroundPaint = paint; } /** * Returns the shadow paint. * * @return The shadow paint. */ public Paint getShadowPaint() { return this.shadowPaint; } /** * Sets the shadow paint. * * @param paint the paint. */ public void setShadowPaint(final Paint paint) { this.shadowPaint = paint; } /** * Returns the x-offset for the shadow effect. * * @return The offset. */ public double getShadowXOffset() { return this.shadowXOffset; } /** * Sets the x-offset for the shadow effect. * * @param offset the offset (in Java2D units). */ public void setShadowXOffset(final double offset) { this.shadowXOffset = offset; } /** * Returns the y-offset for the shadow effect. * * @return The offset. */ public double getShadowYOffset() { return this.shadowYOffset; } /** * Sets the y-offset for the shadow effect. * * @param offset the offset (in Java2D units). */ public void setShadowYOffset(final double offset) { this.shadowYOffset = offset; } /** * Returns the text block. * * @return The text block. */ public TextBlock getTextBlock() { return this.textBlock; } /** * Sets the text block. * * @param block the block. */ public void setTextBlock(final TextBlock block) { this.textBlock = block; } /** * Draws the text box. * * @param g2 the graphics device. * @param x the x-coordinate. * @param y the y-coordinate. * @param anchor the anchor point. */ public void draw(final Graphics2D g2, final float x, final float y, final RectangleAnchor anchor) { final Size2D d1 = this.textBlock.calculateDimensions(g2); final double w = this.interiorGap.extendWidth(d1.getWidth()); final double h = this.interiorGap.extendHeight(d1.getHeight()); final Size2D d2 = new Size2D(w, h); final Rectangle2D bounds = RectangleAnchor.createRectangle(d2, x, y, anchor); double xx = bounds.getX(); double yy = bounds.getY(); if (this.shadowPaint != null) { final Rectangle2D shadow = new Rectangle2D.Double( xx + this.shadowXOffset, yy + this.shadowYOffset, bounds.getWidth(), bounds.getHeight()); g2.setPaint(this.shadowPaint); g2.fill(shadow); } if (this.backgroundPaint != null) { g2.setPaint(this.backgroundPaint); g2.fill(bounds); } if (this.outlinePaint != null && this.outlineStroke != null) { g2.setPaint(this.outlinePaint); g2.setStroke(this.outlineStroke); g2.draw(bounds); } this.textBlock.draw(g2, (float) (xx + this.interiorGap.calculateLeftInset(w)), (float) (yy + this.interiorGap.calculateTopInset(h)), TextBlockAnchor.TOP_LEFT); } /** * Returns the height of the text box. * * @param g2 the graphics device. * * @return The height (in Java2D units). */ public double getHeight(final Graphics2D g2) { final Size2D d = this.textBlock.calculateDimensions(g2); return this.interiorGap.extendHeight(d.getHeight()); } /** * Tests this object for equality with an arbitrary object. * * @param obj the object to test against (null permitted). * * @return A boolean. */ public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof TextBox)) { return false; } final TextBox that = (TextBox) obj; if (!ObjectUtilities.equal(this.outlinePaint, that.outlinePaint)) { return false; } if (!ObjectUtilities.equal(this.outlineStroke, that.outlineStroke)) { return false; } if (!ObjectUtilities.equal(this.interiorGap, that.interiorGap)) { return false; } if (!ObjectUtilities.equal(this.backgroundPaint, that.backgroundPaint)) { return false; } if (!ObjectUtilities.equal(this.shadowPaint, that.shadowPaint)) { return false; } if (this.shadowXOffset != that.shadowXOffset) { return false; } if (this.shadowYOffset != that.shadowYOffset) { return false; } if (!ObjectUtilities.equal(this.textBlock, that.textBlock)) { return false; } return true; } /** * Returns a hash code for this object. * * @return A hash code. */ public int hashCode() { int result; long temp; result = (this.outlinePaint != null ? this.outlinePaint.hashCode() : 0); result = 29 * result + (this.outlineStroke != null ? this.outlineStroke.hashCode() : 0); result = 29 * result + (this.interiorGap != null ? this.interiorGap.hashCode() : 0); result = 29 * result + (this.backgroundPaint != null ? this.backgroundPaint.hashCode() : 0); result = 29 * result + (this.shadowPaint != null ? this.shadowPaint.hashCode() : 0); temp = this.shadowXOffset != +0.0d ? Double.doubleToLongBits(this.shadowXOffset) : 0L; result = 29 * result + (int) (temp ^ (temp >>> 32)); temp = this.shadowYOffset != +0.0d ? Double.doubleToLongBits(this.shadowYOffset) : 0L; result = 29 * result + (int) (temp ^ (temp >>> 32)); result = 29 * result + (this.textBlock != null ? this.textBlock.hashCode() : 0); return result; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(final ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.outlinePaint, stream); SerialUtilities.writeStroke(this.outlineStroke, stream); SerialUtilities.writePaint(this.backgroundPaint, stream); SerialUtilities.writePaint(this.shadowPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.outlinePaint = SerialUtilities.readPaint(stream); this.outlineStroke = SerialUtilities.readStroke(stream); this.backgroundPaint = SerialUtilities.readPaint(stream); this.shadowPaint = SerialUtilities.readPaint(stream); } } jcommon-1.0.16/source/org/jfree/text/TextBlock.java0000644000175000017500000002755611172030703022120 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------- * TextBlock.java * -------------- * (C) Copyright 2003, 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextBlock.java,v 1.15 2007/11/02 17:50:35 taqua Exp $ * * Changes * ------- * 07-Nov-2003 : Version 1 (DG); * 22-Dec-2003 : Added workaround for Java bug 4245442 (DG); * 09-Jan-2004 : Added an extra draw() method for no rotation case (DG); * 25-Feb-2004 : Added getLines() method (DG); * 22-Mar-2004 : Added equals() method and implemented Serializable (DG); * 24-Mar-2004 : Added 'paint' argument to addLine() method (DG); * 01-Apr-2004 : Changed java.awt.geom.Dimension2D to org.jfree.ui.Size2D * because of JDK bug 4976448 which persists on JDK 1.3.1 (DG); * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG); * */ package org.jfree.text; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.geom.Rectangle2D; import java.io.Serializable; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.jfree.ui.HorizontalAlignment; import org.jfree.ui.Size2D; import org.jfree.ui.TextAnchor; import org.jfree.util.ShapeUtilities; /** * A list of {@link TextLine} objects that form a block of text. * * @see TextUtilities#createTextBlock(String, Font, Paint) * * @author David Gilbert */ public class TextBlock implements Serializable { /** For serialization. */ private static final long serialVersionUID = -4333175719424385526L; /** Storage for the lines of text. */ private List lines; /** The alignment of the lines. */ private HorizontalAlignment lineAlignment; /** * Creates a new empty text block. */ public TextBlock() { this.lines = new java.util.ArrayList(); this.lineAlignment = HorizontalAlignment.CENTER; } /** * Returns the alignment of the lines of text within the block. * * @return The alignment (never null). */ public HorizontalAlignment getLineAlignment() { return this.lineAlignment; } /** * Sets the alignment of the lines of text within the block. * * @param alignment the alignment (null not permitted). */ public void setLineAlignment(HorizontalAlignment alignment) { if (alignment == null) { throw new IllegalArgumentException("Null 'alignment' argument."); } this.lineAlignment = alignment; } /** * Adds a line of text that will be displayed using the specified font. * * @param text the text. * @param font the font. * @param paint the paint. */ public void addLine(final String text, final Font font, final Paint paint) { addLine(new TextLine(text, font, paint)); } /** * Adds a {@link TextLine} to the block. * * @param line the line. */ public void addLine(final TextLine line) { this.lines.add(line); } /** * Returns the last line in the block. * * @return The last line in the block. */ public TextLine getLastLine() { TextLine last = null; final int index = this.lines.size() - 1; if (index >= 0) { last = (TextLine) this.lines.get(index); } return last; } /** * Returns an unmodifiable list containing the lines for the text block. * * @return A list of {@link TextLine} objects. */ public List getLines() { return Collections.unmodifiableList(this.lines); } /** * Returns the width and height of the text block. * * @param g2 the graphics device. * * @return The width and height. */ public Size2D calculateDimensions(final Graphics2D g2) { double width = 0.0; double height = 0.0; final Iterator iterator = this.lines.iterator(); while (iterator.hasNext()) { final TextLine line = (TextLine) iterator.next(); final Size2D dimension = line.calculateDimensions(g2); width = Math.max(width, dimension.getWidth()); height = height + dimension.getHeight(); } return new Size2D(width, height); } /** * Returns the bounds of the text block. * * @param g2 the graphics device (null not permitted). * @param anchorX the x-coordinate for the anchor point. * @param anchorY the y-coordinate for the anchor point. * @param anchor the text block anchor (null not permitted). * @param rotateX the x-coordinate for the rotation point. * @param rotateY the y-coordinate for the rotation point. * @param angle the rotation angle. * * @return The bounds. */ public Shape calculateBounds(final Graphics2D g2, final float anchorX, final float anchorY, final TextBlockAnchor anchor, final float rotateX, final float rotateY, final double angle) { final Size2D d = calculateDimensions(g2); final float[] offsets = calculateOffsets( anchor, d.getWidth(), d.getHeight() ); final Rectangle2D bounds = new Rectangle2D.Double( anchorX + offsets[0], anchorY + offsets[1], d.getWidth(), d.getHeight() ); final Shape rotatedBounds = ShapeUtilities.rotateShape( bounds, angle, rotateX, rotateY ); return rotatedBounds; } /** * Draws the text block at a specific location. * * @param g2 the graphics device. * @param x the x-coordinate for the anchor point. * @param y the y-coordinate for the anchor point. * @param anchor the anchor point. */ public void draw(final Graphics2D g2, final float x, final float y, final TextBlockAnchor anchor) { draw(g2, x, y, anchor, 0.0f, 0.0f, 0.0); } /** * Draws the text block, aligning it with the specified anchor point and * rotating it about the specified rotation point. * * @param g2 the graphics device. * @param anchorX the x-coordinate for the anchor point. * @param anchorY the y-coordinate for the anchor point. * @param anchor the point on the text block that is aligned to the * anchor point. * @param rotateX the x-coordinate for the rotation point. * @param rotateY the x-coordinate for the rotation point. * @param angle the rotation (in radians). */ public void draw(final Graphics2D g2, final float anchorX, final float anchorY, final TextBlockAnchor anchor, final float rotateX, final float rotateY, final double angle) { final Size2D d = calculateDimensions(g2); final float[] offsets = calculateOffsets(anchor, d.getWidth(), d.getHeight()); final Iterator iterator = this.lines.iterator(); float yCursor = 0.0f; while (iterator.hasNext()) { TextLine line = (TextLine) iterator.next(); Size2D dimension = line.calculateDimensions(g2); float lineOffset = 0.0f; if (this.lineAlignment == HorizontalAlignment.CENTER) { lineOffset = (float) (d.getWidth() - dimension.getWidth()) / 2.0f; } else if (this.lineAlignment == HorizontalAlignment.RIGHT) { lineOffset = (float) (d.getWidth() - dimension.getWidth()); } line.draw( g2, anchorX + offsets[0] + lineOffset, anchorY + offsets[1] + yCursor, TextAnchor.TOP_LEFT, rotateX, rotateY, angle ); yCursor = yCursor + (float) dimension.getHeight(); } } /** * Calculates the x and y offsets required to align the text block with the * specified anchor point. This assumes that the top left of the text * block is at (0.0, 0.0). * * @param anchor the anchor position. * @param width the width of the text block. * @param height the height of the text block. * * @return The offsets (float[0] = x offset, float[1] = y offset). */ private float[] calculateOffsets(final TextBlockAnchor anchor, final double width, final double height) { final float[] result = new float[2]; float xAdj = 0.0f; float yAdj = 0.0f; if (anchor == TextBlockAnchor.TOP_CENTER || anchor == TextBlockAnchor.CENTER || anchor == TextBlockAnchor.BOTTOM_CENTER) { xAdj = (float) -width / 2.0f; } else if (anchor == TextBlockAnchor.TOP_RIGHT || anchor == TextBlockAnchor.CENTER_RIGHT || anchor == TextBlockAnchor.BOTTOM_RIGHT) { xAdj = (float) -width; } if (anchor == TextBlockAnchor.TOP_LEFT || anchor == TextBlockAnchor.TOP_CENTER || anchor == TextBlockAnchor.TOP_RIGHT) { yAdj = 0.0f; } else if (anchor == TextBlockAnchor.CENTER_LEFT || anchor == TextBlockAnchor.CENTER || anchor == TextBlockAnchor.CENTER_RIGHT) { yAdj = (float) -height / 2.0f; } else if (anchor == TextBlockAnchor.BOTTOM_LEFT || anchor == TextBlockAnchor.BOTTOM_CENTER || anchor == TextBlockAnchor.BOTTOM_RIGHT) { yAdj = (float) -height; } result[0] = xAdj; result[1] = yAdj; return result; } /** * Tests this object for equality with an arbitrary object. * * @param obj the object to test against (null permitted). * * @return A boolean. */ public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof TextBlock) { final TextBlock block = (TextBlock) obj; return this.lines.equals(block.lines); } return false; } /** * Returns a hash code for this object. * * @return A hash code. */ public int hashCode() { return (this.lines != null ? this.lines.hashCode() : 0); } } jcommon-1.0.16/source/org/jfree/text/G2TextMeasurer.java0000644000175000017500000000533611172030703023032 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * G2TextMeasurer.java * ------------------- * (C) Copyright 2004, 2005, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: G2TextMeasurer.java,v 1.4 2005/10/18 13:17:16 mungady Exp $ * * Changes * ------- * 07-Jan-2004 : Version 1 (DG); * */ package org.jfree.text; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; /** * A {@link TextMeasurer} based on a {@link Graphics2D}. * * @author David Gilbert */ public class G2TextMeasurer implements TextMeasurer { /** The graphics device. */ private Graphics2D g2; /** * Creates a new text measurer. * * @param g2 the graphics device. */ public G2TextMeasurer(final Graphics2D g2) { this.g2 = g2; } /** * Returns the string width. * * @param text the text. * @param start the index of the first character to measure. * @param end the index of the last character to measure. * * @return The string width. */ public float getStringWidth(final String text, final int start, final int end) { final FontMetrics fm = this.g2.getFontMetrics(); final Rectangle2D bounds = TextUtilities.getTextBounds( text.substring(start, end), this.g2, fm ); final float result = (float) bounds.getWidth(); return result; } } jcommon-1.0.16/source/org/jfree/text/TextUtilities.java0000644000175000017500000007753411172030703023042 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * TextUtilities.java * ------------------ * (C) Copyright 2004-2006, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextUtilities.java,v 1.24 2008/09/10 09:15:43 mungady Exp $ * * Changes * ------- * 07-Jan-2004 : Version 1 (DG); * 24-Mar-2004 : Added 'paint' argument to createTextBlock() method (DG); * 07-Apr-2004 : Added getTextBounds() method and useFontMetricsGetStringBounds * flag (DG); * 08-Apr-2004 : Changed word break iterator to line break iterator in the * createTextBlock() method - see bug report 926074 (DG); * 03-Sep-2004 : Updated createTextBlock() method to add ellipses when limit * is reached (DG); * 30-Sep-2004 : Modified bounds returned by drawAlignedString() method (DG); * 10-Nov-2004 : Added new createTextBlock() method that works with * newlines (DG); * 19-Apr-2005 : Changed default value of useFontMetricsGetStringBounds (DG); * 17-May-2005 : createTextBlock() now recognises '\n' (DG); * 27-Jun-2005 : Added code to getTextBounds() method to work around Sun's bug * parade item 6183356 (DG); * 06-Jan-2006 : Reformatted (DG); * */ package org.jfree.text; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.text.BreakIterator; import org.jfree.base.BaseBoot; import org.jfree.ui.TextAnchor; import org.jfree.util.Log; import org.jfree.util.LogContext; import org.jfree.util.ObjectUtilities; /** * Some utility methods for working with text. * * @author David Gilbert */ public class TextUtilities { /** Access to logging facilities. */ protected static final LogContext logger = Log.createContext( TextUtilities.class); /** * A flag that controls whether or not the rotated string workaround is * used. */ private static boolean useDrawRotatedStringWorkaround; /** * A flag that controls whether the FontMetrics.getStringBounds() method * is used or a workaround is applied. */ private static boolean useFontMetricsGetStringBounds; static { try { final boolean isJava14 = ObjectUtilities.isJDK14(); final String configRotatedStringWorkaround = BaseBoot.getInstance().getGlobalConfig().getConfigProperty( "org.jfree.text.UseDrawRotatedStringWorkaround", "auto"); if (configRotatedStringWorkaround.equals("auto")) { useDrawRotatedStringWorkaround = (isJava14 == false); } else { useDrawRotatedStringWorkaround = configRotatedStringWorkaround.equals("true"); } final String configFontMetricsStringBounds = BaseBoot.getInstance().getGlobalConfig().getConfigProperty( "org.jfree.text.UseFontMetricsGetStringBounds", "auto"); if (configFontMetricsStringBounds.equals("auto")) { useFontMetricsGetStringBounds = (isJava14 == true); } else { useFontMetricsGetStringBounds = configFontMetricsStringBounds.equals("true"); } } catch (Exception e) { // ignore everything. useDrawRotatedStringWorkaround = true; useFontMetricsGetStringBounds = true; } } /** * Private constructor prevents object creation. */ private TextUtilities() { } /** * Creates a {@link TextBlock} from a String. Line breaks * are added where the String contains '\n' characters. * * @param text the text. * @param font the font. * @param paint the paint. * * @return A text block. */ public static TextBlock createTextBlock(final String text, final Font font, final Paint paint) { if (text == null) { throw new IllegalArgumentException("Null 'text' argument."); } final TextBlock result = new TextBlock(); String input = text; boolean moreInputToProcess = (text.length() > 0); final int start = 0; while (moreInputToProcess) { final int index = input.indexOf("\n"); if (index > start) { final String line = input.substring(start, index); if (index < input.length() - 1) { result.addLine(line, font, paint); input = input.substring(index + 1); } else { moreInputToProcess = false; } } else if (index == start) { if (index < input.length() - 1) { input = input.substring(index + 1); } else { moreInputToProcess = false; } } else { result.addLine(input, font, paint); moreInputToProcess = false; } } return result; } /** * Creates a new text block from the given string, breaking the * text into lines so that the maxWidth value is * respected. * * @param text the text. * @param font the font. * @param paint the paint. * @param maxWidth the maximum width for each line. * @param measurer the text measurer. * * @return A text block. */ public static TextBlock createTextBlock(final String text, final Font font, final Paint paint, final float maxWidth, final TextMeasurer measurer) { return createTextBlock(text, font, paint, maxWidth, Integer.MAX_VALUE, measurer); } /** * Creates a new text block from the given string, breaking the * text into lines so that the maxWidth value is * respected. * * @param text the text. * @param font the font. * @param paint the paint. * @param maxWidth the maximum width for each line. * @param maxLines the maximum number of lines. * @param measurer the text measurer. * * @return A text block. */ public static TextBlock createTextBlock(final String text, final Font font, final Paint paint, final float maxWidth, final int maxLines, final TextMeasurer measurer) { final TextBlock result = new TextBlock(); final BreakIterator iterator = BreakIterator.getLineInstance(); iterator.setText(text); int current = 0; int lines = 0; final int length = text.length(); while (current < length && lines < maxLines) { final int next = nextLineBreak(text, current, maxWidth, iterator, measurer); if (next == BreakIterator.DONE) { result.addLine(text.substring(current), font, paint); return result; } result.addLine(text.substring(current, next), font, paint); lines++; current = next; while (current < text.length()&& text.charAt(current) == '\n') { current++; } } if (current < length) { final TextLine lastLine = result.getLastLine(); final TextFragment lastFragment = lastLine.getLastTextFragment(); final String oldStr = lastFragment.getText(); String newStr = "..."; if (oldStr.length() > 3) { newStr = oldStr.substring(0, oldStr.length() - 3) + "..."; } lastLine.removeFragment(lastFragment); final TextFragment newFragment = new TextFragment(newStr, lastFragment.getFont(), lastFragment.getPaint()); lastLine.addFragment(newFragment); } return result; } /** * Returns the character index of the next line break. * * @param text the text. * @param start the start index. * @param width the target display width. * @param iterator the word break iterator. * @param measurer the text measurer. * * @return The index of the next line break. */ private static int nextLineBreak(final String text, final int start, final float width, final BreakIterator iterator, final TextMeasurer measurer) { // this method is (loosely) based on code in JFreeReport's // TextParagraph class int current = start; int end; float x = 0.0f; boolean firstWord = true; int newline = text.indexOf('\n', start); if (newline < 0) { newline = Integer.MAX_VALUE; } while (((end = iterator.next()) != BreakIterator.DONE)) { if (end > newline) { return newline; } x += measurer.getStringWidth(text, current, end); if (x > width) { if (firstWord) { while (measurer.getStringWidth(text, start, end) > width) { end--; if (end <= start) { return end; } } return end; } else { end = iterator.previous(); return end; } } // we found at least one word that fits ... firstWord = false; current = end; } return BreakIterator.DONE; } /** * Returns the bounds for the specified text. * * @param text the text (null permitted). * @param g2 the graphics context (not null). * @param fm the font metrics (not null). * * @return The text bounds (null if the text * argument is null). */ public static Rectangle2D getTextBounds(final String text, final Graphics2D g2, final FontMetrics fm) { final Rectangle2D bounds; if (TextUtilities.useFontMetricsGetStringBounds) { bounds = fm.getStringBounds(text, g2); // getStringBounds() can return incorrect height for some Unicode // characters...see bug parade 6183356, let's replace it with // something correct LineMetrics lm = fm.getFont().getLineMetrics(text, g2.getFontRenderContext()); bounds.setRect(bounds.getX(), bounds.getY(), bounds.getWidth(), lm.getHeight()); } else { final double width = fm.stringWidth(text); final double height = fm.getHeight(); if (logger.isDebugEnabled()) { logger.debug("Height = " + height); } bounds = new Rectangle2D.Double(0.0, -fm.getAscent(), width, height); } return bounds; } /** * Draws a string such that the specified anchor point is aligned to the * given (x, y) location. * * @param text the text. * @param g2 the graphics device. * @param x the x coordinate (Java 2D). * @param y the y coordinate (Java 2D). * @param anchor the anchor location. * * @return The text bounds (adjusted for the text position). */ public static Rectangle2D drawAlignedString(final String text, final Graphics2D g2, final float x, final float y, final TextAnchor anchor) { final Rectangle2D textBounds = new Rectangle2D.Double(); final float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor, textBounds); // adjust text bounds to match string position textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2], textBounds.getWidth(), textBounds.getHeight()); g2.drawString(text, x + adjust[0], y + adjust[1]); return textBounds; } /** * A utility method that calculates the anchor offsets for a string. * Normally, the (x, y) coordinate for drawing text is a point on the * baseline at the left of the text string. If you add these offsets to * (x, y) and draw the string, then the anchor point should coincide with * the (x, y) point. * * @param g2 the graphics device (not null). * @param text the text. * @param anchor the anchor point. * @param textBounds the text bounds (if not null, this * object will be updated by this method to match the * string bounds). * * @return The offsets. */ private static float[] deriveTextBoundsAnchorOffsets(final Graphics2D g2, final String text, final TextAnchor anchor, final Rectangle2D textBounds) { final float[] result = new float[3]; final FontRenderContext frc = g2.getFontRenderContext(); final Font f = g2.getFont(); final FontMetrics fm = g2.getFontMetrics(f); final Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm); final LineMetrics metrics = f.getLineMetrics(text, frc); final float ascent = metrics.getAscent(); result[2] = -ascent; final float halfAscent = ascent / 2.0f; final float descent = metrics.getDescent(); final float leading = metrics.getLeading(); float xAdj = 0.0f; float yAdj = 0.0f; if (anchor == TextAnchor.TOP_CENTER || anchor == TextAnchor.CENTER || anchor == TextAnchor.BOTTOM_CENTER || anchor == TextAnchor.BASELINE_CENTER || anchor == TextAnchor.HALF_ASCENT_CENTER) { xAdj = (float) -bounds.getWidth() / 2.0f; } else if (anchor == TextAnchor.TOP_RIGHT || anchor == TextAnchor.CENTER_RIGHT || anchor == TextAnchor.BOTTOM_RIGHT || anchor == TextAnchor.BASELINE_RIGHT || anchor == TextAnchor.HALF_ASCENT_RIGHT) { xAdj = (float) -bounds.getWidth(); } if (anchor == TextAnchor.TOP_LEFT || anchor == TextAnchor.TOP_CENTER || anchor == TextAnchor.TOP_RIGHT) { yAdj = -descent - leading + (float) bounds.getHeight(); } else if (anchor == TextAnchor.HALF_ASCENT_LEFT || anchor == TextAnchor.HALF_ASCENT_CENTER || anchor == TextAnchor.HALF_ASCENT_RIGHT) { yAdj = halfAscent; } else if (anchor == TextAnchor.CENTER_LEFT || anchor == TextAnchor.CENTER || anchor == TextAnchor.CENTER_RIGHT) { yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0); } else if (anchor == TextAnchor.BASELINE_LEFT || anchor == TextAnchor.BASELINE_CENTER || anchor == TextAnchor.BASELINE_RIGHT) { yAdj = 0.0f; } else if (anchor == TextAnchor.BOTTOM_LEFT || anchor == TextAnchor.BOTTOM_CENTER || anchor == TextAnchor.BOTTOM_RIGHT) { yAdj = -metrics.getDescent() - metrics.getLeading(); } if (textBounds != null) { textBounds.setRect(bounds); } result[0] = xAdj; result[1] = yAdj; return result; } /** * Sets the flag that controls whether or not a workaround is used for * drawing rotated strings. The related bug is on Sun's bug parade * (id 4312117) and the workaround involves using a TextLayout * instance to draw the text instead of calling the * drawString() method in the Graphics2D class. * * @param use the new flag value. */ public static void setUseDrawRotatedStringWorkaround(final boolean use) { useDrawRotatedStringWorkaround = use; } /** * A utility method for drawing rotated text. *

* A common rotation is -Math.PI/2 which draws text 'vertically' (with the * top of the characters on the left). * * @param text the text. * @param g2 the graphics device. * @param angle the angle of the (clockwise) rotation (in radians). * @param x the x-coordinate. * @param y the y-coordinate. */ public static void drawRotatedString(final String text, final Graphics2D g2, final double angle, final float x, final float y) { drawRotatedString(text, g2, x, y, angle, x, y); } /** * A utility method for drawing rotated text. *

* A common rotation is -Math.PI/2 which draws text 'vertically' (with the * top of the characters on the left). * * @param text the text. * @param g2 the graphics device. * @param textX the x-coordinate for the text (before rotation). * @param textY the y-coordinate for the text (before rotation). * @param angle the angle of the (clockwise) rotation (in radians). * @param rotateX the point about which the text is rotated. * @param rotateY the point about which the text is rotated. */ public static void drawRotatedString(final String text, final Graphics2D g2, final float textX, final float textY, final double angle, final float rotateX, final float rotateY) { if ((text == null) || (text.equals(""))) { return; } final AffineTransform saved = g2.getTransform(); // apply the rotation... final AffineTransform rotate = AffineTransform.getRotateInstance( angle, rotateX, rotateY); g2.transform(rotate); if (useDrawRotatedStringWorkaround) { // workaround for JDC bug ID 4312117 and others... final TextLayout tl = new TextLayout(text, g2.getFont(), g2.getFontRenderContext()); tl.draw(g2, textX, textY); } else { // replaces this code... g2.drawString(text, textX, textY); } g2.setTransform(saved); } /** * Draws a string that is aligned by one anchor point and rotated about * another anchor point. * * @param text the text. * @param g2 the graphics device. * @param x the x-coordinate for positioning the text. * @param y the y-coordinate for positioning the text. * @param textAnchor the text anchor. * @param angle the rotation angle. * @param rotationX the x-coordinate for the rotation anchor point. * @param rotationY the y-coordinate for the rotation anchor point. */ public static void drawRotatedString(final String text, final Graphics2D g2, final float x, final float y, final TextAnchor textAnchor, final double angle, final float rotationX, final float rotationY) { if (text == null || text.equals("")) { return; } final float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor); drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle, rotationX, rotationY); } /** * Draws a string that is aligned by one anchor point and rotated about * another anchor point. * * @param text the text. * @param g2 the graphics device. * @param x the x-coordinate for positioning the text. * @param y the y-coordinate for positioning the text. * @param textAnchor the text anchor. * @param angle the rotation angle (in radians). * @param rotationAnchor the rotation anchor. */ public static void drawRotatedString(final String text, final Graphics2D g2, final float x, final float y, final TextAnchor textAnchor, final double angle, final TextAnchor rotationAnchor) { if (text == null || text.equals("")) { return; } final float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor); final float[] rotateAdj = deriveRotationAnchorOffsets(g2, text, rotationAnchor); drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle, x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]); } /** * Returns a shape that represents the bounds of the string after the * specified rotation has been applied. * * @param text the text (null permitted). * @param g2 the graphics device. * @param x the x coordinate for the anchor point. * @param y the y coordinate for the anchor point. * @param textAnchor the text anchor. * @param angle the angle. * @param rotationAnchor the rotation anchor. * * @return The bounds (possibly null). */ public static Shape calculateRotatedStringBounds(final String text, final Graphics2D g2, final float x, final float y, final TextAnchor textAnchor, final double angle, final TextAnchor rotationAnchor) { if (text == null || text.equals("")) { return null; } final float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor); if (logger.isDebugEnabled()) { logger.debug("TextBoundsAnchorOffsets = " + textAdj[0] + ", " + textAdj[1]); } final float[] rotateAdj = deriveRotationAnchorOffsets(g2, text, rotationAnchor); if (logger.isDebugEnabled()) { logger.debug("RotationAnchorOffsets = " + rotateAdj[0] + ", " + rotateAdj[1]); } final Shape result = calculateRotatedStringBounds(text, g2, x + textAdj[0], y + textAdj[1], angle, x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]); return result; } /** * A utility method that calculates the anchor offsets for a string. * Normally, the (x, y) coordinate for drawing text is a point on the * baseline at the left of the text string. If you add these offsets to * (x, y) and draw the string, then the anchor point should coincide with * the (x, y) point. * * @param g2 the graphics device (not null). * @param text the text. * @param anchor the anchor point. * * @return The offsets. */ private static float[] deriveTextBoundsAnchorOffsets(final Graphics2D g2, final String text, final TextAnchor anchor) { final float[] result = new float[2]; final FontRenderContext frc = g2.getFontRenderContext(); final Font f = g2.getFont(); final FontMetrics fm = g2.getFontMetrics(f); final Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm); final LineMetrics metrics = f.getLineMetrics(text, frc); final float ascent = metrics.getAscent(); final float halfAscent = ascent / 2.0f; final float descent = metrics.getDescent(); final float leading = metrics.getLeading(); float xAdj = 0.0f; float yAdj = 0.0f; if (anchor == TextAnchor.TOP_CENTER || anchor == TextAnchor.CENTER || anchor == TextAnchor.BOTTOM_CENTER || anchor == TextAnchor.BASELINE_CENTER || anchor == TextAnchor.HALF_ASCENT_CENTER) { xAdj = (float) -bounds.getWidth() / 2.0f; } else if (anchor == TextAnchor.TOP_RIGHT || anchor == TextAnchor.CENTER_RIGHT || anchor == TextAnchor.BOTTOM_RIGHT || anchor == TextAnchor.BASELINE_RIGHT || anchor == TextAnchor.HALF_ASCENT_RIGHT) { xAdj = (float) -bounds.getWidth(); } if (anchor == TextAnchor.TOP_LEFT || anchor == TextAnchor.TOP_CENTER || anchor == TextAnchor.TOP_RIGHT) { yAdj = -descent - leading + (float) bounds.getHeight(); } else if (anchor == TextAnchor.HALF_ASCENT_LEFT || anchor == TextAnchor.HALF_ASCENT_CENTER || anchor == TextAnchor.HALF_ASCENT_RIGHT) { yAdj = halfAscent; } else if (anchor == TextAnchor.CENTER_LEFT || anchor == TextAnchor.CENTER || anchor == TextAnchor.CENTER_RIGHT) { yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0); } else if (anchor == TextAnchor.BASELINE_LEFT || anchor == TextAnchor.BASELINE_CENTER || anchor == TextAnchor.BASELINE_RIGHT) { yAdj = 0.0f; } else if (anchor == TextAnchor.BOTTOM_LEFT || anchor == TextAnchor.BOTTOM_CENTER || anchor == TextAnchor.BOTTOM_RIGHT) { yAdj = -metrics.getDescent() - metrics.getLeading(); } result[0] = xAdj; result[1] = yAdj; return result; } /** * A utility method that calculates the rotation anchor offsets for a * string. These offsets are relative to the text starting coordinate * (BASELINE_LEFT). * * @param g2 the graphics device. * @param text the text. * @param anchor the anchor point. * * @return The offsets. */ private static float[] deriveRotationAnchorOffsets(final Graphics2D g2, final String text, final TextAnchor anchor) { final float[] result = new float[2]; final FontRenderContext frc = g2.getFontRenderContext(); final LineMetrics metrics = g2.getFont().getLineMetrics(text, frc); final FontMetrics fm = g2.getFontMetrics(); final Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm); final float ascent = metrics.getAscent(); final float halfAscent = ascent / 2.0f; final float descent = metrics.getDescent(); final float leading = metrics.getLeading(); float xAdj = 0.0f; float yAdj = 0.0f; if (anchor == TextAnchor.TOP_LEFT || anchor == TextAnchor.CENTER_LEFT || anchor == TextAnchor.BOTTOM_LEFT || anchor == TextAnchor.BASELINE_LEFT || anchor == TextAnchor.HALF_ASCENT_LEFT) { xAdj = 0.0f; } else if (anchor == TextAnchor.TOP_CENTER || anchor == TextAnchor.CENTER || anchor == TextAnchor.BOTTOM_CENTER || anchor == TextAnchor.BASELINE_CENTER || anchor == TextAnchor.HALF_ASCENT_CENTER) { xAdj = (float) bounds.getWidth() / 2.0f; } else if (anchor == TextAnchor.TOP_RIGHT || anchor == TextAnchor.CENTER_RIGHT || anchor == TextAnchor.BOTTOM_RIGHT || anchor == TextAnchor.BASELINE_RIGHT || anchor == TextAnchor.HALF_ASCENT_RIGHT) { xAdj = (float) bounds.getWidth(); } if (anchor == TextAnchor.TOP_LEFT || anchor == TextAnchor.TOP_CENTER || anchor == TextAnchor.TOP_RIGHT) { yAdj = descent + leading - (float) bounds.getHeight(); } else if (anchor == TextAnchor.CENTER_LEFT || anchor == TextAnchor.CENTER || anchor == TextAnchor.CENTER_RIGHT) { yAdj = descent + leading - (float) (bounds.getHeight() / 2.0); } else if (anchor == TextAnchor.HALF_ASCENT_LEFT || anchor == TextAnchor.HALF_ASCENT_CENTER || anchor == TextAnchor.HALF_ASCENT_RIGHT) { yAdj = -halfAscent; } else if (anchor == TextAnchor.BASELINE_LEFT || anchor == TextAnchor.BASELINE_CENTER || anchor == TextAnchor.BASELINE_RIGHT) { yAdj = 0.0f; } else if (anchor == TextAnchor.BOTTOM_LEFT || anchor == TextAnchor.BOTTOM_CENTER || anchor == TextAnchor.BOTTOM_RIGHT) { yAdj = metrics.getDescent() + metrics.getLeading(); } result[0] = xAdj; result[1] = yAdj; return result; } /** * Returns a shape that represents the bounds of the string after the * specified rotation has been applied. * * @param text the text (null permitted). * @param g2 the graphics device. * @param textX the x coordinate for the text. * @param textY the y coordinate for the text. * @param angle the angle. * @param rotateX the x coordinate for the rotation point. * @param rotateY the y coordinate for the rotation point. * * @return The bounds (null if text is * null or has zero length). */ public static Shape calculateRotatedStringBounds(final String text, final Graphics2D g2, final float textX, final float textY, final double angle, final float rotateX, final float rotateY) { if ((text == null) || (text.equals(""))) { return null; } final FontMetrics fm = g2.getFontMetrics(); final Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm); final AffineTransform translate = AffineTransform.getTranslateInstance( textX, textY); final Shape translatedBounds = translate.createTransformedShape(bounds); final AffineTransform rotate = AffineTransform.getRotateInstance( angle, rotateX, rotateY); final Shape result = rotate.createTransformedShape(translatedBounds); return result; } /** * Returns the flag that controls whether the FontMetrics.getStringBounds() * method is used or not. If you are having trouble with label alignment * or positioning, try changing the value of this flag. * * @return A boolean. */ public static boolean getUseFontMetricsGetStringBounds() { return useFontMetricsGetStringBounds; } /** * Sets the flag that controls whether the FontMetrics.getStringBounds() * method is used or not. If you are having trouble with label alignment * or positioning, try changing the value of this flag. * * @param use the flag. */ public static void setUseFontMetricsGetStringBounds(final boolean use) { useFontMetricsGetStringBounds = use; } /** * Returns the flag that controls whether or not a workaround is used for * drawing rotated strings. * * @return A boolean. */ public static boolean isUseDrawRotatedStringWorkaround() { return useDrawRotatedStringWorkaround; } } jcommon-1.0.16/source/org/jfree/text/junit/0000755000175000017500000000000011351753320020476 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/text/junit/TextBoxTests.java0000644000175000017500000001223411172030703023755 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * TextBoxTests.java * ----------------- * (C) Copyright 2004, 2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextBoxTests.java,v 1.6 2007/11/02 17:50:35 taqua Exp $ * * Changes: * -------- * 22-Mar-2004 : Version 1 (DG); * */ package org.jfree.text.junit; import java.awt.BasicStroke; import java.awt.Color; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.text.TextBlock; import org.jfree.text.TextBox; import org.jfree.text.TextLine; import org.jfree.ui.RectangleInsets; /** * Tests for the {@link TextBox} class. */ public class TextBoxTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TextBoxTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TextBoxTests(final String name) { super(name); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { final TextBox b1 = new TextBox("Hello"); final TextBox b2 = new TextBox("Hello"); assertTrue(b1.equals(b2)); assertTrue(b2.equals(b1)); // outlinePaint b1.setOutlinePaint(Color.blue); assertFalse(b1.equals(b2)); b2.setOutlinePaint(Color.blue); assertTrue(b1.equals(b2)); // outlineStroke b1.setOutlineStroke(new BasicStroke(1.1f)); assertFalse(b1.equals(b2)); b2.setOutlineStroke(new BasicStroke(1.1f)); assertTrue(b1.equals(b2)); // interiorGap b1.setInteriorGap(new RectangleInsets(10, 10, 10, 10)); assertFalse(b1.equals(b2)); b2.setInteriorGap(new RectangleInsets(10, 10, 10, 10)); assertTrue(b1.equals(b2)); // backgroundPaint b1.setBackgroundPaint(Color.blue); assertFalse(b1.equals(b2)); b2.setBackgroundPaint(Color.blue); assertTrue(b1.equals(b2)); // shadowPaint b1.setShadowPaint(Color.blue); assertFalse(b1.equals(b2)); b2.setShadowPaint(Color.blue); assertTrue(b1.equals(b2)); // shadowXOffset b1.setShadowXOffset(1.0); assertFalse(b1.equals(b2)); b2.setShadowXOffset(1.0); assertTrue(b1.equals(b2)); // shadowYOffset b1.setShadowYOffset(1.0); assertFalse(b1.equals(b2)); b2.setShadowYOffset(1.0); assertTrue(b1.equals(b2)); // textBlock final TextBlock tb1 = new TextBlock(); tb1.addLine(new TextLine("Testing")); b1.setTextBlock(tb1); assertFalse(b1.equals(b2)); final TextBlock tb2 = new TextBlock(); tb2.addLine(new TextLine("Testing")); b2.setTextBlock(tb2); assertTrue(b1.equals(b2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { final TextBox b1 = new TextBox("Hello"); TextBox b2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(b1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); b2 = (TextBox) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertEquals(b1, b2); } } jcommon-1.0.16/source/org/jfree/text/junit/TextBlockAnchorTests.java0000644000175000017500000000657111172030703025421 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * TextBlockAnchorTests.java * ------------------------- * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextBlockAnchorTests.java,v 1.3 2007/11/02 17:50:35 taqua Exp $ * * Changes * ------- * 22-Mar-2004 : Version 1 (DG); * */ package org.jfree.text.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.text.TextBlockAnchor; /** * Tests for the {@link TextBlockAnchor} class. */ public class TextBlockAnchorTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TextBlockAnchorTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TextBlockAnchorTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { assertTrue(TextBlockAnchor.CENTER.equals(TextBlockAnchor.CENTER)); } /** * Serialize an instance, restore it, and check for identity. */ public void testSerialization() { final TextBlockAnchor a1 = TextBlockAnchor.CENTER; TextBlockAnchor a2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(a1); out.close(); final ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); a2 = (TextBlockAnchor) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(a1 == a2); } } jcommon-1.0.16/source/org/jfree/text/junit/TextFragmentTests.java0000644000175000017500000001026511172030703024772 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * TextFragmentTests.java * ---------------------- * (C) Copyright 2004, 2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextFragmentTests.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes: * -------- * 22-Mar-2004 : Version 1 (DG); * */ package org.jfree.text.junit; import java.awt.Color; import java.awt.Font; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.text.TextFragment; /** * Tests for the {@link TextFragment} class. */ public class TextFragmentTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TextFragmentTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TextFragmentTests(final String name) { super(name); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { TextFragment tf1 = new TextFragment("Test"); TextFragment tf2 = new TextFragment("Test"); assertTrue(tf1.equals(tf2)); assertTrue(tf2.equals(tf1)); // text tf1 = new TextFragment("Test 1"); assertFalse(tf1.equals(tf2)); tf2 = new TextFragment("Test 1"); assertTrue(tf1.equals(tf2)); // font tf1 = new TextFragment("Test 1", new Font("Arial", Font.BOLD, 11)); assertFalse(tf1.equals(tf2)); tf2 = new TextFragment("Test 1", new Font("Arial", Font.BOLD, 11)); assertTrue(tf1.equals(tf2)); // paint tf1 = new TextFragment("Test 1", new Font("Arial", Font.BOLD, 11), Color.red); assertFalse(tf1.equals(tf2)); tf2 = new TextFragment("Test 1", new Font("Arial", Font.BOLD, 11), Color.red); assertTrue(tf1.equals(tf2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { final TextFragment tf1 = new TextFragment("Test"); TextFragment tf2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(tf1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); tf2 = (TextFragment) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertEquals(tf1, tf2); } } jcommon-1.0.16/source/org/jfree/text/junit/TextPackageTests.java0000644000175000017500000000502411172030703024557 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * TextPackageTests.java * --------------------- * (C) Copyright 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextPackageTests.java,v 1.2 2005/10/18 13:17:29 mungady Exp $ * * Changes: * -------- * 22-Mar-2004 : Version 1 (DG); * */ package org.jfree.text.junit; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * A collection of tests for the org.jfree.text package. These tests can be run using JUnit * (http://www.junit.org). */ public class TextPackageTests extends TestCase { /** * Returns a test suite to the JUnit test runner. * * @return the test suite. */ public static Test suite() { final TestSuite suite = new TestSuite("org.jfree.text"); suite.addTestSuite(TextBlockTests.class); suite.addTestSuite(TextBlockAnchorTests.class); suite.addTestSuite(TextBoxTests.class); suite.addTestSuite(TextFragmentTests.class); suite.addTestSuite(TextLineTests.class); return suite; } /** * Constructs the test suite. * * @param name the suite name. */ public TextPackageTests(final String name) { super(name); } } jcommon-1.0.16/source/org/jfree/text/junit/TextBlockTests.java0000644000175000017500000000705211172030703024261 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * TextBlockTests.java * ------------------- * (C) Copyright 2004, 2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextBlockTests.java,v 1.5 2007/11/02 17:50:35 taqua Exp $ * * Changes: * -------- * 22-Mar-2004 : Version 1 (DG); * */ package org.jfree.text.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.text.TextBlock; import org.jfree.text.TextLine; /** * Tests for the {@link TextBlock} class. */ public class TextBlockTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TextBlockTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TextBlockTests(final String name) { super(name); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { final TextBlock b1 = new TextBlock(); b1.addLine(new TextLine("Test")); final TextBlock b2 = new TextBlock(); b2.addLine(new TextLine("Test")); assertTrue(b1.equals(b2)); assertTrue(b2.equals(b1)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { final TextBlock b1 = new TextBlock(); b1.addLine(new TextLine("Test")); TextBlock b2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(b1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); b2 = (TextBlock) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertEquals(b1, b2); } } jcommon-1.0.16/source/org/jfree/text/junit/TextLineTests.java0000644000175000017500000000666111172030703024123 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * TextLineTests.java * ------------------ * (C) Copyright 2004, 2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextLineTests.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes: * -------- * 22-Mar-2004 : Version 1 (DG); * */ package org.jfree.text.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.text.TextLine; /** * Tests for the {@link TextLine} class. */ public class TextLineTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TextLineTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TextLineTests(final String name) { super(name); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { final TextLine line1 = new TextLine("Test"); final TextLine line2 = new TextLine("Test"); assertTrue(line1.equals(line2)); assertTrue(line2.equals(line1)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { final TextLine line1 = new TextLine("Test"); TextLine line2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(line1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); line2 = (TextLine) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertEquals(line1, line2); } } jcommon-1.0.16/source/org/jfree/package.html0000644000175000017500000000022611172030703020634 0ustar twernertwerner The root package for the JCommon class library. jcommon-1.0.16/source/org/jfree/threads/0000755000175000017500000000000011351753320020013 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/threads/package.html0000644000175000017500000000022611172030703022266 0ustar twernertwerner Additional support for multi-threaded programs. jcommon-1.0.16/source/org/jfree/threads/ReaderWriterLock.java0000644000175000017500000001335711172030703024071 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * ReaderWriterLock.java * --------------------- * * $Id: ReaderWriterLock.java,v 1.3 2005/10/18 13:18:34 mungady Exp $ * * Changes * ------- * 29-Jan-2003 : Added standard header (DG); * */ package org.jfree.threads; import java.util.ArrayList; import java.util.Iterator; /** * A reader-writer lock from "Java Threads" by Scott Oak and Henry Wong. * * @author Scott Oak and Henry Wong */ public class ReaderWriterLock { /** * A node for the waiting list. * * @author Scott Oak and Henry Wong */ private static class ReaderWriterNode { /** A reader. */ protected static final int READER = 0; /** A writer. */ protected static final int WRITER = 1; /** The thread. */ protected Thread t; /** The state. */ protected int state; /** The number of acquires.*/ protected int nAcquires; /** * Creates a new node. * * @param t the thread. * @param state the state. */ private ReaderWriterNode(final Thread t, final int state) { this.t = t; this.state = state; this.nAcquires = 0; } } /** The waiting threads. */ private ArrayList waiters; /** * Default constructor. */ public ReaderWriterLock() { this.waiters = new ArrayList(); } /** * Grab the read lock. */ public synchronized void lockRead() { final ReaderWriterNode node; final Thread me = Thread.currentThread(); final int index = getIndex(me); if (index == -1) { node = new ReaderWriterNode(me, ReaderWriterNode.READER); this.waiters.add(node); } else { node = (ReaderWriterNode) this.waiters.get(index); } while (getIndex(me) > firstWriter()) { try { wait(); } catch (Exception e) { System.err.println("ReaderWriterLock.lockRead(): exception."); System.err.print(e.getMessage()); } } node.nAcquires++; } /** * Grab the write lock. */ public synchronized void lockWrite() { final ReaderWriterNode node; final Thread me = Thread.currentThread(); final int index = getIndex(me); if (index == -1) { node = new ReaderWriterNode(me, ReaderWriterNode.WRITER); this.waiters.add(node); } else { node = (ReaderWriterNode) this.waiters.get(index); if (node.state == ReaderWriterNode.READER) { throw new IllegalArgumentException("Upgrade lock"); } node.state = ReaderWriterNode.WRITER; } while (getIndex(me) != 0) { try { wait(); } catch (Exception e) { System.err.println("ReaderWriterLock.lockWrite(): exception."); System.err.print(e.getMessage()); } } node.nAcquires++; } /** * Unlock. */ public synchronized void unlock() { final ReaderWriterNode node; final Thread me = Thread.currentThread(); final int index = getIndex(me); if (index > firstWriter()) { throw new IllegalArgumentException("Lock not held"); } node = (ReaderWriterNode) this.waiters.get(index); node.nAcquires--; if (node.nAcquires == 0) { this.waiters.remove(index); } notifyAll(); } /** * Returns the index of the first waiting writer. * * @return The index. */ private int firstWriter() { final Iterator e = this.waiters.iterator(); int index = 0; while (e.hasNext()) { final ReaderWriterNode node = (ReaderWriterNode) e.next(); if (node.state == ReaderWriterNode.WRITER) { return index; } index += 1; } return Integer.MAX_VALUE; } /** * Returns the index of a thread. * * @param t the thread. * * @return The index. */ private int getIndex(final Thread t) { final Iterator e = this.waiters.iterator(); int index = 0; while (e.hasNext()) { final ReaderWriterNode node = (ReaderWriterNode) e.next(); if (node.t == t) { return index; } index += 1; } return -1; } } jcommon-1.0.16/source/org/jfree/util/0000755000175000017500000000000011351753320017336 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/util/StrokeList.java0000644000175000017500000001131311172030703022275 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * StrokeList.java * --------------- * (C) Copyright 2003, 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: StrokeList.java,v 1.5 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------- * 19-Aug-2003 : Version 1 (DG); * */ package org.jfree.util; import java.awt.Stroke; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.io.SerialUtilities; /** * A table of {@link Stroke} objects. * * @author David Gilbert */ public class StrokeList extends AbstractObjectList { /** * Creates a new list. */ public StrokeList() { super(); } /** * Returns a {@link Stroke} object from the list. * * @param index the index (zero-based). * * @return The object. */ public Stroke getStroke(final int index) { return (Stroke) get(index); } /** * Sets the {@link Stroke} for an item in the list. The list is expanded if necessary. * * @param index the index (zero-based). * @param stroke the {@link Stroke}. */ public void setStroke(final int index, final Stroke stroke) { set(index, stroke); } /** * Returns an independent copy of the list. * * @return A clone. * * @throws CloneNotSupportedException if an item in the list cannot be cloned. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Tests the list for equality with another object (typically also a list). * * @param o the other object. * * @return A boolean. */ public boolean equals(final Object o) { if (o == null) { return false; } if (o == this) { return true; } if (o instanceof StrokeList) { return super.equals(o); } return false; } /** * Returns a hash code value for the object. * * @return the hashcode */ public int hashCode() { return super.hashCode(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(final ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); final int count = size(); stream.writeInt(count); for (int i = 0; i < count; i++) { final Stroke stroke = getStroke(i); if (stroke != null) { stream.writeInt(i); SerialUtilities.writeStroke(stroke, stream); } else { stream.writeInt(-1); } } } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); final int count = stream.readInt(); for (int i = 0; i < count; i++) { final int index = stream.readInt(); if (index != -1) { setStroke(index, SerialUtilities.readStroke(stream)); } } } } jcommon-1.0.16/source/org/jfree/util/TableOrder.java0000644000175000017500000000724111172030703022222 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * TableOrder.java * --------------- * (C) Copyright 2004, 2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TableOrder.java,v 1.5 2005/10/18 13:24:19 mungady Exp $ * * Changes: * -------- * 29-Jan-2004 : Version 1 (DG); * */ package org.jfree.util; import java.io.ObjectStreamException; import java.io.Serializable; /** * Used to indicate the processing order for a table (by row or by column). * * @author David Gilbert */ public final class TableOrder implements Serializable { /** For serialization. */ private static final long serialVersionUID = 525193294068177057L; /** By row. */ public static final TableOrder BY_ROW = new TableOrder("TableOrder.BY_ROW"); /** By column. */ public static final TableOrder BY_COLUMN = new TableOrder("TableOrder.BY_COLUMN"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private TableOrder(String name) { this.name = name; } /** * Returns a string representing the object. * * @return The string. */ public String toString() { return this.name; } /** * Returns true if this object is equal to the specified * object, and false otherwise. * * @param obj the other object. * * @return A boolean. */ public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof TableOrder)) { return false; } TableOrder that = (TableOrder) obj; if (!this.name.equals(that.name)) { return false; } return true; } /** * Returns a hash code value for the object. * * @return The hashcode */ public int hashCode() { return this.name.hashCode(); } /** * Ensures that serialization returns the unique instances. * * @return The object. * * @throws ObjectStreamException if there is a problem. */ private Object readResolve() throws ObjectStreamException { if (this.equals(TableOrder.BY_ROW)) { return TableOrder.BY_ROW; } else if (this.equals(TableOrder.BY_COLUMN)) { return TableOrder.BY_COLUMN; } return null; } } jcommon-1.0.16/source/org/jfree/util/StackableException.java0000644000175000017500000001244611172030703023752 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * StackableException.java * ----------------------- * (C)opyright 2002-2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: StackableException.java,v 1.3 2005/11/14 10:56:55 mungady Exp $ * * Changes * ------- * 06-Dec-2002 : Initial version * 10-Dec-2002 : Fixed issues reported by Checkstyle (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.util; import java.io.PrintStream; import java.io.PrintWriter; /** * A baseclass for exceptions, which could have parent exceptions. These parent exceptions * are raised in a subclass and are now wrapped into a subclass of this Exception. *

* The parents are printed when this exception is printed. This class exists mainly for * debugging reasons, as with them it is easier to detect the root cause of an error. * * * * @author Thomas Morgner */ public abstract class StackableException extends Exception { /** The parent exception. */ private Exception parent; /** * Creates a StackableRuntimeException with no message and no parent. */ public StackableException() { super(); } /** * Creates an exception. * * @param message the exception message. * @param ex the parent exception. */ public StackableException(final String message, final Exception ex) { super(message); this.parent = ex; } /** * Creates an exception. * * @param message the exception message. */ public StackableException(final String message) { super(message); } /** * Returns the parent exception (possibly null). * * @return the parent exception. */ public Exception getParent() { return this.parent; } /** * Prints the stack trace to the specified stream. * * @param stream the output stream. */ public void printStackTrace(final PrintStream stream) { super.printStackTrace(stream); if (getParent() != null) { stream.println("ParentException: "); getParent().printStackTrace(stream); } } /** * Prints the stack trace to the specified writer. * * @param writer the writer. */ public void printStackTrace(final PrintWriter writer) { super.printStackTrace(writer); if (getParent() != null) { writer.println("ParentException: "); getParent().printStackTrace(writer); } } /** * Prints this Throwable and its backtrace to the * standard error stream. This method prints a stack trace for this * Throwable object on the error output stream that is * the value of the field System.err. The first line of * output contains the result of the {@link #toString()} method for * this object. Remaining lines represent data previously recorded by * the method {@link #fillInStackTrace()}. The format of this * information depends on the implementation, but the following * example may be regarded as typical: *

     * java.lang.NullPointerException
     *         at MyClass.mash(MyClass.java:9)
     *         at MyClass.crunch(MyClass.java:6)
     *         at MyClass.main(MyClass.java:3)
     * 
* This example was produced by running the program: *
     *
     * class MyClass {
     *
     *     public static void main(String[] argv) {
     *         crunch(null);
     *     }
     *     static void crunch(int[] a) {
     *         mash(a);
     *     }
     *
     *     static void mash(int[] b) {
     *         System.out.println(b[0]);
     *     }
     * }
     * 
* * @see System#err */ public void printStackTrace() { synchronized (System.err) { printStackTrace(System.err); } } } jcommon-1.0.16/source/org/jfree/util/PaintUtilities.java0000644000175000017500000001336011172030703023145 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * PaintUtilities.java * ------------------- * (C) Copyright 2003-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: PaintUtilities.java,v 1.10 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 13-Nov-2003 : Version 1 (DG); * 04-Oct-2004 : Renamed PaintUtils --> PaintUtilities (DG); * 23-Feb-2005 : Rewrote equal() method with less indenting required (DG); * */ package org.jfree.util; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Paint; import java.lang.reflect.Field; import java.lang.reflect.Modifier; /** * Utility code that relates to Paint objects. * * @author David Gilbert */ public class PaintUtilities { /** * Private constructor prevents object creation. */ private PaintUtilities() { } /** * Returns true if the two Paint objects are equal * OR both null. This method handles * GradientPaint as a special case. * * @param p1 paint 1 (null permitted). * @param p2 paint 2 (null permitted). * * @return A boolean. */ public static boolean equal(final Paint p1, final Paint p2) { // handle cases where either or both arguments are null if (p1 == null) { return (p2 == null); } if (p2 == null) { return false; } boolean result = false; // handle GradientPaint as a special case... if (p1 instanceof GradientPaint && p2 instanceof GradientPaint) { final GradientPaint gp1 = (GradientPaint) p1; final GradientPaint gp2 = (GradientPaint) p2; result = gp1.getColor1().equals(gp2.getColor1()) && gp1.getColor2().equals(gp2.getColor2()) && gp1.getPoint1().equals(gp2.getPoint1()) && gp1.getPoint2().equals(gp2.getPoint2()) && gp1.isCyclic() == gp2.isCyclic() && gp1.getTransparency() == gp1.getTransparency(); } else { result = p1.equals(p2); } return result; } /** * Converts a color into a string. If the color is equal to one of the * defined constant colors, that name is returned instead. Otherwise the * color is returned as hex-string. * * @param c the color. * @return the string for this color. */ public static String colorToString (final Color c) { try { final Field[] fields = Color.class.getFields(); for (int i = 0; i < fields.length; i++) { final Field f = fields[i]; if (Modifier.isPublic(f.getModifiers()) && Modifier.isFinal(f.getModifiers()) && Modifier.isStatic(f.getModifiers())) { final String name = f.getName(); final Object oColor = f.get(null); if (oColor instanceof Color) { if (c.equals(oColor)) { return name; } } } } } catch (Exception e) { // } // no defined constant color, so this must be a user defined color final String color = Integer.toHexString(c.getRGB() & 0x00ffffff); final StringBuffer retval = new StringBuffer(7); retval.append("#"); final int fillUp = 6 - color.length(); for (int i = 0; i < fillUp; i++) { retval.append("0"); } retval.append(color); return retval.toString(); } /** * Converts a given string into a color. * * @param value the string, either a name or a hex-string. * @return the color. */ public static Color stringToColor (final String value) { if (value == null) { return Color.black; } try { // get color by hex or octal value return Color.decode(value); } catch (NumberFormatException nfe) { // if we can't decode lets try to get it by name try { // try to get a color by name using reflection final Field f = Color.class.getField(value); return (Color) f.get(null); } catch (Exception ce) { Log.info("No such Color : " + value); // if we can't get any color return black return Color.black; } } } } jcommon-1.0.16/source/org/jfree/util/PaintList.java0000644000175000017500000001131111172030703022077 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------- * PaintList.java * -------------- * (C) Copyright 2003, 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: PaintList.java,v 1.5 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------- * 13-Aug-2003 : Version 1 (DG); * 27-Jun-2005 : Fixed equals() method to handle GradientPaint (DG); * */ package org.jfree.util; import java.awt.Paint; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.io.SerialUtilities; /** * A table of {@link Paint} objects. * * @author David Gilbert */ public class PaintList extends AbstractObjectList { /** * Creates a new list. */ public PaintList() { super(); } /** * Returns a {@link Paint} object from the list. * * @param index the index (zero-based). * * @return The object. */ public Paint getPaint(final int index) { return (Paint) get(index); } /** * Sets the {@link Paint} for an item in the list. The list is expanded if necessary. * * @param index the index (zero-based). * @param paint the {@link Paint}. */ public void setPaint(final int index, final Paint paint) { set(index, paint); } /** * Tests the list for equality with another object (typically also a list). * * @param obj the other object (null permitted). * * @return A boolean. */ public boolean equals(final Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj instanceof PaintList) { PaintList that = (PaintList) obj; int listSize = size(); for (int i = 0; i < listSize; i++) { if (!PaintUtilities.equal(getPaint(i), that.getPaint(i))) { return false; } } } return true; } /** * Returns a hash code value for the object. * * @return the hashcode */ public int hashCode() { return super.hashCode(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(final ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); final int count = size(); stream.writeInt(count); for (int i = 0; i < count; i++) { final Paint paint = getPaint(i); if (paint != null) { stream.writeInt(i); SerialUtilities.writePaint(paint, stream); } else { stream.writeInt(-1); } } } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); final int count = stream.readInt(); for (int i = 0; i < count; i++) { final int index = stream.readInt(); if (index != -1) { setPaint(index, SerialUtilities.readPaint(stream)); } } } } jcommon-1.0.16/source/org/jfree/util/WaitingImageObserver.java0000644000175000017500000001426511172030703024260 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * WaitingImageObserver.java * ------------------------- * (C)opyright 2000-2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner * Contributor(s): Stefan Prange; * * $Id: WaitingImageObserver.java,v 1.8 2008/09/10 09:24:41 mungady Exp $ * * Changes (from 8-Feb-2002) * ------------------------- * 15-Apr-2002 : first version used by ImageElement. * 16-May-2002 : Line delimiters adjusted * 04-Jun-2002 : Documentation and added a NullPointerCheck for the constructor. * 14-Jul-2002 : BugFixed: WaitingImageObserver dead-locked (bugfix by Stefan * Prange) * 18-Mar-2003 : Updated header and made minor Javadoc changes (DG); * 21-Sep-2003 : Moved from JFreeReport. */ package org.jfree.util; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; import java.io.Serializable; /** * This image observer blocks until the image is completely loaded. AWT * defers the loading of images until they are painted on a graphic. * * While printing reports it is not very nice, not to know whether a image * was completely loaded, so this observer forces the loading of the image * until a final state (either ALLBITS, ABORT or ERROR) is reached. * * @author Thomas Morgner */ public class WaitingImageObserver implements ImageObserver, Serializable, Cloneable { /** For serialization. */ static final long serialVersionUID = -807204410581383550L; /** The lock. */ private boolean lock; /** The image. */ private Image image; /** A flag that signals an error. */ private boolean error; /** * Creates a new ImageObserver for the given Image. * The observer has to be started by an external thread. * * @param image the image to observe (null not permitted). */ public WaitingImageObserver(final Image image) { if (image == null) { throw new NullPointerException(); } this.image = image; this.lock = true; } /** * Callback function used by AWT to inform that more data is available. The * observer waits until either all data is loaded or AWT signals that the * image cannot be loaded. * * @param img the image being observed. * @param infoflags the bitwise inclusive OR of the following * flags: WIDTH, HEIGHT, * PROPERTIES, SOMEBITS, * FRAMEBITS, ALLBITS, * ERROR, ABORT. * @param x the x coordinate. * @param y the y coordinate. * @param width the width. * @param height the height. * * @return false if the infoflags indicate that the * image is completely loaded; true otherwise. */ public synchronized boolean imageUpdate( final Image img, final int infoflags, final int x, final int y, final int width, final int height) { if ((infoflags & ImageObserver.ALLBITS) == ImageObserver.ALLBITS) { this.lock = false; this.error = false; notifyAll(); return false; } else if ((infoflags & ImageObserver.ABORT) == ImageObserver.ABORT || (infoflags & ImageObserver.ERROR) == ImageObserver.ERROR) { this.lock = false; this.error = true; notifyAll(); return false; } //notifyAll(); return true; } /** * The workerthread. Simply draws the image to a BufferedImage's * Graphics-Object and waits for the AWT to load the image. */ public synchronized void waitImageLoaded() { if (this.lock == false) { return; } final BufferedImage img = new BufferedImage( 1, 1, BufferedImage.TYPE_INT_RGB ); final Graphics g = img.getGraphics(); while (this.lock) { if (g.drawImage(this.image, 0, 0, img.getWidth(this), img.getHeight(this), this)) { return; } try { wait(500); } catch (InterruptedException e) { Log.info( "WaitingImageObserver.waitImageLoaded(): InterruptedException thrown", e ); } } } /** * Clones this WaitingImageObserver. * * @return a clone. * * @throws CloneNotSupportedException this should never happen. * @deprecated cloning may lock down the observer */ public Object clone() throws CloneNotSupportedException { return (WaitingImageObserver) super.clone(); } /** * Returns true if loading is complete, and false * otherwise. * * @return A boolean. */ public boolean isLoadingComplete() { return this.lock == false; } /** * Returns true if there is an error condition, and false otherwise. * * @return A boolean. */ public boolean isError() { return this.error; } } jcommon-1.0.16/source/org/jfree/util/LogTarget.java0000644000175000017500000000562511172030703022073 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------- * LogTarget.java * -------------- * (C)opyright 2002-2004, by Object Refinery Limited. * * $Id: LogTarget.java,v 1.3 2005/11/14 10:55:59 mungady Exp $ * * Changes * ------- * 11-May-2002 : Initial version * 06-Dec-2002 : LogTargets now use Object-Parameters instead of Strings. * 05-Feb-2003 : Removed unnecessary methods. * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.util; /** * An interface that defines a log target (a consumer of log messages). Classes which * implement this interface can be registered with the {@link org.jfree.util.Log} class * and will then receive logging messages generated by the code. * * @author Thomas Morgner */ public interface LogTarget { /** * Loglevel ERROR. */ public static final int ERROR = 0; /** * Loglevel WARN. */ public static final int WARN = 1; /** * Loglevel INFO. */ public static final int INFO = 2; /** * Loglevel DEBUG. */ public static final int DEBUG = 3; /** Strings for the log levels. */ public static final String[] LEVELS = { "ERROR: ", "WARN: ", "INFO: ", "DEBUG: " }; /** * Logs a message at a specified log level. * * @param level the log level. * @param message the log message. */ public void log(int level, Object message); /** * Logs a message at a specified log level. * * @param level the log level. * @param message the log message. * @param e the exception */ public void log(int level, Object message, Exception e); } jcommon-1.0.16/source/org/jfree/util/AbstractObjectList.java0000644000175000017500000001770311172030703023731 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * AbstractObjectList.java * ----------------------- * (C)opyright 2003, 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Bill Kelemen; * Nicolas Brodu * * $Id: AbstractObjectList.java,v 1.5 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------- * 13-Aug-2003 : Version 1, based on ObjectList (DG); * 24-Aug-2003 : Fixed size (BK); * 15-Sep-2003 : Fix serialization for subclasses (ShapeList, PaintList) (NB); */ package org.jfree.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; /** * A list of objects that can grow as required. * * @author David Gilbert */ public class AbstractObjectList implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 7789833772597351595L; /** The default initial capacity of the list. */ public static final int DEFAULT_INITIAL_CAPACITY = 8; /** Storage for the objects. */ private transient Object[] objects; /** The current list size. */ private int size = 0; /** The default increment. */ private int increment = DEFAULT_INITIAL_CAPACITY; /** * Creates a new list with the default initial capacity. */ protected AbstractObjectList() { this(DEFAULT_INITIAL_CAPACITY); } /** * Creates a new list. * * @param initialCapacity the initial capacity. */ protected AbstractObjectList(final int initialCapacity) { this (initialCapacity, initialCapacity); } /** * Creates a new list. * * @param initialCapacity the initial capacity. * @param increment the increment. */ protected AbstractObjectList(final int initialCapacity, final int increment) { this.objects = new Object[initialCapacity]; this.increment = increment; } /** * Returns the object at the specified index, if there is one, or * null. * * @param index the object index. * * @return The object or null. */ protected Object get(final int index) { Object result = null; if (index >= 0 && index < this.size) { result = this.objects[index]; } return result; } /** * Sets an object reference (overwriting any existing object). * * @param index the object index. * @param object the object (null permitted). */ protected void set(final int index, final Object object) { if (index < 0) { throw new IllegalArgumentException("Requires index >= 0."); } if (index >= this.objects.length) { final Object[] enlarged = new Object[index + this.increment]; System.arraycopy(this.objects, 0, enlarged, 0, this.objects.length); this.objects = enlarged; } this.objects[index] = object; this.size = Math.max(this.size, index + 1); } /** * Clears the list. */ public void clear() { Arrays.fill(this.objects, null); this.size = 0; } /** * Returns the size of the list. * * @return The size of the list. */ public int size() { return this.size; } /** * Returns the index of the specified object, or -1 if the object is not in * the list. * * @param object the object. * * @return The index or -1. */ protected int indexOf(final Object object) { for (int index = 0; index < this.size; index++) { if (this.objects[index] == object) { return (index); } } return -1; } /** * Tests this list for equality with another object. * * @param obj the object to test. * * @return A boolean. */ public boolean equals(final Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (!(obj instanceof AbstractObjectList)) { return false; } final AbstractObjectList other = (AbstractObjectList) obj; final int listSize = size(); for (int i = 0; i < listSize; i++) { if (!ObjectUtilities.equal(get(i), other.get(i))) { return false; } } return true; } /** * Returns a hash code value for the object. * * @return the hashcode */ public int hashCode() { return super.hashCode(); } /** * Clones the list of objects. The objects in the list are not cloned, so * this is method makes a 'shallow' copy of the list. * * @return A clone. * * @throws CloneNotSupportedException if an item in the list does not * support cloning. */ public Object clone() throws CloneNotSupportedException { final AbstractObjectList clone = (AbstractObjectList) super.clone(); if (this.objects != null) { clone.objects = new Object[this.objects.length]; System.arraycopy( this.objects, 0, clone.objects, 0, this.objects.length ); } return clone; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(final ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); final int count = size(); stream.writeInt(count); for (int i = 0; i < count; i++) { final Object object = get(i); if (object != null && object instanceof Serializable) { stream.writeInt(i); stream.writeObject(object); } else { stream.writeInt(-1); } } } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.objects = new Object[this.size]; final int count = stream.readInt(); for (int i = 0; i < count; i++) { final int index = stream.readInt(); if (index != -1) { set(index, stream.readObject()); } } } } jcommon-1.0.16/source/org/jfree/util/ShapeUtilities.java0000644000175000017500000005014711172030703023136 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * ShapeUtilities.java * ------------------- * (C)opyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ShapeUtilities.java,v 1.18 2008/06/02 06:58:28 mungady Exp $ * * Changes * ------- * 13-Aug-2003 : Version 1 (DG); * 16-Mar-2004 : Moved rotateShape() from RefineryUtilities.java to here (DG); * 13-May-2004 : Added new shape creation methods (DG); * 30-Sep-2004 : Added createLineRegion() method (DG); * Moved drawRotatedShape() method from RefineryUtilities class * to this class (DG); * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG); * 26-Oct-2004 : Added a method to test the equality of two Line2D * instances (DG); * 10-Nov-2004 : Added new translateShape() and equal(Ellipse2D, Ellipse2D) * methods (DG); * 11-Nov-2004 : Renamed translateShape() --> createTranslatedShape() (DG); * 07-Jan-2005 : Minor Javadoc fix (DG); * 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG); * 21-Jan-2005 : Modified return type of RectangleAnchor.coordinates() * method (DG); * 22-Feb-2005 : Added equality tests for Arc2D and GeneralPath (DG); * 16-Mar-2005 : Fixed bug where equal(Shape, Shape) fails for two Polygon * instances (DG); * 01-Jun-2008 : Fixed bug in equal(GeneralPath, GeneralPath) method (DG); * */ package org.jfree.util; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.Arrays; import org.jfree.ui.RectangleAnchor; /** * Utility methods for {@link Shape} objects. * * @author David Gilbert */ public class ShapeUtilities { /** * Prevents instantiation. */ private ShapeUtilities() { } /** * Returns a clone of the specified shape, or null. At the * current time, this method supports cloning for instances of * Line2D, RectangularShape, Area * and GeneralPath. *

* RectangularShape includes Arc2D, * Ellipse2D, Rectangle2D, * RoundRectangle2D. * * @param shape the shape to clone (null permitted, * returns null). * * @return A clone or null. */ public static Shape clone(final Shape shape) { if (shape instanceof Cloneable) { try { return (Shape) ObjectUtilities.clone(shape); } catch (CloneNotSupportedException cnse) { } } final Shape result = null; return result; } /** * Tests two shapes for equality. If both shapes are null, * this method will return true. *

* In the current implementation, the following shapes are supported: * Ellipse2D, Line2D and Rectangle2D * (implicit). * * @param s1 the first shape (null permitted). * @param s2 the second shape (null permitted). * * @return A boolean. */ public static boolean equal(final Shape s1, final Shape s2) { if (s1 instanceof Line2D && s2 instanceof Line2D) { return equal((Line2D) s1, (Line2D) s2); } else if (s1 instanceof Ellipse2D && s2 instanceof Ellipse2D) { return equal((Ellipse2D) s1, (Ellipse2D) s2); } else if (s1 instanceof Arc2D && s2 instanceof Arc2D) { return equal((Arc2D) s1, (Arc2D) s2); } else if (s1 instanceof Polygon && s2 instanceof Polygon) { return equal((Polygon) s1, (Polygon) s2); } else if (s1 instanceof GeneralPath && s2 instanceof GeneralPath) { return equal((GeneralPath) s1, (GeneralPath) s2); } else { // this will handle Rectangle2D... return ObjectUtilities.equal(s1, s2); } } /** * Compares two lines are returns true if they are equal or * both null. * * @param l1 the first line (null permitted). * @param l2 the second line (null permitted). * * @return A boolean. */ public static boolean equal(final Line2D l1, final Line2D l2) { if (l1 == null) { return (l2 == null); } if (l2 == null) { return false; } if (!l1.getP1().equals(l2.getP1())) { return false; } if (!l1.getP2().equals(l2.getP2())) { return false; } return true; } /** * Compares two ellipses and returns true if they are equal or * both null. * * @param e1 the first ellipse (null permitted). * @param e2 the second ellipse (null permitted). * * @return A boolean. */ public static boolean equal(final Ellipse2D e1, final Ellipse2D e2) { if (e1 == null) { return (e2 == null); } if (e2 == null) { return false; } if (!e1.getFrame().equals(e2.getFrame())) { return false; } return true; } /** * Compares two arcs and returns true if they are equal or * both null. * * @param a1 the first arc (null permitted). * @param a2 the second arc (null permitted). * * @return A boolean. */ public static boolean equal(final Arc2D a1, final Arc2D a2) { if (a1 == null) { return (a2 == null); } if (a2 == null) { return false; } if (!a1.getFrame().equals(a2.getFrame())) { return false; } if (a1.getAngleStart() != a2.getAngleStart()) { return false; } if (a1.getAngleExtent() != a2.getAngleExtent()) { return false; } if (a1.getArcType() != a2.getArcType()) { return false; } return true; } /** * Tests two polygons for equality. If both are null this * method returns true. * * @param p1 polygon 1 (null permitted). * @param p2 polygon 2 (null permitted). * * @return A boolean. */ public static boolean equal(final Polygon p1, final Polygon p2) { if (p1 == null) { return (p2 == null); } if (p2 == null) { return false; } if (p1.npoints != p2.npoints) { return false; } if (!Arrays.equals(p1.xpoints, p2.xpoints)) { return false; } if (!Arrays.equals(p1.ypoints, p2.ypoints)) { return false; } return true; } /** * Tests two polygons for equality. If both are null this * method returns true. * * @param p1 path 1 (null permitted). * @param p2 path 2 (null permitted). * * @return A boolean. */ public static boolean equal(final GeneralPath p1, final GeneralPath p2) { if (p1 == null) { return (p2 == null); } if (p2 == null) { return false; } if (p1.getWindingRule() != p2.getWindingRule()) { return false; } PathIterator iterator1 = p1.getPathIterator(null); PathIterator iterator2 = p2.getPathIterator(null); double[] d1 = new double[6]; double[] d2 = new double[6]; boolean done = iterator1.isDone() && iterator2.isDone(); while (!done) { if (iterator1.isDone() != iterator2.isDone()) { return false; } int seg1 = iterator1.currentSegment(d1); int seg2 = iterator2.currentSegment(d2); if (seg1 != seg2) { return false; } if (!Arrays.equals(d1, d2)) { return false; } iterator1.next(); iterator2.next(); done = iterator1.isDone() && iterator2.isDone(); } return true; } /** * Creates and returns a translated shape. * * @param shape the shape (null not permitted). * @param transX the x translation (in Java2D space). * @param transY the y translation (in Java2D space). * * @return The translated shape. */ public static Shape createTranslatedShape(final Shape shape, final double transX, final double transY) { if (shape == null) { throw new IllegalArgumentException("Null 'shape' argument."); } final AffineTransform transform = AffineTransform.getTranslateInstance( transX, transY); return transform.createTransformedShape(shape); } /** * Translates a shape to a new location such that the anchor point * (relative to the rectangular bounds of the shape) aligns with the * specified (x, y) coordinate in Java2D space. * * @param shape the shape (null not permitted). * @param anchor the anchor (null not permitted). * @param locationX the x-coordinate (in Java2D space). * @param locationY the y-coordinate (in Java2D space). * * @return A new and translated shape. */ public static Shape createTranslatedShape(final Shape shape, final RectangleAnchor anchor, final double locationX, final double locationY) { if (shape == null) { throw new IllegalArgumentException("Null 'shape' argument."); } if (anchor == null) { throw new IllegalArgumentException("Null 'anchor' argument."); } Point2D anchorPoint = RectangleAnchor.coordinates( shape.getBounds2D(), anchor); final AffineTransform transform = AffineTransform.getTranslateInstance( locationX - anchorPoint.getX(), locationY - anchorPoint.getY()); return transform.createTransformedShape(shape); } /** * Rotates a shape about the specified coordinates. * * @param base the shape (null permitted, returns * null). * @param angle the angle (in radians). * @param x the x coordinate for the rotation point (in Java2D space). * @param y the y coordinate for the rotation point (in Java2D space). * * @return the rotated shape. */ public static Shape rotateShape(final Shape base, final double angle, final float x, final float y) { if (base == null) { return null; } final AffineTransform rotate = AffineTransform.getRotateInstance( angle, x, y); final Shape result = rotate.createTransformedShape(base); return result; } /** * Draws a shape with the specified rotation about (x, y). * * @param g2 the graphics device (null not permitted). * @param shape the shape (null not permitted). * @param angle the angle (in radians). * @param x the x coordinate for the rotation point. * @param y the y coordinate for the rotation point. */ public static void drawRotatedShape(final Graphics2D g2, final Shape shape, final double angle, final float x, final float y) { final AffineTransform saved = g2.getTransform(); final AffineTransform rotate = AffineTransform.getRotateInstance( angle, x, y); g2.transform(rotate); g2.draw(shape); g2.setTransform(saved); } /** A useful constant used internally. */ private static final float SQRT2 = (float) Math.pow(2.0, 0.5); /** * Creates a diagonal cross shape. * * @param l the length of each 'arm'. * @param t the thickness. * * @return A diagonal cross shape. */ public static Shape createDiagonalCross(final float l, final float t) { final GeneralPath p0 = new GeneralPath(); p0.moveTo(-l - t, -l + t); p0.lineTo(-l + t, -l - t); p0.lineTo(0.0f, -t * SQRT2); p0.lineTo(l - t, -l - t); p0.lineTo(l + t, -l + t); p0.lineTo(t * SQRT2, 0.0f); p0.lineTo(l + t, l - t); p0.lineTo(l - t, l + t); p0.lineTo(0.0f, t * SQRT2); p0.lineTo(-l + t, l + t); p0.lineTo(-l - t, l - t); p0.lineTo(-t * SQRT2, 0.0f); p0.closePath(); return p0; } /** * Creates a diagonal cross shape. * * @param l the length of each 'arm'. * @param t the thickness. * * @return A diagonal cross shape. */ public static Shape createRegularCross(final float l, final float t) { final GeneralPath p0 = new GeneralPath(); p0.moveTo(-l, t); p0.lineTo(-t, t); p0.lineTo(-t, l); p0.lineTo(t, l); p0.lineTo(t, t); p0.lineTo(l, t); p0.lineTo(l, -t); p0.lineTo(t, -t); p0.lineTo(t, -l); p0.lineTo(-t, -l); p0.lineTo(-t, -t); p0.lineTo(-l, -t); p0.closePath(); return p0; } /** * Creates a diamond shape. * * @param s the size factor (equal to half the height of the diamond). * * @return A diamond shape. */ public static Shape createDiamond(final float s) { final GeneralPath p0 = new GeneralPath(); p0.moveTo(0.0f, -s); p0.lineTo(s, 0.0f); p0.lineTo(0.0f, s); p0.lineTo(-s, 0.0f); p0.closePath(); return p0; } /** * Creates a triangle shape that points upwards. * * @param s the size factor (equal to half the height of the triangle). * * @return A triangle shape. */ public static Shape createUpTriangle(final float s) { final GeneralPath p0 = new GeneralPath(); p0.moveTo(0.0f, -s); p0.lineTo(s, s); p0.lineTo(-s, s); p0.closePath(); return p0; } /** * Creates a triangle shape that points downwards. * * @param s the size factor (equal to half the height of the triangle). * * @return A triangle shape. */ public static Shape createDownTriangle(final float s) { final GeneralPath p0 = new GeneralPath(); p0.moveTo(0.0f, s); p0.lineTo(s, -s); p0.lineTo(-s, -s); p0.closePath(); return p0; } /** * Creates a region surrounding a line segment by 'widening' the line * segment. A typical use for this method is the creation of a * 'clickable' region for a line that is displayed on-screen. * * @param line the line (null not permitted). * @param width the width of the region. * * @return A region that surrounds the line. */ public static Shape createLineRegion(final Line2D line, final float width) { final GeneralPath result = new GeneralPath(); final float x1 = (float) line.getX1(); final float x2 = (float) line.getX2(); final float y1 = (float) line.getY1(); final float y2 = (float) line.getY2(); if ((x2 - x1) != 0.0) { final double theta = Math.atan((y2 - y1) / (x2 - x1)); final float dx = (float) Math.sin(theta) * width; final float dy = (float) Math.cos(theta) * width; result.moveTo(x1 - dx, y1 + dy); result.lineTo(x1 + dx, y1 - dy); result.lineTo(x2 + dx, y2 - dy); result.lineTo(x2 - dx, y2 + dy); result.closePath(); } else { // special case, vertical line result.moveTo(x1 - width / 2.0f, y1); result.lineTo(x1 + width / 2.0f, y1); result.lineTo(x2 + width / 2.0f, y2); result.lineTo(x2 - width / 2.0f, y2); result.closePath(); } return result; } /** * Returns a point based on (x, y) but constrained to be within the bounds * of a given rectangle. * * @param x the x-coordinate. * @param y the y-coordinate. * @param area the constraining rectangle (null not * permitted). * * @return A point within the rectangle. * * @throws NullPointerException if area is null. */ public static Point2D getPointInRectangle(double x, double y, final Rectangle2D area) { x = Math.max(area.getMinX(), Math.min(x, area.getMaxX())); y = Math.max(area.getMinY(), Math.min(y, area.getMaxY())); return new Point2D.Double(x, y); } /** * Checks, whether the given rectangle1 fully contains rectangle 2 * (even if rectangle 2 has a height or width of zero!). * * @param rect1 the first rectangle. * @param rect2 the second rectangle. * * @return A boolean. */ public static boolean contains(final Rectangle2D rect1, final Rectangle2D rect2) { final double x0 = rect1.getX(); final double y0 = rect1.getY(); final double x = rect2.getX(); final double y = rect2.getY(); final double w = rect2.getWidth(); final double h = rect2.getHeight(); return ((x >= x0) && (y >= y0) && ((x + w) <= (x0 + rect1.getWidth())) && ((y + h) <= (y0 + rect1.getHeight()))); } /** * Checks, whether the given rectangle1 fully contains rectangle 2 * (even if rectangle 2 has a height or width of zero!). * * @param rect1 the first rectangle. * @param rect2 the second rectangle. * * @return A boolean. */ public static boolean intersects (final Rectangle2D rect1, final Rectangle2D rect2) { final double x0 = rect1.getX(); final double y0 = rect1.getY(); final double x = rect2.getX(); final double width = rect2.getWidth(); final double y = rect2.getY(); final double height = rect2.getHeight(); return (x + width >= x0 && y + height >= y0 && x <= x0 + rect1.getWidth() && y <= y0 + rect1.getHeight()); } } jcommon-1.0.16/source/org/jfree/util/ResourceBundleSupport.java0000644000175000017500000004602511172030703024520 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * ReadOnlyIterator.java * --------------------- * (C)opyright 2003-2008, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ResourceBundleSupport.java,v 1.12 2008/12/18 09:57:32 mungady Exp $ * * Changes * ------- * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.util; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.lang.reflect.Field; import java.net.URL; import java.text.MessageFormat; import java.util.Arrays; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.TreeMap; import java.util.TreeSet; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JMenu; import javax.swing.KeyStroke; /** * An utility class to ease up using property-file resource bundles. *

* The class support references within the resource bundle set to minimize the * occurence of duplicate keys. References are given in the format: *

 * a.key.name=@referenced.key
 * 
*

* A lookup to a key in an other resource bundle should be written by *

 * a.key.name=@@resourcebundle_name@referenced.key
 * 
* * @author Thomas Morgner */ public class ResourceBundleSupport { /** * The resource bundle that will be used for local lookups. */ private ResourceBundle resources; /** * A cache for string values, as looking up the cache is faster than looking * up the value in the bundle. */ private TreeMap cache; /** * The current lookup path when performing non local lookups. This prevents * infinite loops during such lookups. */ private TreeSet lookupPath; /** * The name of the local resource bundle. */ private String resourceBase; /** * The locale for this bundle. */ private Locale locale; /** * Creates a new instance. * * @param locale the locale. * @param baseName the base name of the resource bundle, a fully qualified * class name */ public ResourceBundleSupport(final Locale locale, final String baseName) { this(locale, ResourceBundleWrapper.getBundle(baseName, locale), baseName); } /** * Creates a new instance. * * @param locale the locale for which this resource bundle is * created. * @param resourceBundle the resourcebundle * @param baseName the base name of the resource bundle, a fully * qualified class name */ protected ResourceBundleSupport(final Locale locale, final ResourceBundle resourceBundle, final String baseName) { if (locale == null) { throw new NullPointerException("Locale must not be null"); } if (resourceBundle == null) { throw new NullPointerException("Resources must not be null"); } if (baseName == null) { throw new NullPointerException("BaseName must not be null"); } this.locale = locale; this.resources = resourceBundle; this.resourceBase = baseName; this.cache = new TreeMap(); this.lookupPath = new TreeSet(); } /** * Creates a new instance. * * @param locale the locale for which the resource bundle is * created. * @param resourceBundle the resourcebundle */ public ResourceBundleSupport(final Locale locale, final ResourceBundle resourceBundle) { this(locale, resourceBundle, resourceBundle.toString()); } /** * Creates a new instance. * * @param baseName the base name of the resource bundle, a fully qualified * class name */ public ResourceBundleSupport(final String baseName) { this(Locale.getDefault(), ResourceBundleWrapper.getBundle(baseName), baseName); } /** * Creates a new instance. * * @param resourceBundle the resourcebundle * @param baseName the base name of the resource bundle, a fully * qualified class name */ protected ResourceBundleSupport(final ResourceBundle resourceBundle, final String baseName) { this(Locale.getDefault(), resourceBundle, baseName); } /** * Creates a new instance. * * @param resourceBundle the resourcebundle */ public ResourceBundleSupport(final ResourceBundle resourceBundle) { this(Locale.getDefault(), resourceBundle, resourceBundle.toString()); } /** * The base name of the resource bundle. * * @return the resource bundle's name. */ protected final String getResourceBase() { return this.resourceBase; } /** * Gets a string for the given key from this resource bundle or one of its * parents. If the key is a link, the link is resolved and the referenced * string is returned instead. * * @param key the key for the desired string * @return the string for the given key * @throws NullPointerException if key is null * @throws MissingResourceException if no object for the given key can be * found * @throws ClassCastException if the object found for the given key is * not a string */ public synchronized String getString(final String key) { final String retval = (String) this.cache.get(key); if (retval != null) { return retval; } this.lookupPath.clear(); return internalGetString(key); } /** * Performs the lookup for the given key. If the key points to a link the * link is resolved and that key is looked up instead. * * @param key the key for the string * @return the string for the given key */ protected String internalGetString(final String key) { if (this.lookupPath.contains(key)) { throw new MissingResourceException ("InfiniteLoop in resource lookup", getResourceBase(), this.lookupPath.toString()); } final String fromResBundle = this.resources.getString(key); if (fromResBundle.startsWith("@@")) { // global forward ... final int idx = fromResBundle.indexOf('@', 2); if (idx == -1) { throw new MissingResourceException ("Invalid format for global lookup key.", getResourceBase(), key); } try { final ResourceBundle res = ResourceBundleWrapper.getBundle (fromResBundle.substring(2, idx)); return res.getString(fromResBundle.substring(idx + 1)); } catch (Exception e) { Log.error("Error during global lookup", e); throw new MissingResourceException ("Error during global lookup", getResourceBase(), key); } } else if (fromResBundle.startsWith("@")) { // local forward ... final String newKey = fromResBundle.substring(1); this.lookupPath.add(key); final String retval = internalGetString(newKey); this.cache.put(key, retval); return retval; } else { this.cache.put(key, fromResBundle); return fromResBundle; } } /** * Returns an scaled icon suitable for buttons or menus. * * @param key the name of the resource bundle key * @param large true, if the image should be scaled to 24x24, or false for * 16x16 * @return the icon. */ public Icon getIcon(final String key, final boolean large) { final String name = getString(key); return createIcon(name, true, large); } /** * Returns an unscaled icon. * * @param key the name of the resource bundle key * @return the icon. */ public Icon getIcon(final String key) { final String name = getString(key); return createIcon(name, false, false); } /** * Returns the mnemonic stored at the given resourcebundle key. The mnemonic * should be either the symbolic name of one of the KeyEvent.VK_* constants * (without the 'VK_') or the character for that key. *

* For the enter key, the resource bundle would therefore either contain * "ENTER" or "\n". *

   * a.resourcebundle.key=ENTER
   * an.other.resourcebundle.key=\n
   * 
* * @param key the resourcebundle key * @return the mnemonic */ public Integer getMnemonic(final String key) { final String name = getString(key); return createMnemonic(name); } /** * Returns an optional mnemonic. * * @param key the key. * * @return The mnemonic. */ public Integer getOptionalMnemonic(final String key) { final String name = getString(key); if (name != null && name.length() > 0) { return createMnemonic(name); } return null; } /** * Returns the keystroke stored at the given resourcebundle key. *

* The keystroke will be composed of a simple key press and the plattform's * MenuKeyMask. *

* The keystrokes character key should be either the symbolic name of one of * the KeyEvent.VK_* constants or the character for that key. *

* For the 'A' key, the resource bundle would therefore either contain * "VK_A" or "a". *

   * a.resourcebundle.key=VK_A
   * an.other.resourcebundle.key=a
   * 
* * @param key the resourcebundle key * @return the mnemonic * @see Toolkit#getMenuShortcutKeyMask() */ public KeyStroke getKeyStroke(final String key) { return getKeyStroke(key, getMenuKeyMask()); } /** * Returns an optional key stroke. * * @param key the key. * * @return The key stroke. */ public KeyStroke getOptionalKeyStroke(final String key) { return getOptionalKeyStroke(key, getMenuKeyMask()); } /** * Returns the keystroke stored at the given resourcebundle key. *

* The keystroke will be composed of a simple key press and the given * KeyMask. If the KeyMask is zero, a plain Keystroke is returned. *

* The keystrokes character key should be either the symbolic name of one of * the KeyEvent.VK_* constants or the character for that key. *

* For the 'A' key, the resource bundle would therefore either contain * "VK_A" or "a". *

   * a.resourcebundle.key=VK_A
   * an.other.resourcebundle.key=a
   * 
* * @param key the resourcebundle key. * @param mask the mask. * * @return the mnemonic * @see Toolkit#getMenuShortcutKeyMask() */ public KeyStroke getKeyStroke(final String key, final int mask) { final String name = getString(key); return KeyStroke.getKeyStroke(createMnemonic(name).intValue(), mask); } /** * Returns an optional key stroke. * * @param key the key. * @param mask the mask. * * @return The key stroke. */ public KeyStroke getOptionalKeyStroke(final String key, final int mask) { final String name = getString(key); if (name != null && name.length() > 0) { return KeyStroke.getKeyStroke(createMnemonic(name).intValue(), mask); } return null; } /** * Returns a JMenu created from a resource bundle definition. *

* The menu definition consists of two keys, the name of the menu and the * mnemonic for that menu. Both keys share a common prefix, which is * extended by ".name" for the name of the menu and ".mnemonic" for the * mnemonic. *

*

   * # define the file menu
   * menu.file.name=File
   * menu.file.mnemonic=F
   * 
* The menu definition above can be used to create the menu by calling * createMenu ("menu.file"). * * @param keyPrefix the common prefix for that menu * @return the created menu */ public JMenu createMenu(final String keyPrefix) { final JMenu retval = new JMenu(); retval.setText(getString(keyPrefix + ".name")); retval.setMnemonic(getMnemonic(keyPrefix + ".mnemonic").intValue()); return retval; } /** * Returns a URL pointing to a resource located in the classpath. The * resource is looked up using the given key. *

* Example: The load a file named 'logo.gif' which is stored in a java * package named 'org.jfree.resources': *

   * mainmenu.logo=org/jfree/resources/logo.gif
   * 
* The URL for that file can be queried with: getResource("mainmenu.logo");. * * @param key the key for the resource * @return the resource URL */ public URL getResourceURL(final String key) { final String name = getString(key); final URL in = ObjectUtilities.getResource(name, ResourceBundleSupport.class); if (in == null) { Log.warn("Unable to find file in the class path: " + name + "; key=" + key); } return in; } /** * Attempts to load an image from classpath. If this fails, an empty image * icon is returned. * * @param resourceName the name of the image. The name should be a global * resource name. * @param scale true, if the image should be scaled, false otherwise * @param large true, if the image should be scaled to 24x24, or * false for 16x16 * @return the image icon. */ private ImageIcon createIcon(final String resourceName, final boolean scale, final boolean large) { final URL in = ObjectUtilities.getResource(resourceName, ResourceBundleSupport.class); ; if (in == null) { Log.warn("Unable to find file in the class path: " + resourceName); return new ImageIcon(createTransparentImage(1, 1)); } final Image img = Toolkit.getDefaultToolkit().createImage(in); if (img == null) { Log.warn("Unable to instantiate the image: " + resourceName); return new ImageIcon(createTransparentImage(1, 1)); } if (scale) { if (large) { return new ImageIcon(img.getScaledInstance(24, 24, Image.SCALE_SMOOTH)); } return new ImageIcon(img.getScaledInstance(16, 16, Image.SCALE_SMOOTH)); } return new ImageIcon(img); } /** * Creates the Mnemonic from the given String. The String consists of the * name of the VK constants of the class KeyEvent without VK_*. * * @param keyString the string * @return the mnemonic as integer */ private Integer createMnemonic(final String keyString) { if (keyString == null) { throw new NullPointerException("Key is null."); } if (keyString.length() == 0) { throw new IllegalArgumentException("Key is empty."); } int character = keyString.charAt(0); if (keyString.startsWith("VK_")) { try { final Field f = KeyEvent.class.getField(keyString); final Integer keyCode = (Integer) f.get(null); character = keyCode.intValue(); } catch (Exception nsfe) { // ignore the exception ... } } return new Integer(character); } /** * Returns the plattforms default menu shortcut keymask. * * @return the default key mask. */ private int getMenuKeyMask() { try { return Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); } catch (UnsupportedOperationException he) { // headless exception extends UnsupportedOperation exception, // but the HeadlessException is not defined in older JDKs... return InputEvent.CTRL_MASK; } } /** * Creates a transparent image. These can be used for aligning menu items. * * @param width the width. * @param height the height. * @return the created transparent image. */ private BufferedImage createTransparentImage(final int width, final int height) { final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); final int[] data = img.getRGB(0, 0, width, height, null, 0, width); Arrays.fill(data, 0x00000000); img.setRGB(0, 0, width, height, data, 0, width); return img; } /** * Creates a transparent icon. The Icon can be used for aligning menu * items. * * @param width the width of the new icon * @param height the height of the new icon * @return the created transparent icon. */ public Icon createTransparentIcon(final int width, final int height) { return new ImageIcon(createTransparentImage(width, height)); } /** * Formats the message stored in the resource bundle (using a * MessageFormat). * * @param key the resourcebundle key * @param parameter the parameter for the message * @return the formated string */ public String formatMessage(final String key, final Object parameter) { return formatMessage(key, new Object[]{parameter}); } /** * Formats the message stored in the resource bundle (using a * MessageFormat). * * @param key the resourcebundle key * @param par1 the first parameter for the message * @param par2 the second parameter for the message * @return the formated string */ public String formatMessage(final String key, final Object par1, final Object par2) { return formatMessage(key, new Object[]{par1, par2}); } /** * Formats the message stored in the resource bundle (using a * MessageFormat). * * @param key the resourcebundle key * @param parameters the parameter collection for the message * @return the formated string */ public String formatMessage(final String key, final Object[] parameters) { final MessageFormat format = new MessageFormat(getString(key)); format.setLocale(getLocale()); return format.format(parameters); } /** * Returns the current locale for this resource bundle. * * @return the locale. */ public Locale getLocale() { return this.locale; } } jcommon-1.0.16/source/org/jfree/util/ShapeList.java0000644000175000017500000001157211172030703022075 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------- * ShapeList.java * -------------- * (C) Copyright 2003-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ShapeList.java,v 1.5 2008/06/17 08:26:05 mungady Exp $ * * Changes * ------- * 13-Aug-2003 : Version 1 (DG); * 17-Jun-2008 : Fixed bug in equals() (DG); * */ package org.jfree.util; import java.awt.Shape; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.io.SerialUtilities; /** * A table of {@link Shape} objects. */ public class ShapeList extends AbstractObjectList { /** * Creates a new list. */ public ShapeList() { super(); } /** * Returns a {@link Shape} object from the list. * * @param index the index (zero-based). * * @return The object. */ public Shape getShape(final int index) { return (Shape) get(index); } /** * Sets the {@link Shape} for an item in the list. The list is expanded * if necessary. * * @param index the index (zero-based). * @param shape the {@link Shape}. */ public void setShape(final int index, final Shape shape) { set(index, shape); } /** * Returns an independent copy of the list. * * @return A clone. * * @throws CloneNotSupportedException if an item in the list does not * support cloning. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Tests the list for equality with another object (typically also a list). * * @param obj the other object (null permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ShapeList)) { return false; } ShapeList that = (ShapeList) obj; int listSize = size(); for (int i = 0; i < listSize; i++) { if (!ShapeUtilities.equal((Shape) get(i), (Shape) that.get(i))) { return false; } } return true; } /** * Returns a hash code value for the object. * * @return the hashcode */ public int hashCode() { return super.hashCode(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(final ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); final int count = size(); stream.writeInt(count); for (int i = 0; i < count; i++) { final Shape shape = getShape(i); if (shape != null) { stream.writeInt(i); SerialUtilities.writeShape(shape, stream); } else { stream.writeInt(-1); } } } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); final int count = stream.readInt(); for (int i = 0; i < count; i++) { final int index = stream.readInt(); if (index != -1) { setShape(index, SerialUtilities.readShape(stream)); } } } } jcommon-1.0.16/source/org/jfree/util/ExtendedConfiguration.java0000644000175000017500000000673311172030703024474 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------- * ExtendedConfiguration.java * ------------- * (C)opyright 2002-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ExtendedConfiguration.java,v 1.3 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------- * 20-May-2005 : Initial version. */ package org.jfree.util; /** * The extended configuration provides methods to make using the * configuration easier. * * @author Thomas Morgner */ public interface ExtendedConfiguration extends Configuration { /** * Checks, whether a given property is defined. * * @param name the name of the property * @return true, if the property is defined, false otherwise. */ public boolean isPropertySet (String name); /** * Returns a given property as int value. Zero is returned if the * property value is no number or the property is not set. * * @param name the name of the property * @return the parsed number value or zero */ public int getIntProperty (String name); /** * Returns a given property as int value. The specified default value is returned if the * property value is no number or the property is not set. * * @param name the name of the property * @param defaultValue the value to be returned if the property is no integer value * @return the parsed number value or the specified default value */ public int getIntProperty (String name, int defaultValue); /** * Returns the boolean value of a given configuration property. The boolean value true * is returned, if the contained string is equal to 'true'. * * @param name the name of the property * @return the boolean value of the property. */ public boolean getBoolProperty (String name); /** * Returns the boolean value of a given configuration property. The boolean value true * is returned, if the contained string is equal to 'true'. If the property is not set, * the default value is returned. * * @param name the name of the property * @param defaultValue the default value to be returned if the property is not set * @return the boolean value of the property. */ public boolean getBoolProperty (String name, boolean defaultValue); } jcommon-1.0.16/source/org/jfree/util/BooleanList.java0000644000175000017500000000633111172030703022411 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * BooleanList.java * ---------------- * (C) Copyright 2003, 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: BooleanList.java,v 1.5 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------- * 11-Jun-2003 : Version 1 (DG); * 23-Jul-2003 : Renamed BooleanTable --> BooleanList and now extends * ObjectList (DG); * 13-Aug-2003 : Now extends new class AbstractObjectList (DG); * 21-Oct-2004 : Removed duplicate implementation of Cloneable and Serializable, * AbstractObjectList already implements that. */ package org.jfree.util; /** * A list of Boolean objects. * * @author David Gilbert */ public class BooleanList extends AbstractObjectList { /** For serialization. */ private static final long serialVersionUID = -8543170333219422042L; /** * Creates a new list. */ public BooleanList() { } /** * Returns a {@link Boolean} from the list. * * @param index the index (zero-based). * * @return a {@link Boolean} from the list. */ public Boolean getBoolean(final int index) { return (Boolean) get(index); } /** * Sets the value for an item in the list. The list is expanded if * necessary. * * @param index the index (zero-based). * @param b the boolean. */ public void setBoolean(final int index, final Boolean b) { set(index, b); } /** * Tests the list for equality with another object (typically also a list). * * @param o the other object. * * @return A boolean. */ public boolean equals(final Object o) { if (o instanceof BooleanList) { return super.equals(o); } return false; } /** * Returns a hash code value for the object. * * @return the hashcode */ public int hashCode() { return super.hashCode(); } } jcommon-1.0.16/source/org/jfree/util/ReadOnlyIterator.java0000644000175000017500000000563711172030703023435 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * ReadOnlyIterator.java * --------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): -; * * $Id: ReadOnlyIterator.java,v 1.2 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------------------------- * 18-Jul-2003 : Initial version * */ package org.jfree.util; import java.util.Iterator; /** * Protects an given iterator by preventing calls to remove(). * * @author Thomas Morgner */ public class ReadOnlyIterator implements Iterator { /** The base iterator which we protect. */ private Iterator base; /** * Creates a new read-only iterator for the given iterator. * * @param it the iterator. */ public ReadOnlyIterator(final Iterator it) { if (it == null) { throw new NullPointerException("Base iterator is null."); } this.base = it; } /** * Returns true if the iteration has more elements. (In other * words, returns true if next would return an element * rather than throwing an exception.) * * @return true if the iterator has more elements. */ public boolean hasNext() { return this.base.hasNext(); } /** * Returns the next element in the iteration. * Throws NoSuchElementException when iteration has no more elements. * * @return the next element in the iteration. */ public Object next() { return this.base.next(); } /** * Throws UnsupportedOperationException. */ public void remove() { throw new UnsupportedOperationException(); } } jcommon-1.0.16/source/org/jfree/util/ResourceBundleWrapper.java0000644000175000017500000001325711172030703024465 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * ResourceBundleWrapper.java * -------------------------- * (C)opyright 2008, by Jess Thrysoee and Contributors. * * Original Author: Jess Thrysoee; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 18-Dec-2008 : Version 1 (JT); * */ package org.jfree.util; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; /** * Wrapper of ResourceBundle.getBundle() methods. This wrapper is introduced to * avoid a dramatic performance penalty by superfluous resource (and classes * loaded by Class.forName) lookups on web server in applets. * *
 * public class AppletC extends javax.swing.JApplet {
 *    public void init() {
 *       ResourceBundleWrapper.removeCodeBase(getCodeBase(),
 *               (URLClassLoader) getClass().getClassLoader());
 *    ...
 * 
* * @see * Bug ID: 4243379 * @see * Bug ID: 4668479 * * @since 1.0.15 */ public class ResourceBundleWrapper { /** * A special class loader with no code base lookup. This field may be * null (the field is only initialised if removeCodeBase() is * called from an applet. */ private static URLClassLoader noCodeBaseClassLoader; /** * Private constructor. */ private ResourceBundleWrapper() { // all methods are static, no need to instantiate } /** * Instantiate a {@link URLClassLoader} for resource lookups where the * codeBase URL is removed. This method is typically called from an * applet's init() method. If this method is never called, the * getBundle() methods map to the standard * {@link ResourceBundle} lookup methods. * * @param codeBase the codeBase URL. * @param urlClassLoader the class loader. */ public static void removeCodeBase(URL codeBase, URLClassLoader urlClassLoader) { List urlsNoBase = new ArrayList(); URL[] urls = urlClassLoader.getURLs(); for (int i = 0; i < urls.length; i++) { if (! urls[i].sameFile(codeBase)) { urlsNoBase.add(urls[i]); } } // substitute the filtered URL list URL[] urlsNoBaseArray = (URL[]) urlsNoBase.toArray(new URL[0]); noCodeBaseClassLoader = URLClassLoader.newInstance(urlsNoBaseArray); } /** * Finds and returns the specified resource bundle. * * @param baseName the base name. * * @return The resource bundle. */ public static final ResourceBundle getBundle(String baseName) { // the noCodeBaseClassLoader is configured by a call to the // removeCodeBase() method, typically in the init() method of an // applet... if (noCodeBaseClassLoader != null) { return ResourceBundle.getBundle(baseName, Locale.getDefault(), noCodeBaseClassLoader); } else { // standard ResourceBundle behaviour return ResourceBundle.getBundle(baseName); } } /** * Finds and returns the specified resource bundle. * * @param baseName the base name. * @param locale the locale. * * @return The resource bundle. */ public static final ResourceBundle getBundle(String baseName, Locale locale) { // the noCodeBaseClassLoader is configured by a call to the // removeCodeBase() method, typically in the init() method of an // applet... if (noCodeBaseClassLoader != null) { return ResourceBundle.getBundle(baseName, locale, noCodeBaseClassLoader); } else { // standard ResourceBundle behaviour return ResourceBundle.getBundle(baseName, locale); } } /** * Maps directly to ResourceBundle.getBundle(baseName, locale, * loader). * * @param baseName the base name. * @param locale the locale. * @param loader the class loader. * * @return The resource bundle. */ public static ResourceBundle getBundle(String baseName, Locale locale, ClassLoader loader) { return ResourceBundle.getBundle(baseName, locale, loader); } } jcommon-1.0.16/source/org/jfree/util/package.html0000644000175000017500000000017711172030703021616 0ustar twernertwerner General utility classes. jcommon-1.0.16/source/org/jfree/util/ExtendedConfigurationWrapper.java0000644000175000017500000001441411172030703026030 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------------- * ExtendedConfigurationWrapper.java * --------------------------------- * (C)opyright 2002-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ExtendedConfigurationWrapper.java,v 1.8 2008/09/10 09:22:04 mungady Exp $ * * Changes * ------- * 20-May-2005 : Initial version. */ package org.jfree.util; import java.util.Enumeration; import java.util.Iterator; /** * A wrapper for the extended configuration interface around a plain configuration. * * @author Thomas Morgner */ public class ExtendedConfigurationWrapper implements ExtendedConfiguration { /** The base configuration. */ private Configuration parent; /** * Creates a wrapper around the given configuration. * * @param parent the wrapped up configuration. * @throws NullPointerException if the parent is null. */ public ExtendedConfigurationWrapper (final Configuration parent) { if (parent == null) { throw new NullPointerException("Parent given must not be null"); } this.parent = parent; } /** * Returns the boolean value of a given configuration property. The boolean value true * is returned, if the contained string is equal to 'true'. * * @param name the name of the property * @return the boolean value of the property. */ public boolean getBoolProperty (final String name) { return getBoolProperty(name, false); } /** * Returns the boolean value of a given configuration property. The boolean value true * is returned, if the contained string is equal to 'true'. If the property is not set, * the default value is returned. * * @param name the name of the property * @param defaultValue the default value to be returned if the property is not set * @return the boolean value of the property. */ public boolean getBoolProperty (final String name, final boolean defaultValue) { return "true".equals(this.parent.getConfigProperty(name, String.valueOf(defaultValue))); } /** * Returns a given property as int value. Zero is returned if the * property value is no number or the property is not set. * * @param name the name of the property * @return the parsed number value or zero */ public int getIntProperty (final String name) { return getIntProperty(name, 0); } /** * Returns a given property as int value. The specified default value is returned if the * property value is no number or the property is not set. * * @param name the name of the property * @param defaultValue the value to be returned if the property is no integer value * @return the parsed number value or the specified default value */ public int getIntProperty (final String name, final int defaultValue) { final String retval = this.parent.getConfigProperty(name); if (retval == null) { return defaultValue; } try { return Integer.parseInt(retval); } catch (Exception e) { return defaultValue; } } /** * Checks, whether a given property is defined. * * @param name the name of the property * @return true, if the property is defined, false otherwise. */ public boolean isPropertySet (final String name) { return this.parent.getConfigProperty(name) != null; } /** * Returns all keys with the given prefix. * * @param prefix the prefix * @return the iterator containing all keys with that prefix */ public Iterator findPropertyKeys (final String prefix) { return this.parent.findPropertyKeys(prefix); } /** * Returns the configuration property with the specified key. * * @param key the property key. * @return the property value. */ public String getConfigProperty (final String key) { return this.parent.getConfigProperty(key); } /** * Returns the configuration property with the specified key (or the specified default * value if there is no such property). *

* If the property is not defined in this configuration, the code will lookup the * property in the parent configuration. * * @param key the property key. * @param defaultValue the default value. * @return the property value. */ public String getConfigProperty (final String key, final String defaultValue) { return this.parent.getConfigProperty(key, defaultValue); } /** * Returns an enumeration of the configuration properties. * * @return An enumeration. */ public Enumeration getConfigProperties() { return this.parent.getConfigProperties(); } /** * Returns a clone of this instance. * * @return A clone. * * @throws CloneNotSupportedException if there is a problem cloning. */ public Object clone () throws CloneNotSupportedException { ExtendedConfigurationWrapper wrapper = (ExtendedConfigurationWrapper) super.clone(); wrapper.parent = (Configuration) this.parent.clone(); return this.parent; } } jcommon-1.0.16/source/org/jfree/util/LineBreakIterator.java0000644000175000017500000001434211172030703023545 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * LineBreakIterator.java * ---------------------- * (C)opyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: LineBreakIterator.java,v 1.4 2005/11/03 09:55:26 mungady Exp $ * * Changes * ------- * 13-03-2003 : Initial version */ package org.jfree.util; import java.util.Iterator; /** * An iterator that breaks text into lines. * The result is equal to BufferedReader.readLine(). * * @author Thomas Morgner */ public class LineBreakIterator implements Iterator { /** A useful constant. */ public static final int DONE = -1; /** Storage for the text. */ private char[] text; /** The current position. */ private int position; /** * Default constructor. */ public LineBreakIterator() { setText(""); } /** * Creates a new line break iterator. * * @param text the text to be broken up. */ public LineBreakIterator(final String text) { setText(text); } /** * Returns the position of the next break. * * @return A position. */ public synchronized int nextPosition() { if (this.text == null) { return DONE; } if (this.position == DONE) { return DONE; } // recognize \n, \r, \r\n final int nChars = this.text.length; int nextChar = this.position; for (;;) { if (nextChar >= nChars) { /* End of text reached */ this.position = DONE; return DONE; } boolean eol = false; char c = 0; int i; // search the next line break, either \n or \r for (i = nextChar; i < nChars; i++) { c = this.text[i]; if ((c == '\n') || (c == '\r')) { eol = true; break; } } nextChar = i; if (eol) { nextChar++; if (c == '\r') { if ((nextChar < nChars) && (this.text[nextChar] == '\n')) { nextChar++; } } this.position = nextChar; return (this.position); } } } /** * Same like next(), but returns the End-Of-Text as * if there was a linebreak added (Reader.readLine() compatible) * * @return The next position. */ public int nextWithEnd() { final int pos = this.position; if (pos == DONE) { return DONE; } if (pos == this.text.length) { this.position = DONE; return DONE; } final int retval = nextPosition(); if (retval == DONE) { return this.text.length; } return retval; } /** * Returns the text to be broken up. * * @return The text. */ public String getText() { return new String(this.text); } /** * Sets the text to be broken up. * * @param text the text. */ public void setText(final String text) { this.position = 0; this.text = text.toCharArray(); } /** * Returns true if the iteration has more elements. (In other * words, returns true if next would return an element * rather than throwing an exception.) * * @return true if the iterator has more elements. */ public boolean hasNext() { return (this.position != DONE); } /** * Returns the next element in the iteration. * * @return the next element in the iteration. */ public Object next() { if (this.position == DONE) { // allready at the end ... return null; } final int lastFound = this.position; int pos = nextWithEnd(); if (pos == DONE) { // the end of the text has been reached ... return new String(this.text, lastFound, this.text.length - lastFound); } // step one char back if (pos > 0) { final int end = lastFound; for (; ((pos) > end) && ((this.text[pos - 1] == '\n') || this.text[pos - 1] == '\r'); pos--) { // search the end of the current linebreak sequence .. } } //System.out.println ("text: " + new String (text)); //System.out.println ("pos: " + pos + " lastFound: " + lastFound); return new String(this.text, lastFound, pos - lastFound); } /** * * Removes from the underlying collection the last element returned by the * iterator (optional operation). This method can be called only once per * call to next. The behavior of an iterator is unspecified if * the underlying collection is modified while the iteration is in * progress in any way other than by calling this method. * * @exception UnsupportedOperationException if the remove * operation is not supported by this Iterator. * @exception IllegalStateException if the next method has not * yet been called, or the remove method has already * been called after the last call to the next * method. */ public void remove() { throw new UnsupportedOperationException("This iterator is read-only."); } } jcommon-1.0.16/source/org/jfree/util/AttributedStringUtilities.java0000644000175000017500000000715011172030703025370 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------ * AttributedStringUtilities.java * ------------------------------ * (C)opyright 2005, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: AttributedStringUtilities.java,v 1.2 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------- * 29-Jul-2005 : Version 1(DG); * */ package org.jfree.util; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.text.CharacterIterator; import java.util.Map; /** * Some utility methods for working with AttributedString objects. * * @author David Gilbert */ public class AttributedStringUtilities { /** * Private constructor prevents object creation. */ private AttributedStringUtilities() { } /** * Tests two attributed strings for equality. * * @param s1 string 1 (null permitted). * @param s2 string 2 (null permitted). * * @return true if s1 and s2 are * equal or both null, and false * otherwise. */ public static boolean equal(AttributedString s1, AttributedString s2) { if (s1 == null) { return (s2 == null); } if (s2 == null) { return false; } AttributedCharacterIterator it1 = s1.getIterator(); AttributedCharacterIterator it2 = s2.getIterator(); char c1 = it1.first(); char c2 = it2.first(); int start = 0; while (c1 != CharacterIterator.DONE) { int limit1 = it1.getRunLimit(); int limit2 = it2.getRunLimit(); if (limit1 != limit2) { return false; } // if maps aren't equivalent, return false Map m1 = it1.getAttributes(); Map m2 = it2.getAttributes(); if (!m1.equals(m2)) { return false; } // now check characters in the run are the same for (int i = start; i < limit1; i++) { if (c1 != c2) { return false; } c1 = it1.next(); c2 = it2.next(); } start = limit1; } return c2 == CharacterIterator.DONE; } } jcommon-1.0.16/source/org/jfree/util/Rotation.java0000644000175000017500000001063111172030703021773 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------- * Rotation.java * ------------- * (C)opyright 2003-2005, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: Rotation.java,v 1.5 2005/11/16 15:58:41 taqua Exp $ * * Changes * ------- * 19-Aug-2003 : Version 1 (DG); * 20-Feb-2004 : Updated Javadocs (DG); * */ package org.jfree.util; import java.io.ObjectStreamException; import java.io.Serializable; /** * Represents a direction of rotation (CLOCKWISE or * ANTICLOCKWISE). * @author David Gilbert */ public final class Rotation implements Serializable { /** For serialization. */ private static final long serialVersionUID = -4662815260201591676L; /** Clockwise. */ public static final Rotation CLOCKWISE = new Rotation("Rotation.CLOCKWISE", -1.0); /** The reverse order renders the primary dataset first. */ public static final Rotation ANTICLOCKWISE = new Rotation("Rotation.ANTICLOCKWISE", 1.0); /** The name. */ private String name; /** * The factor (-1.0 for CLOCKWISE and 1.0 for * ANTICLOCKWISE). */ private double factor; /** * Private constructor. * * @param name the name. * @param factor the rotation factor. */ private Rotation(final String name, final double factor) { this.name = name; this.factor = factor; } /** * Returns a string representing the object. * * @return the string (never null). */ public String toString() { return this.name; } /** * Returns the rotation factor, which is -1.0 for CLOCKWISE * and 1.0 for ANTICLOCKWISE. * * @return the rotation factor. */ public double getFactor() { return this.factor; } /** * Compares this object for equality with an other object. * Implementation note: This simply compares the factor instead * of the name. * * @param o the other object * @return true or false */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Rotation)) { return false; } final Rotation rotation = (Rotation) o; if (this.factor != rotation.factor) { return false; } return true; } /** * Returns a hash code value for the object. * * @return the hashcode */ public int hashCode() { final long temp = Double.doubleToLongBits(this.factor); return (int) (temp ^ (temp >>> 32)); } /** * Ensures that serialization returns the unique instances. * * @return the object. * * @throws ObjectStreamException if there is a problem. */ private Object readResolve() throws ObjectStreamException { if (this.equals(Rotation.CLOCKWISE)) { return Rotation.CLOCKWISE; } else if (this.equals(Rotation.ANTICLOCKWISE)) { return Rotation.ANTICLOCKWISE; } return null; } } jcommon-1.0.16/source/org/jfree/util/Configuration.java0000644000175000017500000000626711172030703023015 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * Configuration.java * ------------------ * (C)opyright 2002-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner (taquera@sherito.org); * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Configuration.java,v 1.8 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 02-May-2003 : Initial version (TM); * */ package org.jfree.util; import java.io.Serializable; import java.util.Enumeration; import java.util.Iterator; /** * A simple query interface for a configuration. * * @author Thomas Morgner */ public interface Configuration extends Serializable, Cloneable { /** * Returns the configuration property with the specified key. * * @param key the property key. * * @return the property value. */ public String getConfigProperty(String key); /** * Returns the configuration property with the specified key (or the * specified default value if there is no such property). *

* If the property is not defined in this configuration, the code will * lookup the property in the parent configuration. * * @param key the property key. * @param defaultValue the default value. * * @return the property value. */ public String getConfigProperty(String key, String defaultValue); /** * Returns all keys with the given prefix. * * @param prefix the prefix * @return the iterator containing all keys with that prefix */ public Iterator findPropertyKeys(String prefix); /** * Returns the configuration properties. * * @return The configuration properties. */ public Enumeration getConfigProperties(); /** * Returns a clone of the object. * * @return A clone. * * @throws CloneNotSupportedException if cloning is not supported for some reason. */ public Object clone() throws CloneNotSupportedException; } jcommon-1.0.16/source/org/jfree/util/StringUtils.java0000644000175000017500000000635411172030703022472 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * StringUtils.java * ---------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: StringUtils.java,v 1.5 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------------------------- * 21.06.2003 : Initial version * */ package org.jfree.util; /** * String utilities. * * @author Thomas Morgner. */ public class StringUtils { /** * Private constructor prevents object creation. */ private StringUtils() { } /** * Helper functions to query a strings start portion. The comparison is case insensitive. * * @param base the base string. * @param start the starting text. * * @return true, if the string starts with the given starting text. */ public static boolean startsWithIgnoreCase(final String base, final String start) { if (base.length() < start.length()) { return false; } return base.regionMatches(true, 0, start, 0, start.length()); } /** * Helper functions to query a strings end portion. The comparison is case insensitive. * * @param base the base string. * @param end the ending text. * * @return true, if the string ends with the given ending text. */ public static boolean endsWithIgnoreCase(final String base, final String end) { if (base.length() < end.length()) { return false; } return base.regionMatches(true, base.length() - end.length(), end, 0, end.length()); } /** * Queries the system properties for the line separator. If access * to the System properties is forbidden, the UNIX default is returned. * * @return the line separator. */ public static String getLineSeparator() { try { return System.getProperty("line.separator", "\n"); } catch (Exception e) { return "\n"; } } } jcommon-1.0.16/source/org/jfree/util/Log.java0000644000175000017500000003556111172030703020726 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------- * Log.java * -------- * (C)opyright 2002-2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner (taquera@sherito.org); * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Log.java,v 1.5 2006/06/08 17:42:20 taqua Exp $ * * Changes * ------- * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * 11-Jun-2003 : Removing LogTarget did not work. * */ package org.jfree.util; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; /** * A simple logging facility. Create a class implementing the {@link org.jfree.util.LogTarget} * interface to use this feature. * * @author Thomas Morgner */ public class Log { /** * A simple message class. */ public static class SimpleMessage { /** * The message. */ private String message; /** * The parameters. */ private Object[] param; /** * Creates a new message. * * @param message the message text. * @param param1 parameter 1. */ public SimpleMessage(final String message, final Object param1) { this.message = message; this.param = new Object[]{param1}; } /** * Creates a new message. * * @param message the message text. * @param param1 parameter 1. * @param param2 parameter 2. */ public SimpleMessage(final String message, final Object param1, final Object param2) { this.message = message; this.param = new Object[]{param1, param2}; } /** * Creates a new message. * * @param message the message text. * @param param1 parameter 1. * @param param2 parameter 2. * @param param3 parameter 3. */ public SimpleMessage(final String message, final Object param1, final Object param2, final Object param3) { this.message = message; this.param = new Object[]{param1, param2, param3}; } /** * Creates a new message. * * @param message the message text. * @param param1 parameter 1. * @param param2 parameter 2. * @param param3 parameter 3. * @param param4 parameter 4. */ public SimpleMessage(final String message, final Object param1, final Object param2, final Object param3, final Object param4) { this.message = message; this.param = new Object[]{param1, param2, param3, param4}; } /** * Creates a new message. * * @param message the message text. * @param param the parameters. */ public SimpleMessage(final String message, final Object[] param) { this.message = message; this.param = param; } /** * Returns a string representation of the message (useful for debugging). * * @return the string. */ public String toString() { final StringBuffer b = new StringBuffer(); b.append(this.message); if (this.param != null) { for (int i = 0; i < this.param.length; i++) { b.append(this.param[i]); } } return b.toString(); } } /** * The logging threshold. */ private int debuglevel; /** * Storage for the log targets. */ private LogTarget[] logTargets; /** The log contexts. */ private HashMap logContexts; /** * the singleton instance of the Log system. */ private static Log singleton; /** * Creates a new Log instance. The Log is used to manage the log targets. */ protected Log() { this.logContexts = new HashMap(); this.logTargets = new LogTarget[0]; this.debuglevel = 100; } /** * Returns the singleton Log instance. A new instance is created if necessary. * * @return the singleton instance. */ public static synchronized Log getInstance() { if (singleton == null) { singleton = new Log(); } return singleton; } /** * Redefines or clears the currently used log instance. * * @param log the new log instance or null, to return to the default implementation. */ protected static synchronized void defineLog(final Log log) { singleton = log; } /** * Returns the currently defined debug level. The higher the level, the more details * are printed. * * @return the debug level. */ public int getDebuglevel() { return this.debuglevel; } /** * Defines the debug level for the log system. * * @param debuglevel the new debug level * @see #getDebuglevel() */ protected void setDebuglevel(final int debuglevel) { this.debuglevel = debuglevel; } /** * Adds a log target to this facility. Log targets get informed, via the LogTarget interface, * whenever a message is logged with this class. * * @param target the target. */ public synchronized void addTarget(final LogTarget target) { if (target == null) { throw new NullPointerException(); } final LogTarget[] data = new LogTarget[this.logTargets.length + 1]; System.arraycopy(this.logTargets, 0, data, 0, this.logTargets.length); data[this.logTargets.length] = target; this.logTargets = data; } /** * Removes a log target from this facility. * * @param target the target to remove. */ public synchronized void removeTarget(final LogTarget target) { if (target == null) { throw new NullPointerException(); } final ArrayList l = new ArrayList(); l.addAll(Arrays.asList(this.logTargets)); l.remove(target); final LogTarget[] targets = new LogTarget[l.size()]; this.logTargets = (LogTarget[]) l.toArray(targets); } /** * Returns the registered logtargets. * * @return the logtargets. */ public LogTarget[] getTargets() { return (LogTarget[]) this.logTargets.clone(); } /** * Replaces all log targets by the given target. * * @param target the new and only logtarget. */ public synchronized void replaceTargets(final LogTarget target) { if (target == null) { throw new NullPointerException(); } this.logTargets = new LogTarget[]{target}; } /** * A convenience method for logging a 'debug' message. * * @param message the message. */ public static void debug(final Object message) { log(LogTarget.DEBUG, message); } /** * A convenience method for logging a 'debug' message. * * @param message the message. * @param e the exception. */ public static void debug(final Object message, final Exception e) { log(LogTarget.DEBUG, message, e); } /** * A convenience method for logging an 'info' message. * * @param message the message. */ public static void info(final Object message) { log(LogTarget.INFO, message); } /** * A convenience method for logging an 'info' message. * * @param message the message. * @param e the exception. */ public static void info(final Object message, final Exception e) { log(LogTarget.INFO, message, e); } /** * A convenience method for logging a 'warning' message. * * @param message the message. */ public static void warn(final Object message) { log(LogTarget.WARN, message); } /** * A convenience method for logging a 'warning' message. * * @param message the message. * @param e the exception. */ public static void warn(final Object message, final Exception e) { log(LogTarget.WARN, message, e); } /** * A convenience method for logging an 'error' message. * * @param message the message. */ public static void error(final Object message) { log(LogTarget.ERROR, message); } /** * A convenience method for logging an 'error' message. * * @param message the message. * @param e the exception. */ public static void error(final Object message, final Exception e) { log(LogTarget.ERROR, message, e); } /** * Logs a message to the main log stream. All attached log targets will also * receive this message. If the given log-level is higher than the given debug-level * in the main config file, no logging will be done. * * @param level log level of the message. * @param message text to be logged. */ protected void doLog(int level, final Object message) { if (level > 3) { level = 3; } if (level <= this.debuglevel) { for (int i = 0; i < this.logTargets.length; i++) { final LogTarget t = this.logTargets[i]; t.log(level, message); } } } /** * Logs a message to the main log stream. All attached log targets will also * receive this message. If the given log-level is higher than the given debug-level * in the main config file, no logging will be done. * * @param level log level of the message. * @param message text to be logged. */ public static void log(final int level, final Object message) { getInstance().doLog(level, message); } /** * Logs a message to the main log stream. All attached logTargets will also * receive this message. If the given log-level is higher than the given debug-level * in the main config file, no logging will be done. *

* The exception's stacktrace will be appended to the log-stream * * @param level log level of the message. * @param message text to be logged. * @param e the exception, which should be logged. */ public static void log(final int level, final Object message, final Exception e) { getInstance().doLog(level, message, e); } /** * Logs a message to the main log stream. All attached logTargets will also * receive this message. If the given log-level is higher than the given debug-level * in the main config file, no logging will be done. *

* The exception's stacktrace will be appended to the log-stream * * @param level log level of the message. * @param message text to be logged. * @param e the exception, which should be logged. */ protected void doLog(int level, final Object message, final Exception e) { if (level > 3) { level = 3; } if (level <= this.debuglevel) { for (int i = 0; i < this.logTargets.length; i++) { final LogTarget t = this.logTargets[i]; t.log(level, message, e); } } } /** * Initializes the logging system. Implementors should * override this method to supply their own log configuration. */ public void init() { // this method is intentionally empty. } /** * Returns true, if the log level allows debug messages to be * printed. * * @return true, if messages with an log level of DEBUG are allowed. */ public static boolean isDebugEnabled() { return getInstance().getDebuglevel() >= LogTarget.DEBUG; } /** * Returns true, if the log level allows informational * messages to be printed. * * @return true, if messages with an log level of INFO are allowed. */ public static boolean isInfoEnabled() { return getInstance().getDebuglevel() >= LogTarget.INFO; } /** * Returns true, if the log level allows warning messages to be * printed. * * @return true, if messages with an log level of WARN are allowed. */ public static boolean isWarningEnabled() { return getInstance().getDebuglevel() >= LogTarget.WARN; } /** * Returns true, if the log level allows error messages to be * printed. * * @return true, if messages with an log level of ERROR are allowed. */ public static boolean isErrorEnabled() { return getInstance().getDebuglevel() >= LogTarget.ERROR; } /** * Creates a log context. * * @param context the class (null not permitted). * * @return A log context. */ public static LogContext createContext(final Class context) { return createContext(context.getName()); } /** * Creates a log context. * * @param context the label for the context. * * @return A log context. */ public static LogContext createContext(final String context) { return getInstance().internalCreateContext(context); } /** * Creates a log context. * * @param context the name of the logging context (a common prefix). * * @return A log context. */ protected LogContext internalCreateContext(final String context) { synchronized (this) { LogContext ctx = (LogContext) this.logContexts.get(context); if (ctx == null) { ctx = new LogContext(context); this.logContexts.put(context, ctx); } return ctx; } } } jcommon-1.0.16/source/org/jfree/util/ObjectTable.java0000644000175000017500000003027411172030703022357 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * ObjectTable.java * ---------------- * (C) Copyright 2003, 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ObjectTable.java,v 1.10 2008/09/10 09:22:04 mungady Exp $ * * Changes * ------- * 29-Apr-2003 : Version 1, based on PaintTable class (DG); * 21-May-2003 : Copied the array based implementation of StrokeTable and * fixed the serialisation behaviour (TM). */ package org.jfree.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; /** * A lookup table for objects. This implementation is not synchronized, it is up * to the caller to synchronize it properly. * * @author Thomas Morgner */ public class ObjectTable implements Serializable { /** * For serialization. */ private static final long serialVersionUID = -3968322452944912066L; /** * The number of rows. */ private int rows; /** * The number of columns. */ private int columns; /** * An array of objects. The array may contain null values. */ private transient Object[][] data; /** * Defines how many object-slots get reserved each time we run out of * space. */ private int rowIncrement; /** * Defines how many object-slots get reserved each time we run out of * space. */ private int columnIncrement; /** * Creates a new table. */ public ObjectTable() { this(5, 5); } /** * Creates a new table. * * @param increment the row and column size increment. */ public ObjectTable(final int increment) { this(increment, increment); } /** * Creates a new table. * * @param rowIncrement the row size increment. * @param colIncrement the column size increment. */ public ObjectTable(final int rowIncrement, final int colIncrement) { if (rowIncrement < 1) { throw new IllegalArgumentException("Increment must be positive."); } if (colIncrement < 1) { throw new IllegalArgumentException("Increment must be positive."); } this.rows = 0; this.columns = 0; this.rowIncrement = rowIncrement; this.columnIncrement = colIncrement; this.data = new Object[rowIncrement][]; } /** * Returns the column size increment. * * @return the increment. */ public int getColumnIncrement() { return this.columnIncrement; } /** * Returns the row size increment. * * @return the increment. */ public int getRowIncrement() { return this.rowIncrement; } /** * Checks that there is storage capacity for the specified row and resizes * if necessary. * * @param row the row index. */ protected void ensureRowCapacity(final int row) { // does this increase the number of rows? if yes, create new storage if (row >= this.data.length) { final Object[][] enlarged = new Object[row + this.rowIncrement][]; System.arraycopy(this.data, 0, enlarged, 0, this.data.length); // do not create empty arrays - this is more expensive than checking // for null-values. this.data = enlarged; } } /** * Ensures that there is storage capacity for the specified item. * * @param row the row index. * @param column the column index. */ public void ensureCapacity(final int row, final int column) { if (row < 0) { throw new IndexOutOfBoundsException("Row is invalid. " + row); } if (column < 0) { throw new IndexOutOfBoundsException("Column is invalid. " + column); } ensureRowCapacity(row); final Object[] current = this.data[row]; if (current == null) { final Object[] enlarged = new Object[Math.max(column + 1, this.columnIncrement)]; this.data[row] = enlarged; } else if (column >= current.length) { final Object[] enlarged = new Object[column + this.columnIncrement]; System.arraycopy(current, 0, enlarged, 0, current.length); this.data[row] = enlarged; } } /** * Returns the number of rows in the table. * * @return The row count. */ public int getRowCount() { return this.rows; } /** * Returns the number of columns in the table. * * @return The column count. */ public int getColumnCount() { return this.columns; } /** * Returns the object from a particular cell in the table. Returns null, if * there is no object at the given position. *

* Note: throws IndexOutOfBoundsException if row or column is negative. * * @param row the row index (zero-based). * @param column the column index (zero-based). * @return The object. */ protected Object getObject(final int row, final int column) { if (row < this.data.length) { final Object[] current = this.data[row]; if (current == null) { return null; } if (column < current.length) { return current[column]; } } return null; } /** * Sets the object for a cell in the table. The table is expanded if * necessary. * * @param row the row index (zero-based). * @param column the column index (zero-based). * @param object the object. */ protected void setObject(final int row, final int column, final Object object) { ensureCapacity(row, column); this.data[row][column] = object; this.rows = Math.max(this.rows, row + 1); this.columns = Math.max(this.columns, column + 1); } /** * Tests this paint table for equality with another object (typically also * an ObjectTable). * * @param o the other object. * @return A boolean. */ public boolean equals(final Object o) { if (o == null) { return false; } if (this == o) { return true; } if ((o instanceof ObjectTable) == false) { return false; } final ObjectTable ot = (ObjectTable) o; if (getRowCount() != ot.getRowCount()) { return false; } if (getColumnCount() != ot.getColumnCount()) { return false; } for (int r = 0; r < getRowCount(); r++) { for (int c = 0; c < getColumnCount(); c++) { if (ObjectUtilities.equal(getObject(r, c), ot.getObject(r, c)) == false) { return false; } } } return true; } /** * Returns a hash code value for the object. * * @return the hashcode */ public int hashCode() { int result; result = this.rows; result = 29 * result + this.columns; return result; } /** * Handles serialization. * * @param stream the output stream. * @throws java.io.IOException if there is an I/O problem. */ private void writeObject(final ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); final int rowCount = this.data.length; stream.writeInt(rowCount); for (int r = 0; r < rowCount; r++) { final Object[] column = this.data[r]; stream.writeBoolean(column != null); if (column != null) { final int columnCount = column.length; stream.writeInt(columnCount); for (int c = 0; c < columnCount; c++) { writeSerializedData(stream, column[c]); } } } } /** * Handles the serialization of an single element of this table. * * @param stream the stream which should write the object * @param o the object that should be serialized * @throws IOException if an IO error occured */ protected void writeSerializedData(final ObjectOutputStream stream, final Object o) throws IOException { stream.writeObject(o); } /** * Restores a serialized object. * * @param stream the input stream. * @throws java.io.IOException if there is an I/O problem. * @throws ClassNotFoundException if a class cannot be found. */ private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); final int rowCount = stream.readInt(); this.data = new Object[rowCount][]; for (int r = 0; r < rowCount; r++) { final boolean isNotNull = stream.readBoolean(); if (isNotNull) { final int columnCount = stream.readInt(); final Object[] column = new Object[columnCount]; this.data[r] = column; for (int c = 0; c < columnCount; c++) { column[c] = readSerializedData(stream); } } } } /** * Handles the deserialization of a single element of the table. * * @param stream the object input stream from which to read the object. * @return the deserialized object * @throws ClassNotFoundException if a class cannot be found. * @throws IOException Any of the usual Input/Output related * exceptions. */ protected Object readSerializedData(final ObjectInputStream stream) throws ClassNotFoundException, IOException { return stream.readObject(); } /** * Clears the table. */ public void clear() { this.rows = 0; this.columns = 0; for (int i = 0; i < this.data.length; i++) { if (this.data[i] != null) { Arrays.fill(this.data[i], null); } } } /** * Copys the contents of the old column to the new column. * * @param oldColumn the index of the old (source) column * @param newColumn the index of the new column */ protected void copyColumn(final int oldColumn, final int newColumn) { for (int i = 0; i < getRowCount(); i++) { setObject(i, newColumn, getObject(i, oldColumn)); } } /** * Copys the contents of the old row to the new row. This uses raw access to * the data and is remarkably faster than manual copying. * * @param oldRow the index of the old row * @param newRow the index of the new row */ protected void copyRow(final int oldRow, final int newRow) { this.ensureCapacity(newRow, getColumnCount()); final Object[] oldRowStorage = this.data[oldRow]; if (oldRowStorage == null) { final Object[] newRowStorage = this.data[newRow]; if (newRowStorage != null) { Arrays.fill(newRowStorage, null); } } else { this.data[newRow] = (Object[]) oldRowStorage.clone(); } } /** * Sets the table data. * * @param data the data. * @param colCount the number of columns. */ protected void setData(final Object[][] data, final int colCount) { if (data == null) { throw new NullPointerException(); } if (colCount < 0) { throw new IndexOutOfBoundsException(); } this.data = data; this.rows = data.length; this.columns = colCount; } /** * Returns the table data. * * @return The table data. */ protected Object[][] getData() { return this.data; } } jcommon-1.0.16/source/org/jfree/util/SortOrder.java0000644000175000017500000000756711172030703022135 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------- * SortOrder.java * -------------- * (C) Copyright 2003, 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SortOrder.java,v 1.6 2005/10/18 13:24:19 mungady Exp $ * * Changes: * -------- * 05-Mar-2003 : Version 1 (DG); * 13-Mar-2003 : Implemented Serializable (DG); * 27-Aug-2003 : Moved from JFreeChart --> JCommon (DG); * 29-Jul-2004 : Fixed error in readResolve() method (DG); * */ package org.jfree.util; import java.io.ObjectStreamException; import java.io.Serializable; /** * Defines tokens used to indicate sorting order (ascending or descending). * * @author David Gilbert */ public final class SortOrder implements Serializable { /** For serialization. */ private static final long serialVersionUID = -2124469847758108312L; /** Ascending order. */ public static final SortOrder ASCENDING = new SortOrder("SortOrder.ASCENDING"); /** Descending order. */ public static final SortOrder DESCENDING = new SortOrder("SortOrder.DESCENDING"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private SortOrder(final String name) { this.name = name; } /** * Returns a string representing the object. * * @return The string. */ public String toString() { return this.name; } /** * Returns true if this object is equal to the specified * object, and false otherwise. * * @param obj the other object. * * @return A boolean. */ public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof SortOrder)) { return false; } final SortOrder that = (SortOrder) obj; if (!this.name.equals(that.toString())) { return false; } return true; } /** * Returns a hash code value for the object. * * @return The hashcode */ public int hashCode() { return this.name.hashCode(); } /** * Ensures that serialization returns the unique instances. * * @return The object. * * @throws ObjectStreamException if there is a problem. */ private Object readResolve() throws ObjectStreamException { if (this.equals(SortOrder.ASCENDING)) { return SortOrder.ASCENDING; } else if (this.equals(SortOrder.DESCENDING)) { return SortOrder.DESCENDING; } return null; } } jcommon-1.0.16/source/org/jfree/util/DefaultConfiguration.java0000644000175000017500000000777611172030703024330 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * DefaultConfiguration.java * ------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DefaultConfiguration.java,v 1.6 2008/09/10 09:21:30 mungady Exp $ * * Changes * ------- * 04.06.2003 : Initial version (TM); * */ package org.jfree.util; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; import java.util.TreeSet; import org.jfree.base.config.ModifiableConfiguration; /** * Default configuration. * * @author Thomas Morgner. */ public class DefaultConfiguration extends Properties implements ModifiableConfiguration { /** * Creates an empty property list with no default values. */ public DefaultConfiguration() { super(); } /** * Returns the configuration property with the specified key. * * @param key the property key. * @return the property value. */ public String getConfigProperty(final String key) { return getProperty(key); } /** * Returns the configuration property with the specified key (or the * specified default value if there is no such property). *

* If the property is not defined in this configuration, the code will * lookup the property in the parent configuration. * * @param key the property key. * @param defaultValue the default value. * @return the property value. */ public String getConfigProperty(final String key, final String defaultValue) { return getProperty(key, defaultValue); } /** * Searches all property keys that start with a given prefix. * * @param prefix the prefix that all selected property keys should share * @return the properties as iterator. */ public Iterator findPropertyKeys(final String prefix) { final TreeSet collector = new TreeSet(); final Enumeration enum1 = keys(); while (enum1.hasMoreElements()) { final String key = (String) enum1.nextElement(); if (key.startsWith(prefix)) { if (collector.contains(key) == false) { collector.add(key); } } } return Collections.unmodifiableSet(collector).iterator(); } /** * Returns an enumeration of the property keys. * * @return An enumeration of the property keys. */ public Enumeration getConfigProperties() { return keys(); } /** * Sets the value of a configuration property. * * @param key the property key. * @param value the property value. */ public void setConfigProperty(final String key, final String value) { if (value == null) { remove(key); } else { setProperty(key, value); } } } jcommon-1.0.16/source/org/jfree/util/PublicCloneable.java0000644000175000017500000000374511172030703023227 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * PublicCloneable.java * -------------------- * (C) Copyright 2003, 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: PublicCloneable.java,v 1.3 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------- * 18-Aug-2003 : Version 1 (DG); * */ package org.jfree.util; /** * An interface that exposes the clone() method. * @author David Gilbert */ public interface PublicCloneable extends Cloneable { /** * Returns a clone of the object. * * @return A clone. * * @throws CloneNotSupportedException if cloning is not supported for some reason. */ public Object clone() throws CloneNotSupportedException; } jcommon-1.0.16/source/org/jfree/util/ObjectList.java0000644000175000017500000000733311172030703022243 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * ObjectList.java * --------------- * (C)opyright 2003, 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ObjectList.java,v 1.6 2005/11/14 10:56:42 mungady Exp $ * * Changes * ------- * 17-Jul-2003 : Version 1 (DG); * 13-Aug-2003 : Refactored to extend AbstractObjectList (DG); * 21-Oct-2004 : removed duplicate interface declarations and empty methods. * 22-Oct-2004 : Restored removed methods - see note in code (DG); * */ package org.jfree.util; /** * A list of objects that can grow as required. *

* When cloning, the objects in the list are NOT cloned, only the references. * * @author Thomas Morgner */ public class ObjectList extends AbstractObjectList { /** * Default constructor. */ public ObjectList() { } /** * Creates a new list. * * @param initialCapacity the initial capacity. */ public ObjectList(final int initialCapacity) { super(initialCapacity); } // NOTE: the methods below look redundant, but their purpose is to provide public // access to the the get(), set() and indexOf() methods defined in the // AbstractObjectList class, for this class only. For other classes // (e.g. PaintList, ShapeList etc) we don't want the Object versions of these // methods to be visible in the public API. /** * Returns the object at the specified index, if there is one, or null. * * @param index the object index. * * @return The object or null. */ public Object get(final int index) { return super.get(index); } /** * Sets an object reference (overwriting any existing object). * * @param index the object index. * @param object the object (null permitted). */ public void set(final int index, final Object object) { super.set(index, object); } /** * Returns the index of the specified object, or -1 if the object is not in the list. * * @param object the object. * * @return The index or -1. */ public int indexOf(final Object object) { return super.indexOf(object); } } jcommon-1.0.16/source/org/jfree/util/FastStack.java0000644000175000017500000001127511172030703022064 0ustar twernertwerner/** * ======================================== * JCommon : a free Java report library * ======================================== * * Project Info: http://www.jfree.org/jcommon/ * * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------ * $Id: FastStack.java,v 1.3 2008/09/10 09:22:05 mungady Exp $ * ------------ * (C) Copyright 2002-2006, by Object Refinery Limited. */ package org.jfree.util; import java.io.Serializable; import java.util.Arrays; import java.util.EmptyStackException; /** * A very simple unsynchronized stack. This one is faster than the * java.util-Version. * * @author Thomas Morgner */ public final class FastStack implements Serializable, Cloneable { private Object[] contents; private int size; private int initialSize; /** * Creates a new empty stack. */ public FastStack() { this.initialSize = 10; } /** * Creates a new empty stack with the specified initial storage size. * * @param size the initial storage elements. */ public FastStack(int size) { this.initialSize = Math.max(1, size); } /** * Returns true if the stack is empty, and false * otherwise. * * @return A boolean. */ public boolean isEmpty() { return this.size == 0; } /** * Returns the number of elements in the stack. * * @return The element count. */ public int size() { return this.size; } /** * Pushes an object onto the stack. * * @param o the object. */ public void push(Object o) { if (this.contents == null) { this.contents = new Object[this.initialSize]; this.contents[0] = o; this.size = 1; return; } final int oldSize = this.size; this.size += 1; if (this.contents.length == this.size) { // grow .. final Object[] newContents = new Object[this.size + this.initialSize]; System.arraycopy(this.contents, 0, newContents, 0, this.size); this.contents = newContents; } this.contents[oldSize] = o; } /** * Returns the object at the top of the stack without removing it. * * @return The object at the top of the stack. */ public Object peek() { if (this.size == 0) { throw new EmptyStackException(); } return this.contents[this.size - 1]; } /** * Removes and returns the object from the top of the stack. * * @return The object. */ public Object pop() { if (this.size == 0) { throw new EmptyStackException(); } this.size -= 1; final Object retval = this.contents[this.size]; this.contents[this.size] = null; return retval; } /** * Returns a clone of the stack. * * @return A clone. */ public Object clone() { try { FastStack stack = (FastStack) super.clone(); if (this.contents != null) { stack.contents = (Object[]) this.contents.clone(); } return stack; } catch (CloneNotSupportedException cne) { throw new IllegalStateException("Clone not supported? Why?"); } } /** * Clears the stack. */ public void clear() { this.size = 0; if (this.contents != null) { Arrays.fill(this.contents, null); } } /** * Returns the item at the specified slot in the stack. * * @param index the index. * * @return The item. */ public Object get(final int index) { if (index >= this.size) { throw new IndexOutOfBoundsException(); } return this.contents[index]; } } jcommon-1.0.16/source/org/jfree/util/HashNMap.java0000644000175000017500000003124611172030703021640 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------- * HashNMap.java * ------------- * (C)opyright 2002-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: HashNMap.java,v 1.7 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------- * 20-May-2002 : Initial version * 10-Dec-2002 : Minor Javadoc updates (DG); * 29-Jul-2004 : Replaced 'enum' variable name (reserved word in JDK 1.5) (DG); * 12-Mar-2005 : Some performance improvements, this implementation is no * longer forced to use ArrayLists, add/put behaviour changed to * fit the common behaviour of collections. * */ package org.jfree.util; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; /** * The HashNMap can be used to store multiple values by a single key value. The * values stored can be retrieved using a direct query or by creating an * enumeration over the stored elements. * * @author Thomas Morgner */ public class HashNMap implements Serializable, Cloneable { /** Serialization support. */ private static final long serialVersionUID = -670924844536074826L; /** * An helper class to implement an empty iterator. This iterator will always * return false when hasNext is called. */ private static final class EmptyIterator implements Iterator { /** * DefaultConstructor. */ private EmptyIterator() { super(); } /** * Returns true if the iteration has more elements. (In other * words, returns true if next would return an element * rather than throwing an exception.) * * @return true if the iterator has more elements. */ public boolean hasNext() { return false; } /** * Returns the next element in the iteration. * * @return the next element in the iteration. * @throws NoSuchElementException iteration has no more elements. */ public Object next() { throw new NoSuchElementException("This iterator is empty."); } /** * Removes from the underlying collection the last element returned by the * iterator (optional operation). This method can be called only once per * call to next. The behavior of an iterator is unspecified if * the underlying collection is modified while the iteration is in * progress in any way other than by calling this method. * * @throws UnsupportedOperationException if the remove * operation is not supported by this Iterator. * @throws IllegalStateException if the next method has not * yet been called, or the remove method has already * been called after the last call to the next * method. */ public void remove() { throw new UnsupportedOperationException("This iterator is empty, no remove supported."); } } /** * A singleton instance of the empty iterator. This object can be safely * shared. */ private static final Iterator EMPTY_ITERATOR = new EmptyIterator(); /** * The underlying storage. */ private HashMap table; /** * An empty array. */ private static final Object[] EMPTY_ARRAY = new Object[0]; /** * Default constructor. */ public HashNMap() { this.table = new HashMap(); } /** * Returns a new empty list. * * @return A new empty list. */ protected List createList() { return new ArrayList(); } /** * Inserts a new key/value pair into the map. If such a pair already * exists, it gets replaced with the given values. * * @param key the key. * @param val the value. * @return A boolean. */ public boolean put(final Object key, final Object val) { final List v = (List) this.table.get(key); if (v == null) { final List newList = createList(); newList.add(val); this.table.put(key, newList); return true; } else { v.clear(); return v.add(val); } } /** * Adds a new key/value pair into this map. If the key is not yet in the * map, it gets added to the map and the call is equal to * put(Object,Object). * * @param key the key. * @param val the value. * @return true, if the value has been added, false otherwise */ public boolean add(final Object key, final Object val) { final List v = (List) this.table.get(key); if (v == null) { put(key, val); return true; } else { return v.add(val); } } /** * Retrieves the first value registered for an key or null if there was no * such key in the list. * * @param key the key. * @return the value. */ public Object getFirst(final Object key) { return get(key, 0); } /** * Retrieves the n-th value registered for an key or null if there was no * such key in the list. An index out of bounds exception is thrown if * there are less than n elements registered to this key. * * @param key the key. * @param n the index. * @return the object. */ public Object get(final Object key, final int n) { final List v = (List) this.table.get(key); if (v == null) { return null; } return v.get(n); } /** * Returns an iterator over all elements registered to the given key. * * @param key the key. * @return an iterator. */ public Iterator getAll(final Object key) { final List v = (List) this.table.get(key); if (v == null) { return EMPTY_ITERATOR; } return v.iterator(); } /** * Returns all registered keys as an enumeration. * * @return an enumeration of the keys. */ public Iterator keys() { return this.table.keySet().iterator(); } /** * Returns all registered keys as set. * * @return a set of keys. */ public Set keySet() { return this.table.keySet(); } /** * Removes the key/value pair from the map. If the removed entry was the * last entry for this key, the key gets also removed. * * @param key the key. * @param value the value. * @return true, if removing the element was successfull, false otherwise. */ public boolean remove(final Object key, final Object value) { final List v = (List) this.table.get(key); if (v == null) { return false; } if (!v.remove(value)) { return false; } if (v.size() == 0) { this.table.remove(key); } return true; } /** * Removes all elements for the given key. * * @param key the key. */ public void removeAll(final Object key) { this.table.remove(key); } /** * Clears all keys and values of this map. */ public void clear() { this.table.clear(); } /** * Tests whether this map contains the given key. * * @param key the key. * @return true if the key is contained in the map */ public boolean containsKey(final Object key) { return this.table.containsKey(key); } /** * Tests whether this map contains the given value. * * @param value the value. * @return true if the value is registered in the map for an key. */ public boolean containsValue(final Object value) { final Iterator e = this.table.values().iterator(); boolean found = false; while (e.hasNext() && !found) { final List v = (List) e.next(); found = v.contains(value); } return found; } /** * Tests whether this map contains the given value. * * @param value the value. * @param key the key under which to find the value * @return true if the value is registered in the map for an key. */ public boolean containsValue(final Object key, final Object value) { final List v = (List) this.table.get(key); if (v == null) { return false; } return v.contains(value); } /** * Tests whether this map contains the given key or value. * * @param value the value. * @return true if the key or value is contained in the map */ public boolean contains(final Object value) { if (containsKey(value)) { return true; } return containsValue(value); } /** * Creates a deep copy of this HashNMap. * * @return a clone. * @throws CloneNotSupportedException this should never happen. */ public Object clone() throws CloneNotSupportedException { final HashNMap map = (HashNMap) super.clone(); map.table = new HashMap(); final Iterator iterator = keys(); while (iterator.hasNext()) { final Object key = iterator.next(); final List list = (List) map.table.get(key); if (list != null) { map.table.put(key, ObjectUtilities.clone(list)); } } return map; } /** * Returns the contents for the given key as object array. If there were * no objects registered with that key, an empty object array is returned. * * @param key the key. * @param data the object array to receive the contents. * @return the contents. */ public Object[] toArray(final Object key, final Object[] data) { if (key == null) { throw new NullPointerException("Key must not be null."); } final List list = (List) this.table.get(key); if (list != null) { return list.toArray(data); } if (data.length > 0) { data[0] = null; } return data; } /** * Returns the contents for the given key as object array. If there were * no objects registered with that key, an empty object array is returned. * * @param key the key. * @return the contents. */ public Object[] toArray(final Object key) { if (key == null) { throw new NullPointerException("Key must not be null."); } final List list = (List) this.table.get(key); if (list != null) { return list.toArray(); } return EMPTY_ARRAY; } /** * Returns the number of elements registered with the given key. * * @param key the key. * @return the number of element for this key, or 0 if there are no elements * registered. */ public int getValueCount(final Object key) { if (key == null) { throw new NullPointerException("Key must not be null."); } final List list = (List) this.table.get(key); if (list != null) { return list.size(); } return 0; } } jcommon-1.0.16/source/org/jfree/util/ObjectUtilities.java0000644000175000017500000004057211172030703023305 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * ObjectUtilitiess.java * --------------------- * (C) Copyright 2003-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ObjectUtilities.java,v 1.21 2008/09/10 09:24:41 mungady Exp $ * * Changes * ------- * 25-Mar-2003 : Version 1 (DG); * 15-Sep-2003 : Fixed bug in clone(List) method (DG); * 25-Nov-2004 : Modified clone(Object) method to fail with objects that * cannot be cloned, added new deepClone(Collection) method. * Renamed ObjectUtils --> ObjectUtilities (DG); * 11-Jan-2005 : Removed deprecated code in preparation for 1.0.0 release (DG); * 18-Aug-2005 : Added casts to suppress compiler warnings, as suggested in * patch 1260622 (DG); * */ package org.jfree.util; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.StringTokenizer; /** * A collection of useful static utility methods for handling classes and object * instantiation. * * @author Thomas Morgner */ public final class ObjectUtilities { /** * A constant for using the TheadContext as source for the classloader. */ public static final String THREAD_CONTEXT = "ThreadContext"; /** * A constant for using the ClassContext as source for the classloader. */ public static final String CLASS_CONTEXT = "ClassContext"; /** * By default use the thread context. */ private static String classLoaderSource = THREAD_CONTEXT; /** * The custom classloader to be used (if not null). */ private static ClassLoader classLoader; /** * Default constructor - private. */ private ObjectUtilities() { } /** * Returns the internal configuration entry, whether the classloader of * the thread context or the context classloader should be used. * * @return the classloader source, either THREAD_CONTEXT or CLASS_CONTEXT. */ public static String getClassLoaderSource() { return classLoaderSource; } /** * Defines the internal configuration entry, whether the classloader of * the thread context or the context classloader should be used. *

* This setting can only be defined using the API, there is no safe way * to put this into an external configuration file. * * @param classLoaderSource the classloader source, * either THREAD_CONTEXT or CLASS_CONTEXT. */ public static void setClassLoaderSource(final String classLoaderSource) { ObjectUtilities.classLoaderSource = classLoaderSource; } /** * Returns true if the two objects are equal OR both * null. * * @param o1 object 1 (null permitted). * @param o2 object 2 (null permitted). * @return true or false. */ public static boolean equal(final Object o1, final Object o2) { if (o1 == o2) { return true; } if (o1 != null) { return o1.equals(o2); } else { return false; } } /** * Returns a hash code for an object, or zero if the object is * null. * * @param object the object (null permitted). * @return The object's hash code (or zero if the object is * null). */ public static int hashCode(final Object object) { int result = 0; if (object != null) { result = object.hashCode(); } return result; } /** * Returns a clone of the specified object, if it can be cloned, otherwise * throws a CloneNotSupportedException. * * @param object the object to clone (null not permitted). * @return A clone of the specified object. * @throws CloneNotSupportedException if the object cannot be cloned. */ public static Object clone(final Object object) throws CloneNotSupportedException { if (object == null) { throw new IllegalArgumentException("Null 'object' argument."); } if (object instanceof PublicCloneable) { final PublicCloneable pc = (PublicCloneable) object; return pc.clone(); } else { try { final Method method = object.getClass().getMethod("clone", (Class[]) null); if (Modifier.isPublic(method.getModifiers())) { return method.invoke(object, (Object[]) null); } } catch (NoSuchMethodException e) { Log.warn("Object without clone() method is impossible."); } catch (IllegalAccessException e) { Log.warn("Object.clone(): unable to call method."); } catch (InvocationTargetException e) { Log.warn("Object without clone() method is impossible."); } } throw new CloneNotSupportedException("Failed to clone."); } /** * Returns a new collection containing clones of all the items in the * specified collection. * * @param collection the collection (null not permitted). * @return A new collection containing clones of all the items in the * specified collection. * @throws CloneNotSupportedException if any of the items in the collection * cannot be cloned. */ public static Collection deepClone(final Collection collection) throws CloneNotSupportedException { if (collection == null) { throw new IllegalArgumentException("Null 'collection' argument."); } // all JDK-Collections are cloneable ... // and if the collection is not clonable, then we should throw // a CloneNotSupportedException anyway ... final Collection result = (Collection) ObjectUtilities.clone(collection); result.clear(); final Iterator iterator = collection.iterator(); while (iterator.hasNext()) { final Object item = iterator.next(); if (item != null) { result.add(clone(item)); } else { result.add(null); } } return result; } /** * Redefines the custom classloader. * * @param classLoader the new classloader or null to use the default. */ public static synchronized void setClassLoader( final ClassLoader classLoader) { ObjectUtilities.classLoader = classLoader; } /** * Returns the custom classloader or null, if no custom classloader is defined. * * @return the custom classloader or null to use the default. */ public static ClassLoader getClassLoader() { return classLoader; } /** * Returns the classloader, which was responsible for loading the given * class. * * @param c the classloader, either an application class loader or the * boot loader. * @return the classloader, never null. * @throws SecurityException if the SecurityManager does not allow to grab * the context classloader. */ public static ClassLoader getClassLoader(final Class c) { final String localClassLoaderSource; synchronized(ObjectUtilities.class) { if (classLoader != null) { return classLoader; } localClassLoaderSource = classLoaderSource; } if ("ThreadContext".equals(localClassLoaderSource)) { final ClassLoader threadLoader = Thread.currentThread().getContextClassLoader(); if (threadLoader != null) { return threadLoader; } } // Context classloader - do not cache .. final ClassLoader applicationCL = c.getClassLoader(); if (applicationCL == null) { return ClassLoader.getSystemClassLoader(); } else { return applicationCL; } } /** * Returns the resource specified by the absolute name. * * @param name the name of the resource * @param c the source class * @return the url of the resource or null, if not found. */ public static URL getResource(final String name, final Class c) { final ClassLoader cl = getClassLoader(c); if (cl == null) { return null; } return cl.getResource(name); } /** * Returns the resource specified by the relative name. * * @param name the name of the resource relative to the given class * @param c the source class * @return the url of the resource or null, if not found. */ public static URL getResourceRelative(final String name, final Class c) { final ClassLoader cl = getClassLoader(c); final String cname = convertName(name, c); if (cl == null) { return null; } return cl.getResource(cname); } /** * Transform the class-relative resource name into a global name by * appending it to the classes package name. If the name is already a * global name (the name starts with a "/"), then the name is returned * unchanged. * * @param name the resource name * @param c the class which the resource is relative to * @return the tranformed name. */ private static String convertName(final String name, Class c) { if (name.startsWith("/")) { // strip leading slash.. return name.substring(1); } // we cant work on arrays, so remove them ... while (c.isArray()) { c = c.getComponentType(); } // extract the package ... final String baseName = c.getName(); final int index = baseName.lastIndexOf('.'); if (index == -1) { return name; } final String pkgName = baseName.substring(0, index); return pkgName.replace('.', '/') + "/" + name; } /** * Returns the inputstream for the resource specified by the * absolute name. * * @param name the name of the resource * @param context the source class * @return the url of the resource or null, if not found. */ public static InputStream getResourceAsStream(final String name, final Class context) { final URL url = getResource(name, context); if (url == null) { return null; } try { return url.openStream(); } catch (IOException e) { return null; } } /** * Returns the inputstream for the resource specified by the * relative name. * * @param name the name of the resource relative to the given class * @param context the source class * @return the url of the resource or null, if not found. */ public static InputStream getResourceRelativeAsStream (final String name, final Class context) { final URL url = getResourceRelative(name, context); if (url == null) { return null; } try { return url.openStream(); } catch (IOException e) { return null; } } /** * Tries to create a new instance of the given class. This is a short cut * for the common bean instantiation code. * * @param className the class name as String, never null. * @param source the source class, from where to get the classloader. * @return the instantiated object or null, if an error occured. */ public static Object loadAndInstantiate(final String className, final Class source) { try { final ClassLoader loader = getClassLoader(source); final Class c = loader.loadClass(className); return c.newInstance(); } catch (Exception e) { return null; } } /** * Tries to create a new instance of the given class. This is a short cut * for the common bean instantiation code. This method is a type-safe method * and will not instantiate the class unless it is an instance of the given * type. * * @param className the class name as String, never null. * @param source the source class, from where to get the classloader. * @param type the type. * @return the instantiated object or null, if an error occurred. */ public static Object loadAndInstantiate(final String className, final Class source, final Class type) { try { final ClassLoader loader = getClassLoader(source); final Class c = loader.loadClass(className); if (type.isAssignableFrom(c)) { return c.newInstance(); } } catch (Exception e) { return null; } return null; } /** * Returns true if this is version 1.4 or later of the * Java runtime. * * @return A boolean. */ public static boolean isJDK14() { try { final ClassLoader loader = getClassLoader(ObjectUtilities.class); if (loader != null) { try { loader.loadClass("java.util.RandomAccess"); return true; } catch (ClassNotFoundException e) { return false; } catch(Exception e) { // do nothing, but do not crash ... } } } catch (Exception e) { // cant do anything about it, we have to accept and ignore it .. } // OK, the quick and dirty, but secure way failed. Lets try it // using the standard way. try { final String version = System.getProperty ("java.vm.specification.version"); // parse the beast... if (version == null) { return false; } String[] versions = parseVersions(version); String[] target = new String[]{ "1", "4" }; return (ArrayUtilities.compareVersionArrays(versions, target) >= 0); } catch(Exception e) { return false; } } private static String[] parseVersions (String version) { if (version == null) { return new String[0]; } final ArrayList versions = new ArrayList(); final StringTokenizer strtok = new StringTokenizer(version, "."); while (strtok.hasMoreTokens()) { versions.add (strtok.nextToken()); } return (String[]) versions.toArray(new String[versions.size()]); } } jcommon-1.0.16/source/org/jfree/util/PrintStreamLogTarget.java0000644000175000017500000000770611172030703024266 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * PrintStreamLogTarget.java * ------------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: PrintStreamLogTarget.java,v 1.6 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------- * 02-Dec-2003 : Initial version * 11-Feb-2004 : Added missing Javadocs (DG); * */ package org.jfree.util; import java.io.PrintStream; import java.io.Serializable; /** * A log target that sends output to a {@link PrintStream}. * * @author Thomas Morgner */ public class PrintStreamLogTarget implements LogTarget, Serializable { /** For serialization. */ private static final long serialVersionUID = 6510564403264504688L; /** The printstream we use .. */ private PrintStream printStream; /** * The default constructor. Initializes this target with the system.out * stream. *

* All {@link org.jfree.util.LogTarget} implementations need a default * constructor. */ public PrintStreamLogTarget() { this (System.out); } /** * The default constructor. Initializes this target with the given stream. *

* @param printStream the print stream that is used to write the content. */ public PrintStreamLogTarget(final PrintStream printStream) { if (printStream == null) { throw new NullPointerException(); } this.printStream = printStream; } /** * Logs a message to the main log stream. All attached logStreams will also * receive this message. If the given log-level is higher than the given * debug-level in the main config file, no logging will be done. * * @param level log level of the message. * @param message text to be logged. */ public void log(int level, final Object message) { if (level > 3) { level = 3; } this.printStream.print(LEVELS[level]); this.printStream.println(message); if (level < 3) { System.out.flush(); } } /** * logs an message to the main-log stream. All attached logStreams will also * receive this message. If the given log-level is higher than the given * debug-level in the main config file, no logging will be done. * * The exception's stacktrace will be appended to the log-stream * * @param level log level of the message. * @param message text to be logged. * @param e the exception, which should be logged. */ public void log(int level, final Object message, final Exception e) { if (level > 3) { level = 3; } this.printStream.print(LEVELS[level]); this.printStream.println(message); e.printStackTrace(this.printStream); if (level < 3) { System.out.flush(); } } } jcommon-1.0.16/source/org/jfree/util/BooleanUtilities.java0000644000175000017500000000456511172030703023460 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * BooleanUtilities.java * --------------------- * (C) Copyright 2003, 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: BooleanUtilities.java,v 1.4 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------- * 23-Oct-2003 : Version 1 (DG); * 04-Oct-2004 : Renamed BooleanUtils --> BooleanUtilities (DG); * */ package org.jfree.util; /** * Utility methods for working with Boolean objects. * * @author David Gilbert */ public class BooleanUtilities { /** * Private constructor prevents object creation. */ private BooleanUtilities() { } /** * Returns the object equivalent of the boolean primitive. *

* A similar method is provided by the Boolean class in JDK 1.4, but you can use this one * to remain compatible with earlier JDKs. * * @param b the boolean value. * * @return Boolean.TRUE or Boolean.FALSE. */ public static Boolean valueOf(final boolean b) { return (b ? Boolean.TRUE : Boolean.FALSE); } } jcommon-1.0.16/source/org/jfree/util/UnitType.java0000644000175000017500000000716211172030703021762 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------- * UnitType.java * ------------- * (C) Copyright 2004, 2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: UnitType.java,v 1.7 2005/10/18 13:24:19 mungady Exp $ * * Changes: * -------- * 11-Feb-2004 : Version 1 (DG); * */ package org.jfree.util; import java.io.ObjectStreamException; import java.io.Serializable; /** * Used to indicate absolute or relative units. * * @author David Gilbert */ public final class UnitType implements Serializable { /** For serialization. */ private static final long serialVersionUID = 6531925392288519884L; /** Absolute. */ public static final UnitType ABSOLUTE = new UnitType("UnitType.ABSOLUTE"); /** Relative. */ public static final UnitType RELATIVE = new UnitType("UnitType.RELATIVE"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private UnitType(final String name) { this.name = name; } /** * Returns a string representing the object. * * @return The string. */ public String toString() { return this.name; } /** * Returns true if this object is equal to the specified * object, and false otherwise. * * @param obj the other object. * * @return A boolean. */ public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof UnitType)) { return false; } final UnitType that = (UnitType) obj; if (!this.name.equals(that.name)) { return false; } return true; } /** * Returns a hash code value for the object. * * @return The hashcode */ public int hashCode() { return this.name.hashCode(); } /** * Ensures that serialization returns the unique instances. * * @return The object. * * @throws ObjectStreamException if there is a problem. */ private Object readResolve() throws ObjectStreamException { if (this.equals(UnitType.ABSOLUTE)) { return UnitType.ABSOLUTE; } else if (this.equals(UnitType.RELATIVE)) { return UnitType.RELATIVE; } return null; } } jcommon-1.0.16/source/org/jfree/util/SortedConfigurationWriter.java0000644000175000017500000002374411172030703025372 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------ * SortedConfigurationWriter.java * ------------------------------ * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): -; * * $Id: SortedConfigurationWriter.java,v 1.4 2005/11/03 09:55:27 mungady Exp $ * * Changes * ------- * */ package org.jfree.util; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; /** * Writes a Configuration instance into a property file, where * the keys are sorted by their name. Writing sorted keys make it easier for * users to find and change properties in the file. * * @author Thomas Morgner */ public class SortedConfigurationWriter { /** * A constant defining that text should be escaped in a way * which is suitable for property keys. */ private static final int ESCAPE_KEY = 0; /** * A constant defining that text should be escaped in a way * which is suitable for property values. */ private static final int ESCAPE_VALUE = 1; /** * A constant defining that text should be escaped in a way * which is suitable for property comments. */ private static final int ESCAPE_COMMENT = 2; /** The system-dependent End-Of-Line separator. */ private static final String END_OF_LINE = StringUtils.getLineSeparator(); /** * The default constructor, does nothing. */ public SortedConfigurationWriter() { } /** * Returns a description for the given key. This implementation returns * null to indicate that no description should be written. Subclasses can * overwrite this method to provide comments for every key. These descriptions * will be included as inline comments. * * @param key the key for which a description should be printed. * @return the description or null if no description should be printed. */ protected String getDescription(final String key) { return null; } /** * Saves the given configuration into a file specified by the given * filename. * * @param filename the filename * @param config the configuration * @throws IOException if an IOError occurs. */ public void save(final String filename, final Configuration config) throws IOException { save(new File(filename), config); } /** * Saves the given configuration into a file specified by the given * file object. * * @param file the target file * @param config the configuration * @throws IOException if an IOError occurs. */ public void save(final File file, final Configuration config) throws IOException { final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); save(out, config); out.close(); } /** * Writes the configuration into the given output stream. * * @param outStream the target output stream * @param config the configuration * @throws IOException if writing fails. */ public void save(final OutputStream outStream, final Configuration config) throws IOException { final ArrayList names = new ArrayList(); // clear all previously set configuration settings ... final Iterator defaults = config.findPropertyKeys(""); while (defaults.hasNext()) { final String key = (String) defaults.next(); names.add(key); } Collections.sort(names); final OutputStreamWriter out = new OutputStreamWriter(outStream, "iso-8859-1"); for (int i = 0; i < names.size(); i++) { final String key = (String) names.get(i); final String value = config.getConfigProperty(key); final String description = getDescription(key); if (description != null) { writeDescription(description, out); } saveConvert(key, ESCAPE_KEY, out); out.write("="); saveConvert(value, ESCAPE_VALUE, out); out.write(END_OF_LINE); } out.flush(); } /** * Writes a descriptive comment into the given print writer. * * @param text the text to be written. If it contains more than * one line, every line will be prepended by the comment character. * @param writer the writer that should receive the content. * @throws IOException if writing fails */ private void writeDescription(final String text, final Writer writer) throws IOException { // check if empty content ... this case is easy ... if (text.length() == 0) { return; } writer.write("# "); writer.write(END_OF_LINE); final LineBreakIterator iterator = new LineBreakIterator(text); while (iterator.hasNext()) { writer.write("# "); saveConvert((String) iterator.next(), ESCAPE_COMMENT, writer); writer.write(END_OF_LINE); } } /** * Performs the necessary conversion of an java string into a property * escaped string. * * @param text the text to be escaped * @param escapeMode the mode that should be applied. * @param writer the writer that should receive the content. * @throws IOException if writing fails */ private void saveConvert(final String text, final int escapeMode, final Writer writer) throws IOException { final char[] string = text.toCharArray(); for (int x = 0; x < string.length; x++) { final char aChar = string[x]; switch (aChar) { case ' ': { if ((escapeMode != ESCAPE_COMMENT) && (x == 0 || escapeMode == ESCAPE_KEY)) { writer.write('\\'); } writer.write(' '); break; } case '\\': { writer.write('\\'); writer.write('\\'); break; } case '\t': { if (escapeMode == ESCAPE_COMMENT) { writer.write(aChar); } else { writer.write('\\'); writer.write('t'); } break; } case '\n': { writer.write('\\'); writer.write('n'); break; } case '\r': { writer.write('\\'); writer.write('r'); break; } case '\f': { if (escapeMode == ESCAPE_COMMENT) { writer.write(aChar); } else { writer.write('\\'); writer.write('f'); } break; } case '#': case '"': case '!': case '=': case ':': { if (escapeMode == ESCAPE_COMMENT) { writer.write(aChar); } else { writer.write('\\'); writer.write(aChar); } break; } default: if ((aChar < 0x0020) || (aChar > 0x007e)) { writer.write('\\'); writer.write('u'); writer.write(HEX_CHARS[(aChar >> 12) & 0xF]); writer.write(HEX_CHARS[(aChar >> 8) & 0xF]); writer.write(HEX_CHARS[(aChar >> 4) & 0xF]); writer.write(HEX_CHARS[aChar & 0xF]); } else { writer.write(aChar); } } } } /** A lookup-table. */ private static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; } jcommon-1.0.16/source/org/jfree/util/ArrayUtilities.java0000644000175000017500000001403111172030703023144 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * ArrayUtilities.java * ------------------- * (C) Copyright 2003-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ArrayUtilities.java,v 1.7 2008/09/10 09:21:30 mungady Exp $ * * Changes * ------- * 21-Aug-2003 : Version 1 (DG); * 04-Oct-2004 : Renamed ArrayUtils --> ArrayUtilities (DG); * */ package org.jfree.util; import java.util.Arrays; /** * Utility methods for working with arrays. * * @author David Gilbert */ public class ArrayUtilities { /** * Private constructor prevents object creation. */ private ArrayUtilities() { } /** * Clones a two dimensional array of floats. * * @param array the array. * * @return A clone of the array. */ public static float[][] clone(final float[][] array) { if (array == null) { return null; } final float[][] result = new float[array.length][]; System.arraycopy(array, 0, result, 0, array.length); for (int i = 0; i < array.length; i++) { final float[] child = array[i]; final float[] copychild = new float[child.length]; System.arraycopy(child, 0, copychild, 0, child.length); result[i] = copychild; } return result; } /** * Returns true if all the references in array1 * are equal to all the references in array2 (two * null references are considered equal for this test). * * @param array1 the first array (null permitted). * @param array2 the second array (null permitted). * * @return A boolean. */ public static boolean equalReferencesInArrays(final Object[] array1, final Object[] array2) { if (array1 == null) { return (array2 == null); } if (array2 == null) { return false; } if (array1.length != array2.length) { return false; } for (int i = 0; i < array1.length; i++) { if (array1[i] == null) { if (array2[i] != null) { return false; } } if (array2[i] == null) { if (array1[i] != null) { return false; } } if (array1[i] != array2[i]) { return false; } } return true; } /** * Tests two float arrays for equality. * * @param array1 the first array (null permitted). * @param array2 the second arrray (null permitted). * * @return A boolean. */ public static boolean equal(final float[][] array1, final float[][] array2) { if (array1 == null) { return (array2 == null); } if (array2 == null) { return false; } if (array1.length != array2.length) { return false; } for (int i = 0; i < array1.length; i++) { if (!Arrays.equals(array1[i], array2[i])) { return false; } } return true; } /** * Returns true if any two items in the array are equal to * one another. Any null values in the array are ignored. * * @param array the array to check. * * @return A boolean. */ public static boolean hasDuplicateItems(final Object[] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < i; j++) { final Object o1 = array[i]; final Object o2 = array[j]; if (o1 != null && o2 != null) { if (o1.equals(o2)) { return true; } } } } return false; } /** * Compares the initial elements of two arrays. * * @param a1 array 1. * @param a2 array 2. * * @return An integer showing the relative ordering. */ public static int compareVersionArrays (Comparable[] a1, Comparable[] a2) { int length = Math.min (a1.length, a2.length); for (int i = 0; i < length; i++) { Comparable o1 = a1[i]; Comparable o2 = a2[i]; if (o1 == null && o2 == null) { // cannot decide .. continue; } if (o1 == null) { return 1; } if (o2 == null) { return -1; } int retval = o1.compareTo(o2); if (retval != 0) { return retval; } } return 0; } } jcommon-1.0.16/source/org/jfree/util/junit/0000755000175000017500000000000011351753320020467 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/util/junit/RotationTests.java0000644000175000017500000000650611172030703024155 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * RotationTests.java * ------------------ * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: RotationTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 08-Jan-2004 : Version 1 (DG); * */ package org.jfree.util.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.util.Rotation; /** * Tests for the {@link Rotation} class. */ public class RotationTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(RotationTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public RotationTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { assertTrue(Rotation.CLOCKWISE.equals(Rotation.CLOCKWISE)); assertTrue(Rotation.ANTICLOCKWISE.equals(Rotation.ANTICLOCKWISE)); } /** * Serialize an instance, restore it, and check for identity. */ public void testSerialization() { final Rotation r1 = Rotation.CLOCKWISE; Rotation r2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(r1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); r2 = (Rotation) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(r1 == r2); } } jcommon-1.0.16/source/org/jfree/util/junit/SortOrderTests.java0000644000175000017500000000652111172030703024276 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * SortOrderTests.java * ------------------- * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SortOrderTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 08-Jan-2004 : Version 1 (DG); * */ package org.jfree.util.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.util.SortOrder; /** * Tests for the {@link SortOrder} class. */ public class SortOrderTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(SortOrderTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public SortOrderTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { assertTrue(SortOrder.ASCENDING.equals(SortOrder.ASCENDING)); assertTrue(SortOrder.DESCENDING.equals(SortOrder.DESCENDING)); } /** * Serialize an instance, restore it, and check for identity. */ public void testSerialization() { final SortOrder o1 = SortOrder.ASCENDING; SortOrder o2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(o1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); o2 = (SortOrder) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(o1 == o2); } } jcommon-1.0.16/source/org/jfree/util/junit/LogTest.java0000644000175000017500000000771111172030703022713 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------ * LogTest.java * ------------ * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: LogTest.java,v 1.4 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 21-Feb-2004 : Initial version * 07-Jun-2004 : Added JCommon header (DG); */ package org.jfree.util.junit; import junit.framework.TestCase; import org.jfree.util.Log; import org.jfree.util.LogContext; import org.jfree.util.LogTarget; /** * A test for... */ public class LogTest extends TestCase { private class LogTargetImpl implements LogTarget { /** * Default constructor. */ public LogTargetImpl() { super(); } /** * Logs a message at a specified log level. * * @param level the log level. * @param message the log message. */ public void log(final int level, final Object message) { // nothing required. } /** * Logs a message at a specified log level. * * @param level the log level. * @param message the log message. * @param e the exception */ public void log(final int level, final Object message, final Exception e) { // nothing required. } } /** * Creates a new test. * * @param s the test name. */ public LogTest(final String s) { super(s); } /** * Tests the addTarget() and removeTarget() methods. */ public void testAddRemove() { final LogTarget a = new LogTargetImpl(); final LogTarget b = new LogTargetImpl(); Log.getInstance().removeTarget(a); Log.getInstance().removeTarget(b); Log.getInstance().addTarget(a); Log.getInstance().addTarget(b); Log.getInstance().removeTarget(a); Log.getInstance().removeTarget(b); Log.getInstance().addTarget(a); Log.getInstance().addTarget(b); Log.getInstance().removeTarget(b); Log.getInstance().removeTarget(a); Log.getInstance().getTargets(); } /** * Tests the log message methods. */ public void testLogMessage () { Log.debug("Test"); Log.info("Test"); Log.warn("Test"); Log.error("Test"); } /** * Tests the log context. */ public void testLogContext() { final LogContext ctx = Log.createContext((String) null); assertEquals("Context = null", ctx, Log.createContext((String) null)); final LogContext ctx2 = Log.createContext("Test"); assertEquals("Context Test", ctx2, Log.createContext("Test")); } } jcommon-1.0.16/source/org/jfree/util/junit/ShapeUtilitiesTests.java0000644000175000017500000002060511172030703025306 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * ShapeUtilitiesTests.java * ------------------------ * (C) Copyright 2004-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ShapeUtilitiesTests.java,v 1.9 2008/06/02 06:58:28 mungady Exp $ * * Changes * ------- * 26-Oct-2004 : Version 1 (DG); * 10-Nov-2004 : Extended test for equal shapes to include Ellipse2D (DG); * 16-Mar-2005 : Extended test for equal shapes to include Polygon (DG); * 26-Sep-2007 : Removed a couple of checks that don't hold on JRE 1.6 and * later (DG); * 01-Jun-2008 : Added testEqualGeneralPaths() (DG); * */ package org.jfree.util.junit; import java.awt.Polygon; import java.awt.Shape; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.util.ShapeUtilities; /** * Tests for the {@link ShapeUtilities} class. */ public class ShapeUtilitiesTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(ShapeUtilitiesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public ShapeUtilitiesTests(final String name) { super(name); } /** * Tests the equal() method. */ public void testEqualLine2Ds() { assertTrue(ShapeUtilities.equal((Line2D) null, (Line2D) null)); Line2D l1 = new Line2D.Float(1.0f, 2.0f, 3.0f, 4.0f); Line2D l2 = new Line2D.Float(1.0f, 2.0f, 3.0f, 4.0f); assertTrue(ShapeUtilities.equal(l1, l2)); l1 = new Line2D.Float(4.0f, 3.0f, 2.0f, 1.0f); assertFalse(ShapeUtilities.equal(l1, l2)); l2 = new Line2D.Float(4.0f, 3.0f, 2.0f, 1.0f); assertTrue(ShapeUtilities.equal(l1, l2)); l1 = new Line2D.Double(4.0f, 3.0f, 2.0f, 1.0f); assertTrue(ShapeUtilities.equal(l1, l2)); } /** * Some checks for the equal(Shape, Shape) method. */ public void testEqualShapes() { // NULL Shape s1 = null; Shape s2 = null; assertTrue(ShapeUtilities.equal(s1, s2)); // LINE2D s1 = new Line2D.Double(1.0, 2.0, 3.0, 4.0); assertFalse(ShapeUtilities.equal(s1, s2)); s2 = new Line2D.Double(1.0, 2.0, 3.0, 4.0); assertTrue(ShapeUtilities.equal(s1, s2)); assertFalse(s1.equals(s2)); // RECTANGLE2D s1 = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0); assertFalse(ShapeUtilities.equal(s1, s2)); s2 = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0); assertTrue(ShapeUtilities.equal(s1, s2)); assertTrue(s1.equals(s2)); // Rectangle2D overrides equals() // ELLIPSE2D s1 = new Ellipse2D.Double(1.0, 2.0, 3.0, 4.0); assertFalse(ShapeUtilities.equal(s1, s2)); s2 = new Ellipse2D.Double(1.0, 2.0, 3.0, 4.0); assertTrue(ShapeUtilities.equal(s1, s2)); // ARC2D s1 = new Arc2D.Double(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, Arc2D.PIE); assertFalse(ShapeUtilities.equal(s1, s2)); s2 = new Arc2D.Double(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, Arc2D.PIE); assertTrue(ShapeUtilities.equal(s1, s2)); // POLYGON Polygon p1 = new Polygon(new int[] {0, 1, 0}, new int[] {1, 0, 1}, 3); Polygon p2 = new Polygon(new int[] {1, 1, 0}, new int[] {1, 0, 1}, 3); s1 = p1; s2 = p2; assertFalse(ShapeUtilities.equal(s1, s2)); p2 = new Polygon(new int[] {0, 1, 0}, new int[] {1, 0, 1}, 3); s2 = p2; assertTrue(ShapeUtilities.equal(s1, s2)); // GENERALPATH GeneralPath g1 = new GeneralPath(); g1.moveTo(1.0f, 2.0f); g1.lineTo(3.0f, 4.0f); g1.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g1.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g1.closePath(); s1 = g1; assertFalse(ShapeUtilities.equal(s1, s2)); GeneralPath g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); s2 = g2; assertTrue(ShapeUtilities.equal(s1, s2)); assertFalse(s1.equals(s2)); } /** * Some checks for the intersects() method, */ public void testIntersects() { final Rectangle2D r1 = new Rectangle2D.Float(0, 0, 100, 100); final Rectangle2D r2 = new Rectangle2D.Float(0, 0, 100, 100); assertTrue(ShapeUtilities.intersects(r1, r2)); r1.setRect(100, 0, 100, 0); assertTrue(ShapeUtilities.intersects(r1, r2)); assertTrue(ShapeUtilities.intersects(r2, r1)); r1.setRect(0, 0, 0, 0); assertTrue(ShapeUtilities.intersects(r1, r2)); assertTrue(ShapeUtilities.intersects(r2, r1)); r1.setRect(50, 50, 10, 0); assertTrue(ShapeUtilities.intersects(r1, r2)); assertTrue(ShapeUtilities.intersects(r2, r1)); } /** * Some checks for the equal(GeneralPath, GeneralPath) method. */ public void testEqualGeneralPaths() { GeneralPath g1 = new GeneralPath(); g1.moveTo(1.0f, 2.0f); g1.lineTo(3.0f, 4.0f); g1.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g1.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g1.closePath(); GeneralPath g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertTrue(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(11.0f, 22.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(33.0f, 44.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(55.0f, 66.0f, 77.0f, 88.0f, 99.0f, 100.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(11.0f, 22.0f, 33.0f, 44.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); g2 = new GeneralPath(); g2.moveTo(1.0f, 2.0f); g2.lineTo(3.0f, 4.0f); g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g2.lineTo(3.0f, 4.0f); g2.closePath(); assertFalse(ShapeUtilities.equal(g1, g2)); } } jcommon-1.0.16/source/org/jfree/util/junit/AttributedStringUtilitiesTests.java0000644000175000017500000000626111172030703027546 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------------------- * AttributedStringUtilitiesTests.java * ----------------------------------- * (C) Copyright 2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: AttributedStringUtilitiesTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 29-Jul-2005 : Version 1 (DG); * */ package org.jfree.util.junit; import java.awt.Color; import java.awt.font.TextAttribute; import java.text.AttributedString; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.util.AttributedStringUtilities; /** * Some tests for the {@link AttributedStringUtilities} class. */ public class AttributedStringUtilitiesTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(AttributedStringUtilitiesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public AttributedStringUtilitiesTests(String name) { super(name); } /** * Some checks for the equal(AttributedString, AttributedString) method. */ public void testEqual() { assertTrue(AttributedStringUtilities.equal(null, null)); AttributedString s1 = new AttributedString("ABC"); assertFalse(AttributedStringUtilities.equal(s1, null)); assertFalse(AttributedStringUtilities.equal(null, s1)); AttributedString s2 = new AttributedString("ABC"); assertTrue(AttributedStringUtilities.equal(s1, s2)); s1.addAttribute(TextAttribute.BACKGROUND, Color.blue, 1, 2); assertFalse(AttributedStringUtilities.equal(s1, s2)); s2.addAttribute(TextAttribute.BACKGROUND, Color.blue, 1, 2); assertTrue(AttributedStringUtilities.equal(s1, s2)); } } jcommon-1.0.16/source/org/jfree/util/junit/ObjectTableTests.java0000644000175000017500000001031311172030703024523 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * ObjectTableTests.java * -------------------- * (C) Copyright 2003-2005, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ObjectTableTests.java,v 1.6 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 29-Apr-2003 : Version 1 (DG); * */ package org.jfree.util.junit; import java.awt.Color; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.util.ObjectTable; /** * Tests for the {@link ObjectTable} class. */ public class ObjectTableTests extends TestCase { /** * Basic object table. */ public class TObjectTable extends ObjectTable { /** * Constructor. */ public TObjectTable() { super(); } /** * Returns the object from a particular cell in the table. * Returns null, if there is no object at the given position. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The object. */ public Object getObject(final int row, final int column) { return super.getObject(row, column); } /** * Sets the object for a cell in the table. The table is expanded if necessary. * * @param row the row index (zero-based). * @param column the column index (zero-based). * @param object the object. */ public void setObject(final int row, final int column, final Object object) { super.setObject(row, column, object); } } /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(ObjectTableTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public ObjectTableTests(final String name) { super(name); } /** * When an ObjectTable is created, it should be empty and return null for all lookups. */ public void testCreate() { final TObjectTable t = new TObjectTable(); // the new table should have zero rows and zero columns... assertEquals(t.getColumnCount(), 0); assertEquals(t.getRowCount(), 0); // ...and should return null for any lookup assertNull(t.getObject(0, 0)); assertNull(t.getObject(12, 12)); } /** * When an object is added to the table outside the current bounds, the table * should resize automatically. */ public void testSetObject1() { final TObjectTable t = new TObjectTable(); t.setObject(8, 5, Color.red); assertEquals(6, t.getColumnCount()); assertEquals(9, t.getRowCount()); assertNull(t.getObject(7, 4)); assertEquals(Color.red, t.getObject(8, 5)); } } jcommon-1.0.16/source/org/jfree/util/junit/BooleanListTests.java0000644000175000017500000001073311172030703024566 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * BooleanListTests.java * --------------------- * (C) Copyright 2003, 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: BooleanListTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 13-Aug-2003 : Version 1 (DG); * */ package org.jfree.util.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.util.BooleanList; /** * Tests for the {@link BooleanList} class. */ public class BooleanListTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(BooleanListTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public BooleanListTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { final BooleanList l1 = new BooleanList(); l1.setBoolean(0, Boolean.TRUE); l1.setBoolean(1, Boolean.FALSE); l1.setBoolean(2, null); final BooleanList l2 = new BooleanList(); l2.setBoolean(0, Boolean.TRUE); l2.setBoolean(1, Boolean.FALSE); l2.setBoolean(2, null); assertTrue(l1.equals(l2)); assertTrue(l2.equals(l2)); } /** * Confirm that cloning works. */ public void testCloning() { final BooleanList l1 = new BooleanList(); l1.setBoolean(0, Boolean.TRUE); l1.setBoolean(1, Boolean.FALSE); l1.setBoolean(2, null); BooleanList l2 = null; try { l2 = (BooleanList) l1.clone(); } catch (CloneNotSupportedException e) { System.err.println("BooleanListTests.testCloning: failed to clone."); } assertTrue(l1 != l2); assertTrue(l1.getClass() == l2.getClass()); assertTrue(l1.equals(l2)); l2.setBoolean(0, Boolean.FALSE); assertFalse(l1.equals(l2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { final BooleanList l1 = new BooleanList(); l1.setBoolean(0, Boolean.TRUE); l1.setBoolean(1, Boolean.FALSE); l1.setBoolean(2, null); BooleanList l2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(l1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); l2 = (BooleanList) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertEquals(l1, l2); } } jcommon-1.0.16/source/org/jfree/util/junit/PaintUtilitiesTests.java0000644000175000017500000000641311172030703025322 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * PaintUtilitiesTests.java * ------------------------ * (C) Copyright 2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: PaintUtilitiesTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 23-Feb-2005 : Version 1 (DG); * */ package org.jfree.util.junit; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Paint; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.util.PaintUtilities; /** * Some tests for the {@link PaintUtilities} class. */ public class PaintUtilitiesTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(PaintUtilitiesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public PaintUtilitiesTests(String name) { super(name); } /** * Some checks for the equal(Paint, Paint) method. */ public void testEqual() { Paint p1 = Color.red; Paint p2 = Color.blue; Paint p3 = new Color(1, 2, 3, 4); Paint p4 = new Color(1, 2, 3, 4); Paint p5 = new GradientPaint( 1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.yellow ); Paint p6 = new GradientPaint( 1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.yellow ); Paint p7 = new GradientPaint( 1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue ); assertTrue(PaintUtilities.equal(null, null)); assertFalse(PaintUtilities.equal(p1, null)); assertFalse(PaintUtilities.equal(null, p1)); assertFalse(PaintUtilities.equal(p1, p2)); assertTrue(PaintUtilities.equal(p3, p3)); assertTrue(PaintUtilities.equal(p3, p4)); assertTrue(PaintUtilities.equal(p5, p6)); assertFalse(PaintUtilities.equal(p5, p7)); } } jcommon-1.0.16/source/org/jfree/util/junit/package.html0000644000175000017500000000016311172030703022742 0ustar twernertwerner JUnit tests. jcommon-1.0.16/source/org/jfree/util/junit/ObjectListTests.java0000644000175000017500000001232411172030703024413 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * ObjectListTests.java * -------------------- * (C) Copyright 2003, 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ObjectListTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 13-Aug-2003 : Version 1 (DG); * 17-Sep-2003 : Added new tests for equals and serialization (DG); * */ package org.jfree.util.junit; import java.awt.Color; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.util.ObjectList; /** * Tests for the {@link ObjectList} class. */ public class ObjectListTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(ObjectListTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public ObjectListTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { final ObjectList l1 = new ObjectList(); l1.set(0, Color.blue); l1.set(1, Color.red); final ObjectList l2 = new ObjectList(); l2.set(0, Color.blue); l2.set(1, Color.red); assertTrue(l1.equals(l2)); assertTrue(l2.equals(l2)); } /** * Another test of the equals method. The capacity of the internal list shouldn't * be a factor. */ public void testEquals2() { final ObjectList l1 = new ObjectList(20); l1.set(0, Color.blue); l1.set(1, Color.red); final ObjectList l2 = new ObjectList(); l2.set(0, Color.blue); l2.set(1, Color.red); assertTrue(l1.equals(l2)); assertTrue(l2.equals(l2)); } /** * Confirm that cloning works. */ public void testCloning() { final ObjectList l1 = new ObjectList(); l1.set(0, Color.blue); l1.set(1, Color.red); ObjectList l2 = null; try { l2 = (ObjectList) l1.clone(); } catch (CloneNotSupportedException e) { System.err.println("ObjectListTests.testCloning: failed to clone."); } assertTrue(l1 != l2); assertTrue(l1.getClass() == l2.getClass()); assertTrue(l1.equals(l2)); l2.set(0, Color.green); assertFalse(l1.equals(l2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { final ObjectList l1 = new ObjectList(); l1.set(0, Color.red); l1.set(1, Color.blue); l1.set(2, null); ObjectList l2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(l1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); l2 = (ObjectList) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertEquals(l1, l2); } /** * Tests the expand method. This test reproduces a bug where the list was not expanded beyond * the initial default size of 8. This bug is now fixed. */ public void testExpand() { final ObjectList l1 = new ObjectList(); l1.set(10, Color.blue); final Color c = (Color) l1.get(10); assertTrue(c.equals(Color.blue)); } } jcommon-1.0.16/source/org/jfree/util/junit/UtilPackageTests.java0000644000175000017500000000636411172030703024551 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * UtilPackageTests.java * --------------------- * (C) Copyright 2003-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: UtilPackageTests.java,v 1.10 2008/06/17 08:26:05 mungady Exp $ * * Changes: * -------- * 24-Jul-2003 : Version 1 (DG); * 08-Oct-2004 : Added tests for UnitType class (DG); * 26-Oct-2004 : Added tests for ShapeUtilities class (DG); * 17-Jun-2008 : Added tests for ShapeList class (DG); * */ package org.jfree.util.junit; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * A collection of tests for the org.jfree.util package. *

* These tests can be run using JUnit (http://www.junit.org). */ public class UtilPackageTests extends TestCase { /** * Returns a test suite to the JUnit test runner. * * @return The test suite. */ public static Test suite() { TestSuite suite = new TestSuite("org.jfree.util"); suite.addTestSuite(ArrayUtilitiesTests.class); suite.addTestSuite(BooleanListTests.class); suite.addTestSuite(ObjectListTests.class); suite.addTestSuite(ObjectTableTests.class); suite.addTestSuite(ObjectUtilitiesTests.class); suite.addTestSuite(PaintListTests.class); suite.addTestSuite(PaintUtilitiesTests.class); suite.addTestSuite(RotationTests.class); suite.addTestSuite(ShapeListTests.class); suite.addTestSuite(ShapeUtilitiesTests.class); suite.addTestSuite(SortOrderTests.class); suite.addTestSuite(UnitTypeTests.class); return suite; } /** * Constructs the test suite. * * @param name the suite name. */ public UtilPackageTests(String name) { super(name); } /** * Runs the test suite using the JUnit text-based runner. * * @param args ignored. */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } } jcommon-1.0.16/source/org/jfree/util/junit/ObjectUtilitiesTests.java0000644000175000017500000001366111172030703025460 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * ObjectUtilsTests.java * --------------------- * (C) Copyright 2004, 2005, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ObjectUtilitiesTests.java,v 1.4 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 15-Sep-2004 : Version 1 (DG); * 25-Nov-2004 : Added new checks (DG); * */ package org.jfree.util.junit; import java.awt.Point; import java.util.ArrayList; import java.util.Collection; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.util.ObjectUtilities; /** * Some tests for the {@link ObjectUtilities} class. */ public class ObjectUtilitiesTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(ObjectUtilitiesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public ObjectUtilitiesTests(String name) { super(name); } /** * Some checks for the clone(Object) method. The method should * have these properties: * * (1) Return a clone for any object that can be cloned; * (2) Throw a NullPointerException for any object that cannot be cloned; * (3) Throw an IllegalArgumentException for null. * * @throws CloneNotSupportedException if there is a problem cloning. */ public void testCloneObject() throws CloneNotSupportedException { Object obj; Object clone; // check String (not Cloneable) boolean pass = false; obj = "Hello World"; try { clone = ObjectUtilities.clone(obj); pass = false; } catch (CloneNotSupportedException e) { pass = true; } assertTrue(pass); // check Integer (not Cloneable) pass = false; obj = new Integer(123); try { clone = ObjectUtilities.clone(obj); pass = false; } catch (CloneNotSupportedException e) { pass = true; } assertTrue(pass); // check Point (Cloneable) obj = new Point(1, 2); clone = ObjectUtilities.clone(obj); assertEquals(obj, clone); // check null (should throw an IllegalArgumentException) obj = null; try { clone = ObjectUtilities.clone(obj); pass = false; } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } /** * Some checks for the deepClone(Collection) method. */ public void testDeepClone() { Collection c1 = new ArrayList(); Collection c2 = null; // empty list try { c2 = ObjectUtilities.deepClone(c1); assertTrue(c2.isEmpty()); } catch (CloneNotSupportedException e) { assertTrue(false); } // list containing Cloneable objects c1 = new ArrayList(); c1.add(new Point(1, 2)); c1.add(new Point(3, 4)); try { c2 = ObjectUtilities.deepClone(c1); assertEquals(2, c2.size()); assertTrue(c2.contains(new Point(1, 2))); assertTrue(c2.contains(new Point(3, 4))); } catch (CloneNotSupportedException e) { assertTrue(false); } // list containing Cloneable and null objects c1 = new ArrayList(); c1.add(new Point(1, 2)); c1.add(null); c1.add(new Point(3, 4)); try { c2 = ObjectUtilities.deepClone(c1); assertEquals(3, c2.size()); assertTrue(c2.contains(new Point(1, 2))); assertTrue(c2.contains(new Point(3, 4))); } catch (CloneNotSupportedException e) { assertTrue(false); } // list containing non-Cloneable objects c1.clear(); c1.add("S1"); c1.add("S2"); try { c2 = ObjectUtilities.deepClone(c1); assertTrue(false); // if we get to here, the test has failed } catch (CloneNotSupportedException e) { assertTrue(true); } // null list try { c2 = ObjectUtilities.deepClone(null); assertTrue(false); // if we get to here, the test has failed } catch (IllegalArgumentException e) { assertTrue(true); } catch (CloneNotSupportedException e) { assertTrue(false); } } } jcommon-1.0.16/source/org/jfree/util/junit/UnitTypeTests.java0000644000175000017500000000701111172030703024127 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * UnitTypeTests.java * ------------------ * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: UnitTypeTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 08-Oct-2004 : Version 1 (DG); * */ package org.jfree.util.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.util.UnitType; /** * Tests for the {@link UnitType} class. */ public class UnitTypeTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(UnitTypeTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public UnitTypeTests(String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { assertTrue(UnitType.ABSOLUTE.equals(UnitType.ABSOLUTE)); assertTrue(UnitType.RELATIVE.equals(UnitType.RELATIVE)); assertFalse(UnitType.ABSOLUTE.equals(UnitType.RELATIVE)); assertFalse(UnitType.RELATIVE.equals(UnitType.ABSOLUTE)); assertFalse(UnitType.ABSOLUTE.equals(null)); assertFalse(UnitType.RELATIVE.equals(null)); } /** * Serialize an instance, restore it, and check for identity. */ public void testSerialization() { UnitType t1 = UnitType.ABSOLUTE; UnitType t2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(t1); out.close(); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); t2 = (UnitType) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(t1 == t2); } } jcommon-1.0.16/source/org/jfree/util/junit/ArrayUtilitiesTests.java0000644000175000017500000000763211172030703025331 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * ArrayUtilsTests.java * -------------------- * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ArrayUtilitiesTests.java,v 1.4 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 24-Aug-2004 : Version 1 (DG); * 04-Oct-2004 : Renamed ArrayUtilsTests --> ArrayUtilitiesTests (DG); * */ package org.jfree.util.junit; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.util.ArrayUtilities; /** * Tests for the {@link ArrayUtilities} class. */ public class ArrayUtilitiesTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(ArrayUtilitiesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public ArrayUtilitiesTests(String name) { super(name); } /** * Some tests for the hasDuplicateItems() method. */ public void testHasDuplicateItems() { Object[] a1 = new Object[] {"1", "2", "3"}; Object[] a2 = new Object[] {"1", "1", "3"}; Object[] a3 = new Object[] {null, "2", null}; assertFalse(ArrayUtilities.hasDuplicateItems(a1)); assertTrue(ArrayUtilities.hasDuplicateItems(a2)); assertFalse(ArrayUtilities.hasDuplicateItems(a3)); } /** * Some checks for the equalReferencesInArrays() method. */ public void testEqualReferencesInArrays() { Object[] a1 = new Object[] {}; Object[] a2 = new Object[] {}; Object[] a3 = new Object[] {null}; Object[] a4 = new Object[] {null}; Object[] a5 = new Object[] {"A"}; Object[] a6 = new Object[] {"A"}; Object[] a7 = new Object[] {"A", "B"}; Object[] a8 = new Object[] {"A", "B"}; Object[] a9 = new Object[] {"A", null}; Object[] a10 = new Object[] {"A", null}; assertTrue(ArrayUtilities.equalReferencesInArrays(a1, a2)); assertFalse(ArrayUtilities.equalReferencesInArrays(a1, a3)); assertTrue(ArrayUtilities.equalReferencesInArrays(a3, a4)); assertFalse(ArrayUtilities.equalReferencesInArrays(a3, a5)); assertTrue(ArrayUtilities.equalReferencesInArrays(a5, a6)); assertFalse(ArrayUtilities.equalReferencesInArrays(a5, a7)); assertTrue(ArrayUtilities.equalReferencesInArrays(a7, a8)); assertFalse(ArrayUtilities.equalReferencesInArrays(a7, a9)); assertTrue(ArrayUtilities.equalReferencesInArrays(a9, a10)); } } jcommon-1.0.16/source/org/jfree/util/junit/ShapeListTests.java0000644000175000017500000001073411172030703024250 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * ShapeListTests.java * ------------------- * (C) Copyright 2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ShapeListTests.java,v 1.2 2008/09/01 16:00:41 mungady Exp $ * * Changes * ------- * 17-Jun-2008 : Version 1, based on PaintListTests (DG); * */ package org.jfree.util.junit; import java.awt.Rectangle; import java.awt.geom.Line2D; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.util.ShapeList; /** * Some tests for the {@link ShapeList} class. */ public class ShapeListTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(ShapeListTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public ShapeListTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { ShapeList l1 = new ShapeList(); l1.setShape(0, new Rectangle(1, 2, 3, 4)); l1.setShape(1, new Line2D.Double(1.0, 2.0, 3.0, 4.0)); l1.setShape(2, null); ShapeList l2 = new ShapeList(); l2.setShape(0, new Rectangle(1, 2, 3, 4)); l2.setShape(1, new Line2D.Double(1.0, 2.0, 3.0, 4.0)); l2.setShape(2, null); assertTrue(l1.equals(l2)); assertTrue(l2.equals(l2)); } /** * Confirm that cloning works. */ public void testCloning() { ShapeList l1 = new ShapeList(); l1.setShape(0, new Rectangle(1, 2, 3, 4)); l1.setShape(1, new Line2D.Double(1.0, 2.0, 3.0, 4.0)); l1.setShape(2, null); ShapeList l2 = null; try { l2 = (ShapeList) l1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(l1 != l2); assertTrue(l1.getClass() == l2.getClass()); assertTrue(l1.equals(l2)); l2.setShape(0, new Rectangle(5, 6, 7, 8)); assertFalse(l1.equals(l2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { ShapeList l1 = new ShapeList(); l1.setShape(0, new Rectangle(1, 2, 3, 4)); l1.setShape(1, new Line2D.Double(1.0, 2.0, 3.0, 4.0)); l1.setShape(2, null); ShapeList l2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(l1); out.close(); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream( buffer.toByteArray())); l2 = (ShapeList) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(l1, l2); } } jcommon-1.0.16/source/org/jfree/util/junit/PaintListTests.java0000644000175000017500000001302711172030703024261 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * PaintListTests.java * ------------------- * (C) Copyright 2003-2005, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: PaintListTests.java,v 1.4 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 13-Aug-2003 : Version 1 (DG); * 27-Jun-2005 : Added test for equals() where the list contains * GradientPaint instances (DG); */ package org.jfree.util.junit; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Paint; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.util.PaintList; /** * Some tests for the {@link PaintList} class. */ public class PaintListTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(PaintListTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public PaintListTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { final PaintList l1 = new PaintList(); l1.setPaint(0, Color.red); l1.setPaint(1, Color.blue); l1.setPaint(2, null); final PaintList l2 = new PaintList(); l2.setPaint(0, Color.red); l2.setPaint(1, Color.blue); l2.setPaint(2, null); assertTrue(l1.equals(l2)); assertTrue(l2.equals(l2)); } /** * Tests the equals method. */ public void testEquals2() { // check two separate (but equal) colors final PaintList l1 = new PaintList(); final Color color1 = new Color(200, 200, 200); l1.setPaint(0, color1); final PaintList l2 = new PaintList(); final Color color2 = new Color(200, 200, 200); l2.setPaint(0, color2); assertEquals(l1, l2); } /** * Tests the equals() method when the list contains a GradientPaint * instance. */ public void testEquals3() { // check two separate (but equal) colors PaintList l1 = new PaintList(); Paint p1 = new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue); l1.setPaint(0, p1); PaintList l2 = new PaintList(); Paint p2 = new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue); l2.setPaint(0, p2); assertEquals(l1, l2); } /** * Confirm that cloning works. */ public void testCloning() { final PaintList l1 = new PaintList(); l1.setPaint(0, Color.red); l1.setPaint(1, Color.blue); l1.setPaint(2, null); PaintList l2 = null; try { l2 = (PaintList) l1.clone(); } catch (CloneNotSupportedException e) { System.err.println("PaintListTests.testCloning: failed to clone."); } assertTrue(l1 != l2); assertTrue(l1.getClass() == l2.getClass()); assertTrue(l1.equals(l2)); l2.setPaint(0, Color.green); assertFalse(l1.equals(l2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { final PaintList l1 = new PaintList(); l1.setPaint(0, Color.red); l1.setPaint(1, Color.blue); l1.setPaint(2, null); PaintList l2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(l1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); l2 = (PaintList) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertEquals(l1, l2); } } jcommon-1.0.16/source/org/jfree/util/StackableRuntimeException.java0000644000175000017500000000756111172030703025320 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------ * StackableRuntimeException.java * ------------------------------ * (C)opyright 2002-2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: StackableRuntimeException.java,v 1.3 2005/11/14 10:57:07 mungady Exp $ * * Changes * ------- * 06-Dec-2002 : Initial version * 10-Dec-2002 : Fixed issues reported by Checkstyle (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.util; import java.io.PrintStream; import java.io.PrintWriter; /** * A baseclass for RuntimeExceptions, which could have parent exceptions. These parent exceptions * are raised in a subclass and are now wrapped into a subclass of this Exception. *

* The parents are printed when this exception is printed. This class exists mainly for * debugging reasons, as with them it is easier to detect the root cause of an error. * * @author Thomas Morgner */ public class StackableRuntimeException extends RuntimeException { /** The parent exception. */ private Exception parent; /** * Creates a StackableRuntimeException with no message and no parent. */ public StackableRuntimeException() { super(); } /** * Creates an exception. * * @param message the exception message. * @param ex the parent exception. */ public StackableRuntimeException(final String message, final Exception ex) { super(message); this.parent = ex; } /** * Creates an exception. * * @param message the exception message. */ public StackableRuntimeException(final String message) { super(message); } /** * Returns the parent exception (possibly null). * * @return the parent exception. */ public Exception getParent() { return this.parent; } /** * Prints the stack trace to the specified stream. * * @param stream the output stream. */ public void printStackTrace(final PrintStream stream) { super.printStackTrace(stream); if (getParent() != null) { stream.println("ParentException: "); getParent().printStackTrace(stream); } } /** * Prints the stack trace to the specified writer. * * @param writer the writer. */ public void printStackTrace(final PrintWriter writer) { super.printStackTrace(writer); if (getParent() != null) { writer.println("ParentException: "); getParent().printStackTrace(writer); } } } jcommon-1.0.16/source/org/jfree/util/ClassComparator.java0000644000175000017500000001145011172030703023271 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * ClassComparator.java * -------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner (taquera@sherito.org); * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ClassComparator.java,v 1.3 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------- * 02-May-2003 : Initial version * */ package org.jfree.util; import java.io.Serializable; import java.util.Comparator; /** * The class comparator can be used to compare and sort classes and their * superclasses. The comparator is not able to compare classes which have * no relation... * * @author Thomas Morgner */ public class ClassComparator implements Comparator, Serializable { /** For serialization. */ private static final long serialVersionUID = -5225335361837391120L; /** * Defaultconstructor. */ public ClassComparator() { super(); } /** * Compares its two arguments for order. Returns a negative integer, * zero, or a positive integer as the first argument is less than, equal * to, or greater than the second.

*

* Note: throws ClassCastException if the arguments' types prevent them from * being compared by this Comparator. * And IllegalArgumentException if the classes share no relation. * * The implementor must ensure that sgn(compare(x, y)) == * -sgn(compare(y, x)) for all x and y. (This * implies that compare(x, y) must throw an exception if and only * if compare(y, x) throws an exception.)

* * The implementor must also ensure that the relation is transitive: * ((compare(x, y)>0) && (compare(y, z)>0)) implies * compare(x, z)>0.

* * Finally, the implementer must ensure that compare(x, y)==0 * implies that sgn(compare(x, z))==sgn(compare(y, z)) for all * z.

* * It is generally the case, but not strictly required that * (compare(x, y)==0) == (x.equals(y)). Generally speaking, * any comparator that violates this condition should clearly indicate * this fact. The recommended language is "Note: this comparator * imposes orderings that are inconsistent with equals." * * @param o1 the first object to be compared. * @param o2 the second object to be compared. * @return a negative integer, zero, or a positive integer as the * first argument is less than, equal to, or greater than the * second. */ public int compare(final Object o1, final Object o2) { final Class c1 = (Class) o1; final Class c2 = (Class) o2; if (c1.equals(o2)) { return 0; } if (c1.isAssignableFrom(c2)) { return -1; } else { if (!c2.isAssignableFrom(c2)) { throw new IllegalArgumentException( "The classes share no relation" ); } return 1; } } /** * Checks, whether the given classes are comparable. This method will * return true, if one of the classes is assignable from the other class. * * @param c1 the first class to compare * @param c2 the second class to compare * @return true, if the classes share a direct relation, false otherwise. */ public boolean isComparable(final Class c1, final Class c2) { return (c1.isAssignableFrom(c2) || c2.isAssignableFrom(c1)); } } jcommon-1.0.16/source/org/jfree/util/LogContext.java0000644000175000017500000001631611172030703022270 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * LogContext.java * --------------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: LogContext.java,v 1.3 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------- * 26-Apr-2004 : Initial version (TM); * */ package org.jfree.util; /** * A log context. * * @author Thomas Morgner */ public class LogContext { /** The prefix string. */ private String contextPrefix; /** * Creates a new log context. * * @param contextPrefix the prefix. */ public LogContext(final String contextPrefix) { this.contextPrefix = contextPrefix; } /** * Returns true, if the log level allows debug messages to be * printed. * * @return true, if messages with an log level of DEBUG are allowed. */ public boolean isDebugEnabled() { return Log.isDebugEnabled(); } /** * Returns true, if the log level allows informational * messages to be printed. * * @return true, if messages with an log level of INFO are allowed. */ public boolean isInfoEnabled() { return Log.isInfoEnabled(); } /** * Returns true, if the log level allows warning messages to be * printed. * * @return true, if messages with an log level of WARN are allowed. */ public boolean isWarningEnabled() { return Log.isWarningEnabled(); } /** * Returns true, if the log level allows error messages to be * printed. * * @return true, if messages with an log level of ERROR are allowed. */ public boolean isErrorEnabled() { return Log.isErrorEnabled(); } /** * A convenience method for logging a 'debug' message. * * @param message the message. */ public void debug(final Object message) { log(LogTarget.DEBUG, message); } /** * A convenience method for logging a 'debug' message. * * @param message the message. * @param e the exception. */ public void debug(final Object message, final Exception e) { log(LogTarget.DEBUG, message, e); } /** * A convenience method for logging an 'info' message. * * @param message the message. */ public void info(final Object message) { log(LogTarget.INFO, message); } /** * A convenience method for logging an 'info' message. * * @param message the message. * @param e the exception. */ public void info(final Object message, final Exception e) { log(LogTarget.INFO, message, e); } /** * A convenience method for logging a 'warning' message. * * @param message the message. */ public void warn(final Object message) { log(LogTarget.WARN, message); } /** * A convenience method for logging a 'warning' message. * * @param message the message. * @param e the exception. */ public void warn(final Object message, final Exception e) { log(LogTarget.WARN, message, e); } /** * A convenience method for logging an 'error' message. * * @param message the message. */ public void error(final Object message) { log(LogTarget.ERROR, message); } /** * A convenience method for logging an 'error' message. * * @param message the message. * @param e the exception. */ public void error(final Object message, final Exception e) { log(LogTarget.ERROR, message, e); } /** * Logs a message to the main log stream. All attached log targets will also * receive this message. If the given log-level is higher than the given debug-level * in the main config file, no logging will be done. * * @param level log level of the message. * @param message text to be logged. */ public void log(final int level, final Object message) { if (this.contextPrefix != null) { Log.getInstance().doLog(level, new Log.SimpleMessage(this.contextPrefix, ":", message)); } else { Log.getInstance().doLog(level, message); } } /** * Logs a message to the main log stream. All attached logTargets will also * receive this message. If the given log-level is higher than the given debug-level * in the main config file, no logging will be done. *

* The exception's stacktrace will be appended to the log-stream * * @param level log level of the message. * @param message text to be logged. * @param e the exception, which should be logged. */ public void log(final int level, final Object message, final Exception e) { if (this.contextPrefix != null) { Log.getInstance().doLog( level, new Log.SimpleMessage(this.contextPrefix, ":", message), e ); } else { Log.getInstance().doLog(level, message, e); } } /** * Tests this object for equality with an arbitrary object. * * @param o the object to test against (null permitted). * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof LogContext)) { return false; } final LogContext logContext = (LogContext) o; if (this.contextPrefix != null) { if (!this.contextPrefix.equals(logContext.contextPrefix)) { return false; } } else { if (logContext.contextPrefix != null) { return false; } } return true; } /** * Returns a hashcode. * * @return The hashcode. */ public int hashCode() { return (this.contextPrefix != null ? this.contextPrefix.hashCode() : 0); } } jcommon-1.0.16/source/org/jfree/layout/0000755000175000017500000000000011351753320017676 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/layout/CenterLayout.java0000644000175000017500000001330611172030703023154 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * CenterLayout.java * ----------------- * (C) Copyright 2000-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: CenterLayout.java,v 1.6 2005/11/16 15:58:40 taqua Exp $ * * Changes (from 5-Nov-2001) * ------------------------- * 05-Nov-2001 : Changed package to com.jrefinery.layout.* (DG); * 10-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.layout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager; import java.io.Serializable; /** * A layout manager that displays a single component in the center of its * container. * * @author David Gilbert */ public class CenterLayout implements LayoutManager, Serializable { /** For serialization. */ private static final long serialVersionUID = 469319532333015042L; /** * Creates a new layout manager. */ public CenterLayout() { } /** * Returns the preferred size. * * @param parent the parent. * * @return the preferred size. */ public Dimension preferredLayoutSize(final Container parent) { synchronized (parent.getTreeLock()) { final Insets insets = parent.getInsets(); if (parent.getComponentCount() > 0) { final Component component = parent.getComponent(0); final Dimension d = component.getPreferredSize(); return new Dimension( (int) d.getWidth() + insets.left + insets.right, (int) d.getHeight() + insets.top + insets.bottom ); } else { return new Dimension( insets.left + insets.right, insets.top + insets.bottom ); } } } /** * Returns the minimum size. * * @param parent the parent. * * @return the minimum size. */ public Dimension minimumLayoutSize(final Container parent) { synchronized (parent.getTreeLock()) { final Insets insets = parent.getInsets(); if (parent.getComponentCount() > 0) { final Component component = parent.getComponent(0); final Dimension d = component.getMinimumSize(); return new Dimension(d.width + insets.left + insets.right, d.height + insets.top + insets.bottom); } else { return new Dimension(insets.left + insets.right, insets.top + insets.bottom); } } } /** * Lays out the components. * * @param parent the parent. */ public void layoutContainer(final Container parent) { synchronized (parent.getTreeLock()) { if (parent.getComponentCount() > 0) { final Insets insets = parent.getInsets(); final Dimension parentSize = parent.getSize(); final Component component = parent.getComponent(0); final Dimension componentSize = component.getPreferredSize(); final int xx = insets.left + ( Math.max((parentSize.width - insets.left - insets.right - componentSize.width) / 2, 0) ); final int yy = insets.top + ( Math.max((parentSize.height - insets.top - insets.bottom - componentSize.height) / 2, 0)); component.setBounds(xx, yy, componentSize.width, componentSize.height); } } } /** * Not used. * * @param comp the component. */ public void addLayoutComponent(final Component comp) { // not used. } /** * Not used. * * @param comp the component. */ public void removeLayoutComponent(final Component comp) { // not used } /** * Not used. * * @param name the component name. * @param comp the component. */ public void addLayoutComponent(final String name, final Component comp) { // not used } /** * Not used. * * @param name the component name. * @param comp the component. */ public void removeLayoutComponent(final String name, final Component comp) { // not used } } jcommon-1.0.16/source/org/jfree/layout/package.html0000644000175000017500000000017611172030703022155 0ustar twernertwerner Custom layout managers. jcommon-1.0.16/source/org/jfree/layout/FormatLayout.java0000644000175000017500000013044111172030703023164 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * FormatLayout.java * ----------------- * (C) Copyright 2000-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: FormatLayout.java,v 1.4 2005/10/18 13:16:50 mungady Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.layout.* (DG); * 26-Jun-2002 : Removed redundant code (DG); * 10-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.layout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager; import java.io.Serializable; /** * A layout manager that spaces components over six columns in seven different * formats. * * @author David Gilbert */ public class FormatLayout implements LayoutManager, Serializable { /** For serialization. */ private static final long serialVersionUID = 2866692886323930722L; /** A useful constant representing layout format 1. */ public static final int C = 1; /** A useful constant representing layout format 2. */ public static final int LC = 2; /** A useful constant representing layout format 3. */ public static final int LCB = 3; /** A useful constant representing layout format 4. */ public static final int LCLC = 4; /** A useful constant representing layout format 5. */ public static final int LCLCB = 5; /** A useful constant representing layout format 6. */ public static final int LCBLC = 6; /** A useful constant representing layout format 7. */ public static final int LCBLCB = 7; /** The layout format for each row. */ private int[] rowFormats; /** The gap between the rows. */ private int rowGap; /** * The gaps between the columns (gap[0] is the gap following column zero). */ private int[] columnGaps; /** Working array for recording the height of each row. */ private int[] rowHeights; /** The total height of the layout. */ private int totalHeight; /** Working array for recording the width of each column. */ private int[] columnWidths; /** The total width of the layout. */ private int totalWidth; /** Combined width of columns 1 and 2. */ private int columns1and2Width; /** Combined width of columns 4 and 5. */ private int columns4and5Width; /** Combined width of columns 1 to 4. */ private int columns1to4Width; /** Combined width of columns 1 to 5. */ private int columns1to5Width; /** Combined width of columns 0 to 5. */ private int columns0to5Width; /** * Constructs a new layout manager that can be used to create input forms. * The layout manager works by arranging components in rows using six * columns (some components will use more than one column). *

* Any component can be added, but I think of them in terms of Labels, * Components, and Buttons. * The formats available are: C, LC, LCB, LCLC, LCLCB, LCBLC or LCBLCB. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
C1 component in this row (spread across all six columns).
LC2 components, a label in the 1st column, and a component using the * remaining 5 columns).
LCB3 components, a label in the 1st column, a component spread across * the next 4, and a button in the last column.
LCLC4 components, a label in column 1, a component in 2-3, a label in * 4 and a component in 5-6.
LCLCB5 components, a label in column 1, a component in 2-3, a label * in 4, a component in 5 and a button in 6.
LCBLC5 components, a label in column 1, a component in 2, a button in 3, * a label in 4, a component in 5-6.
LCBLCB6 components, one in each column.
*

* Columns 1 and 4 expand to accommodate the widest label, and 3 and 6 to * accommodate the widest button. *

* Each row will contain the number of components indicated by the format. * Be sure to specify enough row formats to cover all the components you * add to the layout. * * @param rowCount the number of rows. * @param rowFormats the row formats. */ public FormatLayout(final int rowCount, final int[] rowFormats) { this.rowFormats = rowFormats; this.rowGap = 2; this.columnGaps = new int[5]; this.columnGaps[0] = 10; this.columnGaps[1] = 5; this.columnGaps[2] = 5; this.columnGaps[3] = 10; this.columnGaps[4] = 5; // working structures... this.rowHeights = new int[rowCount]; this.columnWidths = new int[6]; } /** * Returns the preferred size of the component using this layout manager. * * @param parent the parent. * * @return the preferred size of the component. */ public Dimension preferredLayoutSize(final Container parent) { Component c0, c1, c2, c3, c4, c5; synchronized (parent.getTreeLock()) { final Insets insets = parent.getInsets(); int componentIndex = 0; final int rowCount = this.rowHeights.length; for (int i = 0; i < this.columnWidths.length; i++) { this.columnWidths[i] = 0; } this.columns1and2Width = 0; this.columns4and5Width = 0; this.columns1to4Width = 0; this.columns1to5Width = 0; this.columns0to5Width = 0; this.totalHeight = 0; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { final int format = this.rowFormats[rowIndex % this.rowFormats.length]; switch (format) { case FormatLayout.C: c0 = parent.getComponent(componentIndex); updateC(rowIndex, c0.getPreferredSize()); componentIndex = componentIndex + 1; break; case FormatLayout.LC: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); updateLC(rowIndex, c0.getPreferredSize(), c1.getPreferredSize()); componentIndex = componentIndex + 2; break; case FormatLayout.LCB: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); updateLCB(rowIndex, c0.getPreferredSize(), c1.getPreferredSize(), c2.getPreferredSize()); componentIndex = componentIndex + 3; break; case FormatLayout.LCLC: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); c3 = parent.getComponent(componentIndex + 3); updateLCLC(rowIndex, c0.getPreferredSize(), c1.getPreferredSize(), c2.getPreferredSize(), c3.getPreferredSize()); componentIndex = componentIndex + 4; break; case FormatLayout.LCBLC: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); c3 = parent.getComponent(componentIndex + 3); c4 = parent.getComponent(componentIndex + 4); updateLCBLC(rowIndex, c0.getPreferredSize(), c1.getPreferredSize(), c2.getPreferredSize(), c3.getPreferredSize(), c4.getPreferredSize()); componentIndex = componentIndex + 5; break; case FormatLayout.LCLCB: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); c3 = parent.getComponent(componentIndex + 3); c4 = parent.getComponent(componentIndex + 4); updateLCLCB(rowIndex, c0.getPreferredSize(), c1.getPreferredSize(), c2.getPreferredSize(), c3.getPreferredSize(), c4.getPreferredSize()); componentIndex = componentIndex + 5; break; case FormatLayout.LCBLCB: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); c3 = parent.getComponent(componentIndex + 3); c4 = parent.getComponent(componentIndex + 4); c5 = parent.getComponent(componentIndex + 5); updateLCBLCB(rowIndex, c0.getPreferredSize(), c1.getPreferredSize(), c2.getPreferredSize(), c3.getPreferredSize(), c4.getPreferredSize(), c5.getPreferredSize()); componentIndex = componentIndex + 6; break; } } complete(); return new Dimension(this.totalWidth + insets.left + insets.right, this.totalHeight + (rowCount - 1) * this.rowGap + insets.top + insets.bottom); } } /** * Returns the minimum size of the component using this layout manager. * * @param parent the parent. * * @return the minimum size of the component */ public Dimension minimumLayoutSize(final Container parent) { Component c0, c1, c2, c3, c4, c5; synchronized (parent.getTreeLock()) { final Insets insets = parent.getInsets(); int componentIndex = 0; final int rowCount = this.rowHeights.length; for (int i = 0; i < this.columnWidths.length; i++) { this.columnWidths[i] = 0; } this.columns1and2Width = 0; this.columns4and5Width = 0; this.columns1to4Width = 0; this.columns1to5Width = 0; this.columns0to5Width = 0; final int totalHeight = 0; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { final int format = this.rowFormats[rowIndex % this.rowFormats.length]; switch (format) { case FormatLayout.C: c0 = parent.getComponent(componentIndex); this.columns0to5Width = Math.max( this.columns0to5Width, c0.getMinimumSize().width ); componentIndex = componentIndex + 1; break; case FormatLayout.LC: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); updateLC(rowIndex, c0.getMinimumSize(), c1.getMinimumSize()); componentIndex = componentIndex + 2; break; case FormatLayout.LCB: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); updateLCB(rowIndex, c0.getMinimumSize(), c1.getMinimumSize(), c2.getMinimumSize()); componentIndex = componentIndex + 3; break; case FormatLayout.LCLC: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); c3 = parent.getComponent(componentIndex + 3); updateLCLC(rowIndex, c0.getMinimumSize(), c1.getMinimumSize(), c2.getMinimumSize(), c3.getMinimumSize()); componentIndex = componentIndex + 3; break; case FormatLayout.LCBLC: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); c3 = parent.getComponent(componentIndex + 3); c4 = parent.getComponent(componentIndex + 4); updateLCBLC(rowIndex, c0.getMinimumSize(), c1.getMinimumSize(), c2.getMinimumSize(), c3.getMinimumSize(), c4.getMinimumSize()); componentIndex = componentIndex + 4; break; case FormatLayout.LCLCB: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); c3 = parent.getComponent(componentIndex + 3); c4 = parent.getComponent(componentIndex + 4); updateLCLCB(rowIndex, c0.getMinimumSize(), c1.getMinimumSize(), c2.getMinimumSize(), c3.getMinimumSize(), c4.getMinimumSize()); componentIndex = componentIndex + 4; break; case FormatLayout.LCBLCB: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); c3 = parent.getComponent(componentIndex + 3); c4 = parent.getComponent(componentIndex + 4); c5 = parent.getComponent(componentIndex + 5); updateLCBLCB(rowIndex, c0.getMinimumSize(), c1.getMinimumSize(), c2.getMinimumSize(), c3.getMinimumSize(), c4.getMinimumSize(), c5.getMinimumSize()); componentIndex = componentIndex + 5; break; } } complete(); return new Dimension(this.totalWidth + insets.left + insets.right, totalHeight + (rowCount - 1) * this.rowGap + insets.top + insets.bottom); } } /** * Performs the layout of the container. * * @param parent the parent. */ public void layoutContainer(final Container parent) { Component c0, c1, c2, c3, c4, c5; synchronized (parent.getTreeLock()) { final Insets insets = parent.getInsets(); int componentIndex = 0; final int rowCount = this.rowHeights.length; for (int i = 0; i < this.columnWidths.length; i++) { this.columnWidths[i] = 0; } this.columns1and2Width = 0; this.columns4and5Width = 0; this.columns1to4Width = 0; this.columns1to5Width = 0; this.columns0to5Width = parent.getBounds().width - insets.left - insets.right; this.totalHeight = 0; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { final int format = this.rowFormats[rowIndex % this.rowFormats.length]; switch (format) { case FormatLayout.C: c0 = parent.getComponent(componentIndex); updateC(rowIndex, c0.getPreferredSize()); componentIndex = componentIndex + 1; break; case FormatLayout.LC: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); updateLC(rowIndex, c0.getPreferredSize(), c1.getPreferredSize()); componentIndex = componentIndex + 2; break; case FormatLayout.LCB: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); updateLCB(rowIndex, c0.getPreferredSize(), c1.getPreferredSize(), c2.getPreferredSize()); componentIndex = componentIndex + 3; break; case FormatLayout.LCLC: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); c3 = parent.getComponent(componentIndex + 3); updateLCLC(rowIndex, c0.getPreferredSize(), c1.getPreferredSize(), c2.getPreferredSize(), c3.getPreferredSize()); componentIndex = componentIndex + 4; break; case FormatLayout.LCBLC: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); c3 = parent.getComponent(componentIndex + 3); c4 = parent.getComponent(componentIndex + 4); updateLCBLC(rowIndex, c0.getPreferredSize(), c1.getPreferredSize(), c2.getPreferredSize(), c3.getPreferredSize(), c4.getPreferredSize()); componentIndex = componentIndex + 5; break; case FormatLayout.LCLCB: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); c3 = parent.getComponent(componentIndex + 3); c4 = parent.getComponent(componentIndex + 4); updateLCLCB(rowIndex, c0.getPreferredSize(), c1.getPreferredSize(), c2.getPreferredSize(), c3.getPreferredSize(), c4.getPreferredSize()); componentIndex = componentIndex + 5; break; case FormatLayout.LCBLCB: c0 = parent.getComponent(componentIndex); c1 = parent.getComponent(componentIndex + 1); c2 = parent.getComponent(componentIndex + 2); c3 = parent.getComponent(componentIndex + 3); c4 = parent.getComponent(componentIndex + 4); c5 = parent.getComponent(componentIndex + 5); updateLCBLCB(rowIndex, c0.getPreferredSize(), c1.getPreferredSize(), c2.getPreferredSize(), c3.getPreferredSize(), c4.getPreferredSize(), c5.getPreferredSize()); componentIndex = componentIndex + 6; break; } } complete(); componentIndex = 0; int rowY = insets.top; final int[] rowX = new int[6]; rowX[0] = insets.left; rowX[1] = rowX[0] + this.columnWidths[0] + this.columnGaps[0]; rowX[2] = rowX[1] + this.columnWidths[1] + this.columnGaps[1]; rowX[3] = rowX[2] + this.columnWidths[2] + this.columnGaps[2]; rowX[4] = rowX[3] + this.columnWidths[3] + this.columnGaps[3]; rowX[5] = rowX[4] + this.columnWidths[4] + this.columnGaps[4]; final int w1to2 = this.columnWidths[1] + this.columnGaps[1] + this.columnWidths[2]; final int w4to5 = this.columnWidths[4] + this.columnGaps[4] + this.columnWidths[5]; final int w1to4 = w1to2 + this.columnGaps[2] + this.columnWidths[3] + this.columnGaps[3] + this.columnWidths[4]; final int w1to5 = w1to4 + this.columnGaps[4] + this.columnWidths[5]; final int w0to5 = w1to5 + this.columnWidths[0] + this.columnGaps[0]; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { final int format = this.rowFormats[rowIndex % this.rowFormats.length]; switch (format) { case FormatLayout.C: c0 = parent.getComponent(componentIndex); c0.setBounds(rowX[0], rowY, w0to5, c0.getPreferredSize().height); componentIndex = componentIndex + 1; break; case FormatLayout.LC: c0 = parent.getComponent(componentIndex); c0.setBounds( rowX[0], rowY + (this.rowHeights[rowIndex] - c0.getPreferredSize().height) / 2, this.columnWidths[0], c0.getPreferredSize().height ); c1 = parent.getComponent(componentIndex + 1); c1.setBounds( rowX[1], rowY + (this.rowHeights[rowIndex] - c1.getPreferredSize().height) / 2, w1to5, c1.getPreferredSize().height ); componentIndex = componentIndex + 2; break; case FormatLayout.LCB: c0 = parent.getComponent(componentIndex); c0.setBounds( rowX[0], rowY + (this.rowHeights[rowIndex] - c0.getPreferredSize().height) / 2, this.columnWidths[0], c0.getPreferredSize().height ); c1 = parent.getComponent(componentIndex + 1); c1.setBounds( rowX[1], rowY + (this.rowHeights[rowIndex] - c1.getPreferredSize().height) / 2, w1to4, c1.getPreferredSize().height ); c2 = parent.getComponent(componentIndex + 2); c2.setBounds( rowX[5], rowY + (this.rowHeights[rowIndex] - c2.getPreferredSize().height) / 2, this.columnWidths[5], c2.getPreferredSize().height ); componentIndex = componentIndex + 3; break; case FormatLayout.LCLC: c0 = parent.getComponent(componentIndex); c0.setBounds( rowX[0], rowY + (this.rowHeights[rowIndex] - c0.getPreferredSize().height) / 2, this.columnWidths[0], c0.getPreferredSize().height ); c1 = parent.getComponent(componentIndex + 1); c1.setBounds( rowX[1], rowY + (this.rowHeights[rowIndex] - c1.getPreferredSize().height) / 2, w1to2, c1.getPreferredSize().height ); c2 = parent.getComponent(componentIndex + 2); c2.setBounds( rowX[3], rowY + (this.rowHeights[rowIndex] - c2.getPreferredSize().height) / 2, this.columnWidths[3], c2.getPreferredSize().height ); c3 = parent.getComponent(componentIndex + 3); c3.setBounds( rowX[4], rowY + (this.rowHeights[rowIndex] - c3.getPreferredSize().height) / 2, w4to5, c3.getPreferredSize().height ); componentIndex = componentIndex + 4; break; case FormatLayout.LCBLC: c0 = parent.getComponent(componentIndex); c0.setBounds( rowX[0], rowY + (this.rowHeights[rowIndex] - c0.getPreferredSize().height) / 2, this.columnWidths[0], c0.getPreferredSize().height ); c1 = parent.getComponent(componentIndex + 1); c1.setBounds( rowX[1], rowY + (this.rowHeights[rowIndex] - c1.getPreferredSize().height) / 2, this.columnWidths[1], c1.getPreferredSize().height ); c2 = parent.getComponent(componentIndex + 2); c2.setBounds( rowX[2], rowY + (this.rowHeights[rowIndex] - c2.getPreferredSize().height) / 2, this.columnWidths[2], c2.getPreferredSize().height ); c3 = parent.getComponent(componentIndex + 3); c3.setBounds( rowX[3], rowY + (this.rowHeights[rowIndex] - c3.getPreferredSize().height) / 2, this.columnWidths[3], c3.getPreferredSize().height ); c4 = parent.getComponent(componentIndex + 4); c4.setBounds( rowX[4], rowY + (this.rowHeights[rowIndex] - c4.getPreferredSize().height) / 2, w4to5, c4.getPreferredSize().height ); componentIndex = componentIndex + 5; break; case FormatLayout.LCLCB: c0 = parent.getComponent(componentIndex); c0.setBounds( rowX[0], rowY + (this.rowHeights[rowIndex] - c0.getPreferredSize().height) / 2, this.columnWidths[0], c0.getPreferredSize().height ); c1 = parent.getComponent(componentIndex + 1); c1.setBounds( rowX[1], rowY + (this.rowHeights[rowIndex] - c1.getPreferredSize().height) / 2, w1to2, c1.getPreferredSize().height ); c2 = parent.getComponent(componentIndex + 2); c2.setBounds( rowX[3], rowY + (this.rowHeights[rowIndex] - c2.getPreferredSize().height) / 2, this.columnWidths[3], c2.getPreferredSize().height ); c3 = parent.getComponent(componentIndex + 3); c3.setBounds( rowX[4], rowY + (this.rowHeights[rowIndex] - c3.getPreferredSize().height) / 2, this.columnWidths[4], c3.getPreferredSize().height ); c4 = parent.getComponent(componentIndex + 4); c4.setBounds( rowX[5], rowY + (this.rowHeights[rowIndex] - c4.getPreferredSize().height) / 2, this.columnWidths[5], c4.getPreferredSize().height ); componentIndex = componentIndex + 5; break; case FormatLayout.LCBLCB: c0 = parent.getComponent(componentIndex); c0.setBounds( rowX[0], rowY + (this.rowHeights[rowIndex] - c0.getPreferredSize().height) / 2, this.columnWidths[0], c0.getPreferredSize().height ); c1 = parent.getComponent(componentIndex + 1); c1.setBounds( rowX[1], rowY + (this.rowHeights[rowIndex] - c1.getPreferredSize().height) / 2, this.columnWidths[1], c1.getPreferredSize().height ); c2 = parent.getComponent(componentIndex + 2); c2.setBounds( rowX[2], rowY + (this.rowHeights[rowIndex] - c2.getPreferredSize().height) / 2, this.columnWidths[2], c2.getPreferredSize().height ); c3 = parent.getComponent(componentIndex + 3); c3.setBounds( rowX[3], rowY + (this.rowHeights[rowIndex] - c3.getPreferredSize().height) / 2, this.columnWidths[3], c3.getPreferredSize().height ); c4 = parent.getComponent(componentIndex + 4); c4.setBounds( rowX[4], rowY + (this.rowHeights[rowIndex] - c4.getPreferredSize().height) / 2, this.columnWidths[4], c4.getPreferredSize().height ); c5 = parent.getComponent(componentIndex + 5); c5.setBounds( rowX[5], rowY + (this.rowHeights[rowIndex] - c5.getPreferredSize().height) / 2, this.columnWidths[5], c5.getPreferredSize().height ); componentIndex = componentIndex + 6; break; } rowY = rowY + this.rowHeights[rowIndex] + this.rowGap; } } } /** * Processes a row in 'C' format. * * @param rowIndex the row index. * @param d0 dimension 0. */ protected void updateC(final int rowIndex, final Dimension d0) { this.rowHeights[rowIndex] = d0.height; this.totalHeight = this.totalHeight + this.rowHeights[rowIndex]; this.columns0to5Width = Math.max(this.columns0to5Width, d0.width); } /** * Processes a row in 'LC' format. * * @param rowIndex the row index. * @param d0 dimension 0. * @param d1 dimension 1. */ protected void updateLC(final int rowIndex, final Dimension d0, final Dimension d1) { this.rowHeights[rowIndex] = Math.max(d0.height, d1.height); this.totalHeight = this.totalHeight + this.rowHeights[rowIndex]; this.columnWidths[0] = Math.max(this.columnWidths[0], d0.width); this.columns1to5Width = Math.max(this.columns1to5Width, d1.width); } /** * Processes a row in 'LCB' format. * * @param rowIndex the row index. * @param d0 dimension 0. * @param d1 dimension 1. * @param d2 dimension 2. */ protected void updateLCB(final int rowIndex, final Dimension d0, final Dimension d1, final Dimension d2) { this.rowHeights[rowIndex] = Math.max(d0.height, Math.max(d1.height, d2.height)); this.totalHeight = this.totalHeight + this.rowHeights[rowIndex]; this.columnWidths[0] = Math.max(this.columnWidths[0], d0.width); this.columns1to4Width = Math.max(this.columns1to4Width, d1.width); this.columnWidths[5] = Math.max(this.columnWidths[5], d2.width); } /** * Processes a row in 'LCLC' format. * * @param rowIndex the row index. * @param d0 dimension 0. * @param d1 dimension 1. * @param d2 dimension 2. * @param d3 dimension 3. */ protected void updateLCLC(final int rowIndex, final Dimension d0, final Dimension d1, final Dimension d2, final Dimension d3) { this.rowHeights[rowIndex] = Math.max(Math.max(d0.height, d1.height), Math.max(d2.height, d3.height)); this.totalHeight = this.totalHeight + this.rowHeights[rowIndex]; this.columnWidths[0] = Math.max(this.columnWidths[0], d0.width); this.columns1and2Width = Math.max(this.columns1and2Width, d1.width); this.columnWidths[3] = Math.max(this.columnWidths[3], d2.width); this.columns4and5Width = Math.max(this.columns4and5Width, d3.width); } /** * Processes a row in 'LCBLC' format. * * @param rowIndex the row index. * @param d0 dimension 0. * @param d1 dimension 1. * @param d2 dimension 2. * @param d3 dimension 3. * @param d4 dimension 4. */ protected void updateLCBLC(final int rowIndex, final Dimension d0, final Dimension d1, final Dimension d2, final Dimension d3, final Dimension d4) { this.rowHeights[rowIndex] = (Math.max( d0.height, Math.max(Math.max(d1.height, d2.height), Math.max(d3.height, d4.height))) ); this.totalHeight = this.totalHeight + this.rowHeights[rowIndex]; this.columnWidths[0] = Math.max(this.columnWidths[0], d0.width); this.columnWidths[1] = Math.max(this.columnWidths[1], d1.width); this.columnWidths[2] = Math.max(this.columnWidths[2], d2.width); this.columnWidths[3] = Math.max(this.columnWidths[3], d3.width); this.columns4and5Width = Math.max(this.columns4and5Width, d4.width); } /** * Processes a row in 'LCLCB' format. * * @param rowIndex the row index. * @param d0 dimension 0. * @param d1 dimension 1. * @param d2 dimension 2. * @param d3 dimension 3. * @param d4 dimension 4. */ protected void updateLCLCB(final int rowIndex, final Dimension d0, final Dimension d1, final Dimension d2, final Dimension d3, final Dimension d4) { this.rowHeights[rowIndex] = (Math.max(d0.height, Math.max(Math.max(d1.height, d2.height), Math.max(d3.height, d4.height)))); this.totalHeight = this.totalHeight + this.rowHeights[rowIndex]; this.columnWidths[0] = Math.max(this.columnWidths[0], d0.width); this.columns1and2Width = Math.max(this.columns1and2Width, d1.width); this.columnWidths[3] = Math.max(this.columnWidths[3], d2.width); this.columnWidths[4] = Math.max(this.columnWidths[4], d3.width); this.columnWidths[5] = Math.max(this.columnWidths[5], d4.width); } /** * Processes a row in 'LCBLCB' format. * * @param rowIndex the row index. * @param d0 dimension 0. * @param d1 dimension 1. * @param d2 dimension 2. * @param d3 dimension 3. * @param d4 dimension 4. * @param d5 dimension 5. */ protected void updateLCBLCB(final int rowIndex, final Dimension d0, final Dimension d1, final Dimension d2, final Dimension d3, final Dimension d4, final Dimension d5) { this.rowHeights[rowIndex] = Math.max( Math.max(d0.height, d1.height), Math.max(Math.max(d2.height, d3.height), Math.max(d4.height, d5.height)) ); this.totalHeight = this.totalHeight + this.rowHeights[rowIndex]; this.columnWidths[0] = Math.max(this.columnWidths[0], d0.width); this.columnWidths[1] = Math.max(this.columnWidths[1], d1.width); this.columnWidths[2] = Math.max(this.columnWidths[2], d2.width); this.columnWidths[3] = Math.max(this.columnWidths[3], d3.width); this.columnWidths[4] = Math.max(this.columnWidths[4], d4.width); this.columnWidths[5] = Math.max(this.columnWidths[5], d5.width); } /** * Finishes of the processing. */ public void complete() { this.columnWidths[1] = Math.max( this.columnWidths[1], this.columns1and2Width - this.columnGaps[1] - this.columnWidths[2] ); this.columnWidths[4] = Math.max( this.columnWidths[4], Math.max( this.columns4and5Width - this.columnGaps[4] - this.columnWidths[5], Math.max( this.columns1to4Width - this.columnGaps[1] - this.columnGaps[2] - this.columnGaps[3] - this.columnWidths[1] - this.columnWidths[2] - this.columnWidths[3], this.columns1to5Width - this.columnGaps[1] - this.columnGaps[2] - this.columnGaps[3] - this.columnWidths[1] - this.columnWidths[2] - this.columnWidths[3] - this.columnGaps[4] ) ) ); int leftWidth = this.columnWidths[0] + this.columnGaps[0] + this.columnWidths[1] + this.columnGaps[1] + this.columnWidths[2]; int rightWidth = this.columnWidths[3] + this.columnGaps[3] + this.columnWidths[4] + this.columnGaps[4] + this.columnWidths[5]; if (splitLayout()) { if (leftWidth > rightWidth) { final int mismatch = leftWidth - rightWidth; this.columnWidths[4] = this.columnWidths[4] + mismatch; rightWidth = rightWidth + mismatch; } else { final int mismatch = rightWidth - leftWidth; this.columnWidths[1] = this.columnWidths[1] + mismatch; leftWidth = leftWidth + mismatch; } } this.totalWidth = leftWidth + this.columnGaps[2] + rightWidth; if (this.columns0to5Width > this.totalWidth) { final int spaceToAdd = (this.columns0to5Width - this.totalWidth); if (splitLayout()) { final int halfSpaceToAdd = spaceToAdd / 2; this.columnWidths[1] = this.columnWidths[1] + halfSpaceToAdd; this.columnWidths[4] = this.columnWidths[4] + spaceToAdd - halfSpaceToAdd; this.totalWidth = this.totalWidth + spaceToAdd; } else { this.columnWidths[1] = this.columnWidths[1] + spaceToAdd; this.totalWidth = this.totalWidth + spaceToAdd; } } } /** * Returns true if this layout involves a split into two sections. * * @return true if this layout involves a split into two * sections. */ private boolean splitLayout() { for (int i = 0; i < this.rowFormats.length; i++) { if (this.rowFormats[i] > FormatLayout.LCB) { return true; } } return false; } /** * Not used. * * @param comp the component. */ public void addLayoutComponent(final Component comp) { // not used } /** * Not used. * * @param comp the component. */ public void removeLayoutComponent(final Component comp) { // not used } /** * Not used. * * @param name the component name. * @param comp the component. */ public void addLayoutComponent(final String name, final Component comp) { // not used } /** * Not used. * * @param name the component name. * @param comp the component. */ public void removeLayoutComponent(final String name, final Component comp) { // not used } } jcommon-1.0.16/source/org/jfree/layout/RadialLayout.java0000644000175000017500000002270011172030703023126 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * RadialLayout.java * ----------------- * (C) Copyright 2003, 2004, by Bryan Scott (for Australian Antarctic Division). * * Original Author: Bryan Scott (for Australian Antarctic Division); * Contributor(s): David Gilbert (for Object Refinery Limited); * * * Changes: * -------- * 30-Jun-2003 : Version 1 (BS); * 24-Jul-2003 : Completed missing Javadocs (DG); * */ package org.jfree.layout; import java.awt.Checkbox; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.Panel; import java.io.Serializable; /** * RadialLayout is a component layout manager. Compents are laid out in a * circle. If only one component is contained in the layout it is positioned * centrally, otherwise components are evenly spaced around the centre with * the first component placed to the North. *

* This code was developed to display CTD rosette firing control * * WARNING: Not thoughly tested, use at own risk. * * @author Bryan Scott (for Australian Antarctic Division) */ public class RadialLayout implements LayoutManager, Serializable { /** For serialization. */ private static final long serialVersionUID = -7582156799248315534L; /** The minimum width. */ private int minWidth = 0; /** The minimum height. */ private int minHeight = 0; /** The maximum component width. */ private int maxCompWidth = 0; /** The maximum component height. */ private int maxCompHeight = 0; /** The preferred width. */ private int preferredWidth = 0; /** The preferred height. */ private int preferredHeight = 0; /** Size unknown flag. */ private boolean sizeUnknown = true; /** * Constructs this layout manager with default properties. */ public RadialLayout() { super(); } /** * Not used. * * @param comp the component. */ public void addLayoutComponent(final Component comp) { // not used } /** * Not used. * * @param comp the component. */ public void removeLayoutComponent(final Component comp) { // not used } /** * Not used. * * @param name the component name. * @param comp the component. */ public void addLayoutComponent(final String name, final Component comp) { // not used } /** * Not used. * * @param name the component name. * @param comp the component. */ public void removeLayoutComponent(final String name, final Component comp) { // not used } /** * Sets the sizes attribute of the RadialLayout object. * * @param parent the parent. * * @see LayoutManager */ private void setSizes(final Container parent) { final int nComps = parent.getComponentCount(); //Reset preferred/minimum width and height. this.preferredWidth = 0; this.preferredHeight = 0; this.minWidth = 0; this.minHeight = 0; for (int i = 0; i < nComps; i++) { final Component c = parent.getComponent(i); if (c.isVisible()) { final Dimension d = c.getPreferredSize(); if (this.maxCompWidth < d.width) { this.maxCompWidth = d.width; } if (this.maxCompHeight < d.height) { this.maxCompHeight = d.height; } this.preferredWidth += d.width; this.preferredHeight += d.height; } } this.preferredWidth = this.preferredWidth / 2; this.preferredHeight = this.preferredHeight / 2; this.minWidth = this.preferredWidth; this.minHeight = this.preferredHeight; } /** * Returns the preferred size. * * @param parent the parent. * * @return The preferred size. * @see LayoutManager */ public Dimension preferredLayoutSize(final Container parent) { final Dimension dim = new Dimension(0, 0); setSizes(parent); //Always add the container's insets! final Insets insets = parent.getInsets(); dim.width = this.preferredWidth + insets.left + insets.right; dim.height = this.preferredHeight + insets.top + insets.bottom; this.sizeUnknown = false; return dim; } /** * Returns the minimum size. * * @param parent the parent. * * @return The minimum size. * @see LayoutManager */ public Dimension minimumLayoutSize(final Container parent) { final Dimension dim = new Dimension(0, 0); //Always add the container's insets! final Insets insets = parent.getInsets(); dim.width = this.minWidth + insets.left + insets.right; dim.height = this.minHeight + insets.top + insets.bottom; this.sizeUnknown = false; return dim; } /** * This is called when the panel is first displayed, and every time its size * changes. * Note: You CAN'T assume preferredLayoutSize or minimumLayoutSize will be * called -- in the case of applets, at least, they probably won't be. * * @param parent the parent. * @see LayoutManager */ public void layoutContainer(final Container parent) { final Insets insets = parent.getInsets(); final int maxWidth = parent.getSize().width - (insets.left + insets.right); final int maxHeight = parent.getSize().height - (insets.top + insets.bottom); final int nComps = parent.getComponentCount(); int x = 0; int y = 0; // Go through the components' sizes, if neither preferredLayoutSize nor // minimumLayoutSize has been called. if (this.sizeUnknown) { setSizes(parent); } if (nComps < 2) { final Component c = parent.getComponent(0); if (c.isVisible()) { final Dimension d = c.getPreferredSize(); c.setBounds(x, y, d.width, d.height); } } else { double radialCurrent = Math.toRadians(90); final double radialIncrement = 2 * Math.PI / nComps; final int midX = maxWidth / 2; final int midY = maxHeight / 2; final int a = midX - this.maxCompWidth; final int b = midY - this.maxCompHeight; for (int i = 0; i < nComps; i++) { final Component c = parent.getComponent(i); if (c.isVisible()) { final Dimension d = c.getPreferredSize(); x = (int) (midX - (a * Math.cos(radialCurrent)) - (d.getWidth() / 2) + insets.left); y = (int) (midY - (b * Math.sin(radialCurrent)) - (d.getHeight() / 2) + insets.top); // Set the component's size and position. c.setBounds(x, y, d.width, d.height); } radialCurrent += radialIncrement; } } } /** * Returns the class name. * * @return The class name. */ public String toString() { return getClass().getName(); } /** * Run a demonstration. * * @param args ignored. * * @throws Exception when an error occurs. */ public static void main(final String[] args) throws Exception { final Frame frame = new Frame(); final Panel panel = new Panel(); panel.setLayout(new RadialLayout()); panel.add(new Checkbox("One")); panel.add(new Checkbox("Two")); panel.add(new Checkbox("Three")); panel.add(new Checkbox("Four")); panel.add(new Checkbox("Five")); panel.add(new Checkbox("One")); panel.add(new Checkbox("Two")); panel.add(new Checkbox("Three")); panel.add(new Checkbox("Four")); panel.add(new Checkbox("Five")); frame.add(panel); frame.setSize(300, 500); frame.setVisible(true); } } jcommon-1.0.16/source/org/jfree/layout/LCBLayout.java0000644000175000017500000002252011172030703022332 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------- * LCBLayout.java * -------------- * (C) Copyright 2000-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: LCBLayout.java,v 1.5 2005/11/16 15:58:40 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.layout.* (DG); * 10-Oct-2002 : Fixed errors reported by Checkstyle (DG); */ package org.jfree.layout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager; import java.io.Serializable; /** * Specialised layout manager for a grid of components. * * @author David Gilbert */ public class LCBLayout implements LayoutManager, Serializable { /** For serialization. */ private static final long serialVersionUID = -2531780832406163833L; /** A constant for the number of columns in the layout. */ private static final int COLUMNS = 3; /** Tracks the column widths. */ private int[] colWidth; /** Tracks the row heights. */ private int[] rowHeight; /** The gap between each label and component. */ private int labelGap; /** The gap between each component and button. */ private int buttonGap; /** The gap between rows. */ private int vGap; /** * Creates a new LCBLayout with the specified maximum number of rows. * * @param maxrows the maximum number of rows. */ public LCBLayout(final int maxrows) { this.labelGap = 10; this.buttonGap = 6; this.vGap = 2; this.colWidth = new int[COLUMNS]; this.rowHeight = new int[maxrows]; } /** * Returns the preferred size using this layout manager. * * @param parent the parent. * * @return the preferred size using this layout manager. */ public Dimension preferredLayoutSize(final Container parent) { synchronized (parent.getTreeLock()) { final Insets insets = parent.getInsets(); final int ncomponents = parent.getComponentCount(); final int nrows = ncomponents / COLUMNS; for (int c = 0; c < COLUMNS; c++) { for (int r = 0; r < nrows; r++) { final Component component = parent.getComponent(r * COLUMNS + c); final Dimension d = component.getPreferredSize(); if (this.colWidth[c] < d.width) { this.colWidth[c] = d.width; } if (this.rowHeight[r] < d.height) { this.rowHeight[r] = d.height; } } } int totalHeight = this.vGap * (nrows - 1); for (int r = 0; r < nrows; r++) { totalHeight = totalHeight + this.rowHeight[r]; } final int totalWidth = this.colWidth[0] + this.labelGap + this.colWidth[1] + this.buttonGap + this.colWidth[2]; return new Dimension( insets.left + insets.right + totalWidth + this.labelGap + this.buttonGap, insets.top + insets.bottom + totalHeight + this.vGap ); } } /** * Returns the minimum size using this layout manager. * * @param parent the parent. * * @return the minimum size using this layout manager. */ public Dimension minimumLayoutSize(final Container parent) { synchronized (parent.getTreeLock()) { final Insets insets = parent.getInsets(); final int ncomponents = parent.getComponentCount(); final int nrows = ncomponents / COLUMNS; for (int c = 0; c < COLUMNS; c++) { for (int r = 0; r < nrows; r++) { final Component component = parent.getComponent(r * COLUMNS + c); final Dimension d = component.getMinimumSize(); if (this.colWidth[c] < d.width) { this.colWidth[c] = d.width; } if (this.rowHeight[r] < d.height) { this.rowHeight[r] = d.height; } } } int totalHeight = this.vGap * (nrows - 1); for (int r = 0; r < nrows; r++) { totalHeight = totalHeight + this.rowHeight[r]; } final int totalWidth = this.colWidth[0] + this.labelGap + this.colWidth[1] + this.buttonGap + this.colWidth[2]; return new Dimension( insets.left + insets.right + totalWidth + this.labelGap + this.buttonGap, insets.top + insets.bottom + totalHeight + this.vGap ); } } /** * Lays out the components. * * @param parent the parent. */ public void layoutContainer(final Container parent) { synchronized (parent.getTreeLock()) { final Insets insets = parent.getInsets(); final int ncomponents = parent.getComponentCount(); final int nrows = ncomponents / COLUMNS; for (int c = 0; c < COLUMNS; c++) { for (int r = 0; r < nrows; r++) { final Component component = parent.getComponent(r * COLUMNS + c); final Dimension d = component.getPreferredSize(); if (this.colWidth[c] < d.width) { this.colWidth[c] = d.width; } if (this.rowHeight[r] < d.height) { this.rowHeight[r] = d.height; } } } int totalHeight = this.vGap * (nrows - 1); for (int r = 0; r < nrows; r++) { totalHeight = totalHeight + this.rowHeight[r]; } final int totalWidth = this.colWidth[0] + this.colWidth[1] + this.colWidth[2]; // adjust the width of the second column to use up all of parent final int available = parent.getWidth() - insets.left - insets.right - this.labelGap - this.buttonGap; this.colWidth[1] = this.colWidth[1] + (available - totalWidth); // *** DO THE LAYOUT *** int x = insets.left; for (int c = 0; c < COLUMNS; c++) { int y = insets.top; for (int r = 0; r < nrows; r++) { final int i = r * COLUMNS + c; if (i < ncomponents) { final Component component = parent.getComponent(i); final Dimension d = component.getPreferredSize(); final int h = d.height; final int adjust = (this.rowHeight[r] - h) / 2; parent.getComponent(i).setBounds(x, y + adjust, this.colWidth[c], h); } y = y + this.rowHeight[r] + this.vGap; } x = x + this.colWidth[c]; if (c == 0) { x = x + this.labelGap; } if (c == 1) { x = x + this.buttonGap; } } } } /** * Not used. * * @param comp the component. */ public void addLayoutComponent(final Component comp) { // not used } /** * Not used. * * @param comp the component. */ public void removeLayoutComponent(final Component comp) { // not used } /** * Not used. * * @param name the component name. * @param comp the component. */ public void addLayoutComponent(final String name, final Component comp) { // not used } /** * Not used. * * @param name the component name. * @param comp the component. */ public void removeLayoutComponent(final String name, final Component comp) { // not used } } jcommon-1.0.16/source/org/jfree/io/0000755000175000017500000000000011351753320016770 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/io/IOUtils.java0000644000175000017500000003501111172030703021155 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------ * IOUtils.java * ------------ * (C)opyright 2002-2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: IOUtils.java,v 1.8 2009/01/22 08:34:58 taqua Exp $ * * Changes * ------- * 26-Jan-2003 : Initial version * 23-Feb-2003 : Documentation * 25-Feb-2003 : Fixed Checkstyle issues (DG); * 29-Apr-2003 : Moved to jcommon * 04-Jan-2004 : Fixed JDK 1.2.2 issues with createRelativeURL; * added support for query strings within these urls (TM); */ package org.jfree.io; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; /** * The IOUtils provide some IO related helper methods. * * @author Thomas Morgner. */ public class IOUtils { /** the singleton instance of the utility package. */ private static IOUtils instance; /** * DefaultConstructor. */ private IOUtils() { } /** * Gets the singleton instance of the utility package. * * @return the singleton instance. */ public static IOUtils getInstance() { if (instance == null) { instance = new IOUtils(); } return instance; } /** * Checks, whether the URL uses a file based protocol. * * @param url the url. * @return true, if the url is file based. */ private boolean isFileStyleProtocol(final URL url) { if (url.getProtocol().equals("http")) { return true; } if (url.getProtocol().equals("https")) { return true; } if (url.getProtocol().equals("ftp")) { return true; } if (url.getProtocol().equals("file")) { return true; } if (url.getProtocol().equals("jar")) { return true; } return false; } /** * Parses the given name and returns the name elements as List of Strings. * * @param name the name, that should be parsed. * @return the parsed name. */ private List parseName(final String name) { final ArrayList list = new ArrayList(); final StringTokenizer strTok = new StringTokenizer(name, "/"); while (strTok.hasMoreElements()) { final String s = (String) strTok.nextElement(); if (s.length() != 0) { list.add(s); } } return list; } /** * Transforms the name list back into a single string, separated with "/". * * @param name the name list. * @param query the (optional) query for the URL. * @return the constructed name. */ private String formatName(final List name, final String query) { final StringBuffer b = new StringBuffer(); final Iterator it = name.iterator(); while (it.hasNext()) { b.append(it.next()); if (it.hasNext()) { b.append("/"); } } if (query != null) { b.append('?'); b.append(query); } return b.toString(); } /** * Compares both name lists, and returns the last common index shared * between the two lists. * * @param baseName the name created using the base url. * @param urlName the target url name. * @return the number of shared elements. */ private int startsWithUntil(final List baseName, final List urlName) { final int minIdx = Math.min(urlName.size(), baseName.size()); for (int i = 0; i < minIdx; i++) { final String baseToken = (String) baseName.get(i); final String urlToken = (String) urlName.get(i); if (!baseToken.equals(urlToken)) { return i; } } return minIdx; } /** * Checks, whether the URL points to the same service. A service is equal * if the protocol, host and port are equal. * * @param url a url * @param baseUrl an other url, that should be compared. * @return true, if the urls point to the same host and port and use the * same protocol, false otherwise. */ private boolean isSameService(final URL url, final URL baseUrl) { if (!url.getProtocol().equals(baseUrl.getProtocol())) { return false; } if (!url.getHost().equals(baseUrl.getHost())) { return false; } if (url.getPort() != baseUrl.getPort()) { return false; } return true; } /** * Creates a relative url by stripping the common parts of the the url. * * @param url the to be stripped url * @param baseURL the base url, to which the url is relative * to. * @return the relative url, or the url unchanged, if there is no relation * beween both URLs. */ public String createRelativeURL(final URL url, final URL baseURL) { if (url == null) { throw new NullPointerException("content url must not be null."); } if (baseURL == null) { throw new NullPointerException("baseURL must not be null."); } if (isFileStyleProtocol(url) && isSameService(url, baseURL)) { // If the URL contains a query, ignore that URL; do not // attemp to modify it... final List urlName = parseName(getPath(url)); final List baseName = parseName(getPath(baseURL)); final String query = getQuery(url); if (!isPath(baseURL)) { baseName.remove(baseName.size() - 1); } // if both urls are identical, then return the plain file name... if (url.equals(baseURL)) { return (String) urlName.get(urlName.size() - 1); } int commonIndex = startsWithUntil(urlName, baseName); if (commonIndex == 0) { return url.toExternalForm(); } if (commonIndex == urlName.size()) { // correct the base index if there is some weird mapping // detected, // fi. the file url is fully included in the base url: // // base: /file/test/funnybase // file: /file/test // // this could be a valid configuration whereever virtual // mappings are allowed. commonIndex -= 1; } final ArrayList retval = new ArrayList(); if (baseName.size() >= urlName.size()) { final int levels = baseName.size() - commonIndex; for (int i = 0; i < levels; i++) { retval.add(".."); } } retval.addAll(urlName.subList(commonIndex, urlName.size())); return formatName(retval, query); } return url.toExternalForm(); } /** * Returns true if the URL represents a path, and * false otherwise. * * @param baseURL the URL. * * @return A boolean. */ private boolean isPath(final URL baseURL) { if (getPath(baseURL).endsWith("/")) { return true; } else if (baseURL.getProtocol().equals("file")) { final File f = new File(getPath(baseURL)); try { if (f.isDirectory()) { return true; } } catch (SecurityException se) { // ignored ... } } return false; } /** * Implements the JDK 1.3 method URL.getPath(). The path is defined * as URL.getFile() minus the (optional) query. * * @param url the URL * @return the path */ private String getQuery (final URL url) { final String file = url.getFile(); final int queryIndex = file.indexOf('?'); if (queryIndex == -1) { return null; } return file.substring(queryIndex + 1); } /** * Implements the JDK 1.3 method URL.getPath(). The path is defined * as URL.getFile() minus the (optional) query. * * @param url the URL * @return the path */ private String getPath (final URL url) { final String file = url.getFile(); final int queryIndex = file.indexOf('?'); if (queryIndex == -1) { return file; } return file.substring(0, queryIndex); } /** * Copies the InputStream into the OutputStream, until the end of the stream * has been reached. This method uses a buffer of 4096 kbyte. * * @param in the inputstream from which to read. * @param out the outputstream where the data is written to. * @throws IOException if a IOError occurs. */ public void copyStreams(final InputStream in, final OutputStream out) throws IOException { copyStreams(in, out, 4096); } /** * Copies the InputStream into the OutputStream, until the end of the stream * has been reached. * * @param in the inputstream from which to read. * @param out the outputstream where the data is written to. * @param buffersize the buffer size. * @throws IOException if a IOError occurs. */ public void copyStreams(final InputStream in, final OutputStream out, final int buffersize) throws IOException { // create a 4kbyte buffer to read the file final byte[] bytes = new byte[buffersize]; // the input stream does not supply accurate available() data // the zip entry does not know the size of the data int bytesRead = in.read(bytes); while (bytesRead > -1) { out.write(bytes, 0, bytesRead); bytesRead = in.read(bytes); } } /** * Copies the contents of the Reader into the Writer, until the end of the * stream has been reached. This method uses a buffer of 4096 kbyte. * * @param in the reader from which to read. * @param out the writer where the data is written to. * @throws IOException if a IOError occurs. */ public void copyWriter(final Reader in, final Writer out) throws IOException { copyWriter(in, out, 4096); } /** * Copies the contents of the Reader into the Writer, until the end of the * stream has been reached. * * @param in the reader from which to read. * @param out the writer where the data is written to. * @param buffersize the buffer size. * * @throws IOException if a IOError occurs. */ public void copyWriter(final Reader in, final Writer out, final int buffersize) throws IOException { // create a 4kbyte buffer to read the file final char[] bytes = new char[buffersize]; // the input stream does not supply accurate available() data // the zip entry does not know the size of the data int bytesRead = in.read(bytes); while (bytesRead > -1) { out.write(bytes, 0, bytesRead); bytesRead = in.read(bytes); } } /** * Extracts the file name from the URL. * * @param url the url. * @return the extracted filename. */ public String getFileName(final URL url) { final String file = getPath(url); final int last = file.lastIndexOf("/"); if (last < 0) { return file; } return file.substring(last + 1); } /** * Removes the file extension from the given file name. * * @param file the file name. * @return the file name without the file extension. */ public String stripFileExtension(final String file) { final int idx = file.lastIndexOf("."); // handles unix hidden files and files without an extension. if (idx < 1) { return file; } return file.substring(0, idx); } /** * Returns the file extension of the given file name. * The returned value will contain the dot. * * @param file the file name. * @return the file extension. */ public String getFileExtension(final String file) { final int idx = file.lastIndexOf("."); // handles unix hidden files and files without an extension. if (idx < 1) { return ""; } return file.substring(idx); } /** * Checks, whether the child directory is a subdirectory of the base * directory. * * @param base the base directory. * @param child the suspected child directory. * @return true, if the child is a subdirectory of the base directory. * @throws IOException if an IOError occured during the test. */ public boolean isSubDirectory(File base, File child) throws IOException { base = base.getCanonicalFile(); child = child.getCanonicalFile(); File parentFile = child; while (parentFile != null) { if (base.equals(parentFile)) { return true; } parentFile = parentFile.getParentFile(); } return false; } } jcommon-1.0.16/source/org/jfree/io/package.html0000644000175000017500000000020411172030703021237 0ustar twernertwerner Input/output related classes. jcommon-1.0.16/source/org/jfree/io/SerialUtilities.java0000644000175000017500000005343011172030703022745 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * SerialUtilities.java * -------------------- * (C) Copyright 2000-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Arik Levin; * * $Id: SerialUtilities.java,v 1.14 2008/06/02 06:58:28 mungady Exp $ * * Changes * ------- * 25-Mar-2003 : Version 1 (DG); * 18-Sep-2003 : Added capability to serialize GradientPaint (DG); * 26-Apr-2004 : Added read/writePoint2D() methods (DG); * 22-Feb-2005 : Added support for Arc2D - see patch 1147035 by Arik Levin (DG); * 29-Jul-2005 : Added support for AttributedString (DG); * */ package org.jfree.io; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.text.CharacterIterator; import java.util.HashMap; import java.util.Map; /** * A class containing useful utility methods relating to serialization. * * @author David Gilbert */ public class SerialUtilities { /** * Private constructor prevents object creation. */ private SerialUtilities() { } /** * Returns true if a class implements Serializable * and false otherwise. * * @param c the class. * * @return A boolean. */ public static boolean isSerializable(final Class c) { /** final Class[] interfaces = c.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (interfaces[i].equals(Serializable.class)) { return true; } } Class cc = c.getSuperclass(); if (cc != null) { return isSerializable(cc); } */ return (Serializable.class.isAssignableFrom(c)); } /** * Reads a Paint object that has been serialised by the * {@link SerialUtilities#writePaint(Paint, ObjectOutputStream)} method. * * @param stream the input stream (null not permitted). * * @return The paint object (possibly null). * * @throws IOException if there is an I/O problem. * @throws ClassNotFoundException if there is a problem loading a class. */ public static Paint readPaint(final ObjectInputStream stream) throws IOException, ClassNotFoundException { if (stream == null) { throw new IllegalArgumentException("Null 'stream' argument."); } Paint result = null; final boolean isNull = stream.readBoolean(); if (!isNull) { final Class c = (Class) stream.readObject(); if (isSerializable(c)) { result = (Paint) stream.readObject(); } else if (c.equals(GradientPaint.class)) { final float x1 = stream.readFloat(); final float y1 = stream.readFloat(); final Color c1 = (Color) stream.readObject(); final float x2 = stream.readFloat(); final float y2 = stream.readFloat(); final Color c2 = (Color) stream.readObject(); final boolean isCyclic = stream.readBoolean(); result = new GradientPaint(x1, y1, c1, x2, y2, c2, isCyclic); } } return result; } /** * Serialises a Paint object. * * @param paint the paint object (null permitted). * @param stream the output stream (null not permitted). * * @throws IOException if there is an I/O error. */ public static void writePaint(final Paint paint, final ObjectOutputStream stream) throws IOException { if (stream == null) { throw new IllegalArgumentException("Null 'stream' argument."); } if (paint != null) { stream.writeBoolean(false); stream.writeObject(paint.getClass()); if (paint instanceof Serializable) { stream.writeObject(paint); } else if (paint instanceof GradientPaint) { final GradientPaint gp = (GradientPaint) paint; stream.writeFloat((float) gp.getPoint1().getX()); stream.writeFloat((float) gp.getPoint1().getY()); stream.writeObject(gp.getColor1()); stream.writeFloat((float) gp.getPoint2().getX()); stream.writeFloat((float) gp.getPoint2().getY()); stream.writeObject(gp.getColor2()); stream.writeBoolean(gp.isCyclic()); } } else { stream.writeBoolean(true); } } /** * Reads a Stroke object that has been serialised by the * {@link SerialUtilities#writeStroke(Stroke, ObjectOutputStream)} method. * * @param stream the input stream (null not permitted). * * @return The stroke object (possibly null). * * @throws IOException if there is an I/O problem. * @throws ClassNotFoundException if there is a problem loading a class. */ public static Stroke readStroke(final ObjectInputStream stream) throws IOException, ClassNotFoundException { if (stream == null) { throw new IllegalArgumentException("Null 'stream' argument."); } Stroke result = null; final boolean isNull = stream.readBoolean(); if (!isNull) { final Class c = (Class) stream.readObject(); if (c.equals(BasicStroke.class)) { final float width = stream.readFloat(); final int cap = stream.readInt(); final int join = stream.readInt(); final float miterLimit = stream.readFloat(); final float[] dash = (float[]) stream.readObject(); final float dashPhase = stream.readFloat(); result = new BasicStroke( width, cap, join, miterLimit, dash, dashPhase ); } else { result = (Stroke) stream.readObject(); } } return result; } /** * Serialises a Stroke object. This code handles the * BasicStroke class which is the only Stroke * implementation provided by the JDK (and isn't directly * Serializable). * * @param stroke the stroke object (null permitted). * @param stream the output stream (null not permitted). * * @throws IOException if there is an I/O error. */ public static void writeStroke(final Stroke stroke, final ObjectOutputStream stream) throws IOException { if (stream == null) { throw new IllegalArgumentException("Null 'stream' argument."); } if (stroke != null) { stream.writeBoolean(false); if (stroke instanceof BasicStroke) { final BasicStroke s = (BasicStroke) stroke; stream.writeObject(BasicStroke.class); stream.writeFloat(s.getLineWidth()); stream.writeInt(s.getEndCap()); stream.writeInt(s.getLineJoin()); stream.writeFloat(s.getMiterLimit()); stream.writeObject(s.getDashArray()); stream.writeFloat(s.getDashPhase()); } else { stream.writeObject(stroke.getClass()); stream.writeObject(stroke); } } else { stream.writeBoolean(true); } } /** * Reads a Shape object that has been serialised by the * {@link #writeShape(Shape, ObjectOutputStream)} method. * * @param stream the input stream (null not permitted). * * @return The shape object (possibly null). * * @throws IOException if there is an I/O problem. * @throws ClassNotFoundException if there is a problem loading a class. */ public static Shape readShape(final ObjectInputStream stream) throws IOException, ClassNotFoundException { if (stream == null) { throw new IllegalArgumentException("Null 'stream' argument."); } Shape result = null; final boolean isNull = stream.readBoolean(); if (!isNull) { final Class c = (Class) stream.readObject(); if (c.equals(Line2D.class)) { final double x1 = stream.readDouble(); final double y1 = stream.readDouble(); final double x2 = stream.readDouble(); final double y2 = stream.readDouble(); result = new Line2D.Double(x1, y1, x2, y2); } else if (c.equals(Rectangle2D.class)) { final double x = stream.readDouble(); final double y = stream.readDouble(); final double w = stream.readDouble(); final double h = stream.readDouble(); result = new Rectangle2D.Double(x, y, w, h); } else if (c.equals(Ellipse2D.class)) { final double x = stream.readDouble(); final double y = stream.readDouble(); final double w = stream.readDouble(); final double h = stream.readDouble(); result = new Ellipse2D.Double(x, y, w, h); } else if (c.equals(Arc2D.class)) { final double x = stream.readDouble(); final double y = stream.readDouble(); final double w = stream.readDouble(); final double h = stream.readDouble(); final double as = stream.readDouble(); // Angle Start final double ae = stream.readDouble(); // Angle Extent final int at = stream.readInt(); // Arc type result = new Arc2D.Double(x, y, w, h, as, ae, at); } else if (c.equals(GeneralPath.class)) { final GeneralPath gp = new GeneralPath(); final float[] args = new float[6]; boolean hasNext = stream.readBoolean(); while (!hasNext) { final int type = stream.readInt(); for (int i = 0; i < 6; i++) { args[i] = stream.readFloat(); } switch (type) { case PathIterator.SEG_MOVETO : gp.moveTo(args[0], args[1]); break; case PathIterator.SEG_LINETO : gp.lineTo(args[0], args[1]); break; case PathIterator.SEG_CUBICTO : gp.curveTo(args[0], args[1], args[2], args[3], args[4], args[5]); break; case PathIterator.SEG_QUADTO : gp.quadTo(args[0], args[1], args[2], args[3]); break; case PathIterator.SEG_CLOSE : gp.closePath(); break; default : throw new RuntimeException( "JFreeChart - No path exists"); } gp.setWindingRule(stream.readInt()); hasNext = stream.readBoolean(); } result = gp; } else { result = (Shape) stream.readObject(); } } return result; } /** * Serialises a Shape object. * * @param shape the shape object (null permitted). * @param stream the output stream (null not permitted). * * @throws IOException if there is an I/O error. */ public static void writeShape(final Shape shape, final ObjectOutputStream stream) throws IOException { if (stream == null) { throw new IllegalArgumentException("Null 'stream' argument."); } if (shape != null) { stream.writeBoolean(false); if (shape instanceof Line2D) { final Line2D line = (Line2D) shape; stream.writeObject(Line2D.class); stream.writeDouble(line.getX1()); stream.writeDouble(line.getY1()); stream.writeDouble(line.getX2()); stream.writeDouble(line.getY2()); } else if (shape instanceof Rectangle2D) { final Rectangle2D rectangle = (Rectangle2D) shape; stream.writeObject(Rectangle2D.class); stream.writeDouble(rectangle.getX()); stream.writeDouble(rectangle.getY()); stream.writeDouble(rectangle.getWidth()); stream.writeDouble(rectangle.getHeight()); } else if (shape instanceof Ellipse2D) { final Ellipse2D ellipse = (Ellipse2D) shape; stream.writeObject(Ellipse2D.class); stream.writeDouble(ellipse.getX()); stream.writeDouble(ellipse.getY()); stream.writeDouble(ellipse.getWidth()); stream.writeDouble(ellipse.getHeight()); } else if (shape instanceof Arc2D) { final Arc2D arc = (Arc2D) shape; stream.writeObject(Arc2D.class); stream.writeDouble(arc.getX()); stream.writeDouble(arc.getY()); stream.writeDouble(arc.getWidth()); stream.writeDouble(arc.getHeight()); stream.writeDouble(arc.getAngleStart()); stream.writeDouble(arc.getAngleExtent()); stream.writeInt(arc.getArcType()); } else if (shape instanceof GeneralPath) { stream.writeObject(GeneralPath.class); final PathIterator pi = shape.getPathIterator(null); final float[] args = new float[6]; stream.writeBoolean(pi.isDone()); while (!pi.isDone()) { final int type = pi.currentSegment(args); stream.writeInt(type); // TODO: could write this to only stream the values // required for the segment type for (int i = 0; i < 6; i++) { stream.writeFloat(args[i]); } stream.writeInt(pi.getWindingRule()); pi.next(); stream.writeBoolean(pi.isDone()); } } else { stream.writeObject(shape.getClass()); stream.writeObject(shape); } } else { stream.writeBoolean(true); } } /** * Reads a Point2D object that has been serialised by the * {@link #writePoint2D(Point2D, ObjectOutputStream)} method. * * @param stream the input stream (null not permitted). * * @return The point object (possibly null). * * @throws IOException if there is an I/O problem. */ public static Point2D readPoint2D(final ObjectInputStream stream) throws IOException { if (stream == null) { throw new IllegalArgumentException("Null 'stream' argument."); } Point2D result = null; final boolean isNull = stream.readBoolean(); if (!isNull) { final double x = stream.readDouble(); final double y = stream.readDouble(); result = new Point2D.Double(x, y); } return result; } /** * Serialises a Point2D object. * * @param p the point object (null permitted). * @param stream the output stream (null not permitted). * * @throws IOException if there is an I/O error. */ public static void writePoint2D(final Point2D p, final ObjectOutputStream stream) throws IOException { if (stream == null) { throw new IllegalArgumentException("Null 'stream' argument."); } if (p != null) { stream.writeBoolean(false); stream.writeDouble(p.getX()); stream.writeDouble(p.getY()); } else { stream.writeBoolean(true); } } /** * Reads a AttributedString object that has been serialised by * the {@link SerialUtilities#writeAttributedString(AttributedString, * ObjectOutputStream)} method. * * @param stream the input stream (null not permitted). * * @return The attributed string object (possibly null). * * @throws IOException if there is an I/O problem. * @throws ClassNotFoundException if there is a problem loading a class. */ public static AttributedString readAttributedString( ObjectInputStream stream) throws IOException, ClassNotFoundException { if (stream == null) { throw new IllegalArgumentException("Null 'stream' argument."); } AttributedString result = null; final boolean isNull = stream.readBoolean(); if (!isNull) { // read string and attributes then create result String plainStr = (String) stream.readObject(); result = new AttributedString(plainStr); char c = stream.readChar(); int start = 0; while (c != CharacterIterator.DONE) { int limit = stream.readInt(); Map atts = (Map) stream.readObject(); result.addAttributes(atts, start, limit); start = limit; c = stream.readChar(); } } return result; } /** * Serialises an AttributedString object. * * @param as the attributed string object (null permitted). * @param stream the output stream (null not permitted). * * @throws IOException if there is an I/O error. */ public static void writeAttributedString(AttributedString as, ObjectOutputStream stream) throws IOException { if (stream == null) { throw new IllegalArgumentException("Null 'stream' argument."); } if (as != null) { stream.writeBoolean(false); AttributedCharacterIterator aci = as.getIterator(); // build a plain string from aci // then write the string StringBuffer plainStr = new StringBuffer(); char current = aci.first(); while (current != CharacterIterator.DONE) { plainStr = plainStr.append(current); current = aci.next(); } stream.writeObject(plainStr.toString()); // then write the attributes and limits for each run current = aci.first(); int begin = aci.getBeginIndex(); while (current != CharacterIterator.DONE) { // write the current character - when the reader sees that this // is not CharacterIterator.DONE, it will know to read the // run limits and attributes stream.writeChar(current); // now write the limit, adjusted as if beginIndex is zero int limit = aci.getRunLimit(); stream.writeInt(limit - begin); // now write the attribute set Map atts = new HashMap(aci.getAttributes()); stream.writeObject(atts); current = aci.setIndex(limit); } // write a character that signals to the reader that all runs // are done... stream.writeChar(CharacterIterator.DONE); } else { // write a flag that indicates a null stream.writeBoolean(true); } } } jcommon-1.0.16/source/org/jfree/io/FileUtilities.java0000644000175000017500000000662511172030703022411 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * FileUtilities.java * ------------------ * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: FileUtilities.java,v 1.5 2005/10/18 13:16:02 mungady Exp $ * * Changes (from 5-Nov-2001) * ------------------------- * 05-Nov-2001 : Changed package to com.jrefinery.io.* (DG); * 04-Mar-2002 : Renamed Files.java --> FileUtilities.java (DG); * 10-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.io; import java.io.File; import java.util.StringTokenizer; /** * A class containing useful utility methods relating to files. * * @author David Gilbert */ public class FileUtilities { /** * To prevent unnecessary instantiation. */ private FileUtilities() { } /** * Returns a reference to a file with the specified name that is located * somewhere on the classpath. The code for this method is an adaptation * of code supplied by Dave Postill. * * @param name the filename. * * @return a reference to a file or null if no file could be found. */ public static File findFileOnClassPath(final String name) { final String classpath = System.getProperty("java.class.path"); final String pathSeparator = System.getProperty("path.separator"); final StringTokenizer tokenizer = new StringTokenizer(classpath, pathSeparator); while (tokenizer.hasMoreTokens()) { final String pathElement = tokenizer.nextToken(); final File directoryOrJar = new File(pathElement); final File absoluteDirectoryOrJar = directoryOrJar.getAbsoluteFile(); if (absoluteDirectoryOrJar.isFile()) { final File target = new File(absoluteDirectoryOrJar.getParent(), name); if (target.exists()) { return target; } } else { final File target = new File(directoryOrJar, name); if (target.exists()) { return target; } } } return null; } } jcommon-1.0.16/source/org/jfree/io/junit/0000755000175000017500000000000011351753320020121 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/io/junit/SerialUtilitiesTests.java0000644000175000017500000004071311172030703025121 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * SerialUtilitiesTests.java * ------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SerialUtilitiesTests.java,v 1.10 2008/09/01 16:00:42 mungady Exp $ * * Changes * ------- * 18-Sep-2003 : Version 1 (DG); * 26-Oct-2004 : Added checks for serializing Line2D instances (DG); * 04-Feb-2005 : Added tests for serializing Rectangle2D instances (DG); * */ package org.jfree.io.junit; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Paint; import java.awt.TexturePaint; import java.awt.font.TextAttribute; import java.awt.geom.Arc2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.text.AttributedString; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.io.SerialUtilities; import org.jfree.util.AttributedStringUtilities; import org.jfree.util.ShapeUtilities; /** * Tests for the {@link SerialUtilities} class. */ public class SerialUtilitiesTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(SerialUtilitiesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public SerialUtilitiesTests(final String name) { super(name); } /** * Tests the isSerializable(Class) method for some common cases. */ public void testIsSerializable() { assertTrue(SerialUtilities.isSerializable(Color.class)); assertTrue(SerialUtilities.isSerializable(ColorUIResource.class)); assertFalse(SerialUtilities.isSerializable(GradientPaint.class)); assertFalse(SerialUtilities.isSerializable(TexturePaint.class)); } /** * Serialize a Color and check that it can be deserialized * correctly. */ public void testColorSerialization() { final Paint p1 = Color.blue; Paint p2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writePaint(p1, out); out.close(); final ByteArrayInputStream bias = new ByteArrayInputStream( buffer.toByteArray()); final ObjectInputStream in = new ObjectInputStream(bias); p2 = SerialUtilities.readPaint(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(p1, p2); } /** * Serialize a ColorUIResource and check that it can be * deserialized correctly. */ public void testColorUIResourceSerialization() { Paint p1 = UIManager.getColor("Panel.background"); Paint p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writePaint(p1, out); out.close(); ByteArrayInputStream bias = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bias); p2 = SerialUtilities.readPaint(in); in.close(); } catch (Exception e) { fail(e.toString()); } assertEquals(p1, p2); } /** * Serialize a GradientPaint, restore it, and check for * equality. */ public void testGradientPaintSerialization() { final Paint p1 = new GradientPaint(0.0f, 0.0f, Color.blue, 100.0f, 200.0f, Color.red); Paint p2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writePaint(p1, out); out.close(); final ByteArrayInputStream bias = new ByteArrayInputStream( buffer.toByteArray()); final ObjectInputStream in = new ObjectInputStream(bias); p2 = SerialUtilities.readPaint(in); in.close(); } catch (Exception e) { e.printStackTrace(); } // we want to check that the two objects are equal, but can't rely on // GradientPaint's equals() method because it is just the default // method inherited from Object... final GradientPaint gp1 = (GradientPaint) p1; final GradientPaint gp2 = (GradientPaint) p2; assertEquals(gp1.getColor1(), gp2.getColor1()); assertEquals(gp1.getPoint1(), gp2.getPoint1()); assertEquals(gp1.getColor2(), gp2.getColor2()); assertEquals(gp1.getPoint2(), gp2.getPoint2()); assertEquals(gp1.isCyclic(), gp2.isCyclic()); } /** * Serialize a TexturePaint, restore it, and check for * equality. Since this class is not serializable, we expect null as the * result. */ public void testTexturePaintSerialization() { final Paint p1 = new TexturePaint( new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB), new Rectangle2D.Double(0, 0, 5, 5)); Paint p2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writePaint(p1, out); out.close(); final ByteArrayInputStream bias = new ByteArrayInputStream( buffer.toByteArray()); final ObjectInputStream in = new ObjectInputStream(bias); p2 = SerialUtilities.readPaint(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertNull(p2); } /** * Serialize a Line2D.Float instance, and check that it can be * deserialized correctly. */ public void testLine2DFloatSerialization() { Line2D l1 = new Line2D.Float(1.0f, 2.0f, 3.0f, 4.0f); Line2D l2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(l1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); l2 = (Line2D) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(l1, l2)); } /** * Serialize a Line2D.Double instance and check that it can be * deserialized correctly. */ public void testLine2DDoubleSerialization() { Line2D l1 = new Line2D.Double(1.0, 2.0, 3.0, 4.0); Line2D l2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(l1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); l2 = (Line2D) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(l1, l2)); } /** * Serialize a Rectangle2D.Float instance, and check that it * can be deserialized correctly. */ public void testRectangle2DFloatSerialization() { Rectangle2D r1 = new Rectangle2D.Float(1.0f, 2.0f, 3.0f, 4.0f); Rectangle2D r2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(r1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); r2 = (Rectangle2D) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(r1, r2)); } /** * Serialize a Rectangle2D.Double instance and check that it * can be deserialized correctly. */ public void testRectangle2DDoubleSerialization() { Rectangle2D r1 = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0); Rectangle2D r2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(r1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); r2 = (Rectangle2D) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(r1, r2)); } /** * Serialize an Arc2D.Float instance and check that it * can be deserialized correctly. */ public void testArc2DFloatSerialization() { Arc2D a1 = new Arc2D.Float( 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, Arc2D.PIE ); Arc2D a2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(a1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); a2 = (Arc2D) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(a1, a2)); } /** * Serialize an Arc2D.Double instance and check that it * can be deserialized correctly. */ public void testArc2DDoubleSerialization() { Arc2D a1 = new Arc2D.Double(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, Arc2D.PIE); Arc2D a2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(a1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); a2 = (Arc2D) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(a1, a2)); } /** * Some checks for the serialization of a GeneralPath instance. */ public void testGeneralPathSerialization() { GeneralPath g1 = new GeneralPath(); g1.moveTo(1.0f, 2.0f); g1.lineTo(3.0f, 4.0f); g1.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); g1.quadTo(1.0f, 2.0f, 3.0f, 4.0f); g1.closePath(); GeneralPath g2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeShape(g1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); g2 = (GeneralPath) SerialUtilities.readShape(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(ShapeUtilities.equal(g1, g2)); } /** * Tests the serialization of an {@link AttributedString}. */ public void testAttributedStringSerialization1() { AttributedString s1 = new AttributedString(""); AttributedString s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeAttributedString(s1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray() ); ObjectInputStream in = new ObjectInputStream(bais); s2 = SerialUtilities.readAttributedString(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(AttributedStringUtilities.equal(s1, s2)); } /** * Tests the serialization of an {@link AttributedString}. */ public void testAttributedStringSerialization2() { AttributedString s1 = new AttributedString("ABC"); AttributedString s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeAttributedString(s1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); s2 = SerialUtilities.readAttributedString(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(AttributedStringUtilities.equal(s1, s2)); } /** * Tests the serialization of an {@link AttributedString}. */ public void testAttributedStringSerialization3() { AttributedString s1 = new AttributedString("ABC"); s1.addAttribute(TextAttribute.LANGUAGE, "English"); AttributedString s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); SerialUtilities.writeAttributedString(s1, out); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream( buffer.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); s2 = SerialUtilities.readAttributedString(in); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(AttributedStringUtilities.equal(s1, s2)); } } jcommon-1.0.16/source/org/jfree/io/junit/package.html0000644000175000017500000000022011172030703022366 0ustar twernertwerner JUnit tests for the org.jfree.io package. jcommon-1.0.16/source/org/jfree/io/junit/IOPackageTests.java0000644000175000017500000000517111172030703023570 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * IOPackageTests.java * ------------------- * (C) Copyright 2003-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: IOPackageTests.java,v 1.3 2005/10/18 13:16:15 mungady Exp $ * * Changes: * -------- * 18-Sep-2003 : Version 1 (DG); * 27-Jan-2005 : Added main() method (DG); * */ package org.jfree.io.junit; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * A collection of tests for the org.jfree.io package. *

* These tests can be run using JUnit (http://www.junit.org). * */ public class IOPackageTests extends TestCase { /** * Returns a test suite to the JUnit test runner. * * @return the test suite. */ public static Test suite() { final TestSuite suite = new TestSuite("org.jfree.io"); suite.addTestSuite(SerialUtilitiesTests.class); suite.addTestSuite(IOUtilsTests.class); return suite; } /** * Constructs the test suite. * * @param name the suite name. */ public IOPackageTests(final String name) { super(name); } /** * Runs the test suite using the JUnit text-based runner. * * @param args ignored. */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } } jcommon-1.0.16/source/org/jfree/io/junit/IOUtilsTests.java0000644000175000017500000000674511172030703023345 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * IOUtilsTests.java * ----------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: IOUtilsTests.java,v 1.5 2007/11/02 17:50:35 taqua Exp $ * * Changes * ------- * 05-Jan-2004 : Initial version * */ package org.jfree.io.junit; import java.io.IOException; import java.net.URL; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.io.IOUtils; /** * Creates a new test case. */ public class IOUtilsTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(IOUtilsTests.class); } /** * Constructs a new set of tests. */ public IOUtilsTests() { super(); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public IOUtilsTests(final String name) { super(name); } /** * A test for the createRelativeURL() method. * * @throws IOException if there is an I/O problem. */ public void testCreateRelativeURL() throws IOException { final URL baseurl = new URL ("http://test.com:80/test/a/funny/directory/basefile.xml"); final URL testInput1 = new URL ("http://test.com:80/test/a/funny/directory/datafile.jpg"); String result = IOUtils.getInstance().createRelativeURL(testInput1, baseurl); assertEquals("datafile.jpg", result); assertEquals(testInput1, new URL (baseurl, result)); final URL testInput2 = new URL ("http://test.com:80/test/adatafile.jpg"); result = IOUtils.getInstance().createRelativeURL(testInput2, baseurl); assertEquals("../../../adatafile.jpg", result); assertEquals(testInput2, new URL (baseurl, result)); final URL testInput3 = new URL ("http://test.com:80/test/adatafile.jpg?query=test"); result = IOUtils.getInstance().createRelativeURL(testInput3, baseurl); assertEquals("../../../adatafile.jpg?query=test", result); assertEquals(testInput3, new URL (baseurl, result)); } } jcommon-1.0.16/source/org/jfree/JCommon.java0000644000175000017500000000515611172030703020567 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------ * JCommon.java * ------------ * (C) Copyright 2002-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: JCommon.java,v 1.5 2006/02/19 21:10:47 taqua Exp $ * * Changes * ------- * 28-Feb-2002 : Version 1 (DG); * 22-Mar-2002 : Changed version number to 0.6.0 (DG); * 25-Mar-2002 : Moved the project info details into a class so that the text can be localised * more easily (DG); * 04-Apr-2002 : Added Hari to contributors (DG); * 19-Apr-2002 : Added Sam (oldman) to contributors (DG); * 07-Jun-2002 : Added contributors (DG); * 24-Jun-2002 : Removed unnecessary imports (DG); * 27-Aug-2002 : Updated version number to 0.7.0 (DG); * */ package org.jfree; import org.jfree.ui.about.ProjectInfo; /** * This class contains static information about the JCommon class library. * * @author David Gilbert */ public final class JCommon { /** Information about the project. */ public static final ProjectInfo INFO = JCommonInfo.getInstance(); /** * Hidden constructor. */ private JCommon() { super(); } /** * Prints information about JCommon to standard output. * * @param args no arguments are honored. */ public static void main(final String[] args) { System.out.println(JCommon.INFO.toString()); } } jcommon-1.0.16/source/org/jfree/demo/0000755000175000017500000000000011351753320017305 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/demo/TextBlockDemo.java0000644000175000017500000000572411172030703022656 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * TextBlockDemo.java * ------------------ * (C) Copyright 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextBlockDemo.java,v 1.4 2007/11/02 17:50:35 taqua Exp $ * * Changes * ------- * 07-Jan-2004 : Version 1 (DG); * */ package org.jfree.demo; import java.awt.Font; import javax.swing.JPanel; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; /** * A demo of the TextBlock class. * * @author David Gilbert */ public class TextBlockDemo extends ApplicationFrame { /** * Creates a new demo instance. * * @param title the frame title. */ public TextBlockDemo(final String title) { super(title); setContentPane(createContentPane()); } /** * Creates the content pane for the demo frame. * * @return The content pane. */ private JPanel createContentPane() { final JPanel content = new TextBlockPanel("This is some really long text that we will use " + "for testing purposes. You'll need to resize the window to see how the TextBlock " + "is dynamically updated. Also note what happens when there is a really long " + "word like ABCDEFGHIJKLMNOPQRSTUVWXYZ (OK, that's not really a word).", new Font("Serif", Font.PLAIN, 14)); return content; } /** * The starting point for the demo. * * @param args ignored. */ public static void main(final String[] args) { final TextBlockDemo demo = new TextBlockDemo("TextBlock Demo"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); } } jcommon-1.0.16/source/org/jfree/demo/DateChooserPanelDemo.java0000644000175000017500000000464711172030703024142 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * DateChooserPanelDemo.java * ------------------------- * (C) Copyright 2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: DateChooserPanelDemo.java,v 1.1 2005/11/02 14:11:22 mungady Exp $ * * Changes * ------- * 02-Nov-2005 : Version 1; * */ package org.jfree.demo; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.DateChooserPanel; import org.jfree.ui.RefineryUtilities; /** * A simple demo showing the {@link DateChooserPanel}. */ public class DateChooserPanelDemo extends ApplicationFrame { /** * Creates a new demo. * * @param title the frame title. */ public DateChooserPanelDemo(String title) { super(title); setContentPane(new DateChooserPanel()); } /** * Starting point for the demonstration application. * * @param args ignored. */ public static void main(String[] args) { DateChooserPanelDemo demo = new DateChooserPanelDemo( "DateChooserPanel Demo"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); } } jcommon-1.0.16/source/org/jfree/demo/package.html0000644000175000017500000000021711172030703021560 0ustar twernertwerner Demo code for the JCommon class library. jcommon-1.0.16/source/org/jfree/demo/DrawStringDemo.java0000644000175000017500000002676111172030703023047 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * DrawStringDemo.java * ------------------- * (C) Copyright 2003-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: DrawStringDemo.java,v 1.6 2008/09/10 09:14:22 mungady Exp $ * * Changes * ------- * 10-Jun-2003 : Version 1; * */ package org.jfree.demo; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTabbedPane; import javax.swing.SwingConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.FontChooserPanel; import org.jfree.ui.RefineryUtilities; import org.jfree.ui.TextAnchor; /** * A demo of some of the string drawing methods in the JCommon class library. */ public class DrawStringDemo extends ApplicationFrame implements ActionListener, ChangeListener { /** The alignment anchor for the first panel. */ private JComboBox combo1; /** The alignment anchor for the second panel. */ private JComboBox combo2; /** The rotation anchor for the second panel. */ private JComboBox combo3; /** A slider for the second panel - controls the angle of rotation. */ private JSlider slider; /** String panel 1. */ private DrawStringPanel drawStringPanel1; /** String panel 2. */ private DrawStringPanel drawStringPanel2; /** * Creates a new demo instance. * * @param title the frame title. */ public DrawStringDemo(final String title) { super(title); setContentPane(createContentPane()); } /** * Receives action events. * * @param event the event. */ public void actionPerformed(final ActionEvent event) { if (event.getActionCommand().equals("fontButton.clicked")) { displayFontDialog(); } if (event.getActionCommand().equals("combo1.changed")) { handleCombo1Change(); } if (event.getActionCommand().equals("combo2.changed")) { handleCombo2Change(); } if (event.getActionCommand().equals("combo3.changed")) { handleCombo3Change(); } } /** * Receives change event notification from the slider. * * @param event the event. */ public void stateChanged(ChangeEvent event) { int r = this.slider.getValue(); double angle = Math.PI * 2.0 * (r / 360.0); this.drawStringPanel2.setAngle(angle); this.drawStringPanel2.invalidate(); this.drawStringPanel2.repaint(); } /** * Updates the display when combo 1 is updated. */ private void handleCombo1Change() { final String text = this.combo1.getSelectedItem().toString(); this.drawStringPanel1.setAnchor(convertStringToAnchor(text)); this.drawStringPanel1.invalidate(); this.drawStringPanel1.repaint(); } /** * Updates the display when combo 2 is updated. */ private void handleCombo2Change() { final String text = this.combo2.getSelectedItem().toString(); this.drawStringPanel2.setAnchor(convertStringToAnchor(text)); this.drawStringPanel2.invalidate(); this.drawStringPanel2.repaint(); } /** * Updates the display when combo 3 is updated. */ private void handleCombo3Change() { final String text = this.combo3.getSelectedItem().toString(); this.drawStringPanel2.setRotationAnchor(convertStringToAnchor(text)); this.drawStringPanel2.invalidate(); this.drawStringPanel2.repaint(); } /** * Creates the content pane for the demo frame. * * @return The content pane. */ private JPanel createContentPane() { final JPanel content = new JPanel(new BorderLayout()); final JTabbedPane tabs = new JTabbedPane(); tabs.add("Alignment", createTab1Content()); tabs.add("Rotation", createTab2Content()); content.add(tabs); return content; } /** * Creates the content for tab 1. * * @return The content panel. */ private JPanel createTab1Content() { final JPanel content = new JPanel(new BorderLayout()); this.combo1 = new JComboBox(); this.combo1.setActionCommand("combo1.changed"); populateTextAnchorCombo(this.combo1); this.combo1.addActionListener(this); final JPanel controls = new JPanel(); controls.add(this.combo1); final JButton fontButton = new JButton("Select Font..."); fontButton.setActionCommand("fontButton.clicked"); fontButton.addActionListener(this); controls.add(fontButton); content.add(controls, BorderLayout.NORTH); this.drawStringPanel1 = new DrawStringPanel("0123456789", false); content.add(this.drawStringPanel1); return content; } /** * Creates the content for tab 2. * * @return The content panel. */ private JPanel createTab2Content() { JPanel content = new JPanel(new BorderLayout()); JPanel controls = new JPanel(); controls.add(new JLabel("Text anchor: ")); this.combo2 = new JComboBox(); populateTextAnchorCombo(this.combo2); this.combo2.setActionCommand("combo2.changed"); this.combo2.addActionListener(this); controls.add(this.combo2); controls.add(new JLabel("Rotation anchor: ")); this.combo3 = new JComboBox(); populateTextAnchorCombo(this.combo3); this.combo3.setActionCommand("combo3.changed"); this.combo3.addActionListener(this); controls.add(this.combo3); this.slider = new JSlider(SwingConstants.VERTICAL, 0, 360, 0); this.slider.setMajorTickSpacing(45); this.slider.setMinorTickSpacing(5); this.slider.setPaintLabels(true); this.slider.setPaintTicks(true); this.slider.setPaintTrack(true); this.slider.addChangeListener(this); content.add(controls, BorderLayout.NORTH); content.add(this.slider, BorderLayout.WEST); this.drawStringPanel2 = new DrawStringPanel("Rotated Text", true); content.add(this.drawStringPanel2); return content; } /** * Displays a primitive font chooser dialog to allow the user to change the font. */ private void displayFontDialog() { final FontChooserPanel panel = new FontChooserPanel(this.drawStringPanel1.getFont()); final int result = JOptionPane.showConfirmDialog(this, panel, "Font Selection", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { this.drawStringPanel1.setFont(panel.getSelectedFont()); this.drawStringPanel2.setFont(panel.getSelectedFont()); } } /** * Populates a combo box with the available {@link TextAnchor} options. * * @param combo the combo box. */ private void populateTextAnchorCombo(final JComboBox combo) { combo.addItem("TextAnchor.TOP_LEFT"); combo.addItem("TextAnchor.TOP_CENTER"); combo.addItem("TextAnchor.TOP_RIGHT"); combo.addItem("TextAnchor.HALF_ASCENT_LEFT"); combo.addItem("TextAnchor.HALF_ASCENT_CENTER"); combo.addItem("TextAnchor.HALF_ASCENT_RIGHT"); combo.addItem("TextAnchor.CENTER_LEFT"); combo.addItem("TextAnchor.CENTER"); combo.addItem("TextAnchor.CENTER_RIGHT"); combo.addItem("TextAnchor.BASELINE_LEFT"); combo.addItem("TextAnchor.BASELINE_CENTER"); combo.addItem("TextAnchor.BASELINE_RIGHT"); combo.addItem("TextAnchor.BOTTOM_LEFT"); combo.addItem("TextAnchor.BOTTOM_CENTER"); combo.addItem("TextAnchor.BOTTOM_RIGHT"); } /** * Converts a string to a corresponding {@link TextAnchor} instance. * * @param text the text. * * @return The anchor. */ private TextAnchor convertStringToAnchor(final String text) { if (text.equals("TextAnchor.TOP_LEFT")) { return TextAnchor.TOP_LEFT; } else if (text.equals("TextAnchor.TOP_CENTER")) { return TextAnchor.TOP_CENTER; } else if (text.equals("TextAnchor.TOP_RIGHT")) { return TextAnchor.TOP_RIGHT; } else if (text.equals("TextAnchor.CENTER_LEFT")) { return TextAnchor.CENTER_LEFT; } else if (text.equals("TextAnchor.CENTER")) { return TextAnchor.CENTER; } else if (text.equals("TextAnchor.CENTER_RIGHT")) { return TextAnchor.CENTER_RIGHT; } else if (text.equals("TextAnchor.HALF_ASCENT_LEFT")) { return TextAnchor.HALF_ASCENT_LEFT; } else if (text.equals("TextAnchor.HALF_ASCENT_CENTER")) { return TextAnchor.HALF_ASCENT_CENTER; } else if (text.equals("TextAnchor.HALF_ASCENT_RIGHT")) { return TextAnchor.HALF_ASCENT_RIGHT; } else if (text.equals("TextAnchor.BASELINE_LEFT")) { return TextAnchor.BASELINE_LEFT; } else if (text.equals("TextAnchor.BASELINE_CENTER")) { return TextAnchor.BASELINE_CENTER; } else if (text.equals("TextAnchor.BASELINE_RIGHT")) { return TextAnchor.BASELINE_RIGHT; } else if (text.equals("TextAnchor.BOTTOM_LEFT")) { return TextAnchor.BOTTOM_LEFT; } else if (text.equals("TextAnchor.BOTTOM_CENTER")) { return TextAnchor.BOTTOM_CENTER; } else if (text.equals("TextAnchor.BOTTOM_RIGHT")) { return TextAnchor.BOTTOM_RIGHT; } else { return null; } } /** * The starting point for the demo. * * @param args ignored. */ public static void main(final String[] args) { final DrawStringDemo demo = new DrawStringDemo("DrawString Demo"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); } } jcommon-1.0.16/source/org/jfree/demo/DrawStringPanel.java0000644000175000017500000001234711172030703023215 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * DrawStringPanel.java * -------------------- * (C) Copyright 2003, 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: DrawStringPanel.java,v 1.6 2007/11/02 17:50:35 taqua Exp $ * * Changes * ------- * 10-Jun-2003 : Version 1; * 30-Sep-2004 : Moved drawRotatedString() from RefineryUtilities --> TextUtilities (DG); * */ package org.jfree.demo; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import javax.swing.JPanel; import org.jfree.text.TextUtilities; import org.jfree.ui.TextAnchor; /** * A panel used by the {@link DrawStringDemo} class. * * @author David Gilbert */ public class DrawStringPanel extends JPanel { /** The preferred size for the panel. */ private static final Dimension PREFERRED_SIZE = new Dimension(500, 300); /** Is the text rotated. */ private boolean rotate; /** The text to display. */ private String text = "Hello World"; /** The text anchor. */ private TextAnchor anchor = TextAnchor.TOP_LEFT; /** The rotation anchor. */ private TextAnchor rotationAnchor = TextAnchor.TOP_LEFT; /** The font. */ private Font font = new Font("Serif", Font.PLAIN, 12); /** The rotation angle. */ private double angle; /** * Creates a new panel. * * @param text the text. * @param rotate a flag that controls whether or not the text is rotated. */ public DrawStringPanel(final String text, final boolean rotate) { this.text = text; this.rotate = rotate; } /** * Returns the preferred size for the panel. * * @return The preferred size. */ public Dimension getPreferredSize() { return PREFERRED_SIZE; } /** * Sets the text anchor. * * @param anchor the text anchor. */ public void setAnchor(final TextAnchor anchor) { this.anchor = anchor; } /** * Sets the rotation anchor. * * @param anchor the rotation anchor. */ public void setRotationAnchor(final TextAnchor anchor) { this.rotationAnchor = anchor; } /** * Sets the rotation angle. * * @param angle the rotation angle. */ public void setAngle(final double angle) { this.angle = angle; } /** * Returns the font. * * @return The font. */ public Font getFont() { return this.font; } /** * Sets the font. * * @param font the font. */ public void setFont(final Font font) { this.font = font; } /** * Paints the panel. * * @param g the graphics device. */ public void paintComponent(final Graphics g) { super.paintComponent(g); final Graphics2D g2 = (Graphics2D) g; final Dimension size = getSize(); final Insets insets = getInsets(); final Rectangle2D available = new Rectangle2D.Double( insets.left, insets.top, size.getWidth() - insets.left - insets.right, size.getHeight() - insets.top - insets.bottom ); final double x = available.getCenterX(); final double y = available.getCenterY(); final Line2D line1 = new Line2D.Double(x - 2.0, y + 2.0, x + 2.0, y - 2.0); final Line2D line2 = new Line2D.Double(x - 2.0, y - 2.0, x + 2.0, y + 2.0); g2.setPaint(Color.red); g2.draw(line1); g2.draw(line2); g2.setFont(this.font); g2.setPaint(Color.black); if (this.rotate) { TextUtilities.drawRotatedString( this.text, g2, (float) x, (float) y, this.anchor, this.angle, this.rotationAnchor ); } else { TextUtilities.drawAlignedString(this.text, g2, (float) x, (float) y, this.anchor); } } } jcommon-1.0.16/source/org/jfree/demo/TextBlockPanel.java0000644000175000017500000000771411172030703023032 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * TextBlockPanel.java * ------------------- * (C) Copyright 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextBlockPanel.java,v 1.4 2007/11/02 17:50:35 taqua Exp $ * * Changes * ------- * 07-Jan-2004 : Version 1; * */ package org.jfree.demo; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.geom.Rectangle2D; import javax.swing.JPanel; import org.jfree.text.G2TextMeasurer; import org.jfree.text.TextBlock; import org.jfree.text.TextBlockAnchor; import org.jfree.text.TextUtilities; /** * A panel used by the {@link DrawStringDemo} class. * * @author David Gilbert */ public class TextBlockPanel extends JPanel { /** The preferred size for the panel. */ private static final Dimension PREFERRED_SIZE = new Dimension(500, 300); /** The text to display. */ private String text; /** The font to use. */ private Font font; /** * Creates a new panel. * * @param text the text. * @param font the font. */ public TextBlockPanel(final String text, final Font font) { this.text = text; this.font = font; } /** * Returns the preferred size for the panel. * * @return The preferred size. */ public Dimension getPreferredSize() { return PREFERRED_SIZE; } /** * Returns the font. * * @return The font. */ public Font getFont() { return this.font; } /** * Sets the font. * * @param font the font. */ public void setFont(final Font font) { this.font = font; } /** * Paints the panel. * * @param g the graphics device. */ public void paintComponent(final Graphics g) { super.paintComponent(g); final Graphics2D g2 = (Graphics2D) g; final Dimension size = getSize(); final Insets insets = getInsets(); final Rectangle2D available = new Rectangle2D.Double(insets.left, insets.top, size.getWidth() - insets.left - insets.right, size.getHeight() - insets.top - insets.bottom); final double x = available.getX(); final double y = available.getY(); final float width = (float) available.getWidth(); final TextBlock block = TextUtilities.createTextBlock( this.text, this.font, Color.black, width, new G2TextMeasurer(g2) ); g2.setPaint(Color.black); block.draw(g2, (float) x, (float) y, TextBlockAnchor.TOP_LEFT, 0.0f, 0.0f, 0.0); } } jcommon-1.0.16/source/org/jfree/date/0000755000175000017500000000000011351753320017276 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/date/DayOfWeekInMonthRule.java0000644000175000017500000001243611172030703024104 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * DayOfWeekInMonthRule.java * ------------------------- * (C) Copyright 2000-2003, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: DayOfWeekInMonthRule.java,v 1.5 2005/11/16 15:58:40 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.date.*; * 03-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 01-Jun-2005 : Removed the explicit clonable declaration, it is declared * in the super class. */ package org.jfree.date; /** * An annual date rule that specifies the nth day of the week in a given month * (for example, the third Wednesday in June, or the last Friday in November). * * @author David Gilbert */ public class DayOfWeekInMonthRule extends AnnualDateRule { /** FIRST, SECOND, THIRD, FOURTH or LAST. */ private int count; /** The day of the week (SerialDate.MONDAY, SerialDate.TUESDAY...). */ private int dayOfWeek; /** The month (1 to 12, or SerialDate.JANUARY, SerialDate.FEBRUARY...). */ private int month; /** * Default constructor: builds a rule for the first Monday in January by default. */ public DayOfWeekInMonthRule() { this(1, SerialDate.MONDAY, MonthConstants.JANUARY); } /** * Standard constructor: builds a rule with the specified attributes. * * @param count one of: FIRST, SECOND, THIRD, FOURTH or LAST. * @param dayOfWeek the day-of-the-week (SerialDate.MONDAY, SerialDate.TUESDAY, etc.). * @param month the month (SerialDate.JANUARY, SerialDate.FEBRUARY, etc.). */ public DayOfWeekInMonthRule(final int count, final int dayOfWeek, final int month) { this.count = count; this.dayOfWeek = dayOfWeek; this.month = month; } /** * Returns the 'count' for this rule (one of FIRST, SECOND, THIRD, FOURTH and LAST). * * @return the 'count'. */ public int getCount() { return this.count; } /** * Sets the 'count' for this rule (one of FIRST, SECOND, THIRD, FOURTH and LAST). * * @param count the 'count'. */ public void setCount(final int count) { this.count = count; } /** * Returns the day-of-the-week for this rule (SerialDate.MONDAY, SerialDate.TUESDAY, etc.). * * @return the day-of-the-week. */ public int getDayOfWeek() { return this.dayOfWeek; } /** * Sets the day-of-the-week for this rule. * * @param dayOfWeek the day-of-the-week. */ public void setDayOfWeek(final int dayOfWeek) { this.dayOfWeek = dayOfWeek; } /** * Returns the month for this rule. * * @return the month. */ public int getMonth() { return this.month; } /** * Sets the month for this rule. * * @param month the month (SerialDate.JANUARY, SerialDate.FEBRUARY, etc.). */ public void setMonth(final int month) { this.month = month; } /** * Return the date for this rule, given the year. * * @param year the year. * * @return the date generated by the rule for the given year. */ public SerialDate getDate(final int year) { SerialDate result; if (this.count != SerialDate.LAST_WEEK_IN_MONTH) { // start at the beginning of the month result = SerialDate.createInstance(1, this.month, year); while (result.getDayOfWeek() != this.dayOfWeek) { result = SerialDate.addDays(1, result); } result = SerialDate.addDays(7 * (this.count - 1), result); } else { // start at the end of the month and work backwards... result = SerialDate.createInstance(1, this.month, year); result = result.getEndOfCurrentMonth(result); while (result.getDayOfWeek() != this.dayOfWeek) { result = SerialDate.addDays(-1, result); } } return result; } } jcommon-1.0.16/source/org/jfree/date/AnnualDateRule.java0000644000175000017500000000541611172030703023005 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * AnnualDateRule.java * ------------------- * (C) Copyright 2000-2003, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: AnnualDateRule.java,v 1.4 2005/11/16 15:58:40 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.date.* (DG); * 12-Nov-2001 : Javadoc comments updated (DG); * 03-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.date; /** * The base class for all 'annual' date rules: that is, rules for generating * one date for any given year. *

* One example is Easter Sunday (which can be calculated using published algorithms). * * @author David Gilbert */ public abstract class AnnualDateRule implements Cloneable { /** * Default constructor. */ protected AnnualDateRule() { } /** * Returns the date for this rule, given the year. * * @param year the year (1900 <= year <= 9999). * * @return the date for this rule, given the year. */ public abstract SerialDate getDate(int year); /** * Returns a clone of the rule. *

* You should refer to the documentation of the clone() method in each * subclass for exact details. * * @return a clone of the rule. * * @throws CloneNotSupportedException if the rule is not clonable. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } } jcommon-1.0.16/source/org/jfree/date/SerialDate.java0000644000175000017500000010006211172030703022147 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * SerialDate.java * --------------- * (C) Copyright 2001-2006, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SerialDate.java,v 1.8 2006/08/29 13:44:16 mungady Exp $ * * Changes (from 11-Oct-2001) * -------------------------- * 11-Oct-2001 : Re-organised the class and moved it to new package * com.jrefinery.date (DG); * 05-Nov-2001 : Added a getDescription() method, and eliminated NotableDate * class (DG); * 12-Nov-2001 : IBD requires setDescription() method, now that NotableDate * class is gone (DG); Changed getPreviousDayOfWeek(), * getFollowingDayOfWeek() and getNearestDayOfWeek() to correct * bugs (DG); * 05-Dec-2001 : Fixed bug in SpreadsheetDate class (DG); * 29-May-2002 : Moved the month constants into a separate interface * (MonthConstants) (DG); * 27-Aug-2002 : Fixed bug in addMonths() method, thanks to N???levka Petr (DG); * 03-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 13-Mar-2003 : Implemented Serializable (DG); * 29-May-2003 : Fixed bug in addMonths method (DG); * 04-Sep-2003 : Implemented Comparable. Updated the isInRange javadocs (DG); * 05-Jan-2005 : Fixed bug in addYears() method (1096282) (DG); * */ package org.jfree.date; import java.io.Serializable; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; /** * An abstract class that defines our requirements for manipulating dates, * without tying down a particular implementation. *

* Requirement 1 : match at least what Excel does for dates; * Requirement 2 : the date represented by the class is immutable; *

* Why not just use java.util.Date? We will, when it makes sense. At times, * java.util.Date can be *too* precise - it represents an instant in time, * accurate to 1/1000th of a second (with the date itself depending on the * time-zone). Sometimes we just want to represent a particular day (e.g. 21 * January 2015) without concerning ourselves about the time of day, or the * time-zone, or anything else. That's what we've defined SerialDate for. *

* You can call getInstance() to get a concrete subclass of SerialDate, * without worrying about the exact implementation. * * @author David Gilbert */ public abstract class SerialDate implements Comparable, Serializable, MonthConstants { /** For serialization. */ private static final long serialVersionUID = -293716040467423637L; /** Date format symbols. */ public static final DateFormatSymbols DATE_FORMAT_SYMBOLS = new SimpleDateFormat().getDateFormatSymbols(); /** The serial number for 1 January 1900. */ public static final int SERIAL_LOWER_BOUND = 2; /** The serial number for 31 December 9999. */ public static final int SERIAL_UPPER_BOUND = 2958465; /** The lowest year value supported by this date format. */ public static final int MINIMUM_YEAR_SUPPORTED = 1900; /** The highest year value supported by this date format. */ public static final int MAXIMUM_YEAR_SUPPORTED = 9999; /** Useful constant for Monday. Equivalent to java.util.Calendar.MONDAY. */ public static final int MONDAY = Calendar.MONDAY; /** * Useful constant for Tuesday. Equivalent to java.util.Calendar.TUESDAY. */ public static final int TUESDAY = Calendar.TUESDAY; /** * Useful constant for Wednesday. Equivalent to * java.util.Calendar.WEDNESDAY. */ public static final int WEDNESDAY = Calendar.WEDNESDAY; /** * Useful constant for Thrusday. Equivalent to java.util.Calendar.THURSDAY. */ public static final int THURSDAY = Calendar.THURSDAY; /** Useful constant for Friday. Equivalent to java.util.Calendar.FRIDAY. */ public static final int FRIDAY = Calendar.FRIDAY; /** * Useful constant for Saturday. Equivalent to java.util.Calendar.SATURDAY. */ public static final int SATURDAY = Calendar.SATURDAY; /** Useful constant for Sunday. Equivalent to java.util.Calendar.SUNDAY. */ public static final int SUNDAY = Calendar.SUNDAY; /** The number of days in each month in non leap years. */ static final int[] LAST_DAY_OF_MONTH = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /** The number of days in a (non-leap) year up to the end of each month. */ static final int[] AGGREGATE_DAYS_TO_END_OF_MONTH = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; /** The number of days in a year up to the end of the preceding month. */ static final int[] AGGREGATE_DAYS_TO_END_OF_PRECEDING_MONTH = {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; /** The number of days in a leap year up to the end of each month. */ static final int[] LEAP_YEAR_AGGREGATE_DAYS_TO_END_OF_MONTH = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}; /** * The number of days in a leap year up to the end of the preceding month. */ static final int[] LEAP_YEAR_AGGREGATE_DAYS_TO_END_OF_PRECEDING_MONTH = {0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}; /** A useful constant for referring to the first week in a month. */ public static final int FIRST_WEEK_IN_MONTH = 1; /** A useful constant for referring to the second week in a month. */ public static final int SECOND_WEEK_IN_MONTH = 2; /** A useful constant for referring to the third week in a month. */ public static final int THIRD_WEEK_IN_MONTH = 3; /** A useful constant for referring to the fourth week in a month. */ public static final int FOURTH_WEEK_IN_MONTH = 4; /** A useful constant for referring to the last week in a month. */ public static final int LAST_WEEK_IN_MONTH = 0; /** Useful range constant. */ public static final int INCLUDE_NONE = 0; /** Useful range constant. */ public static final int INCLUDE_FIRST = 1; /** Useful range constant. */ public static final int INCLUDE_SECOND = 2; /** Useful range constant. */ public static final int INCLUDE_BOTH = 3; /** * Useful constant for specifying a day of the week relative to a fixed * date. */ public static final int PRECEDING = -1; /** * Useful constant for specifying a day of the week relative to a fixed * date. */ public static final int NEAREST = 0; /** * Useful constant for specifying a day of the week relative to a fixed * date. */ public static final int FOLLOWING = 1; /** A description for the date. */ private String description; /** * Default constructor. */ protected SerialDate() { } /** * Returns true if the supplied integer code represents a * valid day-of-the-week, and false otherwise. * * @param code the code being checked for validity. * * @return true if the supplied integer code represents a * valid day-of-the-week, and false otherwise. */ public static boolean isValidWeekdayCode(final int code) { switch(code) { case SUNDAY: case MONDAY: case TUESDAY: case WEDNESDAY: case THURSDAY: case FRIDAY: case SATURDAY: return true; default: return false; } } /** * Converts the supplied string to a day of the week. * * @param s a string representing the day of the week. * * @return -1 if the string is not convertable, the day of * the week otherwise. */ public static int stringToWeekdayCode(String s) { final String[] shortWeekdayNames = DATE_FORMAT_SYMBOLS.getShortWeekdays(); final String[] weekDayNames = DATE_FORMAT_SYMBOLS.getWeekdays(); int result = -1; s = s.trim(); for (int i = 0; i < weekDayNames.length; i++) { if (s.equals(shortWeekdayNames[i])) { result = i; break; } if (s.equals(weekDayNames[i])) { result = i; break; } } return result; } /** * Returns a string representing the supplied day-of-the-week. *

* Need to find a better approach. * * @param weekday the day of the week. * * @return a string representing the supplied day-of-the-week. */ public static String weekdayCodeToString(final int weekday) { final String[] weekdays = DATE_FORMAT_SYMBOLS.getWeekdays(); return weekdays[weekday]; } /** * Returns an array of month names. * * @return an array of month names. */ public static String[] getMonths() { return getMonths(false); } /** * Returns an array of month names. * * @param shortened a flag indicating that shortened month names should * be returned. * * @return an array of month names. */ public static String[] getMonths(final boolean shortened) { if (shortened) { return DATE_FORMAT_SYMBOLS.getShortMonths(); } else { return DATE_FORMAT_SYMBOLS.getMonths(); } } /** * Returns true if the supplied integer code represents a valid month. * * @param code the code being checked for validity. * * @return true if the supplied integer code represents a * valid month. */ public static boolean isValidMonthCode(final int code) { switch(code) { case JANUARY: case FEBRUARY: case MARCH: case APRIL: case MAY: case JUNE: case JULY: case AUGUST: case SEPTEMBER: case OCTOBER: case NOVEMBER: case DECEMBER: return true; default: return false; } } /** * Returns the quarter for the specified month. * * @param code the month code (1-12). * * @return the quarter that the month belongs to. */ public static int monthCodeToQuarter(final int code) { switch(code) { case JANUARY: case FEBRUARY: case MARCH: return 1; case APRIL: case MAY: case JUNE: return 2; case JULY: case AUGUST: case SEPTEMBER: return 3; case OCTOBER: case NOVEMBER: case DECEMBER: return 4; default: throw new IllegalArgumentException( "SerialDate.monthCodeToQuarter: invalid month code."); } } /** * Returns a string representing the supplied month. *

* The string returned is the long form of the month name taken from the * default locale. * * @param month the month. * * @return a string representing the supplied month. */ public static String monthCodeToString(final int month) { return monthCodeToString(month, false); } /** * Returns a string representing the supplied month. *

* The string returned is the long or short form of the month name taken * from the default locale. * * @param month the month. * @param shortened if true return the abbreviation of the * month. * * @return a string representing the supplied month. */ public static String monthCodeToString(final int month, final boolean shortened) { // check arguments... if (!isValidMonthCode(month)) { throw new IllegalArgumentException( "SerialDate.monthCodeToString: month outside valid range."); } final String[] months; if (shortened) { months = DATE_FORMAT_SYMBOLS.getShortMonths(); } else { months = DATE_FORMAT_SYMBOLS.getMonths(); } return months[month - 1]; } /** * Converts a string to a month code. *

* This method will return one of the constants JANUARY, FEBRUARY, ..., * DECEMBER that corresponds to the string. If the string is not * recognised, this method returns -1. * * @param s the string to parse. * * @return -1 if the string is not parseable, the month of the * year otherwise. */ public static int stringToMonthCode(String s) { final String[] shortMonthNames = DATE_FORMAT_SYMBOLS.getShortMonths(); final String[] monthNames = DATE_FORMAT_SYMBOLS.getMonths(); int result = -1; s = s.trim(); // first try parsing the string as an integer (1-12)... try { result = Integer.parseInt(s); } catch (NumberFormatException e) { // suppress } // now search through the month names... if ((result < 1) || (result > 12)) { for (int i = 0; i < monthNames.length; i++) { if (s.equals(shortMonthNames[i])) { result = i + 1; break; } if (s.equals(monthNames[i])) { result = i + 1; break; } } } return result; } /** * Returns true if the supplied integer code represents a valid * week-in-the-month, and false otherwise. * * @param code the code being checked for validity. * @return true if the supplied integer code represents a * valid week-in-the-month. */ public static boolean isValidWeekInMonthCode(final int code) { switch(code) { case FIRST_WEEK_IN_MONTH: case SECOND_WEEK_IN_MONTH: case THIRD_WEEK_IN_MONTH: case FOURTH_WEEK_IN_MONTH: case LAST_WEEK_IN_MONTH: return true; default: return false; } } /** * Determines whether or not the specified year is a leap year. * * @param yyyy the year (in the range 1900 to 9999). * * @return true if the specified year is a leap year. */ public static boolean isLeapYear(final int yyyy) { if ((yyyy % 4) != 0) { return false; } else if ((yyyy % 400) == 0) { return true; } else if ((yyyy % 100) == 0) { return false; } else { return true; } } /** * Returns the number of leap years from 1900 to the specified year * INCLUSIVE. *

* Note that 1900 is not a leap year. * * @param yyyy the year (in the range 1900 to 9999). * * @return the number of leap years from 1900 to the specified year. */ public static int leapYearCount(final int yyyy) { final int leap4 = (yyyy - 1896) / 4; final int leap100 = (yyyy - 1800) / 100; final int leap400 = (yyyy - 1600) / 400; return leap4 - leap100 + leap400; } /** * Returns the number of the last day of the month, taking into account * leap years. * * @param month the month. * @param yyyy the year (in the range 1900 to 9999). * * @return the number of the last day of the month. */ public static int lastDayOfMonth(final int month, final int yyyy) { final int result = LAST_DAY_OF_MONTH[month]; if (month != FEBRUARY) { return result; } else if (isLeapYear(yyyy)) { return result + 1; } else { return result; } } /** * Creates a new date by adding the specified number of days to the base * date. * * @param days the number of days to add (can be negative). * @param base the base date. * * @return a new date. */ public static SerialDate addDays(final int days, final SerialDate base) { final int serialDayNumber = base.toSerial() + days; return SerialDate.createInstance(serialDayNumber); } /** * Creates a new date by adding the specified number of months to the base * date. *

* If the base date is close to the end of the month, the day on the result * may be adjusted slightly: 31 May + 1 month = 30 June. * * @param months the number of months to add (can be negative). * @param base the base date. * * @return a new date. */ public static SerialDate addMonths(final int months, final SerialDate base) { final int yy = (12 * base.getYYYY() + base.getMonth() + months - 1) / 12; final int mm = (12 * base.getYYYY() + base.getMonth() + months - 1) % 12 + 1; final int dd = Math.min( base.getDayOfMonth(), SerialDate.lastDayOfMonth(mm, yy) ); return SerialDate.createInstance(dd, mm, yy); } /** * Creates a new date by adding the specified number of years to the base * date. * * @param years the number of years to add (can be negative). * @param base the base date. * * @return A new date. */ public static SerialDate addYears(final int years, final SerialDate base) { final int baseY = base.getYYYY(); final int baseM = base.getMonth(); final int baseD = base.getDayOfMonth(); final int targetY = baseY + years; final int targetD = Math.min( baseD, SerialDate.lastDayOfMonth(baseM, targetY) ); return SerialDate.createInstance(targetD, baseM, targetY); } /** * Returns the latest date that falls on the specified day-of-the-week and * is BEFORE the base date. * * @param targetWeekday a code for the target day-of-the-week. * @param base the base date. * * @return the latest date that falls on the specified day-of-the-week and * is BEFORE the base date. */ public static SerialDate getPreviousDayOfWeek(final int targetWeekday, final SerialDate base) { // check arguments... if (!SerialDate.isValidWeekdayCode(targetWeekday)) { throw new IllegalArgumentException( "Invalid day-of-the-week code." ); } // find the date... final int adjust; final int baseDOW = base.getDayOfWeek(); if (baseDOW > targetWeekday) { adjust = Math.min(0, targetWeekday - baseDOW); } else { adjust = -7 + Math.max(0, targetWeekday - baseDOW); } return SerialDate.addDays(adjust, base); } /** * Returns the earliest date that falls on the specified day-of-the-week * and is AFTER the base date. * * @param targetWeekday a code for the target day-of-the-week. * @param base the base date. * * @return the earliest date that falls on the specified day-of-the-week * and is AFTER the base date. */ public static SerialDate getFollowingDayOfWeek(final int targetWeekday, final SerialDate base) { // check arguments... if (!SerialDate.isValidWeekdayCode(targetWeekday)) { throw new IllegalArgumentException( "Invalid day-of-the-week code." ); } // find the date... final int adjust; final int baseDOW = base.getDayOfWeek(); if (baseDOW > targetWeekday) { adjust = 7 + Math.min(0, targetWeekday - baseDOW); } else { adjust = Math.max(0, targetWeekday - baseDOW); } return SerialDate.addDays(adjust, base); } /** * Returns the date that falls on the specified day-of-the-week and is * CLOSEST to the base date. * * @param targetDOW a code for the target day-of-the-week. * @param base the base date. * * @return the date that falls on the specified day-of-the-week and is * CLOSEST to the base date. */ public static SerialDate getNearestDayOfWeek(final int targetDOW, final SerialDate base) { // check arguments... if (!SerialDate.isValidWeekdayCode(targetDOW)) { throw new IllegalArgumentException( "Invalid day-of-the-week code." ); } // find the date... final int baseDOW = base.getDayOfWeek(); int adjust = -Math.abs(targetDOW - baseDOW); if (adjust >= 4) { adjust = 7 - adjust; } if (adjust <= -4) { adjust = 7 + adjust; } return SerialDate.addDays(adjust, base); } /** * Rolls the date forward to the last day of the month. * * @param base the base date. * * @return a new serial date. */ public SerialDate getEndOfCurrentMonth(final SerialDate base) { final int last = SerialDate.lastDayOfMonth( base.getMonth(), base.getYYYY() ); return SerialDate.createInstance(last, base.getMonth(), base.getYYYY()); } /** * Returns a string corresponding to the week-in-the-month code. *

* Need to find a better approach. * * @param count an integer code representing the week-in-the-month. * * @return a string corresponding to the week-in-the-month code. */ public static String weekInMonthToString(final int count) { switch (count) { case SerialDate.FIRST_WEEK_IN_MONTH : return "First"; case SerialDate.SECOND_WEEK_IN_MONTH : return "Second"; case SerialDate.THIRD_WEEK_IN_MONTH : return "Third"; case SerialDate.FOURTH_WEEK_IN_MONTH : return "Fourth"; case SerialDate.LAST_WEEK_IN_MONTH : return "Last"; default : return "SerialDate.weekInMonthToString(): invalid code."; } } /** * Returns a string representing the supplied 'relative'. *

* Need to find a better approach. * * @param relative a constant representing the 'relative'. * * @return a string representing the supplied 'relative'. */ public static String relativeToString(final int relative) { switch (relative) { case SerialDate.PRECEDING : return "Preceding"; case SerialDate.NEAREST : return "Nearest"; case SerialDate.FOLLOWING : return "Following"; default : return "ERROR : Relative To String"; } } /** * Factory method that returns an instance of some concrete subclass of * {@link SerialDate}. * * @param day the day (1-31). * @param month the month (1-12). * @param yyyy the year (in the range 1900 to 9999). * * @return An instance of {@link SerialDate}. */ public static SerialDate createInstance(final int day, final int month, final int yyyy) { return new SpreadsheetDate(day, month, yyyy); } /** * Factory method that returns an instance of some concrete subclass of * {@link SerialDate}. * * @param serial the serial number for the day (1 January 1900 = 2). * * @return a instance of SerialDate. */ public static SerialDate createInstance(final int serial) { return new SpreadsheetDate(serial); } /** * Factory method that returns an instance of a subclass of SerialDate. * * @param date A Java date object. * * @return a instance of SerialDate. */ public static SerialDate createInstance(final java.util.Date date) { final GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); return new SpreadsheetDate(calendar.get(Calendar.DATE), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.YEAR)); } /** * Returns the serial number for the date, where 1 January 1900 = 2 (this * corresponds, almost, to the numbering system used in Microsoft Excel for * Windows and Lotus 1-2-3). * * @return the serial number for the date. */ public abstract int toSerial(); /** * Returns a java.util.Date. Since java.util.Date has more precision than * SerialDate, we need to define a convention for the 'time of day'. * * @return this as java.util.Date. */ public abstract java.util.Date toDate(); /** * Returns the description that is attached to the date. It is not * required that a date have a description, but for some applications it * is useful. * * @return The description (possibly null). */ public String getDescription() { return this.description; } /** * Sets the description for the date. * * @param description the description for this date (null * permitted). */ public void setDescription(final String description) { this.description = description; } /** * Converts the date to a string. * * @return a string representation of the date. */ public String toString() { return getDayOfMonth() + "-" + SerialDate.monthCodeToString(getMonth()) + "-" + getYYYY(); } /** * Returns the year (assume a valid range of 1900 to 9999). * * @return the year. */ public abstract int getYYYY(); /** * Returns the month (January = 1, February = 2, March = 3). * * @return the month of the year. */ public abstract int getMonth(); /** * Returns the day of the month. * * @return the day of the month. */ public abstract int getDayOfMonth(); /** * Returns the day of the week. * * @return the day of the week. */ public abstract int getDayOfWeek(); /** * Returns the difference (in days) between this date and the specified * 'other' date. *

* The result is positive if this date is after the 'other' date and * negative if it is before the 'other' date. * * @param other the date being compared to. * * @return the difference between this and the other date. */ public abstract int compare(SerialDate other); /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return true if this SerialDate represents the same date as * the specified SerialDate. */ public abstract boolean isOn(SerialDate other); /** * Returns true if this SerialDate represents an earlier date compared to * the specified SerialDate. * * @param other The date being compared to. * * @return true if this SerialDate represents an earlier date * compared to the specified SerialDate. */ public abstract boolean isBefore(SerialDate other); /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return true if this SerialDate represents the same date * as the specified SerialDate. */ public abstract boolean isOnOrBefore(SerialDate other); /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return true if this SerialDate represents the same date * as the specified SerialDate. */ public abstract boolean isAfter(SerialDate other); /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return true if this SerialDate represents the same date * as the specified SerialDate. */ public abstract boolean isOnOrAfter(SerialDate other); /** * Returns true if this {@link SerialDate} is within the * specified range (INCLUSIVE). The date order of d1 and d2 is not * important. * * @param d1 a boundary date for the range. * @param d2 the other boundary date for the range. * * @return A boolean. */ public abstract boolean isInRange(SerialDate d1, SerialDate d2); /** * Returns true if this {@link SerialDate} is within the * specified range (caller specifies whether or not the end-points are * included). The date order of d1 and d2 is not important. * * @param d1 a boundary date for the range. * @param d2 the other boundary date for the range. * @param include a code that controls whether or not the start and end * dates are included in the range. * * @return A boolean. */ public abstract boolean isInRange(SerialDate d1, SerialDate d2, int include); /** * Returns the latest date that falls on the specified day-of-the-week and * is BEFORE this date. * * @param targetDOW a code for the target day-of-the-week. * * @return the latest date that falls on the specified day-of-the-week and * is BEFORE this date. */ public SerialDate getPreviousDayOfWeek(final int targetDOW) { return getPreviousDayOfWeek(targetDOW, this); } /** * Returns the earliest date that falls on the specified day-of-the-week * and is AFTER this date. * * @param targetDOW a code for the target day-of-the-week. * * @return the earliest date that falls on the specified day-of-the-week * and is AFTER this date. */ public SerialDate getFollowingDayOfWeek(final int targetDOW) { return getFollowingDayOfWeek(targetDOW, this); } /** * Returns the nearest date that falls on the specified day-of-the-week. * * @param targetDOW a code for the target day-of-the-week. * * @return the nearest date that falls on the specified day-of-the-week. */ public SerialDate getNearestDayOfWeek(final int targetDOW) { return getNearestDayOfWeek(targetDOW, this); } } jcommon-1.0.16/source/org/jfree/date/package.html0000644000175000017500000000016411172030703021552 0ustar twernertwerner Date classes. jcommon-1.0.16/source/org/jfree/date/SpreadsheetDate.java0000644000175000017500000003551611172030703023212 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * SpreadsheetDate.java * -------------------- * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SpreadsheetDate.java,v 1.10 2006/08/29 13:59:30 mungady Exp $ * * Changes * ------- * 11-Oct-2001 : Version 1 (DG); * 05-Nov-2001 : Added getDescription() and setDescription() methods (DG); * 12-Nov-2001 : Changed name from ExcelDate.java to SpreadsheetDate.java (DG); * Fixed a bug in calculating day, month and year from serial * number (DG); * 24-Jan-2002 : Fixed a bug in calculating the serial number from the day, * month and year. Thanks to Trevor Hills for the report (DG); * 29-May-2002 : Added equals(Object) method (SourceForge ID 558850) (DG); * 03-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 13-Mar-2003 : Implemented Serializable (DG); * 04-Sep-2003 : Completed isInRange() methods (DG); * 05-Sep-2003 : Implemented Comparable (DG); * 21-Oct-2003 : Added hashCode() method (DG); * 29-Aug-2006 : Removed redundant description attribute (DG); * */ package org.jfree.date; import java.util.Calendar; import java.util.Date; /** * Represents a date using an integer, in a similar fashion to the * implementation in Microsoft Excel. The range of dates supported is * 1-Jan-1900 to 31-Dec-9999. *

* Be aware that there is a deliberate bug in Excel that recognises the year * 1900 as a leap year when in fact it is not a leap year. You can find more * information on the Microsoft website in article Q181370: *

* http://support.microsoft.com/support/kb/articles/Q181/3/70.asp *

* Excel uses the convention that 1-Jan-1900 = 1. This class uses the * convention 1-Jan-1900 = 2. * The result is that the day number in this class will be different to the * Excel figure for January and February 1900...but then Excel adds in an extra * day (29-Feb-1900 which does not actually exist!) and from that point forward * the day numbers will match. * * @author David Gilbert */ public class SpreadsheetDate extends SerialDate { /** For serialization. */ private static final long serialVersionUID = -2039586705374454461L; /** * The day number (1-Jan-1900 = 2, 2-Jan-1900 = 3, ..., 31-Dec-9999 = * 2958465). */ private final int serial; /** The day of the month (1 to 28, 29, 30 or 31 depending on the month). */ private final int day; /** The month of the year (1 to 12). */ private final int month; /** The year (1900 to 9999). */ private final int year; /** * Creates a new date instance. * * @param day the day (in the range 1 to 28/29/30/31). * @param month the month (in the range 1 to 12). * @param year the year (in the range 1900 to 9999). */ public SpreadsheetDate(final int day, final int month, final int year) { if ((year >= 1900) && (year <= 9999)) { this.year = year; } else { throw new IllegalArgumentException( "The 'year' argument must be in range 1900 to 9999." ); } if ((month >= MonthConstants.JANUARY) && (month <= MonthConstants.DECEMBER)) { this.month = month; } else { throw new IllegalArgumentException( "The 'month' argument must be in the range 1 to 12." ); } if ((day >= 1) && (day <= SerialDate.lastDayOfMonth(month, year))) { this.day = day; } else { throw new IllegalArgumentException("Invalid 'day' argument."); } // the serial number needs to be synchronised with the day-month-year... this.serial = calcSerial(day, month, year); } /** * Standard constructor - creates a new date object representing the * specified day number (which should be in the range 2 to 2958465. * * @param serial the serial number for the day (range: 2 to 2958465). */ public SpreadsheetDate(final int serial) { if ((serial >= SERIAL_LOWER_BOUND) && (serial <= SERIAL_UPPER_BOUND)) { this.serial = serial; } else { throw new IllegalArgumentException( "SpreadsheetDate: Serial must be in range 2 to 2958465."); } // the day-month-year needs to be synchronised with the serial number... // get the year from the serial date final int days = this.serial - SERIAL_LOWER_BOUND; // overestimated because we ignored leap days final int overestimatedYYYY = 1900 + (days / 365); final int leaps = SerialDate.leapYearCount(overestimatedYYYY); final int nonleapdays = days - leaps; // underestimated because we overestimated years int underestimatedYYYY = 1900 + (nonleapdays / 365); if (underestimatedYYYY == overestimatedYYYY) { this.year = underestimatedYYYY; } else { int ss1 = calcSerial(1, 1, underestimatedYYYY); while (ss1 <= this.serial) { underestimatedYYYY = underestimatedYYYY + 1; ss1 = calcSerial(1, 1, underestimatedYYYY); } this.year = underestimatedYYYY - 1; } final int ss2 = calcSerial(1, 1, this.year); int[] daysToEndOfPrecedingMonth = AGGREGATE_DAYS_TO_END_OF_PRECEDING_MONTH; if (isLeapYear(this.year)) { daysToEndOfPrecedingMonth = LEAP_YEAR_AGGREGATE_DAYS_TO_END_OF_PRECEDING_MONTH; } // get the month from the serial date int mm = 1; int sss = ss2 + daysToEndOfPrecedingMonth[mm] - 1; while (sss < this.serial) { mm = mm + 1; sss = ss2 + daysToEndOfPrecedingMonth[mm] - 1; } this.month = mm - 1; // what's left is d(+1); this.day = this.serial - ss2 - daysToEndOfPrecedingMonth[this.month] + 1; } /** * Returns the serial number for the date, where 1 January 1900 = 2 * (this corresponds, almost, to the numbering system used in Microsoft * Excel for Windows and Lotus 1-2-3). * * @return The serial number of this date. */ public int toSerial() { return this.serial; } /** * Returns a java.util.Date equivalent to this date. * * @return The date. */ public Date toDate() { final Calendar calendar = Calendar.getInstance(); calendar.set(getYYYY(), getMonth() - 1, getDayOfMonth(), 0, 0, 0); return calendar.getTime(); } /** * Returns the year (assume a valid range of 1900 to 9999). * * @return The year. */ public int getYYYY() { return this.year; } /** * Returns the month (January = 1, February = 2, March = 3). * * @return The month of the year. */ public int getMonth() { return this.month; } /** * Returns the day of the month. * * @return The day of the month. */ public int getDayOfMonth() { return this.day; } /** * Returns a code representing the day of the week. *

* The codes are defined in the {@link SerialDate} class as: * SUNDAY, MONDAY, TUESDAY, * WEDNESDAY, THURSDAY, FRIDAY, and * SATURDAY. * * @return A code representing the day of the week. */ public int getDayOfWeek() { return (this.serial + 6) % 7 + 1; } /** * Tests the equality of this date with an arbitrary object. *

* This method will return true ONLY if the object is an instance of the * {@link SerialDate} base class, and it represents the same day as this * {@link SpreadsheetDate}. * * @param object the object to compare (null permitted). * * @return A boolean. */ public boolean equals(final Object object) { if (object instanceof SerialDate) { final SerialDate s = (SerialDate) object; return (s.toSerial() == this.toSerial()); } else { return false; } } /** * Returns a hash code for this object instance. * * @return A hash code. */ public int hashCode() { return toSerial(); } /** * Returns the difference (in days) between this date and the specified * 'other' date. * * @param other the date being compared to. * * @return The difference (in days) between this date and the specified * 'other' date. */ public int compare(final SerialDate other) { return this.serial - other.toSerial(); } /** * Implements the method required by the Comparable interface. * * @param other the other object (usually another SerialDate). * * @return A negative integer, zero, or a positive integer as this object * is less than, equal to, or greater than the specified object. */ public int compareTo(final Object other) { return compare((SerialDate) other); } /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return true if this SerialDate represents the same date as * the specified SerialDate. */ public boolean isOn(final SerialDate other) { return (this.serial == other.toSerial()); } /** * Returns true if this SerialDate represents an earlier date compared to * the specified SerialDate. * * @param other the date being compared to. * * @return true if this SerialDate represents an earlier date * compared to the specified SerialDate. */ public boolean isBefore(final SerialDate other) { return (this.serial < other.toSerial()); } /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return true if this SerialDate represents the same date * as the specified SerialDate. */ public boolean isOnOrBefore(final SerialDate other) { return (this.serial <= other.toSerial()); } /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return true if this SerialDate represents the same date * as the specified SerialDate. */ public boolean isAfter(final SerialDate other) { return (this.serial > other.toSerial()); } /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return true if this SerialDate represents the same date as * the specified SerialDate. */ public boolean isOnOrAfter(final SerialDate other) { return (this.serial >= other.toSerial()); } /** * Returns true if this {@link SerialDate} is within the * specified range (INCLUSIVE). The date order of d1 and d2 is not * important. * * @param d1 a boundary date for the range. * @param d2 the other boundary date for the range. * * @return A boolean. */ public boolean isInRange(final SerialDate d1, final SerialDate d2) { return isInRange(d1, d2, SerialDate.INCLUDE_BOTH); } /** * Returns true if this SerialDate is within the specified range (caller * specifies whether or not the end-points are included). The order of d1 * and d2 is not important. * * @param d1 one boundary date for the range. * @param d2 a second boundary date for the range. * @param include a code that controls whether or not the start and end * dates are included in the range. * * @return true if this SerialDate is within the specified * range. */ public boolean isInRange(final SerialDate d1, final SerialDate d2, final int include) { final int s1 = d1.toSerial(); final int s2 = d2.toSerial(); final int start = Math.min(s1, s2); final int end = Math.max(s1, s2); final int s = toSerial(); if (include == SerialDate.INCLUDE_BOTH) { return (s >= start && s <= end); } else if (include == SerialDate.INCLUDE_FIRST) { return (s >= start && s < end); } else if (include == SerialDate.INCLUDE_SECOND) { return (s > start && s <= end); } else { return (s > start && s < end); } } /** * Calculate the serial number from the day, month and year. *

* 1-Jan-1900 = 2. * * @param d the day. * @param m the month. * @param y the year. * * @return the serial number from the day, month and year. */ private int calcSerial(final int d, final int m, final int y) { final int yy = ((y - 1900) * 365) + SerialDate.leapYearCount(y - 1); int mm = SerialDate.AGGREGATE_DAYS_TO_END_OF_PRECEDING_MONTH[m]; if (m > MonthConstants.FEBRUARY) { if (SerialDate.isLeapYear(y)) { mm = mm + 1; } } final int dd = d; return yy + mm + dd + 1; } } jcommon-1.0.16/source/org/jfree/date/SerialDateUtilities.java0000644000175000017500000003153711172030703024055 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * SerialDateUtilities.java * ------------------------ * (C) Copyright 2001-2003, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SerialDateUtilities.java,v 1.6 2005/11/16 15:58:40 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.date.*; * 08-Dec-2001 : Dropped isLeapYear() method (DG); * 04-Mar-2002 : Renamed SerialDates.java --> SerialDateUtilities.java (DG); * 25-Jun-2002 : Fixed a bug in the dayCountActual() method (DG); * 03-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.date; import java.text.DateFormatSymbols; import java.util.Calendar; /** * A utility class that provides a number of useful methods (some static). * Many of these are used in the implementation of the day-count convention * classes. I recognise some limitations in this implementation: *

* [1] some of the methods assume that the default Calendar is a * GregorianCalendar (used mostly to determine leap years) - so the code * won’t work if some other Calendar is the default. I'm not sure how * to handle this properly? *

* [2] a whole bunch of static methods isn't very object-oriented - but I couldn't think of a good * way to extend the Date and Calendar classes to add the functions I required, * so static methods are doing the job for now. * * @author David Gilbert */ public class SerialDateUtilities { /** The default date format symbols. */ private DateFormatSymbols dateFormatSymbols; /** Strings representing the weekdays. */ private String[] weekdays; /** Strings representing the months. */ private String[] months; /** * Creates a new utility class for the default locale. */ public SerialDateUtilities() { this.dateFormatSymbols = new DateFormatSymbols(); this.weekdays = this.dateFormatSymbols.getWeekdays(); this.months = this.dateFormatSymbols.getMonths(); } /** * Returns an array of strings representing the days-of-the-week. * * @return an array of strings representing the days-of-the-week. */ public String[] getWeekdays() { return this.weekdays; } /** * Returns an array of strings representing the months. * * @return an array of strings representing the months. */ public String[] getMonths() { return this.months; } /** * Converts the specified string to a weekday, using the default locale. * * @param s a string representing the day-of-the-week. * * @return an integer representing the day-of-the-week. */ public int stringToWeekday(final String s) { if (s.equals(this.weekdays[Calendar.SATURDAY])) { return SerialDate.SATURDAY; } else if (s.equals(this.weekdays[Calendar.SUNDAY])) { return SerialDate.SUNDAY; } else if (s.equals(this.weekdays[Calendar.MONDAY])) { return SerialDate.MONDAY; } else if (s.equals(this.weekdays[Calendar.TUESDAY])) { return SerialDate.TUESDAY; } else if (s.equals(this.weekdays[Calendar.WEDNESDAY])) { return SerialDate.WEDNESDAY; } else if (s.equals(this.weekdays[Calendar.THURSDAY])) { return SerialDate.THURSDAY; } else { return SerialDate.FRIDAY; } } /** * Returns the actual number of days between two dates. * * @param start the start date. * @param end the end date. * * @return the number of days between the start date and the end date. */ public static int dayCountActual(final SerialDate start, final SerialDate end) { return end.compare(start); } /** * Returns the number of days between the specified start and end dates, * assuming that there are thirty days in every month (that is, * corresponding to the 30/360 day-count convention). *

* The method handles cases where the start date is before the end date (by * switching the dates and returning a negative result). * * @param start the start date. * @param end the end date. * * @return the number of days between the two dates, assuming the 30/360 day-count convention. */ public static int dayCount30(final SerialDate start, final SerialDate end) { final int d1; final int m1; final int y1; final int d2; final int m2; final int y2; if (start.isBefore(end)) { // check the order of the dates d1 = start.getDayOfMonth(); m1 = start.getMonth(); y1 = start.getYYYY(); d2 = end.getDayOfMonth(); m2 = end.getMonth(); y2 = end.getYYYY(); return 360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1); } else { return -dayCount30(end, start); } } /** * Returns the number of days between the specified start and end dates, * assuming that there are thirty days in every month, and applying the * ISDA adjustments (that is, corresponding to the 30/360 (ISDA) day-count * convention). *

* The method handles cases where the start date is before the end date (by * switching the dates around and returning a negative result). * * @param start the start date. * @param end the end date. * * @return The number of days between the two dates, assuming the 30/360 * (ISDA) day-count convention. */ public static int dayCount30ISDA(final SerialDate start, final SerialDate end) { int d1; final int m1; final int y1; int d2; final int m2; final int y2; if (start.isBefore(end)) { d1 = start.getDayOfMonth(); m1 = start.getMonth(); y1 = start.getYYYY(); if (d1 == 31) { // first ISDA adjustment d1 = 30; } d2 = end.getDayOfMonth(); m2 = end.getMonth(); y2 = end.getYYYY(); if ((d2 == 31) && (d1 == 30)) { // second ISDA adjustment d2 = 30; } return 360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1); } else if (start.isAfter(end)) { return -dayCount30ISDA(end, start); } else { return 0; } } /** * Returns the number of days between the specified start and end dates, * assuming that there are thirty days in every month, and applying the PSA * adjustments (that is, corresponding to the 30/360 (PSA) day-count convention). * The method handles cases where the start date is before the end date (by * switching the dates around and returning a negative result). * * @param start the start date. * @param end the end date. * * @return The number of days between the two dates, assuming the 30/360 * (PSA) day-count convention. */ public static int dayCount30PSA(final SerialDate start, final SerialDate end) { int d1; final int m1; final int y1; int d2; final int m2; final int y2; if (start.isOnOrBefore(end)) { // check the order of the dates d1 = start.getDayOfMonth(); m1 = start.getMonth(); y1 = start.getYYYY(); if (SerialDateUtilities.isLastDayOfFebruary(start)) { d1 = 30; } if ((d1 == 31) || SerialDateUtilities.isLastDayOfFebruary(start)) { // first PSA adjustment d1 = 30; } d2 = end.getDayOfMonth(); m2 = end.getMonth(); y2 = end.getYYYY(); if ((d2 == 31) && (d1 == 30)) { // second PSA adjustment d2 = 30; } return 360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1); } else { return -dayCount30PSA(end, start); } } /** * Returns the number of days between the specified start and end dates, * assuming that there are thirty days in every month, and applying the * European adjustment (that is, corresponding to the 30E/360 day-count * convention). *

* The method handles cases where the start date is before the end date (by * switching the dates around and returning a negative result). * * @param start the start date. * @param end the end date. * * @return the number of days between the two dates, assuming the 30E/360 * day-count convention. */ public static int dayCount30E(final SerialDate start, final SerialDate end) { int d1; final int m1; final int y1; int d2; final int m2; final int y2; if (start.isBefore(end)) { d1 = start.getDayOfMonth(); m1 = start.getMonth(); y1 = start.getYYYY(); if (d1 == 31) { // first European adjustment d1 = 30; } d2 = end.getDayOfMonth(); m2 = end.getMonth(); y2 = end.getYYYY(); if (d2 == 31) { // first European adjustment d2 = 30; } return 360 * (y2 - y1) + 30 * (m2 - m1) + (d2 - d1); } else if (start.isAfter(end)) { return -dayCount30E(end, start); } else { return 0; } } /** * Returns true if the specified date is the last day in February (that is, the * 28th in non-leap years, and the 29th in leap years). * * @param d the date to be tested. * * @return a boolean that indicates whether or not the specified date is * the last day of February. */ public static boolean isLastDayOfFebruary(final SerialDate d) { final int dom; if (d.getMonth() == MonthConstants.FEBRUARY) { dom = d.getDayOfMonth(); if (SerialDate.isLeapYear(d.getYYYY())) { return (dom == 29); } else { return (dom == 28); } } else { // not even February return false; } } /** * Returns the number of times that February 29 falls within the specified * date range. The result needs to correspond to the ACT/365 (Japanese) * day-count convention. The difficult cases are where the start or the * end date is Feb 29 (include or not?). Need to find out how JGBs do this * (since this is where the ACT/365 (Japanese) convention comes from ... * * @param start the start date. * @param end the end date. * * @return the number of times that February 29 occurs within the date * range. */ public static int countFeb29s(final SerialDate start, final SerialDate end) { int count = 0; SerialDate feb29; final int y1; final int y2; int year; // check the order of the dates if (start.isBefore(end)) { y1 = start.getYYYY(); y2 = end.getYYYY(); for (year = y1; year == y2; year++) { if (SerialDate.isLeapYear(year)) { feb29 = SerialDate.createInstance(29, MonthConstants.FEBRUARY, year); if (feb29.isInRange(start, end, SerialDate.INCLUDE_SECOND)) { count++; } } } return count; } else { return countFeb29s(end, start); } } } jcommon-1.0.16/source/org/jfree/date/MonthConstants.java0000644000175000017500000000542411172030703023122 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * MonthConstants.java * ------------------- * (C) Copyright 2002, 2003, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: MonthConstants.java,v 1.4 2005/11/16 15:58:40 taqua Exp $ * * Changes * ------- * 29-May-2002 : Version 1 (code moved from SerialDate class) (DG); * */ package org.jfree.date; /** * Useful constants for months. Note that these are NOT equivalent to the * constants defined by java.util.Calendar (where JANUARY=0 and DECEMBER=11). *

* Used by the SerialDate and RegularTimePeriod classes. * * @author David Gilbert */ public interface MonthConstants { /** Constant for January. */ public static final int JANUARY = 1; /** Constant for February. */ public static final int FEBRUARY = 2; /** Constant for March. */ public static final int MARCH = 3; /** Constant for April. */ public static final int APRIL = 4; /** Constant for May. */ public static final int MAY = 5; /** Constant for June. */ public static final int JUNE = 6; /** Constant for July. */ public static final int JULY = 7; /** Constant for August. */ public static final int AUGUST = 8; /** Constant for September. */ public static final int SEPTEMBER = 9; /** Constant for October. */ public static final int OCTOBER = 10; /** Constant for November. */ public static final int NOVEMBER = 11; /** Constant for December. */ public static final int DECEMBER = 12; } jcommon-1.0.16/source/org/jfree/date/EasterSundayRule.java0000644000175000017500000000634511172030703023402 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * EasterSundayRule.java * --------------------- * (C) Copyright 2000-2003, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: EasterSundayRule.java,v 1.4 2005/11/16 15:58:40 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.date.*; * 03-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 01-Jun-2005 : Removed the explicit clonable declaration, it is declared * in the super class. */ package org.jfree.date; /** * An annual date rule for Easter (Sunday). The algorithm used here was * obtained from a Calendar FAQ which can be found at: *

* http://www.tondering.dk/claus/calendar.html. *

* It is based on an algorithm by Oudin (1940) and quoted in "Explanatory Supplement to the * Astronomical Almanac", P. Kenneth Seidelmann, editor. * * @author David Gilbert */ public class EasterSundayRule extends AnnualDateRule { /** * Default constructor. */ public EasterSundayRule() { } /** * Returns the date of Easter Sunday for the given year. See the class * description for the source of the algorithm. *

* This method supports the AnnualDateRule interface. * * @param year the year to check. * * @return the date of Easter Sunday for the given year. */ public SerialDate getDate(final int year) { final int g = year % 19; final int c = year / 100; final int h = (c - c / 4 - (8 * c + 13) / 25 + 19 * g + 15) % 30; final int i = h - h / 28 * (1 - h / 28 * 29 / (h + 1) * (21 - g) / 11); final int j = (year + year / 4 + i + 2 - c + c / 4) % 7; final int l = i - j; final int month = 3 + (l + 40) / 44; final int day = l + 28 - 31 * (month / 4); return SerialDate.createInstance(day, month, year); } } jcommon-1.0.16/source/org/jfree/date/RelativeDayOfWeekRule.java0000644000175000017500000001537711172030703024312 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * RelativeDayOfWeekRule.java * -------------------------- * (C) Copyright 2000-2003, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: RelativeDayOfWeekRule.java,v 1.6 2005/11/16 15:58:40 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.date.*; * 03-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.date; /** * An annual date rule that returns a date for each year based on (a) a * reference rule; (b) a day of the week; and (c) a selection parameter * (SerialDate.PRECEDING, SerialDate.NEAREST, SerialDate.FOLLOWING). *

* For example, Good Friday can be specified as 'the Friday PRECEDING Easter * Sunday'. * * @author David Gilbert */ public class RelativeDayOfWeekRule extends AnnualDateRule { /** A reference to the annual date rule on which this rule is based. */ private AnnualDateRule subrule; /** * The day of the week (SerialDate.MONDAY, SerialDate.TUESDAY, and so on). */ private int dayOfWeek; /** Specifies which day of the week (PRECEDING, NEAREST or FOLLOWING). */ private int relative; /** * Default constructor - builds a rule for the Monday following 1 January. */ public RelativeDayOfWeekRule() { this(new DayAndMonthRule(), SerialDate.MONDAY, SerialDate.FOLLOWING); } /** * Standard constructor - builds rule based on the supplied sub-rule. * * @param subrule the rule that determines the reference date. * @param dayOfWeek the day-of-the-week relative to the reference date. * @param relative indicates *which* day-of-the-week (preceding, nearest * or following). */ public RelativeDayOfWeekRule(final AnnualDateRule subrule, final int dayOfWeek, final int relative) { this.subrule = subrule; this.dayOfWeek = dayOfWeek; this.relative = relative; } /** * Returns the sub-rule (also called the reference rule). * * @return The annual date rule that determines the reference date for this * rule. */ public AnnualDateRule getSubrule() { return this.subrule; } /** * Sets the sub-rule. * * @param subrule the annual date rule that determines the reference date * for this rule. */ public void setSubrule(final AnnualDateRule subrule) { this.subrule = subrule; } /** * Returns the day-of-the-week for this rule. * * @return the day-of-the-week for this rule. */ public int getDayOfWeek() { return this.dayOfWeek; } /** * Sets the day-of-the-week for this rule. * * @param dayOfWeek the day-of-the-week (SerialDate.MONDAY, * SerialDate.TUESDAY, and so on). */ public void setDayOfWeek(final int dayOfWeek) { this.dayOfWeek = dayOfWeek; } /** * Returns the 'relative' attribute, that determines *which* * day-of-the-week we are interested in (SerialDate.PRECEDING, * SerialDate.NEAREST or SerialDate.FOLLOWING). * * @return The 'relative' attribute. */ public int getRelative() { return this.relative; } /** * Sets the 'relative' attribute (SerialDate.PRECEDING, SerialDate.NEAREST, * SerialDate.FOLLOWING). * * @param relative determines *which* day-of-the-week is selected by this * rule. */ public void setRelative(final int relative) { this.relative = relative; } /** * Creates a clone of this rule. * * @return a clone of this rule. * * @throws CloneNotSupportedException this should never happen. */ public Object clone() throws CloneNotSupportedException { final RelativeDayOfWeekRule duplicate = (RelativeDayOfWeekRule) super.clone(); duplicate.subrule = (AnnualDateRule) duplicate.getSubrule().clone(); return duplicate; } /** * Returns the date generated by this rule, for the specified year. * * @param year the year (1900 <= year <= 9999). * * @return The date generated by the rule for the given year (possibly * null). */ public SerialDate getDate(final int year) { // check argument... if ((year < SerialDate.MINIMUM_YEAR_SUPPORTED) || (year > SerialDate.MAXIMUM_YEAR_SUPPORTED)) { throw new IllegalArgumentException( "RelativeDayOfWeekRule.getDate(): year outside valid range."); } // calculate the date... SerialDate result = null; final SerialDate base = this.subrule.getDate(year); if (base != null) { switch (this.relative) { case(SerialDate.PRECEDING): result = SerialDate.getPreviousDayOfWeek(this.dayOfWeek, base); break; case(SerialDate.NEAREST): result = SerialDate.getNearestDayOfWeek(this.dayOfWeek, base); break; case(SerialDate.FOLLOWING): result = SerialDate.getFollowingDayOfWeek(this.dayOfWeek, base); break; default: break; } } return result; } } jcommon-1.0.16/source/org/jfree/date/junit/0000755000175000017500000000000011351753320020427 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/date/junit/SerialDateTests.java0000644000175000017500000002354111172030703024331 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * SerialDateTests.java * -------------------- * (C) Copyright 2001-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SerialDateTests.java,v 1.7 2007/11/02 17:50:35 taqua Exp $ * * Changes * ------- * 15-Nov-2001 : Version 1 (DG); * 25-Jun-2002 : Removed unnecessary import (DG); * 24-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 13-Mar-2003 : Added serialization test (DG); * 05-Jan-2005 : Added test for bug report 1096282 (DG); * */ package org.jfree.date.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.date.MonthConstants; import org.jfree.date.SerialDate; /** * Some JUnit tests for the {@link SerialDate} class. */ public class SerialDateTests extends TestCase { /** Date representing November 9. */ private SerialDate nov9Y2001; /** * Creates a new test case. * * @param name the name. */ public SerialDateTests(final String name) { super(name); } /** * Returns a test suite for the JUnit test runner. * * @return The test suite. */ public static Test suite() { return new TestSuite(SerialDateTests.class); } /** * Problem set up. */ protected void setUp() { this.nov9Y2001 = SerialDate.createInstance(9, MonthConstants.NOVEMBER, 2001); } /** * 9 Nov 2001 plus two months should be 9 Jan 2002. */ public void testAddMonthsTo9Nov2001() { final SerialDate jan9Y2002 = SerialDate.addMonths(2, this.nov9Y2001); final SerialDate answer = SerialDate.createInstance(9, 1, 2002); assertEquals(answer, jan9Y2002); } /** * A test case for a reported bug, now fixed. */ public void testAddMonthsTo5Oct2003() { final SerialDate d1 = SerialDate.createInstance(5, MonthConstants.OCTOBER, 2003); final SerialDate d2 = SerialDate.addMonths(2, d1); assertEquals(d2, SerialDate.createInstance(5, MonthConstants.DECEMBER, 2003)); } /** * A test case for a reported bug, now fixed. */ public void testAddMonthsTo1Jan2003() { final SerialDate d1 = SerialDate.createInstance(1, MonthConstants.JANUARY, 2003); final SerialDate d2 = SerialDate.addMonths(0, d1); assertEquals(d2, d1); } /** * Monday preceding Friday 9 November 2001 should be 5 November. */ public void testMondayPrecedingFriday9Nov2001() { SerialDate mondayBefore = SerialDate.getPreviousDayOfWeek( SerialDate.MONDAY, this.nov9Y2001 ); assertEquals(5, mondayBefore.getDayOfMonth()); } /** * Monday following Friday 9 November 2001 should be 12 November. */ public void testMondayFollowingFriday9Nov2001() { SerialDate mondayAfter = SerialDate.getFollowingDayOfWeek( SerialDate.MONDAY, this.nov9Y2001 ); assertEquals(12, mondayAfter.getDayOfMonth()); } /** * Monday nearest Friday 9 November 2001 should be 12 November. */ public void testMondayNearestFriday9Nov2001() { SerialDate mondayNearest = SerialDate.getNearestDayOfWeek( SerialDate.MONDAY, this.nov9Y2001 ); assertEquals(12, mondayNearest.getDayOfMonth()); } /** * The Monday nearest to 22nd January 1970 falls on the 19th. */ public void testMondayNearest22Jan1970() { SerialDate jan22Y1970 = SerialDate.createInstance(22, MonthConstants.JANUARY, 1970); SerialDate mondayNearest = SerialDate.getNearestDayOfWeek(SerialDate.MONDAY, jan22Y1970); assertEquals(19, mondayNearest.getDayOfMonth()); } /** * Problem that the conversion of days to strings returns the right result. Actually, this * result depends on the Locale so this test needs to be modified. */ public void testWeekdayCodeToString() { final String test = SerialDate.weekdayCodeToString(SerialDate.SATURDAY); assertEquals("Saturday", test); } /** * Test the conversion of a string to a weekday. Note that this test will fail if the * default locale doesn't use English weekday names...devise a better test! */ public void testStringToWeekday() { int weekday = SerialDate.stringToWeekdayCode("Wednesday"); assertEquals(SerialDate.WEDNESDAY, weekday); weekday = SerialDate.stringToWeekdayCode(" Wednesday "); assertEquals(SerialDate.WEDNESDAY, weekday); weekday = SerialDate.stringToWeekdayCode("Wed"); assertEquals(SerialDate.WEDNESDAY, weekday); } /** * Test the conversion of a string to a month. Note that this test will fail if the default * locale doesn't use English month names...devise a better test! */ public void testStringToMonthCode() { int m = SerialDate.stringToMonthCode("January"); assertEquals(MonthConstants.JANUARY, m); m = SerialDate.stringToMonthCode(" January "); assertEquals(MonthConstants.JANUARY, m); m = SerialDate.stringToMonthCode("Jan"); assertEquals(MonthConstants.JANUARY, m); } /** * Tests the conversion of a month code to a string. */ public void testMonthCodeToStringCode() { final String test = SerialDate.monthCodeToString(MonthConstants.DECEMBER); assertEquals("December", test); } /** * 1900 is not a leap year. */ public void testIsNotLeapYear1900() { assertTrue(!SerialDate.isLeapYear(1900)); } /** * 2000 is a leap year. */ public void testIsLeapYear2000() { assertTrue(SerialDate.isLeapYear(2000)); } /** * The number of leap years from 1900 up-to-and-including 1899 is 0. */ public void testLeapYearCount1899() { assertEquals(SerialDate.leapYearCount(1899), 0); } /** * The number of leap years from 1900 up-to-and-including 1903 is 0. */ public void testLeapYearCount1903() { assertEquals(SerialDate.leapYearCount(1903), 0); } /** * The number of leap years from 1900 up-to-and-including 1904 is 1. */ public void testLeapYearCount1904() { assertEquals(SerialDate.leapYearCount(1904), 1); } /** * The number of leap years from 1900 up-to-and-including 1999 is 24. */ public void testLeapYearCount1999() { assertEquals(SerialDate.leapYearCount(1999), 24); } /** * The number of leap years from 1900 up-to-and-including 2000 is 25. */ public void testLeapYearCount2000() { assertEquals(SerialDate.leapYearCount(2000), 25); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { SerialDate d1 = SerialDate.createInstance(15, 4, 2000); SerialDate d2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); d2 = (SerialDate) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertEquals(d1, d2); } /** * A test for bug report 1096282 (now fixed). */ public void test1096282() { SerialDate d = SerialDate.createInstance(29, 2, 2004); d = SerialDate.addYears(1, d); SerialDate expected = SerialDate.createInstance(28, 2, 2005); assertTrue(d.isOn(expected)); } /** * Miscellaneous tests for the addMonths() method. */ public void testAddMonths() { SerialDate d1 = SerialDate.createInstance(31, 5, 2004); SerialDate d2 = SerialDate.addMonths(1, d1); assertEquals(30, d2.getDayOfMonth()); assertEquals(6, d2.getMonth()); assertEquals(2004, d2.getYYYY()); SerialDate d3 = SerialDate.addMonths(2, d1); assertEquals(31, d3.getDayOfMonth()); assertEquals(7, d3.getMonth()); assertEquals(2004, d3.getYYYY()); SerialDate d4 = SerialDate.addMonths(1, SerialDate.addMonths(1, d1)); assertEquals(30, d4.getDayOfMonth()); assertEquals(7, d4.getMonth()); assertEquals(2004, d4.getYYYY()); } } jcommon-1.0.16/source/org/jfree/date/junit/package.html0000644000175000017500000000023211172030703022677 0ustar twernertwerner Test cases for the classes in com.jrefinery.date.*. jcommon-1.0.16/source/org/jfree/date/junit/DatePackageTests.java0000644000175000017500000000475411172030703024452 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * DatePackageTests.java * --------------------- * (C) Copyright 2001-2003, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: DatePackageTests.java,v 1.3 2005/11/16 15:58:40 taqua Exp $ * * Changes * ------- * 16-Nov-2001 : Version 1 (DG); * 25-Jun-2002 : Added SerialDateUtilitiesTests (DG); * 24-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.date.junit; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * A test suite for the org.jfree.date package. * */ public class DatePackageTests extends TestCase { /** * Returns a test suite for the JUnit test runner. * * @return the test suite. */ public static Test suite() { final TestSuite suite = new TestSuite("org.jfree.date"); suite.addTestSuite(SerialDateTests.class); suite.addTestSuite(SerialDateUtilitiesTests.class); suite.addTestSuite(SpreadsheetDateTests.class); return suite; } /** * Creates a new test case. * * @param name the name. */ public DatePackageTests(final String name) { super(name); } } jcommon-1.0.16/source/org/jfree/date/junit/SpreadsheetDateTests.java0000644000175000017500000002430411172030703025357 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * SpreadsheetDateTests.java * ------------------------- * (C) Copyright 2001-2006, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SpreadsheetDateTests.java,v 1.6 2007/11/02 17:50:35 taqua Exp $ * * Changes * ------- * 15-Nov-2001 : Version 1 (DG); * 24-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 29-Aug-2006 : Added checks for get/setDescription (DG); * */ package org.jfree.date.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.date.MonthConstants; import org.jfree.date.SerialDate; import org.jfree.date.SpreadsheetDate; /** * Tests for the {@link SpreadsheetDate} class. */ public class SpreadsheetDateTests extends TestCase { /** Date representing 1 January 1900. */ private SerialDate jan1Y1900; /** Date representing serial day number 2. */ private SerialDate s2; /** * Returns a test suite for the JUnit test runner. * * @return the test suite. */ public static Test suite() { return new TestSuite(SpreadsheetDateTests.class); } /** * Creates a new test case. * * @param name the name. */ public SpreadsheetDateTests(final String name) { super(name); } /** * Setup. */ protected void setUp() { this.jan1Y1900 = new SpreadsheetDate(1, MonthConstants.JANUARY, 1900); this.s2 = new SpreadsheetDate(2); } /** * 1 January 1900 is a Thursday. */ public void test1Jan1900GetDayOfWeek() { final int dayOfWeek = this.jan1Y1900.getDayOfWeek(); assertEquals(SerialDate.MONDAY, dayOfWeek); } /** * 12 November 2001 is a Monday. */ public void test12Nov2001GetDayOfWeek() { SerialDate nov12Y2001 = new SpreadsheetDate(12, MonthConstants.NOVEMBER, 2001); int dayOfWeek = nov12Y2001.getDayOfWeek(); assertEquals(SerialDate.MONDAY, dayOfWeek); } /** * Day 2 is the first of the month. */ public void testS2GetDayOfMonth() { final int dayOfMonth = this.s2.getDayOfMonth(); assertEquals(1, dayOfMonth); } /** * Day 2 is in January. */ public void testS2GetMonth() { final int month = this.s2.getMonth(); assertEquals(MonthConstants.JANUARY, month); } /** * Day 2 is in 1900. */ public void testS2GetYYYY() { final int year = this.s2.getYYYY(); assertEquals(1900, year); } /** * Day 37986 is 31 Dec 2003. */ public void test37986() { final SpreadsheetDate d = new SpreadsheetDate(37986); assertEquals(31, d.getDayOfMonth()); assertEquals(MonthConstants.DECEMBER, d.getMonth()); assertEquals(2003, d.getYYYY()); } /** * Day 37987 is 1 Jan 2004. */ public void test37987() { final SpreadsheetDate d = new SpreadsheetDate(37987); assertEquals(1, d.getDayOfMonth()); assertEquals(MonthConstants.JANUARY, d.getMonth()); assertEquals(2004, d.getYYYY()); } /** * Day 38352 is 31 Dec 2004. */ public void test38352() { final SpreadsheetDate d = new SpreadsheetDate(38352); assertEquals(31, d.getDayOfMonth()); assertEquals(MonthConstants.DECEMBER, d.getMonth()); assertEquals(2004, d.getYYYY()); } /** * Day 38353 is 1 Jan 2005. */ public void test38353() { final SpreadsheetDate d = new SpreadsheetDate(38353); assertEquals(1, d.getDayOfMonth()); assertEquals(MonthConstants.JANUARY, d.getMonth()); assertEquals(2005, d.getYYYY()); } /** * Create a date for serial number 36584: it should be 28-Feb-2000. */ public void test36584() { final SpreadsheetDate d = new SpreadsheetDate(36584); assertEquals(28, d.getDayOfMonth()); assertEquals(MonthConstants.FEBRUARY, d.getMonth()); assertEquals(2000, d.getYYYY()); } /** * Create a date for serial number 36585: it should be 29-Feb-2000. */ public void test36585() { final SpreadsheetDate d = new SpreadsheetDate(36585); assertEquals(29, d.getDayOfMonth()); assertEquals(MonthConstants.FEBRUARY, d.getMonth()); assertEquals(2000, d.getYYYY()); } /** * Create a date for serial number 36586: it should be 1-Mar-2000. */ public void test36586() { final SpreadsheetDate d = new SpreadsheetDate(36586); assertEquals(1, d.getDayOfMonth()); assertEquals(MonthConstants.MARCH, d.getMonth()); assertEquals(2000, d.getYYYY()); } /** * Create a date for 01-Jan-1900: the serial number should be 2. */ public void test01Jan1900ToSerial() { final int serial = this.jan1Y1900.toSerial(); assertEquals(2, serial); } /** * Create a date for 28-Feb-1900: the serial number should be 60. */ public void test28Feb1900ToSerial() { SpreadsheetDate d = new SpreadsheetDate(28, MonthConstants.FEBRUARY, 1900); assertEquals(60, d.toSerial()); } /** * Create a date for 01-Mar-1900: the serial number should be 61. */ public void test01Mar1900ToSerial() { SpreadsheetDate d = new SpreadsheetDate(1, MonthConstants.MARCH, 1900); assertEquals(61, d.toSerial()); } /** * Create a date for 31-Dec-1999: the serial number should be 36525. */ public void test31Dec1999ToSerial() { SpreadsheetDate d = new SpreadsheetDate(31, MonthConstants.DECEMBER, 1999); assertEquals(36525, d.toSerial()); } /** * Create a date for 1-Jan-2000: the serial number should be 36526. */ public void test01Jan2000ToSerial() { SpreadsheetDate d = new SpreadsheetDate(1, MonthConstants.JANUARY, 2000); assertEquals(36526, d.toSerial()); } /** * Create a date for 31-Jan-2000: the serial number should be 36556. */ public void test31Jan2000ToSerial() { SpreadsheetDate d = new SpreadsheetDate(31, MonthConstants.JANUARY, 2000); assertEquals(36556, d.toSerial()); } /** * Create a date for 01-Feb-2000: the serial number should be 36557. */ public void test01Feb2000ToSerial() { SpreadsheetDate d = new SpreadsheetDate(1, MonthConstants.FEBRUARY, 2000); assertEquals(36557, d.toSerial()); } /** * Create a date for 28-Feb-2000: the serial number should be 36584. */ public void test28Feb2000ToSerial() { SpreadsheetDate d = new SpreadsheetDate(28, MonthConstants.FEBRUARY, 2000); assertEquals(36584, d.toSerial()); } /** * Create a date for 29-Feb-2000: the serial number should be 36585. */ public void test29feb2000ToSerial() { SpreadsheetDate d = new SpreadsheetDate(29, MonthConstants.FEBRUARY, 2000); assertEquals(36585, d.toSerial()); } /** * Create a date for 1-Mar-2000: the serial number should be 36586. */ public void test1mar2000ToSerial() { SpreadsheetDate d = new SpreadsheetDate(1, MonthConstants.MARCH, 2000); assertEquals(36586, d.toSerial()); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { final SpreadsheetDate d1 = new SpreadsheetDate(15, 4, 2000); SpreadsheetDate d2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream( buffer.toByteArray())); d2 = (SpreadsheetDate) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertEquals(d1, d2); } /** * Some checks for the getDescription() method. */ public void testGetDescription() { SpreadsheetDate d1 = new SpreadsheetDate(15, 4, 2000); assertEquals(null, d1.getDescription()); d1.setDescription("XYZ"); assertEquals("XYZ", d1.getDescription()); } /** * Some checks for the setDescription() method. */ public void testSetDescription() { SpreadsheetDate d1 = new SpreadsheetDate(15, 4, 2000); assertEquals(null, d1.getDescription()); d1.setDescription("XYZ"); assertEquals("XYZ", d1.getDescription()); d1.setDescription(null); assertEquals(null, d1.getDescription()); } } jcommon-1.0.16/source/org/jfree/date/junit/SerialDateUtilitiesTests.java0000644000175000017500000001032111172030703026215 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------------- * SerialDateUtilitiesTests.java * ----------------------------- * (C) Copyright 2002, 2003, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SerialDateUtilitiesTests.java,v 1.5 2007/11/02 17:50:35 taqua Exp $ * * Changes * ------- * 25-Jun-2002 : Version 1 (DG); * 24-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.date.junit; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.date.MonthConstants; import org.jfree.date.SerialDate; import org.jfree.date.SerialDateUtilities; /** * Some tests for the SerialDateUtilities class. * */ public class SerialDateUtilitiesTests extends TestCase { /** * Creates a new test case. * * @param name the name. */ public SerialDateUtilitiesTests(final String name) { super(name); } /** * Returns a test suite for the JUnit test runner. * * @return the test suite. */ public static Test suite() { return new TestSuite(SerialDateUtilitiesTests.class); } /** * Problem actual day count. */ public void testDayCountActual() { final SerialDate d1 = SerialDate.createInstance(1, MonthConstants.APRIL, 2002); final SerialDate d2 = SerialDate.createInstance(2, MonthConstants.APRIL, 2002); final int count = SerialDateUtilities.dayCountActual(d1, d2); assertEquals(1, count); } /** * Problem 30/360 day count. */ public void testDayCount30() { final SerialDate d1 = SerialDate.createInstance(1, MonthConstants.APRIL, 2002); final SerialDate d2 = SerialDate.createInstance(2, MonthConstants.APRIL, 2002); final int count = SerialDateUtilities.dayCount30(d1, d2); assertEquals(1, count); } /** * Problem 30/360ISDA day count. */ public void testDayCount30ISDA() { final SerialDate d1 = SerialDate.createInstance(1, MonthConstants.APRIL, 2002); final SerialDate d2 = SerialDate.createInstance(2, MonthConstants.APRIL, 2002); final int count = SerialDateUtilities.dayCount30ISDA(d1, d2); assertEquals(1, count); } /** * Problem 30/360PSA day count. */ public void testDayCount30PSA() { final SerialDate d1 = SerialDate.createInstance(1, MonthConstants.APRIL, 2002); final SerialDate d2 = SerialDate.createInstance(2, MonthConstants.APRIL, 2002); final int count = SerialDateUtilities.dayCount30PSA(d1, d2); assertEquals(1, count); } /** * Problem 30E/360 day count. */ public void testDayCount3030E() { final SerialDate d1 = SerialDate.createInstance(1, MonthConstants.APRIL, 2002); final SerialDate d2 = SerialDate.createInstance(2, MonthConstants.APRIL, 2002); final int count = SerialDateUtilities.dayCount30E(d1, d2); assertEquals(1, count); } } jcommon-1.0.16/source/org/jfree/date/DayAndMonthRule.java0000644000175000017500000001153411172030703023135 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * DayAndMonthRule.java * -------------------- * (C) Copyright 2000-2003, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: DayAndMonthRule.java,v 1.6 2005/11/16 15:58:40 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.date.* (DG); * 12-Nov-2001 : Added some argument checks (DG); * 03-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 01-Jun-2005 : Removed the explicit clonable declaration, it is declared * in the super class. */ package org.jfree.date; /** * An annual date rule where the generated date always falls on the same day * and month each year. *

* An example is ANZAC Day in Australia and New Zealand: it is observed on * 25 April of every year. * * @author David Gilbert */ public class DayAndMonthRule extends AnnualDateRule { /** The day of the month. */ private int dayOfMonth; /** The month (uses 1 to 12 in the obvious way). */ private int month; /** * Default constructor: builds a DayAndMonthRule for 1 January. */ public DayAndMonthRule() { this(1, MonthConstants.JANUARY); } /** * Standard constructor: builds a DayAndMonthRule for the given * day-of-the-month and month. *

* For the month parameter, use SerialDate.JANUARY, etc. Note that there * are no checks to prevent you from entering an invalid combination (such * as 31 February). * * @param dayOfMonth the day of the month (in the range 1 to 31). * @param month the month (use SerialDate.JANUARY, SerialDate.FEBRUARY etc.); */ public DayAndMonthRule(final int dayOfMonth, final int month) { // check arguments delegated to setter methods... setMonth(month); setDayOfMonth(dayOfMonth); } /** * Returns the day of the month. * * @return the day of the month. */ public int getDayOfMonth() { return this.dayOfMonth; } /** * Sets the day-of-the-month for this rule. * * @param dayOfMonth the day-of-the-month. */ public void setDayOfMonth(final int dayOfMonth) { // check arguments... if ((dayOfMonth < 1) || (dayOfMonth > SerialDate.LAST_DAY_OF_MONTH[this.month])) { throw new IllegalArgumentException( "DayAndMonthRule(): dayOfMonth outside valid range."); } // make the change... this.dayOfMonth = dayOfMonth; } /** * Returns an integer code representing the month. *

* The codes JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, * SEPTEMBER, OCTOBER, NOVEMBER and DECEMBER are defined in the SerialDate * class. * * @return an integer code representing the month. */ public int getMonth() { return this.month; } /** * Sets the month for this rule. * * @param month the month for this rule. */ public void setMonth(final int month) { // check arguments... if (!SerialDate.isValidMonthCode(month)) { throw new IllegalArgumentException("DayAndMonthRule(): month code not valid."); } // make the change... this.month = month; } /** * Returns the date, given the year. * * @param yyyy the year. * * @return the date generated by this rule for the specified year (null permitted). */ public SerialDate getDate(final int yyyy) { return SerialDate.createInstance(this.dayOfMonth, this.month, yyyy); } } jcommon-1.0.16/source/org/jfree/date/DateUtilities.java0000644000175000017500000000553011172030703022707 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * DateUtilities.java * ------------------ * (C) Copyright 2002, 2003, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: DateUtilities.java,v 1.4 2005/11/16 15:58:40 taqua Exp $ * * Changes * ------- * 11-Oct-2002 : Version 1 (DG); * 03-Apr-2003 : Added clear() method call (DG) * */ package org.jfree.date; import java.util.Calendar; import java.util.Date; /** * Some useful date methods. * * @author David Gilbert. */ public class DateUtilities { /** * Private constructor to prevent object creation. */ private DateUtilities() { } /** A working calendar. */ private static final Calendar CALENDAR = Calendar.getInstance(); /** * Creates a date. * * @param yyyy the year. * @param month the month (1 - 12). * @param day the day. * * @return a date. */ public static synchronized Date createDate(final int yyyy, final int month, final int day) { CALENDAR.clear(); CALENDAR.set(yyyy, month - 1, day); return CALENDAR.getTime(); } /** * Creates a date. * * @param yyyy the year. * @param month the month (1 - 12). * @param day the day. * @param hour the hour. * @param min the minute. * * @return a date. */ public static synchronized Date createDate(final int yyyy, final int month, final int day, final int hour, final int min) { CALENDAR.clear(); CALENDAR.set(yyyy, month - 1, day, hour, min); return CALENDAR.getTime(); } } jcommon-1.0.16/source/org/jfree/JCommonInfo.java0000644000175000017500000001072311172030703021377 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * JCommonInfo.java * ---------------- * (C)opyright 2003-2008, by Thomas Morgner and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Thomas Morgner; * * $Id: JCommonInfo.java,v 1.8 2008/12/18 09:57:32 mungady Exp $ * * Changes * ------- * 07-Jun-2004 : Added JCommon header (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree; import java.util.Arrays; import java.util.ResourceBundle; import org.jfree.base.BaseBoot; import org.jfree.base.Library; import org.jfree.ui.about.Contributor; import org.jfree.ui.about.Licences; import org.jfree.ui.about.ProjectInfo; import org.jfree.util.ResourceBundleWrapper; /** * Information about the JCommon project. One instance of this class is * assigned to JCommon.INFO. * * @author David Gilbert */ public class JCommonInfo extends ProjectInfo { /** The singleton instance of the project info object. */ private static JCommonInfo singleton; /** * Returns the single instance of this class. * * @return The single instance of information about the JCommon library. */ public static synchronized JCommonInfo getInstance() { if (singleton == null) { singleton = new JCommonInfo(); } return singleton; } /** * Creates a new instance. */ private JCommonInfo() { // get a locale-specific resource bundle... final String baseResourceClass = "org.jfree.resources.JCommonResources"; final ResourceBundle resources = ResourceBundleWrapper.getBundle( baseResourceClass); setName(resources.getString("project.name")); setVersion(resources.getString("project.version")); setInfo(resources.getString("project.info")); setCopyright(resources.getString("project.copyright")); setLicenceName("LGPL"); setLicenceText(Licences.getInstance().getLGPL()); setContributors(Arrays.asList( new Contributor[] { new Contributor("Anthony Boulestreau", "-"), new Contributor("Jeremy Bowman", "-"), new Contributor("J. David Eisenberg", "-"), new Contributor("Paul English", "-"), new Contributor("David Gilbert", "david.gilbert@object-refinery.com"), new Contributor("Hans-Jurgen Greiner", "-"), new Contributor("Arik Levin", "-"), new Contributor("Achilleus Mantzios", "-"), new Contributor("Thomas Meier", "-"), new Contributor("Aaron Metzger", "-"), new Contributor("Thomas Morgner", "-"), new Contributor("Krzysztof Paz", "-"), new Contributor("Nabuo Tamemasa", "-"), new Contributor("Mark Watson", "-"), new Contributor("Matthew Wright", "-"), new Contributor("Hari", "-"), new Contributor("Sam (oldman)", "-") } )); addOptionalLibrary(new Library("JUnit", "3.8", "IBM Public Licence", "http://www.junit.org/")); setBootClass(BaseBoot.class.getName()); } } jcommon-1.0.16/source/org/jfree/junit/0000755000175000017500000000000011351753320017512 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/junit/JCommonTestSuite.java0000644000175000017500000000625111172030703023567 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * JCommonTestSuite.java * --------------------- * (C) Copyright 2001-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: JCommonTestSuite.java,v 1.5 2007/11/02 17:50:35 taqua Exp $ * * Changes * ------- * 11-Nov-2001 : Version 1 (DG); * 02-Sep-2002 : Removed DataPackageTests (DG); * 18-Sep-2003 : Added new org.jfree.io package tests (DG); * 09-Jan-2004 : Added new org.jfree.ui package tests (DG); * 22-Mar-2004 : Added tests for the org.jfree.text package (DG); * 18-Jan-2005 : Added main() method (DG); * */ package org.jfree.junit; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.date.junit.DatePackageTests; import org.jfree.io.junit.IOPackageTests; import org.jfree.text.junit.TextPackageTests; import org.jfree.ui.junit.UIPackageTests; import org.jfree.util.junit.UtilPackageTests; /** * A test suite for the JCommon class library that can be run using JUnit (http://www.junit.org). */ public class JCommonTestSuite extends TestCase { /** * Returns a test suite to the JUnit test runner. * * @return a test suite. */ public static Test suite() { final TestSuite suite = new TestSuite("JCommon"); suite.addTest(DatePackageTests.suite()); suite.addTest(IOPackageTests.suite()); suite.addTest(TextPackageTests.suite()); suite.addTest(UIPackageTests.suite()); suite.addTest(UtilPackageTests.suite()); return suite; } /** * Constructs the test suite. * * @param name the suite name. */ public JCommonTestSuite(final String name) { super(name); } /** * Runs the test suite using the JUnit text-based runner. * * @param args ignored. */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } } jcommon-1.0.16/source/org/jfree/junit/package.html0000644000175000017500000000022111172030703021760 0ustar twernertwerner JUnit tests for the JCommon class library. jcommon-1.0.16/source/org/jfree/junit/JavaTestSuite.java0000644000175000017500000000470011172030703023103 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * JavaTestSuite.java * ------------------ * (C) Copyright 2003, 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: JavaTestSuite.java,v 1.3 2005/11/16 15:58:40 taqua Exp $ * * Changes * ------- * 23-Oct-2003 : Version 1 (DG); * */ package org.jfree.junit; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * A collection of tests that I use to examine the behaviour of Java in particular situations. * I expect some of these tests to fail - that doesn't always indicate a bug, only that Java * doesn't work the way I might want it to. */ public class JavaTestSuite extends TestCase { /** * Returns a test suite to the JUnit test runner. * * @return a test suite. */ public static Test suite() { final TestSuite suite = new TestSuite("Java Tests"); suite.addTest(PaintTests.suite()); suite.addTest(StrokeTests.suite()); return suite; } /** * Constructs the test suite. * * @param name the suite name. */ public JavaTestSuite(final String name) { super(name); } } jcommon-1.0.16/source/org/jfree/junit/PaintTests.java0000644000175000017500000000737711172030703022463 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * PaintTests.java * --------------- * (C) Copyright 2003-2005, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: PaintTests.java,v 1.3 2005/10/18 13:16:37 mungady Exp $ * * Changes * ------- * 23-Oct-2003 : Version 1 (DG); * */ package org.jfree.junit; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Paint; import java.awt.TexturePaint; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Tests for the {@link Paint} interface and known subclasses. */ public class PaintTests extends TestCase { /** * Returns the tests as a test suite. * * @return the test suite. */ public static Test suite() { return new TestSuite(PaintTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public PaintTests(final String name) { super(name); } /** * Check that the equals() method distinguishes all fields. */ public void testColorEquals() { final Paint p1 = new Color(0xFF, 0xEE, 0xDD); final Paint p2 = new Color(0xFF, 0xEE, 0xDD); assertEquals(p1, p2); } /** * Two objects that are equal are required to return the same hashCode. */ public void testColorHashcode() { final Paint p1 = new Color(0xFF, 0xEE, 0xDD); final Paint p2 = new Color(0xFF, 0xEE, 0xDD); assertTrue(p1.equals(p2)); final int h1 = p1.hashCode(); final int h2 = p2.hashCode(); assertEquals(h1, h2); } /** * Check that the equals() method distinguishes all fields. */ public void testGradientPaintEquals() { final Paint p1 = new GradientPaint(10.0f, 20.0f, Color.blue, 30.0f, 40.0f, Color.red); final Paint p2 = new GradientPaint(10.0f, 20.0f, Color.blue, 30.0f, 40.0f, Color.red); assertEquals(p1, p2); } /** * Check that the equals() method distinguishes all fields. */ public void testTexturePaintEquals() { final Paint p1 = new TexturePaint( new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB), new Rectangle2D.Double() ); final Paint p2 = new TexturePaint( new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB), new Rectangle2D.Double() ); assertEquals(p1, p2); } } jcommon-1.0.16/source/org/jfree/junit/StrokeTests.java0000644000175000017500000000554711172030703022654 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * StrokeTests.java * ---------------- * (C) Copyright 2003-2005, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: StrokeTests.java,v 1.3 2005/10/18 13:16:37 mungady Exp $ * * Changes * ------- * 23-Oct-2003 : Version 1 (DG); * */ package org.jfree.junit; import java.awt.BasicStroke; import java.awt.Stroke; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Tests for the {@link Stroke} interface and known subclass {@link BasicStroke}. */ public class StrokeTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(StrokeTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public StrokeTests(final String name) { super(name); } /** * Check that the equals() method distinguishes all fields. */ public void testBasicStrokeEquals() { final Stroke s1 = new BasicStroke(1.5f); final Stroke s2 = new BasicStroke(1.5f); assertEquals(s1, s2); } /** * Two objects that are equal are required to return the same hashCode. */ public void testColorHashcode() { final Stroke s1 = new BasicStroke(1.5f); final Stroke s2 = new BasicStroke(1.5f); assertTrue(s1.equals(s2)); final int h1 = s1.hashCode(); final int h2 = s2.hashCode(); assertEquals(h1, h2); } } jcommon-1.0.16/source/org/jfree/ui/0000755000175000017500000000000011351753320016776 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/ui/ArrowPanel.java0000644000175000017500000001003211172030703021701 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * ArrowPanel.java * --------------- * (C) Copyright 2002-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ArrowPanel.java,v 1.6 2007/11/02 17:50:36 taqua Exp $ * * Changes * ------- * 25-Sep-2002 : Version 1 (DG); * 13-Oct-2002 : Added Javadocs (DG); * */ package org.jfree.ui; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Polygon; import java.awt.Shape; import java.awt.geom.Rectangle2D; import javax.swing.JPanel; /** * A basic panel that displays a small up or down arrow. * * @author David Gilbert */ public class ArrowPanel extends JPanel { /** A constant for the up arrow. */ public static final int UP = 0; /** A constant for the down arrow. */ public static final int DOWN = 1; /** The arrow type. */ private int type = UP; /** The available area. */ private Rectangle2D available = new Rectangle2D.Float(); /** * Creates a new arrow panel. * * @param type the arrow type. */ public ArrowPanel(final int type) { this.type = type; setPreferredSize(new Dimension(14, 9)); } /** * Paints the arrow panel. * * @param g the graphics device for drawing on. */ public void paintComponent(final Graphics g) { super.paintComponent(g); final Graphics2D g2 = (Graphics2D) g; // first determine the size of the drawing area... final Dimension size = getSize(); final Insets insets = getInsets(); this.available.setRect(insets.left, insets.top, size.getWidth() - insets.left - insets.right, size.getHeight() - insets.top - insets.bottom); g2.translate(insets.left, insets.top); g2.fill(getArrow(this.type)); } /** * Returns a shape for the arrow. * * @param t the arrow type. * * @return the arrow shape. */ private Shape getArrow(final int t) { switch (t) { case UP : return getUpArrow(); case DOWN : return getDownArrow(); default : return getUpArrow(); } } /** * Returns an up arrow. * * @return an up arrow. */ private Shape getUpArrow() { final Polygon result = new Polygon(); result.addPoint(7, 2); result.addPoint(2, 7); result.addPoint(12, 7); return result; } /** * Returns a down arrow. * * @return a down arrow. */ private Shape getDownArrow() { final Polygon result = new Polygon(); result.addPoint(7, 7); result.addPoint(2, 2); result.addPoint(12, 2); return result; } } jcommon-1.0.16/source/org/jfree/ui/DateChooserPanel.java0000644000175000017500000004332311172030703023020 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * DateChooserPanel.java * --------------------- * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: DateChooserPanel.java,v 1.11 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.* (DG); * 08-Dec-2001 : Dropped the getMonths() method (DG); * 13-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 02-Nov-2005 : Fixed a bug where the current day-of-the-month is past * the end of the newly selected month when the month or year * combo boxes are changed - see bug id 1344319 (DG); * */ package org.jfree.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.Date; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.UIManager; import org.jfree.date.SerialDate; /** * A panel that allows the user to select a date. * * @author David Gilbert */ public class DateChooserPanel extends JPanel implements ActionListener { /** * The date selected in the panel. */ private Calendar chosenDate; /** * The color for the selected date. */ private Color chosenDateButtonColor; /** * The color for dates in the current month. */ private Color chosenMonthButtonColor; /** * The color for dates that are visible, but not in the current month. */ private Color chosenOtherButtonColor; /** * The first day-of-the-week. */ private int firstDayOfWeek; /** * The range used for selecting years. */ private int yearSelectionRange = 20; /** * The font used to display the date. */ private Font dateFont = new Font("SansSerif", Font.PLAIN, 10); /** * A combo for selecting the month. */ private JComboBox monthSelector; /** * A combo for selecting the year. */ private JComboBox yearSelector; /** * A button for selecting today's date. */ private JButton todayButton; /** * An array of buttons used to display the days-of-the-month. */ private JButton[] buttons; /** * A flag that indicates whether or not we are currently refreshing the * buttons. */ private boolean refreshing = false; /** * The ordered set of all seven days of a week, * beginning with the 'firstDayOfWeek'. */ private int[] WEEK_DAYS; /** * Constructs a new date chooser panel, using today's date as the initial * selection. */ public DateChooserPanel() { this(Calendar.getInstance(), false); } /** * Constructs a new date chooser panel. * * @param calendar the calendar controlling the date. * @param controlPanel a flag that indicates whether or not the 'today' * button should appear on the panel. */ public DateChooserPanel(final Calendar calendar, final boolean controlPanel) { super(new BorderLayout()); this.chosenDateButtonColor = UIManager.getColor("textHighlight"); this.chosenMonthButtonColor = UIManager.getColor("control"); this.chosenOtherButtonColor = UIManager.getColor("controlShadow"); // the default date is today... this.chosenDate = calendar; this.firstDayOfWeek = calendar.getFirstDayOfWeek(); this.WEEK_DAYS = new int[7]; for (int i = 0; i < 7; i++) { this.WEEK_DAYS[i] = ((this.firstDayOfWeek + i - 1) % 7) + 1; } add(constructSelectionPanel(), BorderLayout.NORTH); add(getCalendarPanel(), BorderLayout.CENTER); if (controlPanel) { add(constructControlPanel(), BorderLayout.SOUTH); } setDate(calendar.getTime()); } /** * Sets the date chosen in the panel. * * @param theDate the new date. */ public void setDate(final Date theDate) { this.chosenDate.setTime(theDate); this.monthSelector.setSelectedIndex(this.chosenDate.get( Calendar.MONTH)); refreshYearSelector(); refreshButtons(); } /** * Returns the date selected in the panel. * * @return the selected date. */ public Date getDate() { return this.chosenDate.getTime(); } /** * Handles action-events from the date panel. * * @param e information about the event that occurred. */ public void actionPerformed(final ActionEvent e) { if (e.getActionCommand().equals("monthSelectionChanged")) { final JComboBox c = (JComboBox) e.getSource(); // In most cases, changing the month will not change the selected // day. But if the selected day is 29, 30 or 31 and the newly // selected month doesn't have that many days, we revert to the // last day of the newly selected month... int dayOfMonth = this.chosenDate.get(Calendar.DAY_OF_MONTH); this.chosenDate.set(Calendar.DAY_OF_MONTH, 1); this.chosenDate.set(Calendar.MONTH, c.getSelectedIndex()); int maxDayOfMonth = this.chosenDate.getActualMaximum( Calendar.DAY_OF_MONTH); this.chosenDate.set(Calendar.DAY_OF_MONTH, Math.min(dayOfMonth, maxDayOfMonth)); refreshButtons(); } else if (e.getActionCommand().equals("yearSelectionChanged")) { if (!this.refreshing) { final JComboBox c = (JComboBox) e.getSource(); final Integer y = (Integer) c.getSelectedItem(); // in most cases, changing the year will not change the // selected day. But if the selected day is Feb 29, and the // newly selected year is not a leap year, we revert to // Feb 28... int dayOfMonth = this.chosenDate.get(Calendar.DAY_OF_MONTH); this.chosenDate.set(Calendar.DAY_OF_MONTH, 1); this.chosenDate.set(Calendar.YEAR, y.intValue()); int maxDayOfMonth = this.chosenDate.getActualMaximum( Calendar.DAY_OF_MONTH); this.chosenDate.set(Calendar.DAY_OF_MONTH, Math.min(dayOfMonth, maxDayOfMonth)); refreshYearSelector(); refreshButtons(); } } else if (e.getActionCommand().equals("todayButtonClicked")) { setDate(new Date()); } else if (e.getActionCommand().equals("dateButtonClicked")) { final JButton b = (JButton) e.getSource(); final int i = Integer.parseInt(b.getName()); final Calendar cal = getFirstVisibleDate(); cal.add(Calendar.DATE, i); setDate(cal.getTime()); } } /** * Returns a panel of buttons, each button representing a day in the month. * This is a sub-component of the DatePanel. * * @return the panel. */ private JPanel getCalendarPanel() { final JPanel p = new JPanel(new GridLayout(7, 7)); final DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(); final String[] weekDays = dateFormatSymbols.getShortWeekdays(); for (int i = 0; i < this.WEEK_DAYS.length; i++) { p.add(new JLabel(weekDays[this.WEEK_DAYS[i]], SwingConstants.CENTER)); } this.buttons = new JButton[42]; for (int i = 0; i < 42; i++) { final JButton b = new JButton(""); b.setMargin(new Insets(1, 1, 1, 1)); b.setName(Integer.toString(i)); b.setFont(this.dateFont); b.setFocusPainted(false); b.setActionCommand("dateButtonClicked"); b.addActionListener(this); this.buttons[i] = b; p.add(b); } return p; } /** * Returns the button color according to the specified date. * * @param theDate the date. * @return the color. */ private Color getButtonColor(final Calendar theDate) { if (equalDates(theDate, this.chosenDate)) { return this.chosenDateButtonColor; } else if (theDate.get(Calendar.MONTH) == this.chosenDate.get( Calendar.MONTH)) { return this.chosenMonthButtonColor; } else { return this.chosenOtherButtonColor; } } /** * Returns true if the two dates are equal (time of day is ignored). * * @param c1 the first date. * @param c2 the second date. * @return boolean. */ private boolean equalDates(final Calendar c1, final Calendar c2) { if ((c1.get(Calendar.DATE) == c2.get(Calendar.DATE)) && (c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH)) && (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR))) { return true; } else { return false; } } /** * Returns the first date that is visible in the grid. This should always * be in the month preceding the month of the selected date. * * @return the date. */ private Calendar getFirstVisibleDate() { final Calendar c = Calendar.getInstance(); c.set(this.chosenDate.get(Calendar.YEAR), this.chosenDate.get( Calendar.MONTH), 1); c.add(Calendar.DATE, -1); while (c.get(Calendar.DAY_OF_WEEK) != getFirstDayOfWeek()) { c.add(Calendar.DATE, -1); } return c; } /** * Returns the first day of the week (controls the labels in the date * panel). * * @return the first day of the week. */ private int getFirstDayOfWeek() { return this.firstDayOfWeek; } /** * Update the button labels and colors to reflect date selection. */ private void refreshButtons() { final Calendar c = getFirstVisibleDate(); for (int i = 0; i < 42; i++) { final JButton b = this.buttons[i]; b.setText(Integer.toString(c.get(Calendar.DATE))); b.setBackground(getButtonColor(c)); c.add(Calendar.DATE, 1); } } /** * Changes the contents of the year selection JComboBox to reflect the * chosen date and the year range. */ private void refreshYearSelector() { if (!this.refreshing) { this.refreshing = true; this.yearSelector.removeAllItems(); final Integer[] years = getYears(this.chosenDate.get( Calendar.YEAR)); for (int i = 0; i < years.length; i++) { this.yearSelector.addItem(years[i]); } this.yearSelector.setSelectedItem(new Integer(this.chosenDate.get( Calendar.YEAR))); this.refreshing = false; } } /** * Returns a vector of years preceding and following the specified year. * The number of years preceding and following is determined by the * yearSelectionRange attribute. * * @param chosenYear the selected year. * @return a vector of years. */ private Integer[] getYears(final int chosenYear) { final int size = this.yearSelectionRange * 2 + 1; final int start = chosenYear - this.yearSelectionRange; final Integer[] years = new Integer[size]; for (int i = 0; i < size; i++) { years[i] = new Integer(i + start); } return years; } /** * Constructs a panel containing two JComboBoxes (for the month and year) * and a button (to reset the date to TODAY). * * @return the panel. */ private JPanel constructSelectionPanel() { final JPanel p = new JPanel(); final int minMonth = this.chosenDate.getMinimum(Calendar.MONTH); final int maxMonth = this.chosenDate.getMaximum(Calendar.MONTH); final String[] months = new String[maxMonth - minMonth + 1]; System.arraycopy(SerialDate.getMonths(), minMonth, months, 0, months.length); this.monthSelector = new JComboBox(months); this.monthSelector.addActionListener(this); this.monthSelector.setActionCommand("monthSelectionChanged"); p.add(this.monthSelector); this.yearSelector = new JComboBox(getYears(0)); this.yearSelector.addActionListener(this); this.yearSelector.setActionCommand("yearSelectionChanged"); p.add(this.yearSelector); return p; } /** * Returns a panel that appears at the bottom of the calendar panel - * contains a button for selecting today's date. * * @return the panel. */ private JPanel constructControlPanel() { final JPanel p = new JPanel(); p.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5)); this.todayButton = new JButton("Today"); this.todayButton.addActionListener(this); this.todayButton.setActionCommand("todayButtonClicked"); p.add(this.todayButton); return p; } /** * Returns the color for the currently selected date. * * @return a color. */ public Color getChosenDateButtonColor() { return this.chosenDateButtonColor; } /** * Redefines the color for the currently selected date. * * @param chosenDateButtonColor the new color */ public void setChosenDateButtonColor(final Color chosenDateButtonColor) { if (chosenDateButtonColor == null) { throw new NullPointerException("UIColor must not be null."); } final Color oldValue = this.chosenDateButtonColor; this.chosenDateButtonColor = chosenDateButtonColor; refreshButtons(); firePropertyChange("chosenDateButtonColor", oldValue, chosenDateButtonColor); } /** * Returns the color for the buttons representing the current month. * * @return the color for the current month. */ public Color getChosenMonthButtonColor() { return this.chosenMonthButtonColor; } /** * Defines the color for the buttons representing the current month. * * @param chosenMonthButtonColor the color for the current month. */ public void setChosenMonthButtonColor(final Color chosenMonthButtonColor) { if (chosenMonthButtonColor == null) { throw new NullPointerException("UIColor must not be null."); } final Color oldValue = this.chosenMonthButtonColor; this.chosenMonthButtonColor = chosenMonthButtonColor; refreshButtons(); firePropertyChange("chosenMonthButtonColor", oldValue, chosenMonthButtonColor); } /** * Returns the color for the buttons representing the other months. * * @return a color. */ public Color getChosenOtherButtonColor() { return this.chosenOtherButtonColor; } /** * Redefines the color for the buttons representing the other months. * * @param chosenOtherButtonColor a color. */ public void setChosenOtherButtonColor(final Color chosenOtherButtonColor) { if (chosenOtherButtonColor == null) { throw new NullPointerException("UIColor must not be null."); } final Color oldValue = this.chosenOtherButtonColor; this.chosenOtherButtonColor = chosenOtherButtonColor; refreshButtons(); firePropertyChange("chosenOtherButtonColor", oldValue, chosenOtherButtonColor); } /** * Returns the range of years available for selection (defaults to 20). * * @return The range. */ public int getYearSelectionRange() { return this.yearSelectionRange; } /** * Sets the range of years available for selection. * * @param yearSelectionRange the range. */ public void setYearSelectionRange(final int yearSelectionRange) { final int oldYearSelectionRange = this.yearSelectionRange; this.yearSelectionRange = yearSelectionRange; refreshYearSelector(); firePropertyChange("yearSelectionRange", oldYearSelectionRange, yearSelectionRange); } } jcommon-1.0.16/source/org/jfree/ui/WizardDialog.java0000644000175000017500000002447611172030703022230 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * WizardDialog.java * ----------------- * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: WizardDialog.java,v 1.6 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; /** * A dialog that presents the user with a sequence of steps for completing a task. The dialog * contains "Next" and "Previous" buttons, allowing the user to navigate through the task. *

* When the user backs up by one or more steps, the dialog keeps the completed steps so that * they can be reused if the user doesn't change anything - this handles the cases where the user * backs up a few steps just to review what has been completed. *

* But if the user changes some options in an earlier step, then the dialog may have to discard * the later steps and have them repeated. *

* THIS CLASS IS NOT WORKING CORRECTLY YET. * * * @author David Gilbert */ public class WizardDialog extends JDialog implements ActionListener { /** The end result of the wizard sequence. */ private Object result; /** The current step in the wizard process (starting at step zero). */ private int step; /** A reference to the current panel. */ private WizardPanel currentPanel; /** A list of references to the panels the user has already seen - used for navigating through the steps that have already been completed. */ private java.util.List panels; /** A handy reference to the "previous" button. */ private JButton previousButton; /** A handy reference to the "next" button. */ private JButton nextButton; /** A handy reference to the "finish" button. */ private JButton finishButton; /** A handy reference to the "help" button. */ private JButton helpButton; /** * Standard constructor - builds and returns a new WizardDialog. * * @param owner the owner. * @param modal modal? * @param title the title. * @param firstPanel the first panel. */ public WizardDialog(final JDialog owner, final boolean modal, final String title, final WizardPanel firstPanel) { super(owner, title + " : step 1", modal); this.result = null; this.currentPanel = firstPanel; this.step = 0; this.panels = new ArrayList(); this.panels.add(firstPanel); setContentPane(createContent()); } /** * Standard constructor - builds a new WizardDialog owned by the specified JFrame. * * @param owner the owner. * @param modal modal? * @param title the title. * @param firstPanel the first panel. */ public WizardDialog(final JFrame owner, final boolean modal, final String title, final WizardPanel firstPanel) { super(owner, title + " : step 1", modal); this.result = null; this.currentPanel = firstPanel; this.step = 0; this.panels = new ArrayList(); this.panels.add(firstPanel); setContentPane(createContent()); } /** * Returns the result of the wizard sequence. * * @return the result. */ public Object getResult() { return this.result; } /** * Returns the total number of steps in the wizard sequence, if this number is known. Otherwise * this method returns zero. Subclasses should override this method unless the number of steps * is not known. * * @return the number of steps. */ public int getStepCount() { return 0; } /** * Returns true if it is possible to back up to the previous panel, and false otherwise. * * @return boolean. */ public boolean canDoPreviousPanel() { return (this.step > 0); } /** * Returns true if there is a 'next' panel, and false otherwise. * * @return boolean. */ public boolean canDoNextPanel() { return this.currentPanel.hasNextPanel(); } /** * Returns true if it is possible to finish the sequence at this point (possibly with defaults * for the remaining entries). * * @return boolean. */ public boolean canFinish() { return this.currentPanel.canFinish(); } /** * Returns the panel for the specified step (steps are numbered from zero). * * @param step the current step. * * @return the panel. */ public WizardPanel getWizardPanel(final int step) { if (step < this.panels.size()) { return (WizardPanel) this.panels.get(step); } else { return null; } } /** * Handles events. * * @param event the event. */ public void actionPerformed(final ActionEvent event) { final String command = event.getActionCommand(); if (command.equals("nextButton")) { next(); } else if (command.equals("previousButton")) { previous(); } else if (command.equals("finishButton")) { finish(); } } /** * Handles a click on the "previous" button, by displaying the previous panel in the sequence. */ public void previous() { if (this.step > 0) { final WizardPanel previousPanel = getWizardPanel(this.step - 1); // tell the panel that we are returning previousPanel.returnFromLaterStep(); final Container content = getContentPane(); content.remove(this.currentPanel); content.add(previousPanel); this.step = this.step - 1; this.currentPanel = previousPanel; setTitle("Step " + (this.step + 1)); enableButtons(); pack(); } } /** * Displays the next step in the wizard sequence. */ public void next() { WizardPanel nextPanel = getWizardPanel(this.step + 1); if (nextPanel != null) { if (!this.currentPanel.canRedisplayNextPanel()) { nextPanel = this.currentPanel.getNextPanel(); } } else { nextPanel = this.currentPanel.getNextPanel(); } this.step = this.step + 1; if (this.step < this.panels.size()) { this.panels.set(this.step, nextPanel); } else { this.panels.add(nextPanel); } final Container content = getContentPane(); content.remove(this.currentPanel); content.add(nextPanel); this.currentPanel = nextPanel; setTitle("Step " + (this.step + 1)); enableButtons(); pack(); } /** * Finishes the wizard. */ public void finish() { this.result = this.currentPanel.getResult(); setVisible(false); } /** * Enables/disables the buttons according to the current step. A good idea would be to ask the * panels to return the status... */ private void enableButtons() { this.previousButton.setEnabled(this.step > 0); this.nextButton.setEnabled(canDoNextPanel()); this.finishButton.setEnabled(canFinish()); this.helpButton.setEnabled(false); } /** * Checks, whether the user cancelled the dialog. * * @return false. */ public boolean isCancelled() { return false; } /** * Creates a panel containing the user interface for the dialog. * * @return the panel. */ public JPanel createContent() { final JPanel content = new JPanel(new BorderLayout()); content.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); content.add((JPanel) this.panels.get(0)); final L1R3ButtonPanel buttons = new L1R3ButtonPanel("Help", "Previous", "Next", "Finish"); this.helpButton = buttons.getLeftButton(); this.helpButton.setEnabled(false); this.previousButton = buttons.getRightButton1(); this.previousButton.setActionCommand("previousButton"); this.previousButton.addActionListener(this); this.previousButton.setEnabled(false); this.nextButton = buttons.getRightButton2(); this.nextButton.setActionCommand("nextButton"); this.nextButton.addActionListener(this); this.nextButton.setEnabled(true); this.finishButton = buttons.getRightButton3(); this.finishButton.setActionCommand("finishButton"); this.finishButton.addActionListener(this); this.finishButton.setEnabled(false); buttons.setBorder(BorderFactory.createEmptyBorder(4, 0, 0, 0)); content.add(buttons, BorderLayout.SOUTH); return content; } } jcommon-1.0.16/source/org/jfree/ui/TextAnchor.java0000644000175000017500000001573511172030703021725 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * TextAnchor.java * --------------- * (C) Copyright 2003-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextAnchor.java,v 1.5 2005/10/18 13:18:34 mungady Exp $ * * Changes: * -------- * 10-Jun-2003 : Version 1 (DG); * 11-Jan-2005 : Removed deprecated code (DG); * */ package org.jfree.ui; import java.io.ObjectStreamException; import java.io.Serializable; /** * Used to indicate the position of an anchor point for a text string. This is * frequently used to align a string to a fixed point in some coordinate space. * * @author David Gilbert */ public final class TextAnchor implements Serializable { /** For serialization. */ private static final long serialVersionUID = 8219158940496719660L; /** Top/left. */ public static final TextAnchor TOP_LEFT = new TextAnchor("TextAnchor.TOP_LEFT"); /** Top/center. */ public static final TextAnchor TOP_CENTER = new TextAnchor("TextAnchor.TOP_CENTER"); /** Top/right. */ public static final TextAnchor TOP_RIGHT = new TextAnchor("TextAnchor.TOP_RIGHT"); /** Half-ascent/left. */ public static final TextAnchor HALF_ASCENT_LEFT = new TextAnchor("TextAnchor.HALF_ASCENT_LEFT"); /** Half-ascent/center. */ public static final TextAnchor HALF_ASCENT_CENTER = new TextAnchor("TextAnchor.HALF_ASCENT_CENTER"); /** Half-ascent/right. */ public static final TextAnchor HALF_ASCENT_RIGHT = new TextAnchor("TextAnchor.HALF_ASCENT_RIGHT"); /** Middle/left. */ public static final TextAnchor CENTER_LEFT = new TextAnchor("TextAnchor.CENTER_LEFT"); /** Middle/center. */ public static final TextAnchor CENTER = new TextAnchor("TextAnchor.CENTER"); /** Middle/right. */ public static final TextAnchor CENTER_RIGHT = new TextAnchor("TextAnchor.CENTER_RIGHT"); /** Baseline/left. */ public static final TextAnchor BASELINE_LEFT = new TextAnchor("TextAnchor.BASELINE_LEFT"); /** Baseline/center. */ public static final TextAnchor BASELINE_CENTER = new TextAnchor("TextAnchor.BASELINE_CENTER"); /** Baseline/right. */ public static final TextAnchor BASELINE_RIGHT = new TextAnchor("TextAnchor.BASELINE_RIGHT"); /** Bottom/left. */ public static final TextAnchor BOTTOM_LEFT = new TextAnchor("TextAnchor.BOTTOM_LEFT"); /** Bottom/center. */ public static final TextAnchor BOTTOM_CENTER = new TextAnchor("TextAnchor.BOTTOM_CENTER"); /** Bottom/right. */ public static final TextAnchor BOTTOM_RIGHT = new TextAnchor("TextAnchor.BOTTOM_RIGHT"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private TextAnchor(final String name) { this.name = name; } /** * Returns a string representing the object. * * @return The string. */ public String toString() { return this.name; } /** * Returns true if this object is equal to the specified * object, and false otherwise. * * @param o the other object. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof TextAnchor)) { return false; } final TextAnchor order = (TextAnchor) o; if (!this.name.equals(order.name)) { return false; } return true; } /** * Returns a hash code value for the object. * * @return The hashcode */ public int hashCode() { return this.name.hashCode(); } /** * Ensures that serialization returns the unique instances. * * @return The object. * * @throws ObjectStreamException if there is a problem. */ private Object readResolve() throws ObjectStreamException { TextAnchor result = null; if (this.equals(TextAnchor.TOP_LEFT)) { result = TextAnchor.TOP_LEFT; } else if (this.equals(TextAnchor.TOP_CENTER)) { result = TextAnchor.TOP_CENTER; } else if (this.equals(TextAnchor.TOP_RIGHT)) { result = TextAnchor.TOP_RIGHT; } else if (this.equals(TextAnchor.BOTTOM_LEFT)) { result = TextAnchor.BOTTOM_LEFT; } else if (this.equals(TextAnchor.BOTTOM_CENTER)) { result = TextAnchor.BOTTOM_CENTER; } else if (this.equals(TextAnchor.BOTTOM_RIGHT)) { result = TextAnchor.BOTTOM_RIGHT; } else if (this.equals(TextAnchor.BASELINE_LEFT)) { result = TextAnchor.BASELINE_LEFT; } else if (this.equals(TextAnchor.BASELINE_CENTER)) { result = TextAnchor.BASELINE_CENTER; } else if (this.equals(TextAnchor.BASELINE_RIGHT)) { result = TextAnchor.BASELINE_RIGHT; } else if (this.equals(TextAnchor.CENTER_LEFT)) { result = TextAnchor.CENTER_LEFT; } else if (this.equals(TextAnchor.CENTER)) { result = TextAnchor.CENTER; } else if (this.equals(TextAnchor.CENTER_RIGHT)) { result = TextAnchor.CENTER_RIGHT; } else if (this.equals(TextAnchor.HALF_ASCENT_LEFT)) { result = TextAnchor.HALF_ASCENT_LEFT; } else if (this.equals(TextAnchor.HALF_ASCENT_CENTER)) { result = TextAnchor.HALF_ASCENT_CENTER; } else if (this.equals(TextAnchor.HALF_ASCENT_RIGHT)) { result = TextAnchor.HALF_ASCENT_RIGHT; } return result; } } jcommon-1.0.16/source/org/jfree/ui/StrokeSample.java0000644000175000017500000001277211172030703022255 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2009, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * StrokeSample.java * ----------------- * (C) Copyright 2000-2009, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: StrokeSample.java,v 1.5 2009/02/27 13:58:41 mungady Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 21-Mar-2003 : Fixed null pointer exception, bug 705126 (DG); * */ package org.jfree.ui; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import javax.swing.JComponent; import javax.swing.JList; import javax.swing.ListCellRenderer; /** * A panel that displays a stroke sample. * * @author David Gilbert */ public class StrokeSample extends JComponent implements ListCellRenderer { /** The stroke being displayed (may be null). */ private Stroke stroke; /** The preferred size of the component. */ private Dimension preferredSize; /** * Creates a StrokeSample for the specified stroke. * * @param stroke the sample stroke (null permitted). */ public StrokeSample(final Stroke stroke) { this.stroke = stroke; this.preferredSize = new Dimension(80, 18); setPreferredSize(this.preferredSize); } /** * Returns the current Stroke object being displayed. * * @return The stroke (possibly null). */ public Stroke getStroke() { return this.stroke; } /** * Sets the stroke object being displayed and repaints the component. * * @param stroke the stroke (null permitted). */ public void setStroke(final Stroke stroke) { this.stroke = stroke; repaint(); } /** * Returns the preferred size of the component. * * @return the preferred size of the component. */ public Dimension getPreferredSize() { return this.preferredSize; } /** * Draws a line using the sample stroke. * * @param g the graphics device. */ public void paintComponent(final Graphics g) { final Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final Dimension size = getSize(); final Insets insets = getInsets(); final double xx = insets.left; final double yy = insets.top; final double ww = size.getWidth() - insets.left - insets.right; final double hh = size.getHeight() - insets.top - insets.bottom; // calculate point one final Point2D one = new Point2D.Double(xx + 6, yy + hh / 2); // calculate point two final Point2D two = new Point2D.Double(xx + ww - 6, yy + hh / 2); // draw a circle at point one final Ellipse2D circle1 = new Ellipse2D.Double(one.getX() - 5, one.getY() - 5, 10, 10); final Ellipse2D circle2 = new Ellipse2D.Double(two.getX() - 6, two.getY() - 5, 10, 10); // draw a circle at point two g2.draw(circle1); g2.fill(circle1); g2.draw(circle2); g2.fill(circle2); // draw a line connecting the points final Line2D line = new Line2D.Double(one, two); if (this.stroke != null) { g2.setStroke(this.stroke); g2.draw(line); } } /** * Returns a list cell renderer for the stroke, so the sample can be * displayed in a list or combo. * * @param list the list. * @param value the value. * @param index the index. * @param isSelected selected? * @param cellHasFocus focussed? * * @return the component for rendering. */ public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value instanceof Stroke) { setStroke((Stroke) value); } else { setStroke(null); } return this; } } jcommon-1.0.16/source/org/jfree/ui/IntegerDocument.java0000644000175000017500000000505111172030703022730 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * IntegerDocument.java * -------------------- * (C) Copyright 2000-2004, by Andrzej Porebski. * * Original Author: Andrzej Porebski; * Contributor(s): -; * * $Id: IntegerDocument.java,v 1.3 2005/11/16 15:58:41 taqua Exp $ * * Changes (from 7-Nov-2001) * ------------------------- * 07-Nov-2001 : Added to com.jrefinery.ui package (DG); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; /** * A document for editing integers. * * @author Andrzej Porebski */ public class IntegerDocument extends PlainDocument { /** * Inserts a string. * * @param i i. * @param s s. * @param attributes the attributes. * * @throws BadLocationException ?? */ public void insertString(final int i, final String s, final AttributeSet attributes) throws BadLocationException { super.insertString(i, s, attributes); if (s != null && (!s.equals("-") || i != 0 || s.length() >= 2)) { try { Integer.parseInt(getText(0, getLength())); } catch (NumberFormatException e) { remove(i, s.length()); } } } } jcommon-1.0.16/source/org/jfree/ui/SerialDateChooserPanel.java0000644000175000017500000003126611172030703024163 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------- * SerialDateChooserPanel.java * --------------------------- * (C) Copyright 2001-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SerialDateChooserPanel.java,v 1.7 2007/11/02 17:50:36 taqua Exp $ * * Changes * ------- * 08-Dec-2001 : Version 1 (DG); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import org.jfree.date.SerialDate; /** * A panel that allows the user to select a date. *

* This class is incomplete and untested. You should not use it yet... * * @author David Gilbert */ public class SerialDateChooserPanel extends JPanel implements ActionListener { /** The default background color for the selected date. */ public static final Color DEFAULT_DATE_BUTTON_COLOR = Color.red; /** The default background color for the current month. */ public static final Color DEFAULT_MONTH_BUTTON_COLOR = Color.lightGray; /** The date selected in the panel. */ private SerialDate date; /** The color for the selected date. */ private Color dateButtonColor; /** The color for dates in the current month. */ private Color monthButtonColor; /** The color for dates that are visible, but not in the current month. */ private Color chosenOtherButtonColor = Color.darkGray; /** The first day-of-the-week. */ private int firstDayOfWeek = Calendar.SUNDAY; /** The range used for selecting years. */ private int yearSelectionRange = 20; /** The font used to display the date. */ private Font dateFont = new Font("SansSerif", Font.PLAIN, 10); /** A combo for selecting the month. */ private JComboBox monthSelector = null; /** A combo for selecting the year. */ private JComboBox yearSelector = null; /** A button for selecting today's date. */ private JButton todayButton = null; /** An array of buttons used to display the days-of-the-month. */ private JButton[] buttons = null; /** A flag that indicates whether or not we are currently refreshing the buttons. */ private boolean refreshing = false; /** * Constructs a new date chooser panel, using today's date as the initial selection. */ public SerialDateChooserPanel() { this(SerialDate.createInstance(new Date()), false, DEFAULT_DATE_BUTTON_COLOR, DEFAULT_MONTH_BUTTON_COLOR); } /** * Constructs a new date chooser panel. * * @param date the date. * @param controlPanel a flag that indicates whether or not the 'today' button should * appear on the panel. */ public SerialDateChooserPanel(final SerialDate date, final boolean controlPanel) { this(date, controlPanel, DEFAULT_DATE_BUTTON_COLOR, DEFAULT_MONTH_BUTTON_COLOR); } /** * Constructs a new date chooser panel. * * @param date the date. * @param controlPanel the control panel. * @param dateButtonColor the date button color. * @param monthButtonColor the month button color. */ public SerialDateChooserPanel(final SerialDate date, final boolean controlPanel, final Color dateButtonColor, final Color monthButtonColor) { super(new BorderLayout()); this.date = date; this.dateButtonColor = dateButtonColor; this.monthButtonColor = monthButtonColor; add(constructSelectionPanel(), BorderLayout.NORTH); add(getCalendarPanel(), BorderLayout.CENTER); if (controlPanel) { add(constructControlPanel(), BorderLayout.SOUTH); } } /** * Sets the date chosen in the panel. * * @param date the new date. */ public void setDate(final SerialDate date) { this.date = date; this.monthSelector.setSelectedIndex(date.getMonth() - 1); refreshYearSelector(); refreshButtons(); } /** * Returns the date selected in the panel. * * @return the selected date. */ public SerialDate getDate() { return this.date; } /** * Handles action-events from the date panel. * * @param e information about the event that occurred. */ public void actionPerformed(final ActionEvent e) { if (e.getActionCommand().equals("monthSelectionChanged")) { final JComboBox c = (JComboBox) e.getSource(); this.date = SerialDate.createInstance( this.date.getDayOfMonth(), c.getSelectedIndex() + 1, this.date.getYYYY() ); refreshButtons(); } else if (e.getActionCommand().equals("yearSelectionChanged")) { if (!this.refreshing) { final JComboBox c = (JComboBox) e.getSource(); final Integer y = (Integer) c.getSelectedItem(); this.date = SerialDate.createInstance( this.date.getDayOfMonth(), this.date.getMonth(), y.intValue() ); refreshYearSelector(); refreshButtons(); } } else if (e.getActionCommand().equals("todayButtonClicked")) { setDate(SerialDate.createInstance(new Date())); } else if (e.getActionCommand().equals("dateButtonClicked")) { final JButton b = (JButton) e.getSource(); final int i = Integer.parseInt(b.getName()); final SerialDate first = getFirstVisibleDate(); final SerialDate selected = SerialDate.addDays(i, first); setDate(selected); } } /** * Returns a panel of buttons, each button representing a day in the month. This is a * sub-component of the DatePanel. * * @return the panel. */ private JPanel getCalendarPanel() { final JPanel panel = new JPanel(new GridLayout(7, 7)); panel.add(new JLabel("Sun", SwingConstants.CENTER)); panel.add(new JLabel("Mon", SwingConstants.CENTER)); panel.add(new JLabel("Tue", SwingConstants.CENTER)); panel.add(new JLabel("Wed", SwingConstants.CENTER)); panel.add(new JLabel("Thu", SwingConstants.CENTER)); panel.add(new JLabel("Fri", SwingConstants.CENTER)); panel.add(new JLabel("Sat", SwingConstants.CENTER)); this.buttons = new JButton[42]; for (int i = 0; i < 42; i++) { final JButton button = new JButton(""); button.setMargin(new Insets(1, 1, 1, 1)); button.setName(Integer.toString(i)); button.setFont(this.dateFont); button.setFocusPainted(false); button.setActionCommand("dateButtonClicked"); button.addActionListener(this); this.buttons[i] = button; panel.add(button); } return panel; } /** * Returns the button color according to the specified date. * * @param targetDate the target date. * * @return the button color. */ protected Color getButtonColor(final SerialDate targetDate) { if (this.date.equals(this.date)) { return this.dateButtonColor; } else if (targetDate.getMonth() == this.date.getMonth()) { return this.monthButtonColor; } else { return this.chosenOtherButtonColor; } } /** * Returns the first date that is visible in the grid. This should always be in the month * preceding the month of the selected date. * * @return the first visible date. */ protected SerialDate getFirstVisibleDate() { SerialDate result = SerialDate.createInstance(1, this.date.getMonth(), this.date.getYYYY()); result = SerialDate.addDays(-1, result); while (result.getDayOfWeek() != getFirstDayOfWeek()) { result = SerialDate.addDays(-1, result); } return result; } /** * Returns the first day of the week (controls the labels in the date panel). * * @return the first day of the week. */ private int getFirstDayOfWeek() { return this.firstDayOfWeek; } /** * Update the button labels and colors to reflect date selection. */ protected void refreshButtons() { SerialDate current = getFirstVisibleDate(); for (int i = 0; i < 42; i++) { final JButton button = this.buttons[i]; button.setText(String.valueOf(current.getDayOfWeek())); button.setBackground(getButtonColor(current)); current = SerialDate.addDays(1, current); } } /** * Changes the contents of the year selection JComboBox to reflect the chosen date and the year * range. */ private void refreshYearSelector() { if (!this.refreshing) { this.refreshing = true; this.yearSelector.removeAllItems(); final Vector v = getYears(this.date.getYYYY()); for (Enumeration e = v.elements(); e.hasMoreElements();) { this.yearSelector.addItem(e.nextElement()); } this.yearSelector.setSelectedItem(new Integer(this.date.getYYYY())); this.refreshing = false; } } /** * Returns a vector of years preceding and following the specified year. The number of years * preceding and following is determined by the yearSelectionRange attribute. * * @param chosenYear the current year. * * @return a vector of years. */ private Vector getYears(final int chosenYear) { final Vector v = new Vector(); for (int i = chosenYear - this.yearSelectionRange; i <= chosenYear + this.yearSelectionRange; i++) { v.addElement(new Integer(i)); } return v; } /** * Constructs a panel containing two JComboBoxes (for the month and year) and a button * (to reset the date to TODAY). * * @return the panel. */ private JPanel constructSelectionPanel() { final JPanel p = new JPanel(); this.monthSelector = new JComboBox(SerialDate.getMonths()); this.monthSelector.addActionListener(this); this.monthSelector.setActionCommand("monthSelectionChanged"); p.add(this.monthSelector); this.yearSelector = new JComboBox(getYears(0)); this.yearSelector.addActionListener(this); this.yearSelector.setActionCommand("yearSelectionChanged"); p.add(this.yearSelector); return p; } /** * Returns a panel that appears at the bottom of the calendar panel - contains a button for * selecting today's date. * * @return the panel. */ private JPanel constructControlPanel() { final JPanel p = new JPanel(); p.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5)); this.todayButton = new JButton("Today"); this.todayButton.addActionListener(this); this.todayButton.setActionCommand("todayButtonClicked"); p.add(this.todayButton); return p; } } jcommon-1.0.16/source/org/jfree/ui/StrokeChooserPanel.java0000644000175000017500000000762011172030703023412 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2009, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * StrokeChooserPanel.java * ----------------------- * (C) Copyright 2000-2009, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Dirk Zeitz; * * $Id: StrokeChooserPanel.java,v 1.8 2009/02/27 13:58:41 mungady Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 16-Mar-2004 : Fix for focus problems (DZ); * 27-Feb-2009 : Fixed bug 2612649, NullPointerException (DG); * */ package org.jfree.ui; import java.awt.BorderLayout; import java.awt.Stroke; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JPanel; /** * A component for choosing a stroke from a list of available strokes. This * class needs work. * * @author David Gilbert */ public class StrokeChooserPanel extends JPanel { /** A combo for selecting the stroke. */ private JComboBox selector; /** * Creates a panel containing a combo-box that allows the user to select * one stroke from a list of available strokes. * * @param current the current stroke sample. * @param available an array of 'available' stroke samples. */ public StrokeChooserPanel(StrokeSample current, StrokeSample[] available) { setLayout(new BorderLayout()); // we've changed the behaviour here to populate the combo box // with Stroke objects directly - ideally we'd change the signature // of the constructor too...maybe later. DefaultComboBoxModel model = new DefaultComboBoxModel(); for (int i = 0; i < available.length; i++) { model.addElement(available[i].getStroke()); } this.selector = new JComboBox(model); this.selector.setSelectedItem(current.getStroke()); this.selector.setRenderer(new StrokeSample(null)); add(this.selector); // Changes due to focus problems!! DZ this.selector.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent evt) { getSelector().transferFocus(); } }); } /** * Returns the selector component. * * @return Returns the selector. */ protected final JComboBox getSelector() { return this.selector; } /** * Returns the selected stroke. * * @return The selected stroke (possibly null). */ public Stroke getSelectedStroke() { return (Stroke) this.selector.getSelectedItem(); } } jcommon-1.0.16/source/org/jfree/ui/LocalizationBundle.properties0000644000175000017500000000055711172030703024677 0ustar twernertwerner# org.jfree.ui.ui ResourceBundle properties file # # Changes (from 31-Aug-2003) # -------------------------- # 31-Aug-2003 : Initial version (AL); # Attributes=Attributes: B=B: Bold=Bold Bottom=Bottom Font=Font: Insets=Insets: Italic=Italic L=L: Left=Left No_Font_Selected=No font selected. R=R: Right=Right Size=Size: T=T: Top=Top Help=Help OK=OK Cancel=Cancel jcommon-1.0.16/source/org/jfree/ui/RectangleInsets.java0000644000175000017500000004241011172030703022726 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2007, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * RectangleInsets.java * -------------------- * (C) Copyright 2004, 2005, 2007, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: RectangleInsets.java,v 1.15 2007/03/16 14:29:45 mungady Exp $ * * Changes: * -------- * 11-Feb-2004 : Version 1 (DG); * 14-Jun-2004 : Implemented Serializable (DG); * 02-Feb-2005 : Added new methods and renamed some existing methods (DG); * 22-Feb-2005 : Added a new constructor for convenience (DG); * 19-Apr-2005 : Changed order of parameters in constructors to match * java.awt.Insets (DG); * 16-Mar-2007 : Added default constructor (DG); * */ package org.jfree.ui; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.util.UnitType; /** * Represents the insets for a rectangle, specified in absolute or relative * terms. This class is immutable. * * @author David Gilbert */ public class RectangleInsets implements Serializable { /** For serialization. */ private static final long serialVersionUID = 1902273207559319996L; /** * A useful constant representing zero insets. */ public static final RectangleInsets ZERO_INSETS = new RectangleInsets( UnitType.ABSOLUTE, 0.0, 0.0, 0.0, 0.0); /** Absolute or relative units. */ private UnitType unitType; /** The top insets. */ private double top; /** The left insets. */ private double left; /** The bottom insets. */ private double bottom; /** The right insets. */ private double right; /** * Creates a new instance with all insets initialised to 1.0. * * @since 1.0.9 */ public RectangleInsets() { this(1.0, 1.0, 1.0, 1.0); } /** * Creates a new instance with the specified insets (as 'absolute' units). * * @param top the top insets. * @param left the left insets. * @param bottom the bottom insets. * @param right the right insets. */ public RectangleInsets(final double top, final double left, final double bottom, final double right) { this(UnitType.ABSOLUTE, top, left, bottom, right); } /** * Creates a new instance. * * @param unitType absolute or relative units (null not * permitted). * @param top the top insets. * @param left the left insets. * @param bottom the bottom insets. * @param right the right insets. */ public RectangleInsets(final UnitType unitType, final double top, final double left, final double bottom, final double right) { if (unitType == null) { throw new IllegalArgumentException("Null 'unitType' argument."); } this.unitType = unitType; this.top = top; this.bottom = bottom; this.left = left; this.right = right; } /** * Returns the unit type (absolute or relative). This specifies whether * the insets are measured as Java2D units or percentages. * * @return The unit type (never null). */ public UnitType getUnitType() { return this.unitType; } /** * Returns the top insets. * * @return The top insets. */ public double getTop() { return this.top; } /** * Returns the bottom insets. * * @return The bottom insets. */ public double getBottom() { return this.bottom; } /** * Returns the left insets. * * @return The left insets. */ public double getLeft() { return this.left; } /** * Returns the right insets. * * @return The right insets. */ public double getRight() { return this.right; } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object (null permitted). * * @return A boolean. */ public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof RectangleInsets)) { return false; } final RectangleInsets that = (RectangleInsets) obj; if (that.unitType != this.unitType) { return false; } if (this.left != that.left) { return false; } if (this.right != that.right) { return false; } if (this.top != that.top) { return false; } if (this.bottom != that.bottom) { return false; } return true; } /** * Returns a hash code for the object. * * @return A hash code. */ public int hashCode() { int result; long temp; result = (this.unitType != null ? this.unitType.hashCode() : 0); temp = this.top != +0.0d ? Double.doubleToLongBits(this.top) : 0L; result = 29 * result + (int) (temp ^ (temp >>> 32)); temp = this.bottom != +0.0d ? Double.doubleToLongBits(this.bottom) : 0L; result = 29 * result + (int) (temp ^ (temp >>> 32)); temp = this.left != +0.0d ? Double.doubleToLongBits(this.left) : 0L; result = 29 * result + (int) (temp ^ (temp >>> 32)); temp = this.right != +0.0d ? Double.doubleToLongBits(this.right) : 0L; result = 29 * result + (int) (temp ^ (temp >>> 32)); return result; } /** * Returns a textual representation of this instance, useful for debugging * purposes. * * @return A string representing this instance. */ public String toString() { return "RectangleInsets[t=" + this.top + ",l=" + this.left + ",b=" + this.bottom + ",r=" + this.right + "]"; } /** * Creates an adjusted rectangle using the supplied rectangle, the insets * specified by this instance, and the horizontal and vertical * adjustment types. * * @param base the base rectangle (null not permitted). * @param horizontal the horizontal adjustment type (null not * permitted). * @param vertical the vertical adjustment type (null not * permitted). * * @return The inset rectangle. */ public Rectangle2D createAdjustedRectangle(final Rectangle2D base, final LengthAdjustmentType horizontal, final LengthAdjustmentType vertical) { if (base == null) { throw new IllegalArgumentException("Null 'base' argument."); } double x = base.getX(); double y = base.getY(); double w = base.getWidth(); double h = base.getHeight(); if (horizontal == LengthAdjustmentType.EXPAND) { final double leftOutset = calculateLeftOutset(w); x = x - leftOutset; w = w + leftOutset + calculateRightOutset(w); } else if (horizontal == LengthAdjustmentType.CONTRACT) { final double leftMargin = calculateLeftInset(w); x = x + leftMargin; w = w - leftMargin - calculateRightInset(w); } if (vertical == LengthAdjustmentType.EXPAND) { final double topMargin = calculateTopOutset(h); y = y - topMargin; h = h + topMargin + calculateBottomOutset(h); } else if (vertical == LengthAdjustmentType.CONTRACT) { final double topMargin = calculateTopInset(h); y = y + topMargin; h = h - topMargin - calculateBottomInset(h); } return new Rectangle2D.Double(x, y, w, h); } /** * Creates an 'inset' rectangle. * * @param base the base rectangle (null not permitted). * * @return The inset rectangle. */ public Rectangle2D createInsetRectangle(final Rectangle2D base) { return createInsetRectangle(base, true, true); } /** * Creates an 'inset' rectangle. * * @param base the base rectangle (null not permitted). * @param horizontal apply horizontal insets? * @param vertical apply vertical insets? * * @return The inset rectangle. */ public Rectangle2D createInsetRectangle(final Rectangle2D base, final boolean horizontal, final boolean vertical) { if (base == null) { throw new IllegalArgumentException("Null 'base' argument."); } double topMargin = 0.0; double bottomMargin = 0.0; if (vertical) { topMargin = calculateTopInset(base.getHeight()); bottomMargin = calculateBottomInset(base.getHeight()); } double leftMargin = 0.0; double rightMargin = 0.0; if (horizontal) { leftMargin = calculateLeftInset(base.getWidth()); rightMargin = calculateRightInset(base.getWidth()); } return new Rectangle2D.Double( base.getX() + leftMargin, base.getY() + topMargin, base.getWidth() - leftMargin - rightMargin, base.getHeight() - topMargin - bottomMargin ); } /** * Creates an outset rectangle. * * @param base the base rectangle (null not permitted). * * @return An outset rectangle. */ public Rectangle2D createOutsetRectangle(final Rectangle2D base) { return createOutsetRectangle(base, true, true); } /** * Creates an outset rectangle. * * @param base the base rectangle (null not permitted). * @param horizontal apply horizontal insets? * @param vertical apply vertical insets? * * @return An outset rectangle. */ public Rectangle2D createOutsetRectangle(final Rectangle2D base, final boolean horizontal, final boolean vertical) { if (base == null) { throw new IllegalArgumentException("Null 'base' argument."); } double topMargin = 0.0; double bottomMargin = 0.0; if (vertical) { topMargin = calculateTopOutset(base.getHeight()); bottomMargin = calculateBottomOutset(base.getHeight()); } double leftMargin = 0.0; double rightMargin = 0.0; if (horizontal) { leftMargin = calculateLeftOutset(base.getWidth()); rightMargin = calculateRightOutset(base.getWidth()); } return new Rectangle2D.Double( base.getX() - leftMargin, base.getY() - topMargin, base.getWidth() + leftMargin + rightMargin, base.getHeight() + topMargin + bottomMargin ); } /** * Returns the top margin. * * @param height the height of the base rectangle. * * @return The top margin (in Java2D units). */ public double calculateTopInset(final double height) { double result = this.top; if (this.unitType == UnitType.RELATIVE) { result = (this.top * height); } return result; } /** * Returns the top margin. * * @param height the height of the base rectangle. * * @return The top margin (in Java2D units). */ public double calculateTopOutset(final double height) { double result = this.top; if (this.unitType == UnitType.RELATIVE) { result = (height / (1 - this.top - this.bottom)) * this.top; } return result; } /** * Returns the bottom margin. * * @param height the height of the base rectangle. * * @return The bottom margin (in Java2D units). */ public double calculateBottomInset(final double height) { double result = this.bottom; if (this.unitType == UnitType.RELATIVE) { result = (this.bottom * height); } return result; } /** * Returns the bottom margin. * * @param height the height of the base rectangle. * * @return The bottom margin (in Java2D units). */ public double calculateBottomOutset(final double height) { double result = this.bottom; if (this.unitType == UnitType.RELATIVE) { result = (height / (1 - this.top - this.bottom)) * this.bottom; } return result; } /** * Returns the left margin. * * @param width the width of the base rectangle. * * @return The left margin (in Java2D units). */ public double calculateLeftInset(final double width) { double result = this.left; if (this.unitType == UnitType.RELATIVE) { result = (this.left * width); } return result; } /** * Returns the left margin. * * @param width the width of the base rectangle. * * @return The left margin (in Java2D units). */ public double calculateLeftOutset(final double width) { double result = this.left; if (this.unitType == UnitType.RELATIVE) { result = (width / (1 - this.left - this.right)) * this.left; } return result; } /** * Returns the right margin. * * @param width the width of the base rectangle. * * @return The right margin (in Java2D units). */ public double calculateRightInset(final double width) { double result = this.right; if (this.unitType == UnitType.RELATIVE) { result = (this.right * width); } return result; } /** * Returns the right margin. * * @param width the width of the base rectangle. * * @return The right margin (in Java2D units). */ public double calculateRightOutset(final double width) { double result = this.right; if (this.unitType == UnitType.RELATIVE) { result = (width / (1 - this.left - this.right)) * this.right; } return result; } /** * Trims the given width to allow for the insets. * * @param width the width. * * @return The trimmed width. */ public double trimWidth(final double width) { return width - calculateLeftInset(width) - calculateRightInset(width); } /** * Extends the given width to allow for the insets. * * @param width the width. * * @return The extended width. */ public double extendWidth(final double width) { return width + calculateLeftOutset(width) + calculateRightOutset(width); } /** * Trims the given height to allow for the insets. * * @param height the height. * * @return The trimmed height. */ public double trimHeight(final double height) { return height - calculateTopInset(height) - calculateBottomInset(height); } /** * Extends the given height to allow for the insets. * * @param height the height. * * @return The extended height. */ public double extendHeight(final double height) { return height + calculateTopOutset(height) + calculateBottomOutset(height); } /** * Shrinks the given rectangle by the amount of these insets. * * @param area the area (null not permitted). */ public void trim(final Rectangle2D area) { final double w = area.getWidth(); final double h = area.getHeight(); final double l = calculateLeftInset(w); final double r = calculateRightInset(w); final double t = calculateTopInset(h); final double b = calculateBottomInset(h); area.setRect(area.getX() + l, area.getY() + t, w - l - r, h - t - b); } } jcommon-1.0.16/source/org/jfree/ui/VerticalAlignment.java0000644000175000017500000001024011172030703023240 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * VerticalAlignment.java * ---------------------- * (C) Copyright 2004, 2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: VerticalAlignment.java,v 1.4 2005/10/18 13:18:34 mungady Exp $ * * Changes: * -------- * 08-Jan-2004 : Version 1 (DG); * */ package org.jfree.ui; import java.io.ObjectStreamException; import java.io.Serializable; /** * An enumeration of the vertical alignment types (TOP, * BOTTOM and CENTER). * * @author David Gilbert */ public final class VerticalAlignment implements Serializable { /** For serialization. */ private static final long serialVersionUID = 7272397034325429853L; /** Top alignment. */ public static final VerticalAlignment TOP = new VerticalAlignment("VerticalAlignment.TOP"); /** Bottom alignment. */ public static final VerticalAlignment BOTTOM = new VerticalAlignment("VerticalAlignment.BOTTOM"); /** Center alignment. */ public static final VerticalAlignment CENTER = new VerticalAlignment("VerticalAlignment.CENTER"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private VerticalAlignment(final String name) { this.name = name; } /** * Returns a string representing the object. * * @return the string. */ public String toString() { return this.name; } /** * Returns true if this object is equal to the specified * object, and false otherwise. * * @param o the other object. * * @return a boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof VerticalAlignment)) { return false; } final VerticalAlignment alignment = (VerticalAlignment) o; if (!this.name.equals(alignment.name)) { return false; } return true; } /** * Returns a hash code value for the object. * * @return the hashcode */ public int hashCode() { return this.name.hashCode(); } /** * Ensures that serialization returns the unique instances. * * @return The object. * * @throws ObjectStreamException if there is a problem. */ private Object readResolve() throws ObjectStreamException { if (this.equals(VerticalAlignment.TOP)) { return VerticalAlignment.TOP; } else if (this.equals(VerticalAlignment.BOTTOM)) { return VerticalAlignment.BOTTOM; } else if (this.equals(VerticalAlignment.CENTER)) { return VerticalAlignment.CENTER; } else { return null; // this should never happen } } } jcommon-1.0.16/source/org/jfree/ui/about/0000755000175000017500000000000011351753320020110 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/ui/about/AboutPanel.java0000644000175000017500000001156311172030703023005 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * AboutPanel.java * --------------- * (C) Copyright 2001-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: AboutPanel.java,v 1.6 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Nov-2001 : Version 1 (DG); * 27-Jun-2002 : Added logo (DG); * 08-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui.about; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.Image; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import org.jfree.ui.RefineryUtilities; /** * A standard panel for displaying information about an application. * * @author David Gilbert */ public class AboutPanel extends JPanel { /** * Constructs a panel. * * @param application the application name. * @param version the version. * @param copyright the copyright statement. * @param info other info. */ public AboutPanel(final String application, final String version, final String copyright, final String info) { this(application, version, copyright, info, null); } /** * Constructs a panel. * * @param application the application name. * @param version the version. * @param copyright the copyright statement. * @param info other info. * @param logo an optional logo. */ public AboutPanel(final String application, final String version, final String copyright, final String info, final Image logo) { setLayout(new BorderLayout()); final JPanel textPanel = new JPanel(new GridLayout(4, 1, 0, 4)); final JPanel appPanel = new JPanel(); final Font f1 = new Font("Dialog", Font.BOLD, 14); final JLabel appLabel = RefineryUtilities.createJLabel(application, f1, Color.black); appLabel.setHorizontalTextPosition(SwingConstants.CENTER); appPanel.add(appLabel); final JPanel verPanel = new JPanel(); final Font f2 = new Font("Dialog", Font.PLAIN, 12); final JLabel verLabel = RefineryUtilities.createJLabel(version, f2, Color.black); verLabel.setHorizontalTextPosition(SwingConstants.CENTER); verPanel.add(verLabel); final JPanel copyrightPanel = new JPanel(); final JLabel copyrightLabel = RefineryUtilities.createJLabel(copyright, f2, Color.black); copyrightLabel.setHorizontalTextPosition(SwingConstants.CENTER); copyrightPanel.add(copyrightLabel); final JPanel infoPanel = new JPanel(); final JLabel infoLabel = RefineryUtilities.createJLabel(info, f2, Color.black); infoLabel.setHorizontalTextPosition(SwingConstants.CENTER); infoPanel.add(infoLabel); textPanel.add(appPanel); textPanel.add(verPanel); textPanel.add(copyrightPanel); textPanel.add(infoPanel); add(textPanel); if (logo != null) { final JPanel imagePanel = new JPanel(new BorderLayout()); imagePanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(logo))); imagePanel.setBorder(BorderFactory.createLineBorder(Color.black)); final JPanel imageContainer = new JPanel(new BorderLayout()); imageContainer.add(imagePanel, BorderLayout.NORTH); add(imageContainer, BorderLayout.WEST); } } } jcommon-1.0.16/source/org/jfree/ui/about/ContributorsPanel.java0000644000175000017500000000524611172030703024431 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * ContributorsPanel.java * ---------------------- * (C) Copyright 2001-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ContributorsPanel.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes * ------- * 10-Dec-2001 : Version 1 (DG); * 28-Feb-2002 : Moved into package com.jrefinery.ui.about. Changed import statements and * updated Javadoc comments (DG); * 08-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui.about; import java.awt.BorderLayout; import java.util.List; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.TableModel; /** * A panel containing a table that lists the contributors to a project. *

* Used in the AboutFrame class. * * @author David Gilbert */ public class ContributorsPanel extends JPanel { /** The table. */ private JTable table; /** The data. */ private TableModel model; /** * Creates a new contributors panel. * * @param contributors a list of contributors (represented by Contributor objects). */ public ContributorsPanel(final List contributors) { setLayout(new BorderLayout()); this.model = new ContributorsTableModel(contributors); this.table = new JTable(this.model); add(new JScrollPane(this.table)); } } jcommon-1.0.16/source/org/jfree/ui/about/AboutDialog.java0000644000175000017500000002345311172030703023146 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * AboutFrame.java * --------------- * (C) Copyright 2001-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: AboutDialog.java,v 1.4 2008/12/18 09:57:32 mungady Exp $ * * Changes (from 26-Nov-2001) * -------------------------- * 30-Jan-2006 : Version 1, based on the AboutFrame (TM); * 18-Dec-2008 : Use ResourceBundleWrapper (DG); * */ package org.jfree.ui.about; import java.awt.BorderLayout; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.Image; import java.util.List; import java.util.ResourceBundle; import javax.swing.BorderFactory; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.border.Border; import org.jfree.util.ResourceBundleWrapper; /** * A dialog that displays information about the demonstration application. * * @author David Gilbert */ public class AboutDialog extends JDialog { /** The preferred size for the frame. */ public static final Dimension PREFERRED_SIZE = new Dimension(560, 360); /** The default border for the panels in the tabbed pane. */ public static final Border STANDARD_BORDER = BorderFactory.createEmptyBorder(5, 5, 5, 5); /** Localised resources. */ private ResourceBundle resources; /** The application name. */ private String application; /** The application version. */ private String version; /** The copyright string. */ private String copyright; /** Other info about the application. */ private String info; /** The project logo. */ private Image logo; /** A list of contributors. */ private List contributors; /** The licence. */ private String licence; /** * Constructs an about frame. * * @param title the frame title. * @param project information about the project. */ public AboutDialog(final String title, final ProjectInfo project) { init(title, project.getName(), "Version " + project.getVersion(), project.getInfo(), project.getLogo(), project.getCopyright(), project.getLicenceText(), project.getContributors(), project); } /** * Creates a non-modal dialog without a title with the specifed * Frame as its owner. * * @param owner the Frame from which the dialog is displayed. * @param title the title, * @param project the project. */ public AboutDialog(final Frame owner, final String title, final ProjectInfo project) { super(owner); init(title, project.getName(), "Version " + project.getVersion(), project.getInfo(), project.getLogo(), project.getCopyright(), project.getLicenceText(), project.getContributors(), project); } /** * Creates a non-modal dialog without a title with the specifed * Dialog as its owner. * * @param owner the Dialog from which the dialog is displayed. * @param title the title. * @param project the project. */ public AboutDialog(final Dialog owner, final String title, final ProjectInfo project) { super(owner); init(title, project.getName(), "Version " + project.getVersion(), project.getInfo(), project.getLogo(), project.getCopyright(), project.getLicenceText(), project.getContributors(), project); } /** * Constructs an 'About' frame. * * @param title the frame title. * @param application the application name. * @param version the version. * @param info other info. * @param logo an optional logo. * @param copyright the copyright notice. * @param licence the licence. * @param contributors a list of developers/contributors. * @param libraries a list of libraries. */ private void init (final String title, final String application, final String version, final String info, final Image logo, final String copyright, final String licence, final List contributors, final ProjectInfo libraries) { setTitle(title); this.application = application; this.version = version; this.copyright = copyright; this.info = info; this.logo = logo; this.contributors = contributors; this.licence = licence; final String baseName = "org.jfree.ui.about.resources.AboutResources"; this.resources = ResourceBundleWrapper.getBundle(baseName); final JPanel content = new JPanel(new BorderLayout()); content.setBorder(STANDARD_BORDER); final JTabbedPane tabs = createTabs(libraries); content.add(tabs); setContentPane(content); pack(); } /** * Returns the preferred size for the about frame. * * @return the preferred size. */ public Dimension getPreferredSize() { return PREFERRED_SIZE; } /** * Creates a tabbed pane containing an about panel and a system properties * panel. * * @param info project information. * * @return a tabbed pane. */ private JTabbedPane createTabs(final ProjectInfo info) { final JTabbedPane tabs = new JTabbedPane(); final JPanel aboutPanel = createAboutPanel(info); aboutPanel.setBorder(AboutDialog.STANDARD_BORDER); final String aboutTab = this.resources.getString( "about-frame.tab.about"); tabs.add(aboutTab, aboutPanel); final JPanel systemPanel = new SystemPropertiesPanel(); systemPanel.setBorder(AboutDialog.STANDARD_BORDER); final String systemTab = this.resources.getString( "about-frame.tab.system"); tabs.add(systemTab, systemPanel); return tabs; } /** * Creates a panel showing information about the application, including the * name, version, copyright notice, URL for further information, and a list * of contributors. * * @param info project info. * * @return a panel. */ private JPanel createAboutPanel(final ProjectInfo info) { final JPanel about = new JPanel(new BorderLayout()); final JPanel details = new AboutPanel(this.application, this.version, this.copyright, this.info, this.logo); boolean includetabs = false; final JTabbedPane tabs = new JTabbedPane(); if (this.contributors != null) { final JPanel contributorsPanel = new ContributorsPanel( this.contributors); contributorsPanel.setBorder(AboutDialog.STANDARD_BORDER); final String contributorsTab = this.resources.getString( "about-frame.tab.contributors"); tabs.add(contributorsTab, contributorsPanel); includetabs = true; } if (this.licence != null) { final JPanel licencePanel = createLicencePanel(); licencePanel.setBorder(STANDARD_BORDER); final String licenceTab = this.resources.getString( "about-frame.tab.licence"); tabs.add(licenceTab, licencePanel); includetabs = true; } if (info != null) { final JPanel librariesPanel = new LibraryPanel(info); librariesPanel.setBorder(AboutDialog.STANDARD_BORDER); final String librariesTab = this.resources.getString( "about-frame.tab.libraries"); tabs.add(librariesTab, librariesPanel); includetabs = true; } about.add(details, BorderLayout.NORTH); if (includetabs) { about.add(tabs); } return about; } /** * Creates a panel showing the licence. * * @return a panel. */ private JPanel createLicencePanel() { final JPanel licencePanel = new JPanel(new BorderLayout()); final JTextArea area = new JTextArea(this.licence); area.setLineWrap(true); area.setWrapStyleWord(true); area.setCaretPosition(0); area.setEditable(false); licencePanel.add(new JScrollPane(area)); return licencePanel; } } jcommon-1.0.16/source/org/jfree/ui/about/AboutFrame.java0000644000175000017500000002141611172030703022776 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * AboutFrame.java * --------------- * (C) Copyright 2001-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: AboutFrame.java,v 1.8 2008/12/18 09:57:32 mungady Exp $ * * Changes (from 26-Nov-2001) * -------------------------- * 26-Nov-2001 : Version 1, based on code from JFreeChart demo application (DG); * 27-Nov-2001 : Added getPreferredSize() method (DG); * 08-Feb-2002 : List of developers is now optional (DG); * 15-Mar-2002 : Modified to use a ResourceBundle for elements that require * localisation (DG); * 25-Mar-2002 : Added new constructor (DG); * 26-Jun-2002 : Removed redundant code (DG); * 08-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.ui.about; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Image; import java.util.List; import java.util.ResourceBundle; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.border.Border; import org.jfree.util.ResourceBundleWrapper; /** * A frame that displays information about the demonstration application. * * @author David Gilbert */ public class AboutFrame extends JFrame { /** The preferred size for the frame. */ public static final Dimension PREFERRED_SIZE = new Dimension(560, 360); /** The default border for the panels in the tabbed pane. */ public static final Border STANDARD_BORDER = BorderFactory.createEmptyBorder(5, 5, 5, 5); /** Localised resources. */ private ResourceBundle resources; /** The application name. */ private String application; /** The application version. */ private String version; /** The copyright string. */ private String copyright; /** Other info about the application. */ private String info; /** The project logo. */ private Image logo; /** A list of contributors. */ private List contributors; /** The licence. */ private String licence; /** * Constructs an about frame. * * @param title the frame title. * @param project information about the project. */ public AboutFrame(final String title, final ProjectInfo project) { this(title, project.getName(), "Version " + project.getVersion(), project.getInfo(), project.getLogo(), project.getCopyright(), project.getLicenceText(), project.getContributors(), project); } /** * Constructs an 'About' frame. * * @param title the frame title. * @param application the application name. * @param version the version. * @param info other info. * @param logo an optional logo. * @param copyright the copyright notice. * @param licence the licence. * @param contributors a list of developers/contributors. * @param project info about the project. */ public AboutFrame(final String title, final String application, final String version, final String info, final Image logo, final String copyright, final String licence, final List contributors, final ProjectInfo project) { super(title); this.application = application; this.version = version; this.copyright = copyright; this.info = info; this.logo = logo; this.contributors = contributors; this.licence = licence; final String baseName = "org.jfree.ui.about.resources.AboutResources"; this.resources = ResourceBundleWrapper.getBundle(baseName); final JPanel content = new JPanel(new BorderLayout()); content.setBorder(STANDARD_BORDER); final JTabbedPane tabs = createTabs(project); content.add(tabs); setContentPane(content); pack(); } /** * Returns the preferred size for the about frame. * * @return the preferred size. */ public Dimension getPreferredSize() { return PREFERRED_SIZE; } /** * Creates a tabbed pane containing an about panel and a system properties * panel. * * @return a tabbed pane. * @param project */ private JTabbedPane createTabs(final ProjectInfo project) { final JTabbedPane tabs = new JTabbedPane(); final JPanel aboutPanel = createAboutPanel(project); aboutPanel.setBorder(AboutFrame.STANDARD_BORDER); final String aboutTab = this.resources.getString( "about-frame.tab.about"); tabs.add(aboutTab, aboutPanel); final JPanel systemPanel = new SystemPropertiesPanel(); systemPanel.setBorder(AboutFrame.STANDARD_BORDER); final String systemTab = this.resources.getString( "about-frame.tab.system"); tabs.add(systemTab, systemPanel); return tabs; } /** * Creates a panel showing information about the application, including the * name, version, copyright notice, URL for further information, and a list * of contributors. * @param project * * @return a panel. */ private JPanel createAboutPanel(final ProjectInfo project) { final JPanel about = new JPanel(new BorderLayout()); final JPanel details = new AboutPanel(this.application, this.version, this.copyright, this.info, this.logo); boolean includetabs = false; final JTabbedPane tabs = new JTabbedPane(); if (this.contributors != null) { final JPanel contributorsPanel = new ContributorsPanel( this.contributors); contributorsPanel.setBorder(AboutFrame.STANDARD_BORDER); final String contributorsTab = this.resources.getString( "about-frame.tab.contributors"); tabs.add(contributorsTab, contributorsPanel); includetabs = true; } if (this.licence != null) { final JPanel licencePanel = createLicencePanel(); licencePanel.setBorder(STANDARD_BORDER); final String licenceTab = this.resources.getString( "about-frame.tab.licence"); tabs.add(licenceTab, licencePanel); includetabs = true; } if (project != null) { final JPanel librariesPanel = new LibraryPanel(project); librariesPanel.setBorder(AboutFrame.STANDARD_BORDER); final String librariesTab = this.resources.getString( "about-frame.tab.libraries"); tabs.add(librariesTab, librariesPanel); includetabs = true; } about.add(details, BorderLayout.NORTH); if (includetabs) { about.add(tabs); } return about; } /** * Creates a panel showing the licence. * * @return a panel. */ private JPanel createLicencePanel() { final JPanel licencePanel = new JPanel(new BorderLayout()); final JTextArea area = new JTextArea(this.licence); area.setLineWrap(true); area.setWrapStyleWord(true); area.setCaretPosition(0); area.setEditable(false); licencePanel.add(new JScrollPane(area)); return licencePanel; } } jcommon-1.0.16/source/org/jfree/ui/about/resources/0000755000175000017500000000000011351753320022122 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/ui/about/resources/AboutResources_de.java0000644000175000017500000001012211172030703026370 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * AboutResources_de.java * ---------------------- * (C) Copyright 2002-2004, by Object Refinery Limited. * * Original Author: Thomas Meier; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AboutResources_de.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes * ------- * 04-Apr-2002 : Version 1, translation by Thomas Meier (DG); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui.about.resources; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.ListResourceBundle; import javax.swing.KeyStroke; /** * A resource bundle that stores all the user interface items that might need localisation. * * @author Thomas Meier */ public class AboutResources_de extends ListResourceBundle { /** * Default constructor. */ public AboutResources_de() { } /** * Returns the array of strings in the resource bundle. * * @return the resources. */ public Object[][] getContents() { return CONTENTS; } /** The resources to be localised. */ private static final Object[][] CONTENTS = { {"about-frame.tab.about", "\u00dcber"}, {"about-frame.tab.system", "System"}, {"about-frame.tab.contributors", "Entwickler"}, {"about-frame.tab.licence", "Lizenz"}, {"about-frame.tab.libraries", "Bibliotheken"}, {"contributors-table.column.name", "Name:"}, {"contributors-table.column.contact", "Kontakt:"}, {"libraries-table.column.name", "Name:"}, {"libraries-table.column.version", "Version:"}, {"libraries-table.column.licence", "Lizenz:"}, {"libraries-table.column.info", "Zus. Information:"}, {"system-frame.title", "Systemeigenschaften"}, {"system-frame.button.close", "Schlie\u00dfen"}, {"system-frame.button.close.mnemonic", new Character('C')}, {"system-frame.menu.file", "Datei" }, {"system-frame.menu.file.mnemonic", new Character('D')}, {"system-frame.menu.file.close", "Beenden" }, {"system-frame.menu.file.close.mnemonic", new Character('B')}, {"system-frame.menu.edit", "Bearbeiten"}, {"system-frame.menu.edit.mnemonic", new Character('B')}, {"system-frame.menu.edit.copy", "Kopieren"}, {"system-frame.menu.edit.copy.mnemonic", new Character('K')}, {"system-properties-table.column.name", "Eigenschaft:"}, {"system-properties-table.column.value", "Wert:"}, {"system-properties-panel.popup-menu.copy", "Kopieren"}, {"system-properties-panel.popup-menu.copy.accelerator", KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK)} }; } jcommon-1.0.16/source/org/jfree/ui/about/resources/package.html0000644000175000017500000000023411172030703024374 0ustar twernertwerner Resource bundles for items that require localisation. jcommon-1.0.16/source/org/jfree/ui/about/resources/AboutResources_es.java0000644000175000017500000001010711172030703026412 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * AboutResources_es.java * ---------------------- * (C) Copyright 2002-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Hans-Jurgen Greiner; * * $Id: AboutResources_es.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes * ------- * 26-Mar-2002 : Version 1, translation by Hans-Jurgen Greiner (DG); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui.about.resources; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.ListResourceBundle; import javax.swing.KeyStroke; /** * A resource bundle that stores all the user interface items that might need localisation. * * @author Hans-Jurgen Greiner. */ public class AboutResources_es extends ListResourceBundle { /** * Default constructor. */ public AboutResources_es() { } /** * Returns the array of strings in the resource bundle. * * @return the resources. */ public Object[][] getContents() { return CONTENTS; } /** The resources to be localised. */ private static final Object[][] CONTENTS = { {"about-frame.tab.about", "Acerca"}, {"about-frame.tab.system", "Sistema"}, {"about-frame.tab.contributors", "Desarrolladores"}, {"about-frame.tab.licence", "Licencia"}, {"about-frame.tab.libraries", "Bibliotecas"}, {"contributors-table.column.name", "Nombre:"}, {"contributors-table.column.contact", "Contacto:"}, {"libraries-table.column.name", "Nombre::"}, {"libraries-table.column.version", "Versi\u00f5n:"}, {"libraries-table.column.licence", "Licencia:"}, {"libraries-table.column.info", "Otra Informaci?n:"}, {"system-frame.title", "propiedades del Sistema"}, {"system-frame.button.close", "Cerrar"}, {"system-frame.menu.file", "Archivo"}, {"system-frame.menu.file.mnemonic", new Character('F')}, {"system-frame.menu.file.close", "Cerrar"}, {"system-frame.menu.file.close.mnemonic", new Character('C')}, {"system-frame.menu.edit", "Edici?n"}, {"system-frame.menu.edit.mnemonic", new Character('E')}, {"system-frame.menu.edit.copy", "Copiar"}, {"system-frame.menu.edit.copy.mnemonic", new Character('C')}, {"system-properties-table.column.name", "Nombre de Propiedad:"}, {"system-properties-table.column.value", "Valor:"}, {"system-properties-panel.popup-menu.copy", "Copiar" }, {"system-properties-panel.popup-menu.copy.accelerator", KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK) }, }; } jcommon-1.0.16/source/org/jfree/ui/about/resources/AboutResources.java0000644000175000017500000001001611172030703025722 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * AboutResources.java * ------------------- * (C) Copyright 2002-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: AboutResources.java,v 1.6 2007/11/02 17:50:36 taqua Exp $ * * Changes * ------- * 15-Mar-2002 : Version 1 (DG); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui.about.resources; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.ListResourceBundle; import javax.swing.KeyStroke; /** * A resource bundle that stores all the user interface items that might need localisation. * * @author David Gilbert */ public class AboutResources extends ListResourceBundle { /** * Default constructor. */ public AboutResources() { } /** * Returns the array of strings in the resource bundle. * * @return the resources. */ public Object[][] getContents() { return CONTENTS; } /** The resources to be localised. */ private static final Object[][] CONTENTS = { {"about-frame.tab.about", "About"}, {"about-frame.tab.system", "System"}, {"about-frame.tab.contributors", "Developers"}, {"about-frame.tab.licence", "Licence"}, {"about-frame.tab.libraries", "Libraries"}, {"contributors-table.column.name", "Name:"}, {"contributors-table.column.contact", "Contact:"}, {"libraries-table.column.name", "Name:"}, {"libraries-table.column.version", "Version:"}, {"libraries-table.column.licence", "Licence:"}, {"libraries-table.column.info", "Other Information:"}, {"system-frame.title", "System Properties"}, {"system-frame.button.close", "Close"}, {"system-frame.button.close.mnemonic", new Character('C')}, {"system-frame.menu.file", "File"}, {"system-frame.menu.file.mnemonic", new Character('F')}, {"system-frame.menu.file.close", "Close"}, {"system-frame.menu.file.close.mnemonic", new Character('C')}, {"system-frame.menu.edit", "Edit"}, {"system-frame.menu.edit.mnemonic", new Character('E')}, {"system-frame.menu.edit.copy", "Copy"}, {"system-frame.menu.edit.copy.mnemonic", new Character('C')}, {"system-properties-table.column.name", "Property Name:"}, {"system-properties-table.column.value", "Value:"}, {"system-properties-panel.popup-menu.copy", "Copy" }, {"system-properties-panel.popup-menu.copy.accelerator", KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK) }, }; } jcommon-1.0.16/source/org/jfree/ui/about/resources/AboutResources_fr.java0000644000175000017500000000762311172030703026423 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * AboutResources_fr.java * ---------------------- * * Original Author: Anthony Boulestreau; * Contributor(s): -; * * $Id: AboutResources_fr.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes * ------- * 26-Mar-2002 : Version 1 (AB); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui.about.resources; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.ListResourceBundle; import javax.swing.KeyStroke; /** * A resource bundle that stores all the user interface items that might need localisation. * * @author Anthony Boulestreau */ public class AboutResources_fr extends ListResourceBundle { /** * Default constructor. */ public AboutResources_fr() { } /** * Returns the array of strings in the resource bundle. * * @return the resources. */ public Object[][] getContents() { return CONTENTS; } /** The resources to be localised. */ private static final Object[][] CONTENTS = { {"about-frame.tab.about", "A propos de"}, {"about-frame.tab.system", "Syst\u00e8me"}, {"about-frame.tab.contributors", "D\u00e9veloppeurs"}, {"about-frame.tab.licence", "Licence"}, {"about-frame.tab.libraries", "Biblioth\u00e8que"}, {"contributors-table.column.name", "Nom:"}, {"contributors-table.column.contact", "Contact:"}, {"libraries-table.column.name", "Nom:"}, {"libraries-table.column.version", "Version:"}, {"libraries-table.column.licence", "Licence:"}, {"libraries-table.column.info", "Autre Renseignement:"}, {"system-frame.title", "Propri\u00e9t\u00e9s du Syst\u00e8me"}, {"system-frame.button.close", "Fermer"}, {"system-frame.menu.file", "Fichier"}, {"system-frame.menu.file.mnemonic", new Character('F')}, {"system-frame.menu.file.close", "Fermer"}, {"system-frame.menu.file.close.mnemonic", new Character('C')}, {"system-frame.menu.edit", "Edition"}, {"system-frame.menu.edit.mnemonic", new Character('E')}, {"system-frame.menu.edit.copy", "Copier"}, {"system-frame.menu.edit.copy.mnemonic", new Character('C')}, {"system-properties-table.column.name", "Nom de la Propri\u00e9t\u00e9:"}, {"system-properties-table.column.value", "Valeur:"}, {"system-properties-panel.popup-menu.copy", "Copier" }, {"system-properties-panel.popup-menu.copy.accelerator", KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK) }, }; } jcommon-1.0.16/source/org/jfree/ui/about/resources/AboutResources_pl.java0000644000175000017500000001035011172030703026416 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * AboutResources_pl.java * ---------------------- * (C) Copyright 2002-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Polish translation: Krzysztof Paz (kpaz@samorzad.pw.edu.pl); * Fixed char-encoding Piotr Bzdyl (piotr@geek.krakow.pl) * * $Id: AboutResources_pl.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes * ------- * 15-Mar-2002 : Version 1 (DG); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 31-Jan-2003 : Fixed character encoding (PB); * */ package org.jfree.ui.about.resources; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.ListResourceBundle; import javax.swing.KeyStroke; /** * A resource bundle that stores all the user interface items that might need localisation. * * @author KP */ public class AboutResources_pl extends ListResourceBundle { /** * Default constructor. */ public AboutResources_pl() { } /** * Returns the array of strings in the resource bundle. * * @return the resources. */ public Object[][] getContents() { return CONTENTS; } /** The resources to be localised. */ private static final Object[][] CONTENTS = { {"about-frame.tab.about", "Informacja o"}, {"about-frame.tab.system", "System"}, {"about-frame.tab.contributors", "Tw\u00f3rcy"}, {"about-frame.tab.licence", "Licencja"}, {"about-frame.tab.libraries", "Biblioteki"}, {"contributors-table.column.name", "Nazwa:"}, {"contributors-table.column.contact", "Kontakt:"}, {"libraries-table.column.name", "Nazwa:"}, {"libraries-table.column.version", "Wersja:"}, {"libraries-table.column.licence", "Licencja:"}, {"libraries-table.column.info", "Inne informacje:"}, {"system-frame.title", "W?a\u015bciwo\u015bci systemowe"}, {"system-frame.button.close", "Zamknij"}, {"system-frame.button.close.mnemonic", new Character('Z')}, {"system-frame.menu.file", "Plik"}, {"system-frame.menu.file.mnemonic", new Character('P')}, {"system-frame.menu.file.close", "Zamknij"}, {"system-frame.menu.file.close.mnemonic", new Character('K')}, {"system-frame.menu.edit", "Edycja"}, {"system-frame.menu.edit.mnemonic", new Character('E')}, {"system-frame.menu.edit.copy", "Kopiuj"}, {"system-frame.menu.edit.copy.mnemonic", new Character('C')}, {"system-properties-table.column.name", "Nazwa w?a\u015bciwo\u015bci:"}, {"system-properties-table.column.value", "Warto\u015b\u0107:"}, {"system-properties-panel.popup-menu.copy", "Kopiuj" }, {"system-properties-panel.popup-menu.copy.accelerator", KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK) }, }; } jcommon-1.0.16/source/org/jfree/ui/about/Contributor.java0000644000175000017500000000510211172030703023255 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * Contributor.java * ---------------- * (C) Copyright 2001-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: Contributor.java,v 1.4 2005/11/16 15:58:41 taqua Exp $ * * Changes * ------- * 10-Dec-2001 : Version 1 (DG); * 28-Feb-2002 : Moved into package com.jrefinery.ui.about (DG); * 08-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui.about; /** * A simple class representing a contributor to a software project. *

* Used in the AboutFrame class. * * @author David Gilbert */ public class Contributor { /** The name. */ private String name; /** The e-mail address. */ private String email; /** * Creates a new contributor. * * @param name the name. * @param email the e-mail address. */ public Contributor(final String name, final String email) { this.name = name; this.email = email; } /** * Returns the contributor's name. * * @return the contributor's name. */ public String getName() { return this.name; } /** * Returns the contributor's e-mail address. * * @return the contributor's e-mail address. */ public String getEmail() { return this.email; } } jcommon-1.0.16/source/org/jfree/ui/about/package.html0000644000175000017500000000023611172030703022364 0ustar twernertwerner Classes for providing information about an application. jcommon-1.0.16/source/org/jfree/ui/about/LibraryPanel.java0000644000175000017500000001047711172030703023342 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * LibraryReferencePanel.java * -------------------------- * (C) Copyright 2002-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: LibraryPanel.java,v 1.6 2008/09/10 09:18:12 mungady Exp $ * * Changes * ------- * 28-Feb-2002 : Version 1 (DG); * 08-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui.about; import java.awt.BorderLayout; import java.util.ArrayList; import java.util.List; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; /** * A panel containing a table that lists the libraries used in a project. *

* Used in the AboutFrame class. * * @author David Gilbert */ public class LibraryPanel extends JPanel { /** The table. */ private JTable table; /** The data. */ private LibraryTableModel model; /** * Constructs a LibraryPanel. * * @param libraries a list of libraries (represented by Library objects). */ public LibraryPanel(final List libraries) { setLayout(new BorderLayout()); this.model = new LibraryTableModel(libraries); this.table = new JTable(this.model); add(new JScrollPane(this.table)); } /** * Creates a new library panel for the specified project. * * @param projectInfo the project information. */ public LibraryPanel(final ProjectInfo projectInfo) { this(getLibraries(projectInfo)); } private static List getLibraries (final ProjectInfo info) { if (info == null) { return new ArrayList(); } final ArrayList libs = new ArrayList(); collectLibraries(info, libs); return libs; } private static void collectLibraries (final ProjectInfo info, final List list) { org.jfree.base.Library[] libs = info.getLibraries(); for (int i = 0; i < libs.length; i++) { final org.jfree.base.Library lib = libs[i]; if (list.contains(lib) == false) { // prevent duplicates, they look ugly .. list.add(lib); if (lib instanceof ProjectInfo) { collectLibraries((ProjectInfo) lib, list); } } } libs = info.getOptionalLibraries(); for (int i = 0; i < libs.length; i++) { final org.jfree.base.Library lib = libs[i]; if (list.contains(lib) == false) { // prevent duplicates, they look ugly .. list.add(lib); if (lib instanceof ProjectInfo) { collectLibraries((ProjectInfo) lib, list); } } } } /** * Returns the table model for the library. * * @return The table model. */ public LibraryTableModel getModel() { return this.model; } /** * Returns the JTable for the library. * * @return The table. */ protected JTable getTable() { return this.table; } } jcommon-1.0.16/source/org/jfree/ui/about/SystemPropertiesTableModel.java0000644000175000017500000002277111172030703026250 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------- * SystemPropertiesTableModel.java * ------------------------------- * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SystemPropertiesTableModel.java,v 1.6 2008/12/18 09:57:32 mungady Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui (DG); * 28-Feb-2001 : Changed package to com.jrefinery.ui.about (DG); * 15-Mar-2002 : Modified to use a ResourceBundle for elements that require * localisation (DG); * 08-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.ui.about; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.ResourceBundle; import org.jfree.ui.SortableTableModel; import org.jfree.util.ResourceBundleWrapper; /** * A sortable table model containing the system properties. * * @author David Gilbert */ public class SystemPropertiesTableModel extends SortableTableModel { /** * Useful class for holding the name and value of a system property. * */ protected static class SystemProperty { /** The property name. */ private String name; /** The property value. */ private String value; /** * Standard constructor - builds a new SystemProperty. * * @param name the property name. * @param value the property value. */ public SystemProperty(final String name, final String value) { this.name = name; this.value = value; } /** * Returns the property name. * * @return the property name. */ public String getName() { return this.name; } /** * Returns the property value. * * @return the property value. */ public String getValue() { return this.value; } } /** * A class for comparing SystemProperty objects. * */ protected static class SystemPropertyComparator implements Comparator { /** Indicates the sort order. */ private boolean ascending; /** * Standard constructor. * * @param ascending a flag that controls the sort order (ascending or * descending). */ public SystemPropertyComparator(final boolean ascending) { this.ascending = ascending; } /** * Compares two objects. * * @param o1 the first object. * @param o2 the second object. * * @return an integer that indicates the relative order of the objects. */ public int compare(final Object o1, final Object o2) { if ((o1 instanceof SystemProperty) && (o2 instanceof SystemProperty)) { final SystemProperty sp1 = (SystemProperty) o1; final SystemProperty sp2 = (SystemProperty) o2; if (this.ascending) { return sp1.getName().compareTo(sp2.getName()); } else { return sp2.getName().compareTo(sp1.getName()); } } else { return 0; } } /** * Returns true if this object is equal to the specified * object, and false otherwise. * * @param o the other object. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof SystemPropertyComparator)) { return false; } final SystemPropertyComparator systemPropertyComparator = (SystemPropertyComparator) o; if (this.ascending != systemPropertyComparator.ascending) { return false; } return true; } /** * Returns a hash code value for the object. * * @return the hashcode */ public int hashCode() { return (this.ascending ? 1 : 0); } } /** Storage for the properties. */ private List properties; /** Localised name column label. */ private String nameColumnLabel; /** Localised property column label. */ private String valueColumnLabel; /** * Creates a new table model using the properties of the current Java * Virtual Machine. */ public SystemPropertiesTableModel() { this.properties = new java.util.ArrayList(); try { final Properties p = System.getProperties(); final Iterator iterator = p.keySet().iterator(); while (iterator.hasNext()) { final String name = (String) iterator.next(); final String value = System.getProperty(name); final SystemProperty sp = new SystemProperty(name, value); this.properties.add(sp); } } catch (SecurityException se) { // ignore SecurityExceptions } Collections.sort(this.properties, new SystemPropertyComparator(true)); final String baseName = "org.jfree.ui.about.resources.AboutResources"; final ResourceBundle resources = ResourceBundleWrapper.getBundle( baseName); this.nameColumnLabel = resources.getString( "system-properties-table.column.name"); this.valueColumnLabel = resources.getString( "system-properties-table.column.value"); } /** * Returns true for the first column, and false otherwise - sorting is only * allowed on the first column. * * @param column the column index. * * @return true for column 0, and false for all other columns. */ public boolean isSortable(final int column) { if (column == 0) { return true; } else { return false; } } /** * Returns the number of rows in the table model (that is, the number of * system properties). * * @return the row count. */ public int getRowCount() { return this.properties.size(); } /** * Returns the number of columns in the table model. In this case, there * are two columns: one for the property name, and one for the property * value. * * @return the column count (always 2 in this case). */ public int getColumnCount() { return 2; } /** * Returns the name of the specified column. * * @param column the column index. * * @return the column name. */ public String getColumnName(final int column) { if (column == 0) { return this.nameColumnLabel; } else { return this.valueColumnLabel; } } /** * Returns the value at the specified row and column. This method supports * the TableModel interface. * * @param row the row index. * @param column the column index. * * @return the value. */ public Object getValueAt(final int row, final int column) { final SystemProperty sp = (SystemProperty) this.properties.get(row); if (column == 0) { return sp.getName(); } else { if (column == 1) { return sp.getValue(); } else { return null; } } } /** * Sorts on the specified column. * * @param column the column index. * @param ascending a flag that controls the sort order. * */ public void sortByColumn(final int column, final boolean ascending) { if (isSortable(column)) { super.sortByColumn(column, ascending); Collections.sort(this.properties, new SystemPropertyComparator(ascending)); } } } jcommon-1.0.16/source/org/jfree/ui/about/Licences.java0000644000175000017500000015626311172030703022507 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------- * Licences.java * ------------- * (C) Copyright 2001-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: Licences.java,v 1.4 2005/11/16 15:58:41 taqua Exp $ * * Changes * ------- * 26-Nov-2001 : Version 1 (DG); * 29-Jan-2002 : Appended the instructions to the end of the GNU LGPL and GPL to comply with * GNU requirements (DG); * 28-Feb-2002 : Moved to package com.jrefinery.ui.about (DG); * 08-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui.about; /** * Contains the full texts of the GNU General Public Licence and the GNU Lesser General Public * Licence. *

* These are used in the presentation of a standard 'About' frame. * * @author David Gilbert */ public class Licences { /** The GNU General Public Licence. */ public static final String GPL = "GNU GENERAL PUBLIC LICENSE\n" + "\n" + "Version 2, June 1991\n" + "\n" + "Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, " + "MA 02139, USA. Everyone is permitted to copy and distribute verbatim copies of this " + "license document, but changing it is not allowed.\n" + "\n" + "Preamble\n" + "The licenses for most software are designed to take away your freedom to share and " + "change it. By contrast, the GNU General Public License is intended to guarantee your " + "freedom to share and change free software--to make sure the software is free for all " + "its users. This General Public License applies to most of the Free Software " + "Foundation's software and to any other program whose authors commit to using it. (Some " + "other Free Software Foundation software is covered by the GNU Library General Public " + "License instead.) You can apply it to your programs, too.\n" + "\n" + "When we speak of free software, we are referring to freedom, not price. Our General " + "Public Licenses are designed to make sure that you have the freedom to distribute " + "copies of free software (and charge for this service if you wish), that you receive " + "source code or can get it if you want it, that you can change the software or use " + "pieces of it in new free programs; and that you know you can do these things." + "\n" + "To protect your rights, we need to make restrictions that forbid anyone to deny you " + "these rights or to ask you to surrender the rights. These restrictions translate to " + "certain responsibilities for you if you distribute copies of the software, or if you " + "modify it.\n" + "\n" + "For example, if you distribute copies of such a program, whether gratis or for a fee, " + "you must give the recipients all the rights that you have. You must make sure that " + "they, too, receive or can get the source code. And you must show them these terms so " + "they know their rights.\n" + "\n" + "We protect your rights with two steps: (1) copyright the software, and (2) offer you " + "this license which gives you legal permission to copy, distribute and/or modify the " + "software.\n" + "\n" + "Also, for each author's protection and ours, we want to make certain that everyone " + "understands that there is no warranty for this free software. If the software is " + "modified by someone else and passed on, we want its recipients to know that what they " + "have is not the original, so that any problems introduced by others will not reflect " + "on the original authors' reputations.\n" + "\n" + "Finally, any free program is threatened constantly by software patents. We wish to " + "avoid the danger that redistributors of a free program will individually obtain patent " + "licenses, in effect making the program proprietary. To prevent this, we have made it " + "clear that any patent must be licensed for everyone's free use or not licensed at " + "all.\n" + "\n" + "The precise terms and conditions for copying, distribution and modification follow.\n" + "\n" + "GNU GENERAL PUBLIC LICENSE\n" + "TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n" + "\n" + "0. This License applies to any program or other work which contains a notice placed by " + "the copyright holder saying it may be distributed under the terms of this General " + "Public License. The \"Program\", below, refers to any such program or work, and a " + "\"work based on the Program\" means either the Program or any derivative work under " + "copyright law: that is to say, a work containing the Program or a portion of it, " + "either verbatim or with modifications and/or translated into another language. " + "(Hereinafter, translation is included without limitation in the term " + "\"modification\".) Each licensee is addressed as \"you\".\n" + "\n" + "Activities other than copying, distribution and modification are not covered by this " + "License; they are outside its scope. The act of running the Program is not restricted, " + "and the output from the Program is covered only if its contents constitute a work " + "based on the Program (independent of having been made by running the Program). Whether " + "that is true depends on what the Program does.\n" + "\n" + "1. You may copy and distribute verbatim copies of the Program's source code as you " + "receive it, in any medium, provided that you conspicuously and appropriately publish " + "on each copy an appropriate copyright notice and disclaimer of warranty; keep intact " + "all the notices that refer to this License and to the absence of any warranty; and " + "give any other recipients of the Program a copy of this License along with the " + "Program.\n" + "\n" + "You may charge a fee for the physical act of transferring a copy, and you may at your " + "option offer warranty protection in exchange for a fee.\n" + "\n" + "2. You may modify your copy or copies of the Program or any portion of it, thus " + "forming a work based on the Program, and copy and distribute such modifications or " + "work under the terms of Section 1 above, provided that you also meet all of these " + "conditions:\n" + "\n" + "a) You must cause the modified files to carry prominent notices stating that you " + "changed the files and the date of any change.\n" + "\n" + "b) You must cause any work that you distribute or publish, that in whole or in part " + "contains or is derived from the Program or any part thereof, to be licensed as a whole " + "at no charge to all third parties under the terms of this License.\n" + "\n" + "c) If the modified program normally reads commands interactively when run, you must " + "cause it, when started running for such interactive use in the most ordinary way, to " + "print or display an announcement including an appropriate copyright notice and a " + "notice that there is no warranty (or else, saying that you provide a warranty) and " + "that users may redistribute the program under these conditions, and telling the user " + "how to view a copy of this License. (Exception: if the Program itself is interactive " + "but does not normally print such an announcement, your work based on the Program is " + "not required to print an announcement.)\n" + "\n" + "These requirements apply to the modified work as a whole. If identifiable sections of " + "that work are not derived from the Program, and can be reasonably considered " + "independent and separate works in themselves, then this License, and its terms, do not " + "apply to those sections when you distribute them as separate works. But when you " + "distribute the same sections as part of a whole which is a work based on the Program, " + "the distribution of the whole must be on the terms of this License, whose permissions " + "for other licensees extend to the entire whole, and thus to each and every part " + "regardless of who wrote it.\n" + "\n" + "Thus, it is not the intent of this section to claim rights or contest your rights to " + "work written entirely by you; rather, the intent is to exercise the right to control " + "the distribution of derivative or collective works based on the Program.\n" + "\n" + "In addition, mere aggregation of another work not based on the Program with the " + "Program (or with a work based on the Program) on a volume of a storage or distribution " + "medium does not bring the other work under the scope of this License.\n" + "\n" + "3. You may copy and distribute the Program (or a work based on it, under Section 2) in " + "object code or executable form under the terms of Sections 1 and 2 above provided that " + "you also do one of the following:\n" + "\n" + "a) Accompany it with the complete corresponding machine-readable source code, which " + "must be distributed under the terms of Sections 1 and 2 above on a medium customarily " + "used for software interchange; or,\n" + "b) Accompany it with a written offer, valid for at least three years, to give any " + "third party, for a charge no more than your cost of physically performing source " + "distribution, a complete machine-readable copy of the corresponding source code, to be " + "distributed under the terms of Sections 1 and 2 above on a medium customarily used for " + "software interchange; or,\n" + "c) Accompany it with the information you received as to the offer to distribute " + "corresponding source code. (This alternative is allowed only for noncommercial " + "distribution and only if you received the program in object code or executable form " + "with such an offer, in accord with Subsection b above.)\n" + "\n" + "The source code for a work means the preferred form of the work for making " + "modifications to it. For an executable work, complete source code means all the source " + "code for all modules it contains, plus any associated interface definition files, plus " + "the scripts used to control compilation and installation of the executable. However, " + "as a special exception, the source code distributed need not include anything that is " + "normally distributed (in either source or binary form) with the major components " + "(compiler, kernel, and so on) of the operating system on which the executable runs, " + "unless that component itself accompanies the executable.\n" + "\n" + "If distribution of executable or object code is made by offering access to copy from a " + "designated place, then offering equivalent access to copy the source code from the " + "same place counts as distribution of the source code, even though third parties are " + "not compelled to copy the source along with the object code.\n" + "\n" + "4. You may not copy, modify, sublicense, or distribute the Program except as expressly " + "provided under this License. Any attempt otherwise to copy, modify, sublicense or " + "distribute the Program is void, and will automatically terminate your rights under " + "this License. However, parties who have received copies, or rights, from you under " + "this License will not have their licenses terminated so long as such parties remain in " + "full compliance." + "\n" + "5. You are not required to accept this License, since you have not signed it. However, " + "nothing else grants you permission to modify or distribute the Program or its " + "derivative works. These actions are prohibited by law if you do not accept this " + "License. Therefore, by modifying or distributing the Program (or any work based on the " + "Program), you indicate your acceptance of this License to do so, and all its terms and " + "conditions for copying, distributing or modifying the Program or works based on it.\n" + "\n" + "6. Each time you redistribute the Program (or any work based on the Program), the " + "recipient automatically receives a license from the original licensor to copy, " + "distribute or modify the Program subject to these terms and conditions. You may not " + "impose any further restrictions on the recipients' exercise of the rights granted " + "herein. You are not responsible for enforcing compliance by third parties to this " + "License." + "\n" + "7. If, as a consequence of a court judgment or allegation of patent infringement or " + "for any other reason (not limited to patent issues), conditions are imposed on you " + "(whether by court order, agreement or otherwise) that contradict the conditions of " + "this License, they do not excuse you from the conditions of this License. If you " + "cannot distribute so as to satisfy simultaneously your obligations under this License " + "and any other pertinent obligations, then as a consequence you may not distribute the " + "Program at all. For example, if a patent license would not permit royalty-free " + "redistribution of the Program by all those who receive copies directly or indirectly " + "through you, then the only way you could satisfy both it and this License would be to " + "refrain entirely from distribution of the Program.\n" + "\n" + "If any portion of this section is held invalid or unenforceable under any particular " + "circumstance, the balance of the section is intended to apply and the section as a " + "whole is intended to apply in other circumstances.\n" + "\n" + "It is not the purpose of this section to induce you to infringe any patents or other " + "property right claims or to contest validity of any such claims; this section has the " + "sole purpose of protecting the integrity of the free software distribution system, " + "which is implemented by public license practices. Many people have made generous " + "contributions to the wide range of software distributed through that system in " + "reliance on consistent application of that system; it is up to the author/donor to " + "decide if he or she is willing to distribute software through any other system and a " + "licensee cannot impose that choice.\n" + "\n" + "This section is intended to make thoroughly clear what is believed to be a consequence " + "of the rest of this License.\n" + "\n" + "8. If the distribution and/or use of the Program is restricted in certain countries " + "either by patents or by copyrighted interfaces, the original copyright holder who " + "places the Program under this License may add an explicit geographical distribution " + "limitation excluding those countries, so that distribution is permitted only in or " + "among countries not thus excluded. In such case, this License incorporates the " + "limitation as if written in the body of this License.\n" + "\n" + "9. The Free Software Foundation may publish revised and/or new versions of the General " + "Public License from time to time. Such new versions will be similar in spirit to the " + "present version, but may differ in detail to address new problems or concerns.\n" + "\n" + "Each version is given a distinguishing version number. If the Program specifies a " + "version number of this License which applies to it and \"any later version\", you have " + "the option of following the terms and conditions either of that version or of any " + "later version published by the Free Software Foundation. If the Program does not " + "specify a version number of this License, you may choose any version ever published by " + "the Free Software Foundation.\n" + "\n" + "10. If you wish to incorporate parts of the Program into other free programs whose " + "distribution conditions are different, write to the author to ask for permission. For " + "software which is copyrighted by the Free Software Foundation, write to the Free " + "Software Foundation; we sometimes make exceptions for this. Our decision will be " + "guided by the two goals of preserving the free status of all derivatives of our free " + "software and of promoting the sharing and reuse of software generally.\n" + "\n" + "NO WARRANTY\n" + "\n" + "11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE " + "PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN " + "WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" " + "WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED " + "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. " + "THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD " + "THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR " + "CORRECTION.\n" + "\n" + "12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY " + "COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS " + "PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, " + "INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE " + "PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE " + "OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE " + "WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE " + "POSSIBILITY OF SUCH DAMAGES.\n" + "\n" + "END OF TERMS AND CONDITIONS\n" + "\n" + "\n" + "How to Apply These Terms to Your New Programs\n" + "\n" + "If you develop a new program, and you want it to be of the greatest possible use to " + "the public, the best way to achieve this is to make it free software which everyone " + "can redistribute and change under these terms.\n" + "\n" + "To do so, attach the following notices to the program. It is safest to attach them to " + "the start of each source file to most effectively convey the exclusion of warranty; " + "and each file should have at least the \"copyright\" line and a pointer to where the " + "full notice is found.\n" + "\n" + "\n" + "Copyright (C) \n" + "\n" + "This program is free software; you can redistribute it and/or modify it under the " + "terms of the GNU General Public License as published by the Free Software Foundation; " + "either version 2 of the License, or (at your option) any later version.\n" + "\n" + "This program is distributed in the hope that it will be useful, but WITHOUT ANY " + "WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A " + "PARTICULAR PURPOSE. See the GNU General Public License for more details.\n" + "\n" + "You should have received a copy of the GNU General Public License along with this " + "program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite " + "330, Boston, MA 02111-1307 USA\n" + "\n" + "Also add information on how to contact you by electronic and paper mail.\n" + "\n" + "If the program is interactive, make it output a short notice like this when it starts " + "in an interactive mode:\n" + "\n" + "Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with " + "ABSOLUTELY NO WARRANTY; for details type `show w'.\n" + "This is free software, and you are welcome to redistribute it under certain " + "conditions; type `show c' for details.\n" + "\n" + "The hypothetical commands `show w' and `show c' should show the appropriate parts of " + "the General Public License. Of course, the commands you use may be called something " + "other than `show w' and `show c'; they could even be mouse-clicks or menu items" + "--whatever suits your program.\n" + "\n" + "You should also get your employer (if you work as a programmer) or your school, if " + "any, to sign a \"copyright disclaimer\" for the program, if necessary. Here is a " + "sample; alter the names:\n" + "\n" + "Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' " + "(which makes passes at compilers) written by James Hacker.\n" + "\n" + ", 1 April 1989\n" + "Ty Coon, President of Vice\n" + "\n" + "This General Public License does not permit incorporating your program into " + "proprietary programs. If your program is a subroutine library, you may consider it " + "more useful to permit linking proprietary applications with the library. If this is " + "what you want to do, use the GNU Library General Public License instead of this " + "License.\n"; /** The GNU Lesser General Public Licence. */ public static final String LGPL = "GNU LESSER GENERAL PUBLIC LICENSE\n" + "\n" + "Version 2.1, February 1999\n" + "\n" + "Copyright (C) 1991, 1999 Free Software Foundation, Inc.\n" + "59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n" + "Everyone is permitted to copy and distribute verbatim copies of this license document, " + "but changing it is not allowed.\n" + "\n" + "[This is the first released version of the Lesser GPL. It also counts as the " + "successor of the GNU Library Public License, version 2, hence the version number " + "2.1.]\n" + "\n" + "Preamble\n" + "\n" + "The licenses for most software are designed to take away your freedom to share and " + "change it. By contrast, the GNU General Public Licenses are intended to guarantee your " + "freedom to share and change free software--to make sure the software is free for all " + "its users.\n" + "\n" + "This license, the Lesser General Public License, applies to some specially designated " + "software packages--typically libraries--of the Free Software Foundation and other " + "authors who decide to use it. You can use it too, but we suggest you first think " + "carefully about whether this license or the ordinary General Public License is the " + "better strategy to use in any particular case, based on the explanations below.\n" + "\n" + "When we speak of free software, we are referring to freedom of use, not price. Our " + "General Public Licenses are designed to make sure that you have the freedom to " + "distribute copies of free software (and charge for this service if you wish); that you " + "receive source code or can get it if you want it; that you can change the software and " + "use pieces of it in new free programs; and that you are informed that you can do these " + "things.\n" + "\n" + "To protect your rights, we need to make restrictions that forbid distributors to deny " + "you these rights or to ask you to surrender these rights. These restrictions translate " + "to certain responsibilities for you if you distribute copies of the library or if you " + "modify it.\n" + "\n" + "For example, if you distribute copies of the library, whether gratis or for a fee, you " + "must give the recipients all the rights that we gave you. You must make sure that " + "they, too, receive or can get the source code. If you link other code with the " + "library, you must provide complete object files to the recipients, so that they can " + "relink them with the library after making changes to the library and recompiling it. " + "And you must show them these terms so they know their rights.\n" + "\n" + "We protect your rights with a two-step method: (1) we copyright the library, and (2) " + "we offer you this license, which gives you legal permission to copy, distribute and/or " + "modify the library.\n" + "\n" + "To protect each distributor, we want to make it very clear that there is no warranty " + "for the free library. Also, if the library is modified by someone else and passed on, " + "the recipients should know that what they have is not the original version, so that " + "the original author's reputation will not be affected by problems that might be " + "introduced by others.\n" + "\n" + "Finally, software patents pose a constant threat to the existence of any free program. " + "We wish to make sure that a company cannot effectively restrict the users of a free " + "program by obtaining a restrictive license from a patent holder. Therefore, we insist " + "that any patent license obtained for a version of the library must be consistent with " + "the full freedom of use specified in this license.\n" + "\n" + "Most GNU software, including some libraries, is covered by the ordinary GNU General " + "Public License. This license, the GNU Lesser General Public License, applies to " + "certain designated libraries, and is quite different from the ordinary General Public " + "License. We use this license for certain libraries in order to permit linking those " + "libraries into non-free programs.\n" + "\n" + "When a program is linked with a library, whether statically or using a shared library, " + "the combination of the two is legally speaking a combined work, a derivative of the " + "original library. The ordinary General Public License therefore permits such linking " + "only if the entire combination fits its criteria of freedom. The Lesser General Public " + "License permits more lax criteria for linking other code with the library.\n" + "\n" + "We call this license the \"Lesser\" General Public License because it does Less to " + "protect the user's freedom than the ordinary General Public License. It also provides " + "other free software developers Less of an advantage over competing non-free programs. " + "These disadvantages are the reason we use the ordinary General Public License for many " + "libraries. However, the Lesser license provides advantages in certain special " + "circumstances.\n" + "\n" + "For example, on rare occasions, there may be a special need to encourage the widest " + "possible use of a certain library, so that it becomes a de-facto standard. To achieve " + "this, non-free programs must be allowed to use the library. A more frequent case is " + "that a free library does the same job as widely used non-free libraries. In this case, " + "there is little to gain by limiting the free library to free software only, so we use " + "the Lesser General Public License.\n" + "\n" + "In other cases, permission to use a particular library in non-free programs enables a " + "greater number of people to use a large body of free software. For example, permission " + "to use the GNU C Library in non-free programs enables many more people to use the " + "whole GNU operating system, as well as its variant, the GNU/Linux operating system.\n" + "\n" + "Although the Lesser General Public License is Less protective of the users' freedom, " + "it does ensure that the user of a program that is linked with the Library has the " + "freedom and the wherewithal to run that program using a modified version of the " + "Library.\n" + "\n" + "The precise terms and conditions for copying, distribution and modification follow. " + "Pay close attention to the difference between a \"work based on the library\" and a " + "\"work that uses the library\". The former contains code derived from the library, " + "whereas the latter must be combined with the library in order to run.\n" + "\n" + "TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n" + "\n" + "0. This License Agreement applies to any software library or other program which " + "contains a notice placed by the copyright holder or other authorized party saying it " + "may be distributed under the terms of this Lesser General Public License (also called " + "\"this License\"). Each licensee is addressed as \"you\"." + "\n" + "A \"library\" means a collection of software functions and/or data prepared so as to " + "be conveniently linked with application programs (which use some of those functions " + "and data) to form executables.\n" + "\n" + "The \"Library\", below, refers to any such software library or work which has been " + "distributed under these terms. A \"work based on the Library\" means either the " + "Library or any derivative work under copyright law: that is to say, a work containing " + "the Library or a portion of it, either verbatim or with modifications and/or " + "translated straightforwardly into another language. (Hereinafter, translation is " + "included without limitation in the term \"modification\".)\n" + "\n" + "\"Source code\" for a work means the preferred form of the work for making " + "modifications to it. For a library, complete source code means all the source code for " + "all modules it contains, plus any associated interface definition files, plus the " + "scripts used to control compilation and installation of the library.\n" + "\n" + "Activities other than copying, distribution and modification are not covered by this " + "License; they are outside its scope. The act of running a program using the Library is " + "not restricted, and output from such a program is covered only if its contents " + "constitute a work based on the Library (independent of the use of the Library in a " + "tool for writing it). Whether that is true depends on what the Library does and what " + "the program that uses the Library does." + "\n" + "1. You may copy and distribute verbatim copies of the Library's complete source code " + "as you receive it, in any medium, provided that you conspicuously and appropriately " + "publish on each copy an appropriate copyright notice and disclaimer of warranty; keep " + "intact all the notices that refer to this License and to the absence of any warranty; " + "and distribute a copy of this License along with the Library.\n" + "\n" + "You may charge a fee for the physical act of transferring a copy, and you may at your " + "option offer warranty protection in exchange for a fee.\n" + "\n" + "2. You may modify your copy or copies of the Library or any portion of it, thus " + "forming a work based on the Library, and copy and distribute such modifications or " + "work under the terms of Section 1 above, provided that you also meet all of these " + "conditions:\n" + "\n" + "* a) The modified work must itself be a software library.\n" + "* b) You must cause the files modified to carry prominent notices stating that you " + "changed the files and the date of any change.\n" + "* c) You must cause the whole of the work to be licensed at no charge to all third " + "parties under the terms of this License.\n" + "* d) If a facility in the modified Library refers to a function or a table of data " + "to be supplied by an application program that uses the facility, other than as an " + "argument passed when the facility is invoked, then you must make a good faith effort " + "to ensure that, in the event an application does not supply such function or table, " + "the facility still operates, and performs whatever part of its purpose remains " + "meaningful.\n" + "\n" + "(For example, a function in a library to compute square roots has a purpose that is " + "entirely well-defined independent of the application. Therefore, Subsection 2d " + "requires that any application-supplied function or table used by this function must be " + "optional: if the application does not supply it, the square root function must still " + "compute square roots.)\n" + "\n" + "These requirements apply to the modified work as a whole. If identifiable sections of " + "that work are not derived from the Library, and can be reasonably considered " + "independent and separate works in themselves, then this License, and its terms, do not " + "apply to those sections when you distribute them as separate works. But when you " + "distribute the same sections as part of a whole which is a work based on the Library, " + "the distribution of the whole must be on the terms of this License, whose permissions " + "for other licensees extend to the entire whole, and thus to each and every part " + "regardless of who wrote it.\n" + "\n" + "Thus, it is not the intent of this section to claim rights or contest your rights to " + "work written entirely by you; rather, the intent is to exercise the right to control " + "the distribution of derivative or collective works based on the Library.\n" + "\n" + "In addition, mere aggregation of another work not based on the Library with the " + "Library (or with a work based on the Library) on a volume of a storage or distribution " + "medium does not bring the other work under the scope of this License.\n" + "\n" + "3. You may opt to apply the terms of the ordinary GNU General Public License instead " + "of this License to a given copy of the Library. To do this, you must alter all the " + "notices that refer to this License, so that they refer to the ordinary GNU General " + "Public License, version 2, instead of to this License. (If a newer version than " + "version 2 of the ordinary GNU General Public License has appeared, then you can " + "specify that version instead if you wish.) Do not make any other change in these " + "notices.\n" + "\n" + "Once this change is made in a given copy, it is irreversible for that copy, so the " + "ordinary GNU General Public License applies to all subsequent copies and derivative " + "works made from that copy.\n" + "\n" + "This option is useful when you wish to copy part of the code of the Library into a " + "program that is not a library.\n" + "\n" + "4. You may copy and distribute the Library (or a portion or derivative of it, under " + "Section 2) in object code or executable form under the terms of Sections 1 and 2 above " + "provided that you accompany it with the complete corresponding machine-readable source " + "code, which must be distributed under the terms of Sections 1 and 2 above on a medium " + "customarily used for software interchange.\n" + "\n" + "If distribution of object code is made by offering access to copy from a designated " + "place, then offering equivalent access to copy the source code from the same place " + "satisfies the requirement to distribute the source code, even though third parties are " + "not compelled to copy the source along with the object code.\n" + "\n" + "5. A program that contains no derivative of any portion of the Library, but is " + "designed to work with the Library by being compiled or linked with it, is called a " + "\"work that uses the Library\". Such a work, in isolation, is not a derivative work of " + "the Library, and therefore falls outside the scope of this License.\n" + "\n" + "However, linking a \"work that uses the Library\" with the Library creates an " + "executable that is a derivative of the Library (because it contains portions of the " + "Library), rather than a \"work that uses the library\". The executable is therefore " + "covered by this License. Section 6 states terms for distribution of such executables.\n" + "\n" + "When a \"work that uses the Library\" uses material from a header file that is part of " + "the Library, the object code for the work may be a derivative work of the Library even " + "though the source code is not. Whether this is true is especially significant if the " + "work can be linked without the Library, or if the work is itself a library. The " + "threshold for this to be true is not precisely defined by law.\n" + "\n" + "If such an object file uses only numerical parameters, data structure layouts and " + "accessors, and small macros and small inline functions (ten lines or less in length), " + "then the use of the object file is unrestricted, regardless of whether it is legally a " + "derivative work. (Executables containing this object code plus portions of the Library " + "will still fall under Section 6.)\n" + "\n" + "Otherwise, if the work is a derivative of the Library, you may distribute the object " + "code for the work under the terms of Section 6. Any executables containing that work " + "also fall under Section 6, whether or not they are linked directly with the Library " + "itself.\n" + "\n" + "6. As an exception to the Sections above, you may also combine or link a \"work that " + "uses the Library\" with the Library to produce a work containing portions of the " + "Library, and distribute that work under terms of your choice, provided that the terms " + "permit modification of the work for the customer's own use and reverse engineering for " + "debugging such modifications.\n" + "\n" + "You must give prominent notice with each copy of the work that the Library is used in " + "it and that the Library and its use are covered by this License. You must supply a " + "copy of this License. If the work during execution displays copyright notices, you " + "must include the copyright notice for the Library among them, as well as a reference " + "directing the user to the copy of this License. Also, you must do one of these " + "things:\n" + "\n" + "* a) Accompany the work with the complete corresponding machine-readable source " + "code for the Library including whatever changes were used in the work (which must be " + "distributed under Sections 1 and 2 above); and, if the work is an executable linked " + "with the Library, with the complete machine-readable \"work that uses the Library\", " + "as object code and/or source code, so that the user can modify the Library and then " + "relink to produce a modified executable containing the modified Library. (It is " + "understood that the user who changes the contents of definitions files in the Library " + "will not necessarily be able to recompile the application to use the modified " + "definitions.)\n" + "* b) Use a suitable shared library mechanism for linking with the Library. A " + "suitable mechanism is one that (1) uses at run time a copy of the library already " + "present on the user's computer system, rather than copying library functions into the " + "executable, and (2) will operate properly with a modified version of the library, if " + "the user installs one, as long as the modified version is interface-compatible with " + "the version that the work was made with.\n" + "* c) Accompany the work with a written offer, valid for at least three years, to " + "give the same user the materials specified in Subsection 6a, above, for a charge no " + "more than the cost of performing this distribution.\n" + "* d) If distribution of the work is made by offering access to copy from a " + "designated place, offer equivalent access to copy the above specified materials from " + "the same place.\n" + "* e) Verify that the user has already received a copy of these materials or that " + "you have already sent this user a copy.\n" + "\n" + "For an executable, the required form of the \"work that uses the Library\" must " + "include any data and utility programs needed for reproducing the executable from it. " + "However, as a special exception, the materials to be distributed need not include " + "anything that is normally distributed (in either source or binary form) with the major " + "components (compiler, kernel, and so on) of the operating system on which the " + "executable runs, unless that component itself accompanies the executable.\n" + "\n" + "It may happen that this requirement contradicts the license restrictions of other " + "proprietary libraries that do not normally accompany the operating system. Such a " + "contradiction means you cannot use both them and the Library together in an executable " + "that you distribute.\n" + "\n" + "7. You may place library facilities that are a work based on the Library side-by-side " + "in a single library together with other library facilities not covered by this " + "License, and distribute such a combined library, provided that the separate " + "distribution of the work based on the Library and of the other library facilities is " + "otherwise permitted, and provided that you do these two things:\n" + "\n" + "* a) Accompany the combined library with a copy of the same work based on the " + "Library, uncombined with any other library facilities. This must be distributed under " + "the terms of the Sections above.\n" + "* b) Give prominent notice with the combined library of the fact that part of it is " + "a work based on the Library, and explaining where to find the accompanying uncombined " + "form of the same work.\n" + "\n" + "8. You may not copy, modify, sublicense, link with, or distribute the Library except " + "as expressly provided under this License. Any attempt otherwise to copy, modify, " + "sublicense, link with, or distribute the Library is void, and will automatically " + "terminate your rights under this License. However, parties who have received copies, " + "or rights, from you under this License will not have their licenses terminated so " + "long as such parties remain in full compliance.\n" + "\n" + "9. You are not required to accept this License, since you have not signed it. However, " + "nothing else grants you permission to modify or distribute the Library or its " + "derivative works. These actions are prohibited by law if you do not accept this " + "License. Therefore, by modifying or distributing the Library (or any work based on the " + "Library), you indicate your acceptance of this License to do so, and all its terms and " + "conditions for copying, distributing or modifying the Library or works based on it.\n" + "\n" + "10. Each time you redistribute the Library (or any work based on the Library), the " + "recipient automatically receives a license from the original licensor to copy, " + "distribute, link with or modify the Library subject to these terms and conditions. You " + "may not impose any further restrictions on the recipients' exercise of the rights " + "granted herein. You are not responsible for enforcing compliance by third parties with " + "this License.\n" + "\n" + "11. If, as a consequence of a court judgment or allegation of patent infringement or " + "for any other reason (not limited to patent issues), conditions are imposed on you " + "(whether by court order, agreement or otherwise) that contradict the conditions of " + "this License, they do not excuse you from the conditions of this License. If you " + "cannot distribute so as to satisfy simultaneously your obligations under this License " + "and any other pertinent obligations, then as a consequence you may not distribute the " + "Library at all. For example, if a patent license would not permit royalty-free " + "redistribution of the Library by all those who receive copies directly or indirectly " + "through you, then the only way you could satisfy both it and this License would be to " + "refrain entirely from distribution of the Library.\n" + "\n" + "If any portion of this section is held invalid or unenforceable under any particular " + "circumstance, the balance of the section is intended to apply, and the section as a " + "whole is intended to apply in other circumstances.\n" + "\n" + "It is not the purpose of this section to induce you to infringe any patents or other " + "property right claims or to contest validity of any such claims; this section has the " + "sole purpose of protecting the integrity of the free software distribution system " + "which is implemented by public license practices. Many people have made generous " + "contributions to the wide range of software distributed through that system in " + "reliance on consistent application of that system; it is up to the author/donor to " + "decide if he or she is willing to distribute software through any other system and a " + "licensee cannot impose that choice.\n" + "\n" + "This section is intended to make thoroughly clear what is believed to be a consequence " + "of the rest of this License.\n" + "\n" + "12. If the distribution and/or use of the Library is restricted in certain countries " + "either by patents or by copyrighted interfaces, the original copyright holder who " + "places the Library under this License may add an explicit geographical distribution " + "limitation excluding those countries, so that distribution is permitted only in or " + "among countries not thus excluded. In such case, this License incorporates the " + "limitation as if written in the body of this License.\n" + "\n" + "13. The Free Software Foundation may publish revised and/or new versions of the Lesser " + "General Public License from time to time. Such new versions will be similar in spirit " + "to the present version, but may differ in detail to address new problems or concerns.\n" + "\n" + "Each version is given a distinguishing version number. If the Library specifies a " + "version number of this License which applies to it and \"any later version\", you have " + "the option of following the terms and conditions either of that version or of any " + "later version published by the Free Software Foundation. If the Library does not " + "specify a license version number, you may choose any version ever published by the " + "Free Software Foundation.\n" + "\n" + "14. If you wish to incorporate parts of the Library into other free programs whose " + "distribution conditions are incompatible with these, write to the author to ask for " + "permission. For software which is copyrighted by the Free Software Foundation, write " + "to the Free Software Foundation; we sometimes make exceptions for this. Our decision " + "will be guided by the two goals of preserving the free status of all derivatives of " + "our free software and of promoting the sharing and reuse of software generally.\n" + "\n" + "NO WARRANTY\n" + "\n" + "15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE " + "LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN " + "WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY \"AS IS\" " + "WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED " + "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. " + "THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD " + "THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR " + "CORRECTION.\n" + "\n" + "16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY " + "COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS " + "PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, " + "INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE " + "LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE " + "OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE " + "WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE " + "POSSIBILITY OF SUCH DAMAGES.\n" + "\n" + "END OF TERMS AND CONDITIONS\n" + "\n" + "\n" + "How to Apply These Terms to Your New Libraries\n" + "\n" + "If you develop a new library, and you want it to be of the greatest possible use to " + "the public, we recommend making it free software that everyone can redistribute and " + "change. You can do so by permitting redistribution under these terms (or, " + "alternatively, under the terms of the ordinary General Public License).\n" + "\n" + "To apply these terms, attach the following notices to the library. It is safest to " + "attach them to the start of each source file to most effectively convey the exclusion " + "of warranty; and each file should have at least the \"copyright\" line and a pointer " + "to where the full notice is found.\n" + "\n" + "\n" + "Copyright (C) \n" + "\n" + "This library is free software; you can redistribute it and/or modify it under the " + "terms of the GNU Lesser General Public License as published by the Free Software " + "Foundation; either version 2.1 of the License, or (at your option) any later version.\n" + "\n" + "This library is distributed in the hope that it will be useful, but WITHOUT ANY " + "WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A " + "PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n" + "\n" + "You should have received a copy of the GNU Lesser General Public License along with " + "this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, " + "Suite 330, Boston, MA 02111-1307 USA\n" + "\n" + "Also add information on how to contact you by electronic and paper mail.\n" + "\n" + "You should also get your employer (if you work as a programmer) or your school, if " + "any, to sign a \"copyright disclaimer\" for the library, if necessary. Here is a " + "sample; alter the names:\n" + "\n" + "Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a " + "library for tweaking knobs) written by James Random Hacker.\n" + "\n" + ", 1 April 1990\n" + "Ty Coon, President of Vice\n" + "\n" + "That's all there is to it!\n"; /** The singleton instance of this class. */ private static Licences singleton; /** * Returns a reference to this class. * * @return the instance reference. */ public static Licences getInstance() { if (singleton == null) { singleton = new Licences(); } return singleton; } /** * Returns the GPL text in a non static way to prevent the compiler * to copy the contents of the field. * * @return the GPL licence text. */ public String getGPL() { return GPL; } /** * Returns the LGPL text in a non static way to prevent the compiler * to copy the contents of the field. * * @return the LGPL licence text. */ public String getLGPL() { return LGPL; } } jcommon-1.0.16/source/org/jfree/ui/about/SystemProperties.java0000644000175000017500000000560411172030703024313 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * SystemProperties.java * --------------------- * (C) Copyright 2002-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SystemProperties.java,v 1.5 2005/11/16 15:58:41 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 04-Mar-2002 : Version 1 (DG); * 08-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui.about; import javax.swing.JTable; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import org.jfree.ui.SortableTable; /** * A utility class for working with system properties. * * @author David Gilbert */ public class SystemProperties { /** * Private constructor prevents object creation. */ private SystemProperties () { } /** * Creates and returns a JTable containing all the system properties. This method returns a * table that is configured so that the user can sort the properties by clicking on the table * header. * * @return a system properties table. */ public static SortableTable createSystemPropertiesTable() { final SystemPropertiesTableModel properties = new SystemPropertiesTableModel(); final SortableTable table = new SortableTable(properties); final TableColumnModel model = table.getColumnModel(); TableColumn column = model.getColumn(0); column.setPreferredWidth(200); column = model.getColumn(1); column.setPreferredWidth(350); table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS); return table; } } jcommon-1.0.16/source/org/jfree/ui/about/SystemPropertiesFrame.java0000644000175000017500000001610311172030703025262 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * SystemPropertiesFrame.java * -------------------------- * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SystemPropertiesFrame.java,v 1.7 2008/12/18 09:57:32 mungady Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui (DG); * 26-Nov-2001 : Made a separate class SystemPropertiesPanel.java (DG); * 28-Feb-2002 : Moved to package com.jrefinery.ui.about (DG); * 15-Mar-2002 : Modified to use a ResourceBundle for elements that require * localisation (DG); * 08-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.ui.about; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ResourceBundle; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.WindowConstants; import org.jfree.util.ResourceBundleWrapper; /** * A frame containing a table that displays the system properties for the * current Java Virtual Machine (JVM). It is useful to incorporate this frame * into an application for diagnostic purposes, since it provides a convenient * means for the user to return configuration and version information when * reporting problems. * * @author David Gilbert */ public class SystemPropertiesFrame extends JFrame implements ActionListener { /** Copy action command. */ private static final String COPY_COMMAND = "COPY"; /** Close action command. */ private static final String CLOSE_COMMAND = "CLOSE"; /** A system properties panel. */ private SystemPropertiesPanel panel; /** * Constructs a standard frame that displays system properties. *

* If a menu is requested, it provides a menu item that allows the user to * copy the contents of the table to the clipboard in tab-delimited format. * * @param menu flag indicating whether or not the frame should display a * menu to allow the user to copy properties to the clipboard. */ public SystemPropertiesFrame(final boolean menu) { final String baseName = "org.jfree.ui.about.resources.AboutResources"; final ResourceBundle resources = ResourceBundleWrapper.getBundle( baseName); final String title = resources.getString("system-frame.title"); setTitle(title); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); if (menu) { setJMenuBar(createMenuBar(resources)); } final JPanel content = new JPanel(new BorderLayout()); this.panel = new SystemPropertiesPanel(); this.panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); content.add(this.panel, BorderLayout.CENTER); final JPanel buttonPanel = new JPanel(new BorderLayout()); buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0)); final String label = resources.getString("system-frame.button.close"); final Character mnemonic = (Character) resources.getObject( "system-frame.button.close.mnemonic"); final JButton closeButton = new JButton(label); closeButton.setMnemonic(mnemonic.charValue()); closeButton.setActionCommand(CLOSE_COMMAND); closeButton.addActionListener(this); buttonPanel.add(closeButton, BorderLayout.EAST); content.add(buttonPanel, BorderLayout.SOUTH); setContentPane(content); } /** * Handles action events generated by the user. * * @param e the event. */ public void actionPerformed(final ActionEvent e) { final String command = e.getActionCommand(); if (command.equals(CLOSE_COMMAND)) { dispose(); } else if (command.equals(COPY_COMMAND)) { this.panel.copySystemPropertiesToClipboard(); } } /** * Creates and returns a menu-bar for the frame. * * @param resources localised resources. * * @return a menu bar. */ private JMenuBar createMenuBar(final ResourceBundle resources) { final JMenuBar menuBar = new JMenuBar(); String label = resources.getString("system-frame.menu.file"); Character mnemonic = (Character) resources.getObject( "system-frame.menu.file.mnemonic"); final JMenu fileMenu = new JMenu(label, true); fileMenu.setMnemonic(mnemonic.charValue()); label = resources.getString("system-frame.menu.file.close"); mnemonic = (Character) resources.getObject( "system-frame.menu.file.close.mnemonic"); final JMenuItem closeItem = new JMenuItem(label, mnemonic.charValue()); closeItem.setActionCommand(CLOSE_COMMAND); closeItem.addActionListener(this); fileMenu.add(closeItem); label = resources.getString("system-frame.menu.edit"); mnemonic = (Character) resources.getObject( "system-frame.menu.edit.mnemonic"); final JMenu editMenu = new JMenu(label); editMenu.setMnemonic(mnemonic.charValue()); label = resources.getString("system-frame.menu.edit.copy"); mnemonic = (Character) resources.getObject( "system-frame.menu.edit.copy.mnemonic"); final JMenuItem copyItem = new JMenuItem(label, mnemonic.charValue()); copyItem.setActionCommand(COPY_COMMAND); copyItem.addActionListener(this); editMenu.add(copyItem); menuBar.add(fileMenu); menuBar.add(editMenu); return menuBar; } } jcommon-1.0.16/source/org/jfree/ui/about/SystemPropertiesPanel.java0000644000175000017500000001535611172030703025300 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * SystemPropertiesPanel.java * -------------------------- * (C) Copyright 2001-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SystemPropertiesPanel.java,v 1.7 2008/12/18 09:57:32 mungady Exp $ * * Changes * ------- * 26-Nov-2001 : Version 1 (DG); * 28-Feb-2002 : Changed package to com.jrefinery.ui.about (DG); * 04-Mar-2002 : Added popup menu code by Carl ?? (DG); * 15-Mar-2002 : Modified to use ResourceBundle for elements that require * localisation (DG); * 26-Jun-2002 : Removed unnecessary import (DG); * 08-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.ui.about; import java.awt.BorderLayout; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ResourceBundle; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import org.jfree.util.ResourceBundleWrapper; /** * A panel containing a table of system properties. * * @author David Gilbert */ public class SystemPropertiesPanel extends JPanel { /** The table that displays the system properties. */ private JTable table; /** Allows for a popup menu for copying. */ private JPopupMenu copyPopupMenu; /** A copy menu item. */ private JMenuItem copyMenuItem; /** A popup listener. */ private PopupListener copyPopupListener; /** * Constructs a new panel. */ public SystemPropertiesPanel() { final String baseName = "org.jfree.ui.about.resources.AboutResources"; final ResourceBundle resources = ResourceBundleWrapper.getBundle( baseName); setLayout(new BorderLayout()); this.table = SystemProperties.createSystemPropertiesTable(); add(new JScrollPane(this.table)); // Add a popup menu to copy to the clipboard... this.copyPopupMenu = new JPopupMenu(); final String label = resources.getString( "system-properties-panel.popup-menu.copy"); final KeyStroke accelerator = (KeyStroke) resources.getObject( "system-properties-panel.popup-menu.copy.accelerator"); this.copyMenuItem = new JMenuItem(label); this.copyMenuItem.setAccelerator(accelerator); this.copyMenuItem.getAccessibleContext().setAccessibleDescription( label); this.copyMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { copySystemPropertiesToClipboard(); } }); this.copyPopupMenu.add(this.copyMenuItem); // add popup Listener to the table this.copyPopupListener = new PopupListener(); this.table.addMouseListener(this.copyPopupListener); } /** * Copies the selected cells in the table to the clipboard, in * tab-delimited format. */ public void copySystemPropertiesToClipboard() { final StringBuffer buffer = new StringBuffer(); final ListSelectionModel selection = this.table.getSelectionModel(); final int firstRow = selection.getMinSelectionIndex(); final int lastRow = selection.getMaxSelectionIndex(); if ((firstRow != -1) && (lastRow != -1)) { for (int r = firstRow; r <= lastRow; r++) { for (int c = 0; c < this.table.getColumnCount(); c++) { buffer.append(this.table.getValueAt(r, c)); if (c != 2) { buffer.append("\t"); } } buffer.append("\n"); } } final StringSelection ss = new StringSelection(buffer.toString()); final Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); cb.setContents(ss, ss); } /** * Returns the copy popup menu. * * @return Returns the copyPopupMenu. */ protected final JPopupMenu getCopyPopupMenu() { return this.copyPopupMenu; } /** * Returns the table containing the system properties. * @return Returns the table. */ protected final JTable getTable() { return this.table; } /** * A popup listener. */ private class PopupListener extends MouseAdapter { /** * Default constructor. */ public PopupListener() { } /** * Mouse pressed event. * * @param e the event. */ public void mousePressed(final MouseEvent e) { maybeShowPopup(e); } /** * Mouse released event. * * @param e the event. */ public void mouseReleased(final MouseEvent e) { maybeShowPopup(e); } /** * Event handler. * * @param e the event. */ private void maybeShowPopup(final MouseEvent e) { if (e.isPopupTrigger()) { getCopyPopupMenu().show( getTable(), e.getX(), e.getY() ); } } } } jcommon-1.0.16/source/org/jfree/ui/about/ProjectInfo.java0000644000175000017500000001457711172030703023205 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * ProjectInfo.java * ---------------- * (C) Copyright 2001-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ProjectInfo.java,v 1.5 2005/11/16 15:58:41 taqua Exp $ * * Changes (since 27-Jun-2002) * --------------------------- * 27-Jun-2002 : Added logo, updated source header and Javadocs (DG); * 08-Oct-2002 : Added set methods for most attributes. Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui.about; import java.awt.Image; import java.util.Iterator; import java.util.List; import org.jfree.base.BootableProjectInfo; import org.jfree.base.Library; /** * A class for recording the basic information about a free or open source software project. * * @author David Gilbert */ public class ProjectInfo extends BootableProjectInfo { /** An optional project logo. */ private Image logo; /** The licence text. */ private String licenceText; /** A list of contributors. */ private List contributors; /** * Constructs an empty project info object. */ public ProjectInfo() { // nothing required } /** * Constructs a project info object. * * @param name the name of the project. * @param version the version. * @param info other info (usually a URL). * @param logo the project logo. * @param copyright a copyright statement. * @param licenceName the name of the licence that applies to the project. * @param licenceText the text of the licence that applies to the project. */ public ProjectInfo(final String name, final String version, final String info, final Image logo, final String copyright, final String licenceName, final String licenceText) { super(name, version, info, copyright, licenceName); this.logo = logo; this.licenceText = licenceText; } /** * Returns the logo. * * @return the project logo. */ public Image getLogo() { return this.logo; } /** * Sets the project logo. * * @param logo the project logo. */ public void setLogo(final Image logo) { this.logo = logo; } /** * Returns the licence text. * * @return the licence text. */ public String getLicenceText() { return this.licenceText; } /** * Sets the project licence text. * * @param licenceText the licence text. */ public void setLicenceText(final String licenceText) { this.licenceText = licenceText; } /** * Returns the list of contributors for the project. * * @return the list of contributors. */ public List getContributors() { return this.contributors; } /** * Sets the list of contributors. * * @param contributors the list of contributors. */ public void setContributors(final List contributors) { this.contributors = contributors; } /** * Returns a string describing the project. * * @return a string describing the project. */ public String toString() { final StringBuffer result = new StringBuffer(); result.append(getName()); result.append(" version "); result.append(getVersion()); result.append(".\n"); result.append(getCopyright()); result.append(".\n"); result.append("\n"); result.append("For terms of use, see the licence below.\n"); result.append("\n"); result.append("FURTHER INFORMATION:"); result.append(getInfo()); result.append("\n"); result.append("CONTRIBUTORS:"); if (this.contributors != null) { final Iterator iterator = this.contributors.iterator(); while (iterator.hasNext()) { final Contributor contributor = (Contributor) iterator.next(); result.append(contributor.getName()); result.append(" ("); result.append(contributor.getEmail()); result.append(")."); } } else { result.append("None"); } result.append("\n"); result.append("OTHER LIBRARIES USED BY "); result.append(getName()); result.append(":"); final Library[] libraries = getLibraries(); if (libraries.length != 0) { for (int i = 0; i < libraries.length; i++) { final Library lib = libraries[i]; result.append(lib.getName()); result.append(" "); result.append(lib.getVersion()); result.append(" ("); result.append(lib.getInfo()); result.append(")."); } } else { result.append("None"); } result.append("\n"); result.append(getName()); result.append(" LICENCE TERMS:"); result.append("\n"); result.append(getLicenceText()); return result.toString(); } } jcommon-1.0.16/source/org/jfree/ui/about/Library.java0000644000175000017500000000462211172030703022355 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------ * Library.java * ------------ * (C) Copyright 2001-2004, by Thomas Morgner. * * Original Author: Thomas Morgner; * Contributor(s): -; * * $Id: Library.java,v 1.5 2005/11/08 14:24:34 mungady Exp $ * * Changes * ------- * */ package org.jfree.ui.about; /** * Library specification moved to base package to allow more control * over the boot process. * * @author David Gilbert * @deprecated shadow class for deprecation */ public class Library extends org.jfree.base.Library { /** * Creates a new library reference. * * @param name the name. * @param version the version. * @param licence the licence. * @param info the web address or other info. */ public Library(final String name, final String version, final String licence, final String info) { super(name, version, licence, info); } /** * Constructs a library reference from a ProjectInfo object. * * @param project information about a project. */ public Library(final ProjectInfo project) { this(project.getName(), project.getVersion(), project.getLicenceName(), project.getInfo()); } } jcommon-1.0.16/source/org/jfree/ui/about/ContributorsTableModel.java0000644000175000017500000001126511172030703025400 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------- * ContributorsTableModel.java * --------------------------- * (C) Copyright 2001-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ContributorsTableModel.java,v 1.6 2008/12/18 09:57:32 mungady Exp $ * * Changes * ------- * 10-Dec-2001 : Version 1 (DG); * 28-Feb-2002 : Moved into package com.jrefinery.ui.about. Changed import * statements and updated Javadoc comments (DG); * 08-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.ui.about; import java.util.List; import java.util.ResourceBundle; import javax.swing.table.AbstractTableModel; import org.jfree.util.ResourceBundleWrapper; /** * A table model containing a list of contributors to a project. *

* Used in the ContributorsPanel class. * * @author David Gilbert */ public class ContributorsTableModel extends AbstractTableModel { /** Storage for the contributors. */ private List contributors; /** Localised version of the name column label. */ private String nameColumnLabel; /** Localised version of the contact column label. */ private String contactColumnLabel; /** * Constructs a ContributorsTableModel. * * @param contributors the contributors. */ public ContributorsTableModel(final List contributors) { this.contributors = contributors; final String baseName = "org.jfree.ui.about.resources.AboutResources"; final ResourceBundle resources = ResourceBundleWrapper.getBundle( baseName); this.nameColumnLabel = resources.getString( "contributors-table.column.name"); this.contactColumnLabel = resources.getString( "contributors-table.column.contact"); } /** * Returns the number of rows in the table model. * * @return The number of rows. */ public int getRowCount() { return this.contributors.size(); } /** * Returns the number of columns in the table model. In this case, there * are always two columns (name and e-mail address). * * @return The number of columns in the table model. */ public int getColumnCount() { return 2; } /** * Returns the name of a column in the table model. * * @param column the column index (zero-based). * * @return the name of the specified column. */ public String getColumnName(final int column) { String result = null; switch (column) { case 0: result = this.nameColumnLabel; break; case 1: result = this.contactColumnLabel; break; } return result; } /** * Returns the value for a cell in the table model. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return the value. */ public Object getValueAt(final int row, final int column) { Object result = null; final Contributor contributor = (Contributor) this.contributors.get(row); if (column == 0) { result = contributor.getName(); } else if (column == 1) { result = contributor.getEmail(); } return result; } } jcommon-1.0.16/source/org/jfree/ui/about/LibraryTableModel.java0000644000175000017500000001301011172030703024275 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * LibraryTableModel.java * ---------------------- * (C) Copyright 2002-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: LibraryTableModel.java,v 1.8 2008/12/18 09:57:32 mungady Exp $ * * Changes * ------- * 28-Feb-2002 : Version 1 (DG); * 15-Mar-2002 : Modified to use ResourceBundle for elements that require * localisation (DG); * 08-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.ui.about; import java.util.List; import java.util.ResourceBundle; import javax.swing.table.AbstractTableModel; import org.jfree.base.Library; import org.jfree.util.ResourceBundleWrapper; /** * A table model containing a list of libraries used in a project. *

* Used in the LibraryPanel class. * * @author David Gilbert */ public class LibraryTableModel extends AbstractTableModel { /** Storage for the libraries. */ private Library[] libraries; /** Localised name column label. */ private String nameColumnLabel; /** Localised version column label. */ private String versionColumnLabel; /** Localised licence column label. */ private String licenceColumnLabel; /** Localised info column label. */ private String infoColumnLabel; /** * Constructs a LibraryTableModel. * * @param libraries the libraries. */ public LibraryTableModel(final List libraries) { this.libraries = (Library[]) libraries.toArray(new Library[libraries.size()]); final String baseName = "org.jfree.ui.about.resources.AboutResources"; final ResourceBundle resources = ResourceBundleWrapper.getBundle( baseName); this.nameColumnLabel = resources.getString( "libraries-table.column.name"); this.versionColumnLabel = resources.getString( "libraries-table.column.version"); this.licenceColumnLabel = resources.getString( "libraries-table.column.licence"); this.infoColumnLabel = resources.getString( "libraries-table.column.info"); } /** * Returns the number of rows in the table model. * * @return the number of rows. */ public int getRowCount() { return this.libraries.length; } /** * Returns the number of columns in the table model. In this case, there * are always four columns (name, version, licence and other info). * * @return the number of columns in the table model. */ public int getColumnCount() { return 4; } /** * Returns the name of a column in the table model. * * @param column the column index (zero-based). * * @return the name of the specified column. */ public String getColumnName(final int column) { String result = null; switch (column) { case 0: result = this.nameColumnLabel; break; case 1: result = this.versionColumnLabel; break; case 2: result = this.licenceColumnLabel; break; case 3: result = this.infoColumnLabel; break; } return result; } /** * Returns the value for a cell in the table model. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return the value. */ public Object getValueAt(final int row, final int column) { Object result = null; final Library library = this.libraries[row]; if (column == 0) { result = library.getName(); } else if (column == 1) { result = library.getVersion(); } else if (column == 2) { result = library.getLicenceName(); } else if (column == 3) { result = library.getInfo(); } return result; } /** * Returns an array of the libraries in the table. * * @return An array of libraries. */ public Library[] getLibraries() { return (Library[]) this.libraries.clone(); } } jcommon-1.0.16/source/org/jfree/ui/L1R1ButtonPanel.java0000644000175000017500000000617411172030703022476 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * L1R1ButtonPanel.java * -------------------- * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: L1R1ButtonPanel.java,v 1.4 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.* (DG); * 26-Jun-2002 : Removed unnecessary import (DG); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JPanel; /** * A 'ready-made' panel that has one button on the left and another button on the right - a layout * manager takes care of resizing. * * @author David Gilbert */ public class L1R1ButtonPanel extends JPanel { /** The button on the left. */ private JButton left; /** The button on the right. */ private JButton right; /** * Standard constructor - creates a two-button panel with the specified labels. * * @param leftLabel the label for the left button. * @param rightLabel the label for the right button. */ public L1R1ButtonPanel(final String leftLabel, final String rightLabel) { setLayout(new BorderLayout()); this.left = new JButton(leftLabel); this.right = new JButton(rightLabel); add(this.left, BorderLayout.WEST); add(this.right, BorderLayout.EAST); } /** * Returns a reference to button 1, allowing the caller to set labels, action-listeners etc. * * @return the button. */ public JButton getLeftButton() { return this.left; } /** * Returns a reference to button 2, allowing the caller to set labels, action-listeners etc. * * @return the button. */ public JButton getRightButton() { return this.right; } } jcommon-1.0.16/source/org/jfree/ui/DateCellRenderer.java0000644000175000017500000000700711172030703023003 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * DateCellRenderer.java * --------------------- * (C) Copyright 2003, 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: DateCellRenderer.java,v 1.7 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 24-Jul-2003 : Version 1 (DG); * */ package org.jfree.ui; import java.awt.Component; import java.text.DateFormat; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; /** * A table cell renderer that formats dates. * * @author David Gilbert */ public class DateCellRenderer extends DefaultTableCellRenderer { /** The formatter. */ private DateFormat formatter; /** * Default constructor. */ public DateCellRenderer() { this(DateFormat.getDateTimeInstance()); } /** * Creates a new renderer. * * @param formatter the formatter. */ public DateCellRenderer(final DateFormat formatter) { super(); this.formatter = formatter; setHorizontalAlignment(SwingConstants.CENTER); } /** * Returns itself as the renderer. Supports the TableCellRenderer interface. * * @param table the table. * @param value the data to be rendered. * @param isSelected a boolean that indicates whether or not the cell is * selected. * @param hasFocus a boolean that indicates whether or not the cell has * the focus. * @param row the (zero-based) row index. * @param column the (zero-based) column index. * * @return the component that can render the contents of the cell. */ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { setFont(null); if (value != null) { setText(this.formatter.format(value)); } else { setText(""); } if (isSelected) { setBackground(table.getSelectionBackground()); } else { setBackground(null); } return this; } } jcommon-1.0.16/source/org/jfree/ui/RectangleEdge.java0000644000175000017500000001445111172030703022331 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------- * RectangleEdge * ------------- * (C) Copyright 2003-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: RectangleEdge.java,v 1.4 2005/10/18 13:18:34 mungady Exp $ * * Changes: * -------- * 14-Jul-2003 (DG); * */ package org.jfree.ui; import java.awt.geom.Rectangle2D; import java.io.ObjectStreamException; import java.io.Serializable; /** * Used to indicate the edge of a rectangle. * * @author David Gilbert */ public final class RectangleEdge implements Serializable { /** For serialization. */ private static final long serialVersionUID = -7400988293691093548L; /** Top. */ public static final RectangleEdge TOP = new RectangleEdge("RectangleEdge.TOP"); /** Bottom. */ public static final RectangleEdge BOTTOM = new RectangleEdge("RectangleEdge.BOTTOM"); /** Left. */ public static final RectangleEdge LEFT = new RectangleEdge("RectangleEdge.LEFT"); /** Right. */ public static final RectangleEdge RIGHT = new RectangleEdge("RectangleEdge.RIGHT"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private RectangleEdge(final String name) { this.name = name; } /** * Returns a string representing the object. * * @return The string. */ public String toString() { return this.name; } /** * Returns true if this object is equal to the specified * object, and false otherwise. * * @param o the other object. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof RectangleEdge)) { return false; } final RectangleEdge order = (RectangleEdge) o; if (!this.name.equals(order.name)) { return false; } return true; } /** * Returns a hash code value for the object. * * @return the hashcode */ public int hashCode() { return this.name.hashCode(); } /** * Returns true if the edge is TOP or * BOTTOM, and false otherwise. * * @param edge the edge. * * @return A boolean. */ public static boolean isTopOrBottom(final RectangleEdge edge) { return (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM); } /** * Returns true if the edge is LEFT or * RIGHT, and false otherwise. * * @param edge the edge. * * @return A boolean. */ public static boolean isLeftOrRight(final RectangleEdge edge) { return (edge == RectangleEdge.LEFT || edge == RectangleEdge.RIGHT); } /** * Returns the opposite edge. * * @param edge an edge. * * @return The opposite edge. */ public static RectangleEdge opposite(final RectangleEdge edge) { RectangleEdge result = null; if (edge == RectangleEdge.TOP) { result = RectangleEdge.BOTTOM; } else if (edge == RectangleEdge.BOTTOM) { result = RectangleEdge.TOP; } else if (edge == RectangleEdge.LEFT) { result = RectangleEdge.RIGHT; } else if (edge == RectangleEdge.RIGHT) { result = RectangleEdge.LEFT; } return result; } /** * Returns the x or y coordinate of the specified edge. * * @param rectangle the rectangle. * @param edge the edge. * * @return The coordinate. */ public static double coordinate(final Rectangle2D rectangle, final RectangleEdge edge) { double result = 0.0; if (edge == RectangleEdge.TOP) { result = rectangle.getMinY(); } else if (edge == RectangleEdge.BOTTOM) { result = rectangle.getMaxY(); } else if (edge == RectangleEdge.LEFT) { result = rectangle.getMinX(); } else if (edge == RectangleEdge.RIGHT) { result = rectangle.getMaxX(); } return result; } /** * Ensures that serialization returns the unique instances. * * @return The object. * * @throws ObjectStreamException if there is a problem. */ private Object readResolve() throws ObjectStreamException { RectangleEdge result = null; if (this.equals(RectangleEdge.TOP)) { result = RectangleEdge.TOP; } else if (this.equals(RectangleEdge.BOTTOM)) { result = RectangleEdge.BOTTOM; } else if (this.equals(RectangleEdge.LEFT)) { result = RectangleEdge.LEFT; } else if (this.equals(RectangleEdge.RIGHT)) { result = RectangleEdge.RIGHT; } return result; } } jcommon-1.0.16/source/org/jfree/ui/action/0000755000175000017500000000000011351753320020253 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/ui/action/ActionConcentrator.java0000644000175000017500000000672211172030703024716 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * ActionConcentrator.java * ----------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ActionConcentrator.java,v 1.4 2007/11/02 17:50:36 taqua Exp $ * * Changes * ------- * 24-Aug-2003 : Initial version * 07-Jun-2004 : Corrected source headers (DG); */ package org.jfree.ui.action; import java.util.ArrayList; import javax.swing.Action; /** * This class is used to collect actions to be enabled or disabled * by a sinle call. * * @author Thomas Morgner */ public class ActionConcentrator { /** The collection used to store the actions of this concentrator. */ private final ArrayList actions; /** * DefaultConstructor. */ public ActionConcentrator() { this.actions = new ArrayList(); } /** * Adds the action to this concentrator. * * @param a the action to be added. */ public void addAction(final Action a) { if (a == null) { throw new NullPointerException(); } this.actions.add(a); } /** * Removes the action from this concentrator. * * @param a the action to be removed. */ public void removeAction(final Action a) { if (a == null) { throw new NullPointerException(); } this.actions.remove(a); } /** * Defines the state for all actions. * * @param b the new state for all actions. */ public void setEnabled(final boolean b) { for (int i = 0; i < this.actions.size(); i++) { final Action a = (Action) this.actions.get(i); a.setEnabled(b); } } /** * Returns, whether all actions are disabled. * If one action is enabled, then this method will return * true. * * @return true, if at least one action is enabled, false * otherwise. */ public boolean isEnabled() { for (int i = 0; i < this.actions.size(); i++) { final Action a = (Action) this.actions.get(i); if (a.isEnabled()) { return true; } } return false; } } jcommon-1.0.16/source/org/jfree/ui/action/package.html0000644000175000017500000000032311172030703022524 0ustar twernertwerner Provides an Action facility matching that introduced in JDK 1.3 (JCommon aims to run on JDK 1.2.2 or later). jcommon-1.0.16/source/org/jfree/ui/action/AbstractFileSelectionAction.java0000644000175000017500000001160711172030703026464 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------- * AbstractFileSelectionAction.java * ---------------------------- * (C)opyright 2002-2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AbstractFileSelectionAction.java,v 1.4 2005/10/18 13:22:13 mungady Exp $ * * Changes * ------- * 21-Nov-2004 : Initial version * */ package org.jfree.ui.action; import java.awt.Component; import java.io.File; import javax.swing.JFileChooser; import org.jfree.ui.ExtensionFileFilter; import org.jfree.util.StringUtils; /** * A base class for all file operations. This implementation provides all methods * to let the user select a file. * * @author Thomas Morgner */ public abstract class AbstractFileSelectionAction extends AbstractActionDowngrade { /** * The FileChooser that is used to perform the selection. */ private JFileChooser fileChooser; /** * The (optional) parent component. */ private Component parent; /** * Creates a new FileSelectionAction with the given optional parent component * as parent for the file chooser dialog. * * @param parent the parent */ public AbstractFileSelectionAction(final Component parent) { this.parent = parent; } /** * Returns the file extension that should be used for the operation. * * @return the file extension. */ protected abstract String getFileExtension(); /** * Returns a descriptive text describing the file extension. * * @return the file description. */ protected abstract String getFileDescription(); /** * Returns the working directory that should be used when initializing * the FileChooser. * * @return the working directory. */ protected File getCurrentDirectory() { return new File("."); } /** * Selects a file to use as target for the operation. * * @param selectedFile the selected file. * @param dialogType the dialog type. * @param appendExtension true, if the file extension should be added if * necessary, false if the unmodified filename should be used. * * @return the selected and approved file or null, if the user canceled * the operation */ protected File performSelectFile(final File selectedFile, final int dialogType, final boolean appendExtension) { if (this.fileChooser == null) { this.fileChooser = createFileChooser(); } this.fileChooser.setSelectedFile(selectedFile); this.fileChooser.setDialogType(dialogType); final int option = this.fileChooser.showDialog(this.parent, null); if (option == JFileChooser.APPROVE_OPTION) { final File selFile = this.fileChooser.getSelectedFile(); String selFileName = selFile.getAbsolutePath(); if (StringUtils.endsWithIgnoreCase(selFileName, getFileExtension()) == false) { selFileName = selFileName + getFileExtension(); } return new File(selFileName); } return null; } /** * Creates the file chooser. * * @return the initialized file chooser. */ protected JFileChooser createFileChooser() { final JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter( new ExtensionFileFilter(getFileDescription(), getFileExtension()) ); fc.setMultiSelectionEnabled(false); fc.setCurrentDirectory(getCurrentDirectory()); return fc; } } jcommon-1.0.16/source/org/jfree/ui/action/ActionRadioButton.java0000644000175000017500000002114211172030703024500 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * ActionButton.java * ----------------- * (C)opyright 2002, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ActionRadioButton.java,v 1.4 2007/11/02 17:50:37 taqua Exp $ * * ChangeLog * --------- * 30-Aug-2002 : Initial version * 01-Sep-2002 : Documentation * 10-Dec-2002 : Minor Javadoc updates (DG); * 07-Jun-2004 : Corrected source headers (DG); * */ package org.jfree.ui.action; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JRadioButton; import javax.swing.KeyStroke; import org.jfree.util.Log; /** * The ActionRadioButton is used to connect an Action and its properties to a JRadioButton. * This functionality is already implemented in JDK 1.3 but needed for JDK 1.2.2 compatibility. * * @author Thomas Morgner */ public class ActionRadioButton extends JRadioButton { /** The action. */ private Action action; /** The property change handler. */ private ActionEnablePropertyChangeHandler propertyChangeHandler; /** * Helperclass to handle the property change event raised by the action. Changed properties in * the action will affect the button. */ private class ActionEnablePropertyChangeHandler implements PropertyChangeListener { /** * Receives notification of a property change event. * * @param event the property change event. */ public void propertyChange(final PropertyChangeEvent event) { try { if (event.getPropertyName().equals("enabled")) { setEnabled(getAction().isEnabled()); } else if (event.getPropertyName().equals(Action.SMALL_ICON)) { setIcon((Icon) getAction().getValue(Action.SMALL_ICON)); } else if (event.getPropertyName().equals(Action.NAME)) { setText((String) getAction().getValue (Action.NAME)); } else if (event.getPropertyName().equals(Action.SHORT_DESCRIPTION)) { ActionRadioButton.this.setToolTipText((String) getAction().getValue(Action.SHORT_DESCRIPTION)); } final Action ac = getAction(); if (event.getPropertyName().equals(ActionDowngrade.ACCELERATOR_KEY)) { final KeyStroke oldVal = (KeyStroke) event.getOldValue(); if (oldVal != null) { unregisterKeyboardAction (oldVal); } final Object o = ac.getValue(ActionDowngrade.ACCELERATOR_KEY); if (o instanceof KeyStroke && o != null) { final KeyStroke k = (KeyStroke) o; registerKeyboardAction(ac, k, WHEN_IN_FOCUSED_WINDOW); } } else if (event.getPropertyName().equals(ActionDowngrade.MNEMONIC_KEY)) { final Object o = ac.getValue(ActionDowngrade.MNEMONIC_KEY); if (o != null) { if (o instanceof Character) { final Character c = (Character) o; setMnemonic(c.charValue()); } else if (o instanceof Integer) { final Integer c = (Integer) o; setMnemonic(c.intValue()); } } } } catch (Exception e) { Log.warn("Error on PropertyChange in ActionButton: ", e); } } } /** * Creates a Button without any text and without an assigned Action. */ public ActionRadioButton() { super(); } /** * Creates a Button and set the given text as label. * * @param text the label for the new button. */ public ActionRadioButton(final String text) { super(text); } /** * Creates an ActionButton and sets the given text and icon on the button. * * @param text the label for the new button. * @param icon the icon for the button. */ public ActionRadioButton(final String text, final Icon icon) { super(text, icon); } /** * Creates an ActionButton and sets the given icon on the button. * * @param icon the icon for the button. */ public ActionRadioButton(final Icon icon) { super(icon); } /** * Nreates an ActionButton and assigns the given action with the button. * * @param action the action. */ public ActionRadioButton(final Action action) { setAction(action); } /** * Returns the assigned action or null if no action has been assigned. * * @return the action (possibly null). */ public Action getAction() { return this.action; } /** * Returns and initializes the PropertyChangehandler for this ActionButton. * The PropertyChangeHandler monitors the action and updates the button if necessary. * * @return the property change handler. */ private ActionEnablePropertyChangeHandler getPropertyChangeHandler() { if (this.propertyChangeHandler == null) { this.propertyChangeHandler = new ActionEnablePropertyChangeHandler(); } return this.propertyChangeHandler; } /** * Enables and disables this button and if an action is assigned to this button the * propertychange is forwarded to the assigned action. * * @param b the new enable-state of this button */ public void setEnabled(final boolean b) { super.setEnabled(b); if (getAction() != null) { getAction().setEnabled(b); } } /** * Assigns the given action to this button. The properties of the action will be assigned to * the button. If an previous action was set, the old action is unregistered. *

*

    *
  • NAME - specifies the button text *
  • SMALL_ICON - specifies the buttons icon *
  • MNEMONIC_KEY - specifies the buttons mnemonic key *
  • ACCELERATOR_KEY - specifies the buttons accelerator *
* * @param newAction the new action */ public void setAction(final Action newAction) { final Action oldAction = getAction(); if (oldAction != null) { removeActionListener(oldAction); oldAction.removePropertyChangeListener(getPropertyChangeHandler()); final Object o = oldAction.getValue(ActionDowngrade.ACCELERATOR_KEY); if (o instanceof KeyStroke && o != null) { final KeyStroke k = (KeyStroke) o; unregisterKeyboardAction(k); } } this.action = newAction; if (this.action != null) { addActionListener(newAction); newAction.addPropertyChangeListener(getPropertyChangeHandler()); setText((String) (newAction.getValue(Action.NAME))); setToolTipText((String) (newAction.getValue(Action.SHORT_DESCRIPTION))); setIcon((Icon) newAction.getValue(Action.SMALL_ICON)); setEnabled(this.action.isEnabled()); Object o = newAction.getValue(ActionDowngrade.MNEMONIC_KEY); if (o != null) { if (o instanceof Character) { final Character c = (Character) o; setMnemonic(c.charValue()); } else if (o instanceof Integer) { final Integer c = (Integer) o; setMnemonic(c.intValue()); } } o = newAction.getValue(ActionDowngrade.ACCELERATOR_KEY); if (o instanceof KeyStroke && o != null) { final KeyStroke k = (KeyStroke) o; registerKeyboardAction(newAction, k, WHEN_IN_FOCUSED_WINDOW); } } } } jcommon-1.0.16/source/org/jfree/ui/action/DowngradeActionMap.java0000644000175000017500000001362511172030703024625 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * DowngradeActionMap.java * ----------------------- * (C)opyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DowngradeActionMap.java,v 1.4 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 28-Oct-2003 : Initial version * 07-Jun-2004 : Corrected source headers (DG); * */ package org.jfree.ui.action; import java.util.ArrayList; import java.util.HashMap; import javax.swing.Action; /** * An actionmap, which is JDK 1.2.2 compatible. *

* This implementation does not implement the ActionMap interface of * JDK 1.3 or higher to maintain the compatibility with JDK 1.2 which * does not know this interface. *

* The usage is still the same. * * @author Thomas Morger */ public class DowngradeActionMap { /** A map containing the key to action mapping. */ private final HashMap actionMap; /** A list containing the actionkeys in their order of addition. */ private final ArrayList actionList; /** The parent of this action map. */ private DowngradeActionMap parent; /** * Default Constructor. Creates a new empty map. */ public DowngradeActionMap() { this.actionMap = new HashMap(); this.actionList = new ArrayList(); } /** * Sets this ActionMap's parent. * * @param map the ActionMap that is the parent of this one */ public void setParent(final DowngradeActionMap map) { this.parent = map; } /** * Returns this ActionMap's parent. * * @return the ActionMap that is the parent of this one, * or null if this ActionMap has no parent */ public DowngradeActionMap getParent() { return this.parent; } /** * Adds a binding for key to action. * If action is null, this removes the current binding * for key. *

In most instances, key will be * action.getValue(NAME). * * @param key the key for the action. * @param action the action to be added. */ public void put(final Object key, final Action action) { if (action == null) { remove(key); } else { if (this.actionMap.containsKey(key)) { remove(key); } this.actionMap.put(key, action); this.actionList.add (key); } } /** * Returns the binding for key, messaging the * parent ActionMap if the binding is not locally defined. * * @param key the key to be queried. * @return the action for this key, or null if there is no such action. */ public Action get(final Object key) { final Action retval = (Action) this.actionMap.get(key); if (retval != null) { return retval; } if (this.parent != null) { return this.parent.get(key); } return null; } /** * Removes the binding for key from this ActionMap. * * @param key the key to be removed. */ public void remove(final Object key) { this.actionMap.remove(key); this.actionList.remove(key); } /** * Removes all the mappings from this ActionMap. */ public void clear() { this.actionMap.clear(); this.actionList.clear(); } /** * Returns the Action names that are bound in this ActionMap. * * @return the keys which are directly bound to this map. */ public Object[] keys() { return this.actionList.toArray(); } /** * Returns the number of bindings. * * @return the number of entries in this map. */ public int size() { return this.actionMap.size(); } /** * Returns an array of the keys defined in this ActionMap and * its parent. This method differs from keys() in that * this method includes the keys defined in the parent. * * @return all keys of this map and all parents. */ public Object[] allKeys() { if (this.parent == null) { return keys(); } final Object[] parentKeys = this.parent.allKeys(); final Object[] key = keys(); final Object[] retval = new Object[parentKeys.length + key.length]; System.arraycopy(key, 0, retval, 0, key.length); System.arraycopy(retval, 0, retval, key.length, retval.length); return retval; } } jcommon-1.0.16/source/org/jfree/ui/action/ActionMenuItem.java0000644000175000017500000002032711172030703023775 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * ActionMenuItem.java * ------------------- * (C)opyright 2002-2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ActionMenuItem.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * ChangeLog * --------- * 30-Aug-2002 : Initial version * 01-Aug-2002 : Documentation * 10-Dec-2002 : Minor Javadoc updates (DG); * */ package org.jfree.ui.action; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JMenuItem; import javax.swing.KeyStroke; import org.jfree.util.Log; /** * The ActionMenuItem is used to connect an Action and its properties to an * MenuItem. *

* This functionality is already implemented in JDK 1.3 but needed for JDK 1.2.2 * compatibility. * * @author Thomas Morgner */ public class ActionMenuItem extends JMenuItem { /** The action. */ private Action action; /** The property change handler. */ private ActionEnablePropertyChangeHandler propertyChangeHandler; /** * Helperclass to handle the property change event raised by the action. * Changed properties in the action will affect the button. */ private class ActionEnablePropertyChangeHandler implements PropertyChangeListener { public ActionEnablePropertyChangeHandler() { } /** * Receives notification of a property change event. * * @param event the property change event. */ public void propertyChange(final PropertyChangeEvent event) { try { if (event.getPropertyName().equals("enabled")) { setEnabled(getAction().isEnabled()); } else if (event.getPropertyName().equals(Action.SMALL_ICON)) { setIcon((Icon) getAction().getValue(Action.SMALL_ICON)); } else if (event.getPropertyName().equals(Action.NAME)) { setText((String) getAction().getValue(Action.NAME)); } else if (event.getPropertyName().equals(Action.SHORT_DESCRIPTION)) { ActionMenuItem.this.setToolTipText((String) getAction().getValue(Action.SHORT_DESCRIPTION)); } final Action ac = getAction(); if (event.getPropertyName().equals(ActionDowngrade.ACCELERATOR_KEY)) { setAccelerator((KeyStroke) ac.getValue(ActionDowngrade.ACCELERATOR_KEY)); } else if (event.getPropertyName().equals(ActionDowngrade.MNEMONIC_KEY)) { final Object o = ac.getValue(ActionDowngrade.MNEMONIC_KEY); if (o != null) { if (o instanceof Character) { final Character c = (Character) o; setMnemonic(c.charValue()); } else if (o instanceof Integer) { final Integer c = (Integer) o; setMnemonic(c.intValue()); } } else { setMnemonic(KeyEvent.VK_UNDEFINED); } } } catch (Exception e) { Log.warn("Error on PropertyChange in ActionButton: ", e); } } } /** Default constructor. */ public ActionMenuItem() { // nothing required } /** * Creates a menu item with the specified icon. * * @param icon the icon. */ public ActionMenuItem(final Icon icon) { super(icon); } /** * Creates a menu item with the specified label. * * @param text the label. */ public ActionMenuItem(final String text) { super(text); } /** * Creates a menu item with the specified label and icon. * * @param text the label. * @param icon the icon. */ public ActionMenuItem(final String text, final Icon icon) { super(text, icon); } /** * Creates a new menu item with the specified label and mnemonic. * * @param text the label. * @param i the mnemonic. */ public ActionMenuItem(final String text, final int i) { super(text, i); } /** * Creates a new menu item based on the specified action. * * @param action the action. */ public ActionMenuItem(final Action action) { setAction(action); } /** * Returns the assigned action or null if no action has been assigned. * * @return the action. */ public Action getAction() { return this.action; } /** * Returns and initializes the PropertyChangehandler for this ActionMenuItem. * The PropertyChangeHandler monitors the action and updates the menuitem if * necessary. * * @return the property change handler. */ private ActionEnablePropertyChangeHandler getPropertyChangeHandler() { if (this.propertyChangeHandler == null) { this.propertyChangeHandler = new ActionEnablePropertyChangeHandler(); } return this.propertyChangeHandler; } /** * Enables and disables this button and if an action is assigned to this * menuitem the propertychange is forwarded to the assigned action. * * @param b the new enable-state of this menuitem */ public void setEnabled(final boolean b) { super.setEnabled(b); if (getAction() != null) { getAction().setEnabled(b); } } /** * Assigns the given action to this menuitem. The properties of the action * will be assigned to the menuitem. If an previous action was set, the old * action is unregistered. *

*

  • NAME - specifies the menuitem text
  • SMALL_ICON - specifies the * menuitems icon
  • MNEMONIC_KEY - specifies the menuitems mnemonic key *
  • ACCELERATOR_KEY - specifies the menuitems accelerator
* * @param newAction the new action */ public void setAction(final Action newAction) { final Action oldAction = getAction(); if (oldAction != null) { removeActionListener(oldAction); oldAction.removePropertyChangeListener(getPropertyChangeHandler()); setAccelerator(null); } this.action = newAction; if (this.action != null) { addActionListener(newAction); newAction.addPropertyChangeListener(getPropertyChangeHandler()); setText((String) (newAction.getValue(Action.NAME))); setToolTipText((String) (newAction.getValue(Action.SHORT_DESCRIPTION))); setIcon((Icon) newAction.getValue(Action.SMALL_ICON)); setEnabled(this.action.isEnabled()); Object o = newAction.getValue(ActionDowngrade.MNEMONIC_KEY); if (o != null) { if (o instanceof Character) { final Character c = (Character) o; setMnemonic(c.charValue()); } else if (o instanceof Integer) { final Integer c = (Integer) o; setMnemonic(c.intValue()); } } else { setMnemonic(KeyEvent.VK_UNDEFINED); } o = newAction.getValue(ActionDowngrade.ACCELERATOR_KEY); if (o instanceof KeyStroke) { setAccelerator((KeyStroke) o); } } } } jcommon-1.0.16/source/org/jfree/ui/action/AbstractActionDowngrade.java0000644000175000017500000000527511172030703025655 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------- * AbstractActionDowngrade.java * ---------------------------- * (C)opyright 2002-2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AbstractActionDowngrade.java,v 1.2 2005/10/18 13:22:13 mungady Exp $ * * Changes * ------- * 30-Aug-2002 : Initial version * 10-Dec-2002 : Updated Javadocs (DG); * 07-Jun-2004 : Corrected source headers (DG); * */ package org.jfree.ui.action; import javax.swing.AbstractAction; /** * A class that allows Action features introduced in JDK 1.3 to be used with JDK 1.2.2, by * defining the two new constants introduced by Sun in JDK 1.3. * * @author Thomas Morgner */ public abstract class AbstractActionDowngrade extends AbstractAction implements ActionDowngrade { // kills a compile error for JDK's >= 1.3 // ambiguous reference error ... /** * The key used for storing a KeyStroke to be used as the * accelerator for the action. */ public static final String ACCELERATOR_KEY = ActionDowngrade.ACCELERATOR_KEY; /** * The key used for storing an int key code to be used as the mnemonic * for the action. */ public static final String MNEMONIC_KEY = ActionDowngrade.MNEMONIC_KEY; /** * Creates a new action with a default (transparent) icon. */ protected AbstractActionDowngrade() { // nothing required } } jcommon-1.0.16/source/org/jfree/ui/action/ActionButton.java0000644000175000017500000002251511172030703023526 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * ActionButton.java * ----------------- * (C)opyright 2002-2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ActionButton.java,v 1.7 2007/11/02 17:50:36 taqua Exp $ * * ChangeLog * --------- * 30-Aug-2002 : Initial version * 01-Sep-2002 : Documentation * 10-Dec-2002 : Minor Javadoc updates (DG); * 07-Jun-2004 : Corrected source headers (DG); * */ package org.jfree.ui.action; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.KeyStroke; import org.jfree.util.Log; /** * The ActionButton is used to connect an Action and its properties to a Button. This functionality * is already implemented in JDK 1.3 but needed for JDK 1.2.2 compatibility. * * @author Thomas Morgner */ public class ActionButton extends JButton { /** * The action. */ private Action action; /** * The property change handler. */ private ActionEnablePropertyChangeHandler propertyChangeHandler; /** * Helperclass to handle the property change event raised by the action. Changed properties in * the action will affect the button. */ private class ActionEnablePropertyChangeHandler implements PropertyChangeListener { /** * Default constructor. */ public ActionEnablePropertyChangeHandler() { } /** * Receives notification of a property change event. * * @param event the property change event. */ public void propertyChange(final PropertyChangeEvent event) { try { if (event.getPropertyName().equals("enabled")) { setEnabled(getAction().isEnabled()); } else if (event.getPropertyName().equals(Action.SMALL_ICON)) { setIcon((Icon) getAction().getValue(Action.SMALL_ICON)); } else if (event.getPropertyName().equals(Action.NAME)) { setText((String) getAction().getValue (Action.NAME)); } else if (event.getPropertyName().equals(Action.SHORT_DESCRIPTION)) { ActionButton.this.setToolTipText((String) getAction().getValue(Action.SHORT_DESCRIPTION)); } final Action ac = getAction(); if (event.getPropertyName().equals(ActionDowngrade.ACCELERATOR_KEY)) { final KeyStroke oldVal = (KeyStroke) event.getOldValue(); if (oldVal != null) { unregisterKeyboardAction(oldVal); } final Object o = ac.getValue(ActionDowngrade.ACCELERATOR_KEY); if (o instanceof KeyStroke) { final KeyStroke k = (KeyStroke) o; registerKeyboardAction(ac, k, WHEN_IN_FOCUSED_WINDOW); } } else if (event.getPropertyName().equals(ActionDowngrade.MNEMONIC_KEY)) { final Object o = ac.getValue(ActionDowngrade.MNEMONIC_KEY); if (o != null) { if (o instanceof Character) { final Character c = (Character) o; setMnemonic(c.charValue()); } else if (o instanceof Integer) { final Integer c = (Integer) o; setMnemonic(c.intValue()); } } } } catch (Exception e) { Log.warn("Error on PropertyChange in ActionButton: ", e); } } } /** * Creates a Button without any text and without an assigned Action. */ public ActionButton() { super(); } /** * Creates a Button and set the given text as label. * * @param text the label for the new button. */ public ActionButton(final String text) { super(text); } /** * Creates an ActionButton and sets the given text and icon on the button. * * @param text the label for the new button. * @param icon the icon for the button. */ public ActionButton(final String text, final Icon icon) { super(text, icon); } /** * Creates an ActionButton and sets the given icon on the button. * * @param icon the icon for the button. */ public ActionButton(final Icon icon) { super(icon); } /** * Nreates an ActionButton and assigns the given action with the button. * * @param action the action. */ public ActionButton(final Action action) { setAction(action); } /** * Returns the assigned action or null if no action has been assigned. * * @return the action (possibly null). */ public Action getAction() { return this.action; } /** * Returns and initializes the PropertyChangehandler for this ActionButton. * The PropertyChangeHandler monitors the action and updates the button if necessary. * * @return the property change handler. */ private ActionEnablePropertyChangeHandler getPropertyChangeHandler() { if (this.propertyChangeHandler == null) { this.propertyChangeHandler = new ActionEnablePropertyChangeHandler(); } return this.propertyChangeHandler; } /** * Enables and disables this button and if an action is assigned to this button the * propertychange is forwarded to the assigned action. * * @param b the new enable-state of this button */ public void setEnabled(final boolean b) { super.setEnabled(b); if (getAction() != null) { getAction().setEnabled(b); } } /** * Assigns the given action to this button. The properties of the action will be assigned to * the button. If an previous action was set, the old action is unregistered. *

*

    *
  • NAME - specifies the button text *
  • SMALL_ICON - specifies the buttons icon *
  • MNEMONIC_KEY - specifies the buttons mnemonic key *
  • ACCELERATOR_KEY - specifies the buttons accelerator *
* * @param newAction the new action */ public void setAction(final Action newAction) { final Action oldAction = getAction(); if (oldAction != null) { removeActionListener(oldAction); oldAction.removePropertyChangeListener(getPropertyChangeHandler()); final Object o = oldAction.getValue(ActionDowngrade.ACCELERATOR_KEY); if (o instanceof KeyStroke) { final KeyStroke k = (KeyStroke) o; unregisterKeyboardAction(k); } } this.action = newAction; if (this.action != null) { addActionListener(newAction); newAction.addPropertyChangeListener(getPropertyChangeHandler()); setText((String) (newAction.getValue(Action.NAME))); setToolTipText((String) (newAction.getValue(Action.SHORT_DESCRIPTION))); setIcon((Icon) newAction.getValue(Action.SMALL_ICON)); setEnabled(this.action.isEnabled()); Object o = newAction.getValue(ActionDowngrade.MNEMONIC_KEY); if (o != null) { if (o instanceof Character) { final Character c = (Character) o; setMnemonic(c.charValue()); } else if (o instanceof Integer) { final Integer c = (Integer) o; setMnemonic(c.intValue()); } } o = newAction.getValue(ActionDowngrade.ACCELERATOR_KEY); if (o instanceof KeyStroke) { final KeyStroke k = (KeyStroke) o; registerKeyboardAction(newAction, k, WHEN_IN_FOCUSED_WINDOW); } } } } jcommon-1.0.16/source/org/jfree/ui/action/ActionDowngrade.java0000644000175000017500000000437311172030703024167 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * ActionDowngrade.java * -------------------- * (C)opyright 2002-2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ActionDowngrade.java,v 1.2 2005/10/18 13:22:13 mungady Exp $ * * ChangeLog * --------- * 07-Jul-2003 : Ported from com.jrefinery to org.jfree * 07-Jun-2004 : Corrected source header (DG); * */ package org.jfree.ui.action; import javax.swing.Action; /** * Defines the 2 new constants introduced by Sun in version 1.3 of the J2SDK. * * @author Thomas Morgner */ public interface ActionDowngrade extends Action { /** * The key used for storing a KeyStroke to be used as the * accelerator for the action. */ public static final String ACCELERATOR_KEY = "AcceleratorKey"; /** * The key used for storing an int key code to be used as the mnemonic * for the action. */ public static final String MNEMONIC_KEY = "MnemonicKey"; } jcommon-1.0.16/source/org/jfree/ui/InsetsChooserPanel.java0000644000175000017500000002010111172030703023375 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * InsetsChooserPanel.java * ----------------------- * (C) Copyright 2000-2008, by Andrzej Porebski and Contributors. * * Original Author: Andrzej Porebski; * Contributor(s): David Gilbert (for Object Refinery Limited); * Arnaud Lelievre; * * $Id: InsetsChooserPanel.java,v 1.8 2008/12/18 09:57:32 mungady Exp $ * * Changes (from 7-Nov-2001) * ------------------------- * 07-Nov-2001 : Added to com.jrefinery.ui package (DG); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 03-Feb-2003 : Added Math.abs() to ensure no negative insets can be set (DG); * 08-Sep-2003 : Added internationalization via use of properties * resourceBundle (RFE 690236) (AL); * 07-Oct-2005 : Renamed getInsets() --> getInsetsValue() to avoid conflict * with JComponent's getInsets() (DG); * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.ui; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.ResourceBundle; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.TitledBorder; import org.jfree.util.ResourceBundleWrapper; /** * A component for editing an instance of the Insets class. * * @author Andrzej Porebski */ public class InsetsChooserPanel extends JPanel { /** A text field for the 'top' setting. */ private JTextField topValueEditor; /** A text field for the 'left' setting. */ private JTextField leftValueEditor; /** A text field for the 'bottom' setting. */ private JTextField bottomValueEditor; /** A text field for the 'right' setting. */ private JTextField rightValueEditor; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.ui.LocalizationBundle"); /** * Creates a chooser panel that allows manipulation of Insets values. * The values are initialized to the empty insets (0,0,0,0). */ public InsetsChooserPanel() { this(new Insets(0, 0, 0, 0)); } /** * Creates a chooser panel that allows manipulation of Insets values. * The values are initialized to the current values of provided insets. * * @param current the insets. */ public InsetsChooserPanel(Insets current) { current = (current == null) ? new Insets(0, 0, 0, 0) : current; this.topValueEditor = new JTextField(new IntegerDocument(), "" + current.top, 0); this.leftValueEditor = new JTextField(new IntegerDocument(), "" + current.left, 0); this.bottomValueEditor = new JTextField(new IntegerDocument(), "" + current.bottom, 0); this.rightValueEditor = new JTextField(new IntegerDocument(), "" + current.right, 0); final JPanel panel = new JPanel(new GridBagLayout()); panel.setBorder( new TitledBorder(localizationResources.getString("Insets"))); // First row panel.add(new JLabel(localizationResources.getString("Top")), new GridBagConstraints(1, 0, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); // Second row panel.add(new JLabel(" "), new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 12, 0, 12), 8, 0)); panel.add(this.topValueEditor, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); panel.add(new JLabel(" "), new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 12, 0, 11), 8, 0)); // Third row panel.add(new JLabel(localizationResources.getString("Left")), new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 4, 0, 4), 0, 0)); panel.add(this.leftValueEditor, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); panel.add(new JLabel(" "), new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 12, 0, 12), 8, 0)); panel.add(this.rightValueEditor, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); panel.add(new JLabel(localizationResources.getString("Right")), new GridBagConstraints(4, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 4, 0, 4), 0, 0)); // Fourth row panel.add(this.bottomValueEditor, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); // Fifth row panel.add(new JLabel(localizationResources.getString("Bottom")), new GridBagConstraints(1, 4, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); setLayout(new BorderLayout()); add(panel, BorderLayout.CENTER); } /** * Returns a new Insets instance to match the values entered * on the panel. * * @return The insets. */ public Insets getInsetsValue() { return new Insets( Math.abs(stringToInt(this.topValueEditor.getText())), Math.abs(stringToInt(this.leftValueEditor.getText())), Math.abs(stringToInt(this.bottomValueEditor.getText())), Math.abs(stringToInt(this.rightValueEditor.getText()))); } /** * Converts a string representing an integer into its numerical value. * If this string does not represent a valid integer value, value of 0 * is returned. * * @param value the string. * * @return the value. */ protected int stringToInt(String value) { value = value.trim(); if (value.length() == 0) { return 0; } else { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return 0; } } } /** * Calls super removeNotify and removes all subcomponents from this panel. */ public void removeNotify() { super.removeNotify(); removeAll(); } } jcommon-1.0.16/source/org/jfree/ui/LocalizationBundle_pt_PT.properties0000644000175000017500000000065411172030703026003 0ustar twernertwerner# org.jfree.chart.ChartPanel ResourceBundle properties file - portuguese version # # Changes (from 09-Set-2003) # -------------------------- # 09-Set-2003 : Initial version (Eduardo Ramalho); # Attributes=Atributos: B=B: Bold=Negrito Bottom=Fundo Font=Fonte: Insets=Posi\u00e7\u00e3o: Italic=It\u00e1lico L=E: Left=Esquerda No_Font_Selected=Nenhuma fonte est\u00e1 seleccionada. R=D: Right=Direita Size=Tamanho: T=T: Top=Topo jcommon-1.0.16/source/org/jfree/ui/L1R2ButtonPanel.java0000644000175000017500000000747011172030703022477 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * L1R2ButtonPanel.java * -------------------- * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: L1R2ButtonPanel.java,v 1.4 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 26-Jun-2002 : Removed unnecessary import (DG); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.awt.BorderLayout; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JPanel; /** * A 'ready-made' panel that has one button on the left and two buttons on the right - nested * panels and layout managers take care of resizing. * * @author David Gilbert */ public class L1R2ButtonPanel extends JPanel { /** The left button. */ private JButton left; /** The first button on the right of the panel. */ private JButton right1; /** The second button on the right of the panel. */ private JButton right2; /** * Standard constructor - creates a three button panel with the specified button labels. * * @param label1 the label for button 1. * @param label2 the label for button 2. * @param label3 the label for button 3. */ public L1R2ButtonPanel(final String label1, final String label2, final String label3) { setLayout(new BorderLayout()); // create the pieces... this.left = new JButton(label1); final JPanel rightButtonPanel = new JPanel(new GridLayout(1, 2)); this.right1 = new JButton(label2); this.right2 = new JButton(label3); rightButtonPanel.add(this.right1); rightButtonPanel.add(this.right2); // ...and put them together add(this.left, BorderLayout.WEST); add(rightButtonPanel, BorderLayout.EAST); } /** * Returns a reference to button 1, allowing the caller to set labels, action-listeners etc. * * @return the left button. */ public JButton getLeftButton() { return this.left; } /** * Returns a reference to button 2, allowing the caller to set labels, action-listeners etc. * * @return the right button 1. */ public JButton getRightButton1() { return this.right1; } /** * Returns a reference to button 3, allowing the caller to set labels, action-listeners etc. * * @return the right button 2. */ public JButton getRightButton2() { return this.right2; } } jcommon-1.0.16/source/org/jfree/ui/WizardPanel.java0000644000175000017500000000753611172030703022066 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * WizardPanel.java * ---------------- * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: WizardPanel.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.awt.LayoutManager; import javax.swing.JPanel; /** * A panel that provides the user interface for a single step in a WizardDialog. * * @author David Gilbert */ public abstract class WizardPanel extends JPanel { /** The owner. */ private WizardDialog owner; /** * Creates a new panel. * * @param layout the layout manager. */ protected WizardPanel(final LayoutManager layout) { super(layout); } /** * Returns a reference to the dialog that owns the panel. * * @return the owner. */ public WizardDialog getOwner() { return this.owner; } /** * Sets the reference to the dialog that owns the panel (this is called automatically by * the dialog when the panel is added to the dialog). * * @param owner the owner. */ public void setOwner(final WizardDialog owner) { this.owner = owner; } /** * Returns the result. * * @return the result. */ public Object getResult() { return null; } /** * This method is called when the dialog redisplays this panel as a result of the user clicking * the "Previous" button. Inside this method, subclasses should make a note of their current * state, so that they can decide what to do when the user hits "Next". */ public abstract void returnFromLaterStep(); /** * Returns true if it is OK to redisplay the last version of the next panel, or false if a new * version is required. * * @return boolean. */ public abstract boolean canRedisplayNextPanel(); /** * Returns true if there is a next panel. * * @return boolean. */ public abstract boolean hasNextPanel(); /** * Returns true if it is possible to finish from this panel. * * @return boolean. */ public abstract boolean canFinish(); /** * Returns the next panel in the sequence, given the current user input. Returns null if this * panel is the last one in the sequence. * * @return the next panel in the sequence. */ public abstract WizardPanel getNextPanel(); } jcommon-1.0.16/source/org/jfree/ui/StandardGradientPaintTransformer.java0000644000175000017500000001460611172030703026277 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2007, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------------- * StandardGradientPaintTransformer.java * ------------------------------------- * (C) Copyright 2003-2007, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: StandardGradientPaintTransformer.java,v 1.11 2007/04/03 13:55:13 mungady Exp $ * * Changes * ------- * 28-Oct-2003 : Version 1 (DG); * 19-Mar-2004 : Added equals() method (DG); * */ package org.jfree.ui; import java.awt.GradientPaint; import java.awt.Shape; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.util.PublicCloneable; /** * Transforms a GradientPaint to range over the width of a target * shape. Instances of this class are immutable. * * @author David Gilbert */ public class StandardGradientPaintTransformer implements GradientPaintTransformer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -8155025776964678320L; /** The transform type. */ private GradientPaintTransformType type; /** * Creates a new transformer with the type * {@link GradientPaintTransformType#VERTICAL}. */ public StandardGradientPaintTransformer() { this(GradientPaintTransformType.VERTICAL); } /** * Creates a new transformer with the specified type. * * @param type the transform type (null not permitted). */ public StandardGradientPaintTransformer( final GradientPaintTransformType type) { if (type == null) { throw new IllegalArgumentException("Null 'type' argument."); } this.type = type; } /** * Returns the type of transform. * * @return The type of transform (never null). * * @since 1.0.10 */ public GradientPaintTransformType getType() { return this.type; } /** * Transforms a GradientPaint instance to fit the specified * target shape. * * @param paint the original paint (null not permitted). * @param target the target shape (null not permitted). * * @return The transformed paint. */ public GradientPaint transform(final GradientPaint paint, final Shape target) { GradientPaint result = paint; final Rectangle2D bounds = target.getBounds2D(); if (this.type.equals(GradientPaintTransformType.VERTICAL)) { result = new GradientPaint((float) bounds.getCenterX(), (float) bounds.getMinY(), paint.getColor1(), (float) bounds.getCenterX(), (float) bounds.getMaxY(), paint.getColor2()); } else if (this.type.equals(GradientPaintTransformType.HORIZONTAL)) { result = new GradientPaint((float) bounds.getMinX(), (float) bounds.getCenterY(), paint.getColor1(), (float) bounds.getMaxX(), (float) bounds.getCenterY(), paint.getColor2()); } else if (this.type.equals( GradientPaintTransformType.CENTER_HORIZONTAL)) { result = new GradientPaint((float) bounds.getCenterX(), (float) bounds.getCenterY(), paint.getColor2(), (float) bounds.getMaxX(), (float) bounds.getCenterY(), paint.getColor1(), true); } else if (this.type.equals(GradientPaintTransformType.CENTER_VERTICAL)) { result = new GradientPaint((float) bounds.getCenterX(), (float) bounds.getMinY(), paint.getColor1(), (float) bounds.getCenterX(), (float) bounds.getCenterY(), paint.getColor2(), true); } return result; } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object (null permitted). * * @return A boolean. */ public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof StandardGradientPaintTransformer)) { return false; } StandardGradientPaintTransformer that = (StandardGradientPaintTransformer) obj; if (this.type != that.type) { return false; } return true; } /** * Returns a clone of the transformer. Note that instances of this class * are immutable, so cloning an instance isn't really necessary. * * @return A clone. * * @throws CloneNotSupportedException not thrown by this class, but * subclasses (if any) might. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Returns a hash code for this object. * * @return A hash code. */ public int hashCode() { return (this.type != null ? this.type.hashCode() : 0); } } jcommon-1.0.16/source/org/jfree/ui/FloatDimension.java0000644000175000017500000001311711172030703022551 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * FloatDimension.java * ------------------- * (C)opyright 2002-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: FloatDimension.java,v 1.4 2005/11/03 09:26:51 mungady Exp $ * * Changes * ------- * 05-Dec-2002 : Updated Javadocs (DG); * 29-Apr-2003 : Moved to JCommon * */ package org.jfree.ui; import java.awt.geom.Dimension2D; import java.io.Serializable; /** * A dimension object specified using float values. * * @author Thomas Morgner */ public class FloatDimension extends Dimension2D implements Serializable { /** For serialization. */ private static final long serialVersionUID = 5367882923248086744L; /** The width. */ private float width; /** The height. */ private float height; /** * Creates a new dimension object with width and height set to zero. */ public FloatDimension() { this.width = 0.0f; this.height = 0.0f; } /** * Creates a new dimension that is a copy of another dimension. * * @param fd the dimension to copy. */ public FloatDimension(final FloatDimension fd) { this.width = fd.width; this.height = fd.height; } /** * Creates a new dimension. * * @param width the width. * @param height the height. */ public FloatDimension(final float width, final float height) { this.width = width; this.height = height; } /** * Returns the width. * * @return the width. */ public double getWidth() { return this.width; } /** * Returns the height. * * @return the height. */ public double getHeight() { return this.height; } /** * Sets the width. * * @param width the width. */ public void setWidth(final double width) { this.width = (float) width; } /** * Sets the height. * * @param height the height. */ public void setHeight(final double height) { this.height = (float) height; } /** * Sets the size of this Dimension object to the specified * width and height. This method is included for completeness, to parallel * the {@link java.awt.Component#getSize() getSize} method of * {@link java.awt.Component}. * * @param width the new width for the Dimension object * @param height the new height for the Dimension object */ public void setSize(final double width, final double height) { setHeight((float) height); setWidth((float) width); } /** * Creates and returns a copy of this object. * * @return a clone of this instance. * @see java.lang.Cloneable */ public Object clone() { return super.clone(); } /** * Returns a string representation of the object. In general, the * toString method returns a string that * "textually represents" this object. The result should * be a concise but informative representation that is easy for a * person to read. *

* * @return a string representation of the object. */ public String toString() { return getClass().getName() + ":={width=" + getWidth() + ", height=" + getHeight() + "}"; } /** * Tests this object for equality with another object. * * @param o the other object. * * @return true or false. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof FloatDimension)) { return false; } final FloatDimension floatDimension = (FloatDimension) o; if (this.height != floatDimension.height) { return false; } if (this.width != floatDimension.width) { return false; } return true; } /** * Returns a hash code. * * @return A hash code. */ public int hashCode() { int result; result = Float.floatToIntBits(this.width); result = 29 * result + Float.floatToIntBits(this.height); return result; } } jcommon-1.0.16/source/org/jfree/ui/Spinner.java0000644000175000017500000001066011172030703021254 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------ * Spinner.java * ------------ * (C) Copyright 2002-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id $ * * Changes * ------- * 14-Oct-2002 : Version 1 (DG); * */ package org.jfree.ui; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; /** * A very basic spinner component, used for demo purposes only. * * @author David Gilbert */ public class Spinner extends JPanel implements MouseListener { /** The current value. */ private int value; /** The text field displaying the value. */ private JTextField textField; /** The arrow button panel. */ private JPanel buttonPanel; /** The up button. */ private ArrowPanel upButton; /** The down button. */ private ArrowPanel downButton; /** * Creates a new spinner. * * @param value the initial value. */ public Spinner(final int value) { super(new BorderLayout()); this.value = value; this.textField = new JTextField(Integer.toString(this.value)); this.textField.setHorizontalAlignment(SwingConstants.RIGHT); add(this.textField); this.buttonPanel = new JPanel(new GridLayout(2, 1, 0, 1)); this.upButton = new ArrowPanel(ArrowPanel.UP); this.upButton.addMouseListener(this); this.downButton = new ArrowPanel(ArrowPanel.DOWN); this.downButton.addMouseListener(this); this.buttonPanel.add(this.upButton); this.buttonPanel.add(this.downButton); add(this.buttonPanel, BorderLayout.EAST); } /** * Returns the current value. * * @return the current value. */ public int getValue() { return this.value; } /** * Receives notification of mouse clicks. * * @param e the mouse event. */ public void mouseClicked(final MouseEvent e) { if (e.getSource() == this.upButton) { this.value++; this.textField.setText(Integer.toString(this.value)); firePropertyChange("value", this.value - 1, this.value); } else if (e.getSource() == this.downButton) { this.value--; this.textField.setText(Integer.toString(this.value)); firePropertyChange("value", this.value + 1, this.value); } } /** * Receives notification of mouse events. * * @param e the mouse event. */ public void mouseEntered(final MouseEvent e) { // ignored } /** * Receives notification of mouse events. * * @param e the mouse event. */ public void mouseExited(final MouseEvent e) { // ignored } /** * Receives notification of mouse events. * * @param e the mouse event. */ public void mousePressed(final MouseEvent e) { // ignored } /** * Receives notification of mouse events. * * @param e the mouse event. */ public void mouseReleased(final MouseEvent e) { // ignored } } jcommon-1.0.16/source/org/jfree/ui/package.html0000644000175000017500000000022411172030704021250 0ustar twernertwerner Utility classes for creating user interfaces. jcommon-1.0.16/source/org/jfree/ui/StandardDialog.java0000644000175000017500000001211611172030703022514 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * StandardDialog.java * ------------------- * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Arnaud Lelievre; * * $Id: StandardDialog.java,v 1.7 2008/12/18 09:57:32 mungady Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 08-Sep-2003 : Added internationalization via use of properties * resourceBundle (RFE 690236) (AL); * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.ui; import java.awt.Dialog; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ResourceBundle; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import org.jfree.util.ResourceBundleWrapper; /** * The base class for standard dialogs. * * @author David Gilbert */ public class StandardDialog extends JDialog implements ActionListener { /** Flag that indicates whether or not the dialog was cancelled. */ private boolean cancelled; /** The resourceBundle for the localization. */ protected static final ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.ui.LocalizationBundle"); /** * Standard constructor - builds a dialog... * * @param owner the owner. * @param title the title. * @param modal modal? */ public StandardDialog(final Frame owner, final String title, final boolean modal) { super(owner, title, modal); this.cancelled = false; } /** * Standard constructor - builds a dialog... * * @param owner the owner. * @param title the title. * @param modal modal? */ public StandardDialog(final Dialog owner, final String title, final boolean modal) { super(owner, title, modal); this.cancelled = false; } /** * Returns a flag that indicates whether or not the dialog has been * cancelled. * * @return boolean. */ public boolean isCancelled() { return this.cancelled; } /** * Handles clicks on the standard buttons. * * @param event the event. */ public void actionPerformed(final ActionEvent event) { final String command = event.getActionCommand(); if (command.equals("helpButton")) { // display help information } else if (command.equals("okButton")) { this.cancelled = false; setVisible(false); } else if (command.equals("cancelButton")) { this.cancelled = true; setVisible(false); } } /** * Builds and returns the user interface for the dialog. This method is * shared among the constructors. * * @return the button panel. */ protected JPanel createButtonPanel() { final L1R2ButtonPanel buttons = new L1R2ButtonPanel( localizationResources.getString("Help"), localizationResources.getString("OK"), localizationResources.getString("Cancel")); final JButton helpButton = buttons.getLeftButton(); helpButton.setActionCommand("helpButton"); helpButton.addActionListener(this); final JButton okButton = buttons.getRightButton1(); okButton.setActionCommand("okButton"); okButton.addActionListener(this); final JButton cancelButton = buttons.getRightButton2(); cancelButton.setActionCommand("cancelButton"); cancelButton.addActionListener(this); buttons.setBorder(BorderFactory.createEmptyBorder(4, 0, 0, 0)); return buttons; } } jcommon-1.0.16/source/org/jfree/ui/tabbedui/0000755000175000017500000000000011351753320020555 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/ui/tabbedui/TabbedFrame.java0000644000175000017500000001025511172030703023551 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * AbstractTabbedGUI.java * ---------------------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: TabbedFrame.java,v 1.8 2008/09/10 09:19:04 mungady Exp $ * * Changes * ------------------------- * 16-Feb-2004 : Initial version * 07-Jun-2004 : Added standard header (DG); */ package org.jfree.ui.tabbedui; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JFrame; import javax.swing.JPanel; /** * A JFrame implementation that uses a tabbed UI as backend. * * @author Thomas Morgner */ public class TabbedFrame extends JFrame { /** The backend. */ private AbstractTabbedUI tabbedUI; /** * A property change listener that waits for the menubar to change. */ private class MenuBarChangeListener implements PropertyChangeListener { /** * Creates a new change listener. */ public MenuBarChangeListener() { } /** * This method gets called when a bound property is changed. * * @param evt A PropertyChangeEvent object describing the event source * and the property that has changed. */ public void propertyChange(final PropertyChangeEvent evt) { if (evt.getPropertyName().equals(AbstractTabbedUI.JMENUBAR_PROPERTY)) { setJMenuBar(getTabbedUI().getJMenuBar()); } } } /** * Default constructor. */ public TabbedFrame() { } /** * Creates a new tabbed frame with the specified title. * * @param title the frame title. */ public TabbedFrame(final String title) { super(title); } /** * Returns the UI implementation for the frame. * * @return Returns the tabbedUI. */ protected final AbstractTabbedUI getTabbedUI() { return this.tabbedUI; } /** * Initialises the dialog. * * @param tabbedUI the UI that controls the dialog. */ public void init(final AbstractTabbedUI tabbedUI) { this.tabbedUI = tabbedUI; this.tabbedUI.addPropertyChangeListener( AbstractTabbedUI.JMENUBAR_PROPERTY, new MenuBarChangeListener() ); addWindowListener(new WindowAdapter() { public void windowClosing(final WindowEvent e) { getTabbedUI().getCloseAction().actionPerformed (new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null, 0)); } }); final JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(tabbedUI, BorderLayout.CENTER); setContentPane(panel); setJMenuBar(tabbedUI.getJMenuBar()); } } jcommon-1.0.16/source/org/jfree/ui/tabbedui/VerticalLayout.java0000644000175000017500000001532011172030703024362 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * VerticalLayout.java * ------------------- * (C)opyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Simba Management Limited); * * $Id: VerticalLayout.java,v 1.2 2005/10/18 13:23:37 mungady Exp $ * * Changes * ------------------------- * 31.08.2003 : Initial version * */ package org.jfree.ui.tabbedui; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.Rectangle; /** * A simple layout manager, which aligns all components in a vertical * flow layout. * * @author Thomas Morgner */ public class VerticalLayout implements LayoutManager { /** * Defines, whether to use the parents size or whether to compute * the size from the parent's childs during the layouting. */ private final boolean useSizeFromParent; /** * DefaultConstructor. */ public VerticalLayout() { this(true); } /** * Creates a new vertical layout. If useParent is set to true, * the parents size will be used when performing the layouting, * else only the parents childs are used to compute the layout. * * @param useParent defines, whether the parent's size is used. */ public VerticalLayout(final boolean useParent) { this.useSizeFromParent = useParent; } /** * Adds the specified component with the specified name to * the layout. * * @param name the component name * @param comp the component to be added */ public void addLayoutComponent(final String name, final Component comp) { // ignored } /** * Removes the specified component from the layout. * * @param comp the component to be removed */ public void removeLayoutComponent(final Component comp) { // ignored } /** * Calculates the preferred size dimensions for the specified * panel given the components in the specified parent container. * * @param parent the component to be laid out * @return the preferred layout size * @see #minimumLayoutSize */ public Dimension preferredLayoutSize(final Container parent) { synchronized (parent.getTreeLock()) { final Insets ins = parent.getInsets(); final Component[] comps = parent.getComponents(); int height = ins.top + ins.bottom; int width = ins.left + ins.right; for (int i = 0; i < comps.length; i++) { if (comps[i].isVisible() == false) { continue; } final Dimension pref = comps[i].getPreferredSize(); height += pref.height; if (pref.width > width) { width = pref.width; } } return new Dimension(width + ins.left + ins.right, height + ins.top + ins.bottom); } } /** * Calculates the minimum size dimensions for the specified * panel given the components in the specified parent container. * * @param parent the component to be laid out * @return the minimul layoutsize * @see #preferredLayoutSize */ public Dimension minimumLayoutSize(final Container parent) { synchronized (parent.getTreeLock()) { final Insets ins = parent.getInsets(); final Component[] comps = parent.getComponents(); int height = ins.top + ins.bottom; int width = ins.left + ins.right; for (int i = 0; i < comps.length; i++) { if (comps[i].isVisible() == false) { continue; } final Dimension min = comps[i].getMinimumSize(); height += min.height; if (min.width > width) { width = min.width; } } return new Dimension(width + ins.left + ins.right, height + ins.top + ins.bottom); } } /** * Returns, whether the parent's defined size is used during the layouting, * or whether the childs are used to compute the size. * * @return true, if the parent's size is used, false otherwise. */ public boolean isUseSizeFromParent() { return this.useSizeFromParent; } /** * Lays out the container in the specified panel. * * @param parent the component which needs to be laid out */ public void layoutContainer(final Container parent) { synchronized (parent.getTreeLock()) { final Insets ins = parent.getInsets(); final int insHorizontal = ins.left + ins.right; final int width; if (isUseSizeFromParent()) { final Rectangle bounds = parent.getBounds(); width = bounds.width - insHorizontal; } else { width = preferredLayoutSize(parent).width - insHorizontal; } final Component[] comps = parent.getComponents(); int y = ins.top; for (int i = 0; i < comps.length; i++) { final Component c = comps[i]; if (c.isVisible() == false) { continue; } final Dimension dim = c.getPreferredSize(); c.setBounds(ins.left, y, width, dim.height); y += dim.height; } } } } jcommon-1.0.16/source/org/jfree/ui/tabbedui/package.html0000644000175000017500000000022311172030703023025 0ustar twernertwerner Provides classes for tabbed user interfaces. jcommon-1.0.16/source/org/jfree/ui/tabbedui/DetailEditor.java0000644000175000017500000001006311172030703023763 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * DetailEditor.java * ----------------- * (C) Copyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DetailEditor.java,v 1.3 2005/10/18 13:23:37 mungady Exp $ * * Changes * ------- * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.ui.tabbedui; import javax.swing.JComponent; /** * A detail editor. * * @author Thomas Morgner */ public abstract class DetailEditor extends JComponent { /** The object, that is edited. */ private Object object; /** whether the edit process has been confirmed (user pressed OK). */ private boolean confirmed; /** * Creates a new editor. */ public DetailEditor() { // nothing required } /** * Updates the object. */ public void update() { if (this.object == null) { throw new IllegalStateException(); } else { updateObject(this.object); } setConfirmed(false); } /** * Returns the object. * * @return The object. */ public Object getObject() { return this.object; } /** * Sets the object to be edited. * * @param object the object. */ public void setObject(final Object object) { if (object == null) { throw new NullPointerException(); } this.object = object; setConfirmed(false); fillObject(); } /** * Parses an integer. * * @param text the text. * @param def the default value. * * @return The parsed integer, or the default value if the string didn't contain a * value. */ protected static int parseInt(final String text, final int def) { try { return Integer.parseInt(text); } catch (NumberFormatException fe) { return def; } } /** * Clears the editor. */ public abstract void clear(); /** * Edits the object. The object itself should not be modified, until * update or create was called. */ protected abstract void fillObject(); /** * Updates the object. * * @param object the object. */ protected abstract void updateObject(Object object); /** * Returns the confirmed flag. * * @return The confirmed flag. */ public boolean isConfirmed() { return this.confirmed; } /** * Sets the confirmed flag. * * @param confirmed the confirmed flag. */ protected void setConfirmed(final boolean confirmed) { final boolean oldConfirmed = this.confirmed; this.confirmed = confirmed; firePropertyChange("confirmed", oldConfirmed, confirmed); } } jcommon-1.0.16/source/org/jfree/ui/tabbedui/RootEditor.java0000644000175000017500000000701211172030703023504 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * RootEditor.java * --------------- * (C) Copyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: RootEditor.java,v 1.5 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.ui.tabbedui; import java.beans.PropertyChangeListener; import javax.swing.JComponent; import javax.swing.JMenu; /** * A root editor reprensents a tab in a TabbedUI. * * @author Thomas Morgner */ public interface RootEditor { /** * Sets the editor active or inactive. * * @param b a boolean. */ public void setActive(boolean b); /** * Returns the active or inactive status of the editor. * * @return A boolean. */ public boolean isActive(); /** * Returns the editor name. * * @return The editor name. */ public String getEditorName(); /** * Returns the menus. * * @return The menus. */ public JMenu[] getMenus(); /** * Returns the toolbar. * * @return The toolbar. */ public JComponent getToolbar(); /** * Returns the main panel. * * @return The main panel. */ public JComponent getMainPanel(); /** * Checks, whether this root editor is enabled. * * @return true, if the editor is enabled, false otherwise. */ public boolean isEnabled(); /** * Adds a property change listener. * * @param property the property name. * @param l the listener. */ public void addPropertyChangeListener(String property, PropertyChangeListener l); /** * Removes a property change listener. * * @param property the property name. * @param l the listener. */ public void removePropertyChangeListener(String property, PropertyChangeListener l); /** * Adds a property change listener. * * @param l the listener. */ public void addPropertyChangeListener(PropertyChangeListener l); /** * Removes a property change listener. * * @param l the listener. */ public void removePropertyChangeListener(PropertyChangeListener l); } jcommon-1.0.16/source/org/jfree/ui/tabbedui/AbstractTabbedUI.java0000644000175000017500000003455311172030703024527 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * AbstractTabbedUI.java * --------------------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AbstractTabbedUI.java,v 1.10 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------------------------- * 16-Feb-2004 : Initial version * 07-Jun-2004 : Added standard header (DG); */ package org.jfree.ui.tabbedui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Window; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.jfree.util.Log; /** * A tabbed GUI. All views on the data are contained in tabs. * * @author Thomas Morgner */ public abstract class AbstractTabbedUI extends JComponent { /** The menu bar property key. */ public static final String JMENUBAR_PROPERTY = "jMenuBar"; /** The global menu property. */ public static final String GLOBAL_MENU_PROPERTY = "globalMenu"; /** * An exit action. */ protected class ExitAction extends AbstractAction { /** * Defines an Action object with a default * description string and default icon. */ public ExitAction() { putValue(NAME, "Exit"); } /** * Invoked when an action occurs. * * @param e the event. */ public void actionPerformed(final ActionEvent e) { attempExit(); } } /** * A tab change handler. */ private class TabChangeHandler implements ChangeListener { /** The tabbed pane to which this handler is registered. */ private final JTabbedPane pane; /** * Creates a new handler. * * @param pane the pane. */ public TabChangeHandler(final JTabbedPane pane) { this.pane = pane; } /** * Invoked when the target of the listener has changed its state. * * @param e a ChangeEvent object */ public void stateChanged(final ChangeEvent e) { setSelectedEditor(this.pane.getSelectedIndex()); } } /** * A tab enable change listener. */ private class TabEnableChangeListener implements PropertyChangeListener { /** * Default constructor. */ public TabEnableChangeListener() { } /** * This method gets called when a bound property is changed. * * @param evt A PropertyChangeEvent object describing the event source * and the property that has changed. */ public void propertyChange(final PropertyChangeEvent evt) { if (evt.getPropertyName().equals("enabled") == false) { Log.debug ("PropertyName"); return; } if (evt.getSource() instanceof RootEditor == false) { Log.debug ("Source"); return; } final RootEditor editor = (RootEditor) evt.getSource(); updateRootEditorEnabled(editor); } } /** The list of root editors. One for each tab. */ private ArrayList rootEditors; /** The tabbed pane filling the content area. */ private JTabbedPane tabbedPane; /** The index of the currently selected root editor. */ private int selectedRootEditor; /** The current toolbar. */ private JComponent currentToolbar; /** The container component for the toolbar. */ private JPanel toolbarContainer; /** The close action assigned to this UI. */ private Action closeAction; /** The current menu bar. */ private JMenuBar jMenuBar; /** Whether the UI should build a global menu from all root editors. */ private boolean globalMenu; /** * Default constructor. */ public AbstractTabbedUI() { this.selectedRootEditor = -1; this.toolbarContainer = new JPanel(); this.toolbarContainer.setLayout(new BorderLayout()); this.tabbedPane = new JTabbedPane(SwingConstants.BOTTOM); this.tabbedPane.addChangeListener(new TabChangeHandler(this.tabbedPane)); this.rootEditors = new ArrayList(); setLayout(new BorderLayout()); add(this.toolbarContainer, BorderLayout.NORTH); add(this.tabbedPane, BorderLayout.CENTER); this.closeAction = createCloseAction(); } /** * Returns the tabbed pane. * * @return The tabbed pane. */ protected JTabbedPane getTabbedPane() { return this.tabbedPane; } /** * Defines whether to use a global unified menu bar, which contains * all menus from all tab-panes or whether to use local menubars. *

* From an usability point of view, global menubars should be preferred, * as this way users always see which menus are possibly available and * do not wonder where the menus are disappearing. * * @return true, if global menus should be used, false otherwise. */ public boolean isGlobalMenu() { return this.globalMenu; } /** * Sets the global menu flag. * * @param globalMenu the flag. */ public void setGlobalMenu(final boolean globalMenu) { this.globalMenu = globalMenu; if (isGlobalMenu()) { setJMenuBar(updateGlobalMenubar()); } else { if (getRootEditorCount () > 0) { setJMenuBar(createEditorMenubar(getRootEditor(getSelectedEditor()))); } } } /** * Returns the menu bar. * * @return The menu bar. */ public JMenuBar getJMenuBar() { return this.jMenuBar; } /** * Sets the menu bar. * * @param menuBar the menu bar. */ protected void setJMenuBar(final JMenuBar menuBar) { final JMenuBar oldMenuBar = this.jMenuBar; this.jMenuBar = menuBar; firePropertyChange(JMENUBAR_PROPERTY, oldMenuBar, menuBar); } /** * Creates a close action. * * @return A close action. */ protected Action createCloseAction() { return new ExitAction(); } /** * Returns the close action. * * @return The close action. */ public Action getCloseAction() { return this.closeAction; } /** * Returns the prefix menus. * * @return The prefix menus. */ protected abstract JMenu[] getPrefixMenus(); /** * The postfix menus. * * @return The postfix menus. */ protected abstract JMenu[] getPostfixMenus(); /** * Adds menus. * * @param menuBar the menu bar * @param customMenus the menus that should be added. */ private void addMenus(final JMenuBar menuBar, final JMenu[] customMenus) { for (int i = 0; i < customMenus.length; i++) { menuBar.add(customMenus[i]); } } /** * Updates the global menu bar. * @return the fully initialized menu bar. */ private JMenuBar updateGlobalMenubar () { JMenuBar menuBar = getJMenuBar(); if (menuBar == null) { menuBar = new JMenuBar(); } else { menuBar.removeAll(); } addMenus(menuBar, getPrefixMenus()); for (int i = 0; i < this.rootEditors.size(); i++) { final RootEditor editor = (RootEditor) this.rootEditors.get(i); addMenus(menuBar, editor.getMenus()); } addMenus(menuBar, getPostfixMenus()); return menuBar; } /** * Creates a menu bar. * * @param root * @return A menu bar. */ private JMenuBar createEditorMenubar(final RootEditor root) { JMenuBar menuBar = getJMenuBar(); if (menuBar == null) { menuBar = new JMenuBar(); } else { menuBar.removeAll(); } addMenus(menuBar, getPrefixMenus()); if (isGlobalMenu()) { for (int i = 0; i < this.rootEditors.size(); i++) { final RootEditor editor = (RootEditor) this.rootEditors.get(i); addMenus(menuBar, editor.getMenus()); } } else { addMenus(menuBar, root.getMenus()); } addMenus(menuBar, getPostfixMenus()); return menuBar; } /** * Adds a root editor. * * @param rootPanel the root panel. */ public void addRootEditor(final RootEditor rootPanel) { this.rootEditors.add(rootPanel); this.tabbedPane.add(rootPanel.getEditorName(), rootPanel.getMainPanel()); rootPanel.addPropertyChangeListener("enabled", new TabEnableChangeListener()); updateRootEditorEnabled(rootPanel); if (getRootEditorCount () == 1) { setSelectedEditor(0); } else if (isGlobalMenu()) { setJMenuBar(updateGlobalMenubar()); } } /** * Returns the number of root editors. * * @return The count. */ public int getRootEditorCount () { return this.rootEditors.size(); } /** * Returns the specified editor. * * @param pos the position index. * * @return The editor at the given position. */ public RootEditor getRootEditor(final int pos) { return (RootEditor) this.rootEditors.get(pos); } /** * Returns the selected editor. * * @return The selected editor. */ public int getSelectedEditor() { return this.selectedRootEditor; } /** * Sets the selected editor. * * @param selectedEditor the selected editor. */ public void setSelectedEditor(final int selectedEditor) { final int oldEditor = this.selectedRootEditor; if (oldEditor == selectedEditor) { // no change - so nothing to do! return; } this.selectedRootEditor = selectedEditor; // make sure that only the selected editor is active. // all other editors will be disabled, if needed and // not touched if they are already in the correct state for (int i = 0; i < this.rootEditors.size(); i++) { final boolean shouldBeActive = (i == selectedEditor); final RootEditor container = (RootEditor) this.rootEditors.get(i); if (container.isActive() && (shouldBeActive == false)) { container.setActive(false); } } if (this.currentToolbar != null) { closeToolbar(); this.toolbarContainer.removeAll(); this.currentToolbar = null; } for (int i = 0; i < this.rootEditors.size(); i++) { final boolean shouldBeActive = (i == selectedEditor); final RootEditor container = (RootEditor) this.rootEditors.get(i); if ((container.isActive() == false) && (shouldBeActive == true)) { container.setActive(true); setJMenuBar(createEditorMenubar(container)); this.currentToolbar = container.getToolbar(); if (this.currentToolbar != null) { this.toolbarContainer.add (this.currentToolbar, BorderLayout.CENTER); this.toolbarContainer.setVisible(true); this.currentToolbar.setVisible(true); } else { this.toolbarContainer.setVisible(false); } this.getJMenuBar().repaint(); } } } /** * Closes the toolbar. */ private void closeToolbar() { if (this.currentToolbar != null) { if (this.currentToolbar.getParent() != this.toolbarContainer) { // ha!, the toolbar is floating ... // Log.debug (currentToolbar.getParent()); final Window w = SwingUtilities.windowForComponent(this.currentToolbar); if (w != null) { w.setVisible(false); w.dispose(); } } this.currentToolbar.setVisible(false); } } /** * Attempts to exit. */ protected abstract void attempExit(); /** * Update handler for the enable state of the root editor. * * @param editor the editor. */ protected void updateRootEditorEnabled(final RootEditor editor) { final boolean enabled = editor.isEnabled(); for (int i = 0; i < this.tabbedPane.getTabCount(); i++) { final Component tab = this.tabbedPane.getComponentAt(i); if (tab == editor.getMainPanel()) { this.tabbedPane.setEnabledAt(i, enabled); return; } } } } jcommon-1.0.16/source/org/jfree/ui/tabbedui/TabbedApplet.java0000644000175000017500000000713511172030703023747 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * TabbedApplet.java * ----------------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: TabbedApplet.java,v 1.7 2008/09/10 09:19:04 mungady Exp $ * * Changes * ------------------------- * 16-Feb-2004 : Initial version * 07-Jun-2004 : Added standard header (DG); */ package org.jfree.ui.tabbedui; import java.awt.BorderLayout; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JApplet; import javax.swing.JPanel; /** * An applet implementation that uses a tabbed GUI as backend. * * @author Thomas Morgner */ public class TabbedApplet extends JApplet { /** * A property change listener that waits for the menubar to change. */ private class MenuBarChangeListener implements PropertyChangeListener { /** * Creates a new change listener. */ public MenuBarChangeListener() { } /** * This method gets called when a bound property is changed. * * @param evt A PropertyChangeEvent object describing the event source * and the property that has changed. */ public void propertyChange(final PropertyChangeEvent evt) { if (evt.getPropertyName().equals(AbstractTabbedUI.JMENUBAR_PROPERTY)) { setJMenuBar(getTabbedUI().getJMenuBar()); } } } /** The UI for the applet. */ private AbstractTabbedUI tabbedUI; /** * Default constructor. */ public TabbedApplet() { } /** * Returns the UI implementation for the applet. * * @return Returns the tabbedUI. */ protected final AbstractTabbedUI getTabbedUI() { return this.tabbedUI; } /** * Initialises the applet. * * @param tabbedUI the UI that controls the applet. */ public void init(final AbstractTabbedUI tabbedUI) { this.tabbedUI = tabbedUI; this.tabbedUI.addPropertyChangeListener (AbstractTabbedUI.JMENUBAR_PROPERTY, new MenuBarChangeListener()); final JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(tabbedUI, BorderLayout.CENTER); setContentPane(panel); setJMenuBar(tabbedUI.getJMenuBar()); } } jcommon-1.0.16/source/org/jfree/ui/tabbedui/TabbedDialog.java0000644000175000017500000001342011172030703023713 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * AbstractTabbedGUI.java * ---------------------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: TabbedDialog.java,v 1.7 2008/09/10 09:19:04 mungady Exp $ * * Changes * ------------------------- * 16-Feb-2004 : Initial version * 07-Jun-2004 : Added standard header (DG); */ package org.jfree.ui.tabbedui; import java.awt.BorderLayout; import java.awt.Dialog; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JDialog; import javax.swing.JPanel; /** * A JDialog implementation that uses a tabbed UI as backend. * * @author Thomas Morgner */ public class TabbedDialog extends JDialog { /** The backend. */ private AbstractTabbedUI tabbedUI; /** * A property change listener that waits for the menubar to change. */ private class MenuBarChangeListener implements PropertyChangeListener { /** * Creates a new change listener. */ public MenuBarChangeListener() { } /** * This method gets called when a bound property is changed. * * @param evt A PropertyChangeEvent object describing the event source * and the property that has changed. */ public void propertyChange(final PropertyChangeEvent evt) { if (evt.getPropertyName().equals(AbstractTabbedUI.JMENUBAR_PROPERTY)) { setJMenuBar(getTabbedUI().getJMenuBar()); } } } /** * Default constructor. */ public TabbedDialog() { } /** * Creates a new dialog. * * @param owner the owner. */ public TabbedDialog(final Dialog owner) { super(owner); } /** * Creates a new dialog. * * @param owner the owner. * @param modal modal dialog? */ public TabbedDialog(final Dialog owner, final boolean modal) { super(owner, modal); } /** * Creates a new dialog. * * @param owner the owner. * @param title the dialog title. */ public TabbedDialog(final Dialog owner, final String title) { super(owner, title); } /** * Creates a new dialog. * * @param owner the owner. * @param title the dialog title. * @param modal modal dialog? */ public TabbedDialog(final Dialog owner, final String title, final boolean modal) { super(owner, title, modal); } /** * Creates a new dialog. * * @param owner the owner. */ public TabbedDialog(final Frame owner) { super(owner); } /** * Creates a new dialog. * * @param owner the owner. * @param modal modal dialog? */ public TabbedDialog(final Frame owner, final boolean modal) { super(owner, modal); } /** * Creates a new dialog. * * @param owner the owner. * @param title the dialog title. */ public TabbedDialog(final Frame owner, final String title) { super(owner, title); } /** * Creates a new dialog. * * @param owner the owner. * @param title the dialog title. * @param modal modal dialog? */ public TabbedDialog(final Frame owner, final String title, final boolean modal) { super(owner, title, modal); } /** * Returns the UI implementation for the dialog. * * @return Returns the tabbedUI. */ protected final AbstractTabbedUI getTabbedUI() { return this.tabbedUI; } /** * Initialises the dialog. * * @param tabbedUI the UI that controls the dialog. */ public void init(final AbstractTabbedUI tabbedUI) { this.tabbedUI = tabbedUI; this.tabbedUI.addPropertyChangeListener (AbstractTabbedUI.JMENUBAR_PROPERTY, new MenuBarChangeListener()); addWindowListener(new WindowAdapter() { public void windowClosing(final WindowEvent e) { getTabbedUI().getCloseAction().actionPerformed (new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null, 0)); } }); final JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(tabbedUI, BorderLayout.CENTER); setContentPane(panel); setJMenuBar(tabbedUI.getJMenuBar()); } } jcommon-1.0.16/source/org/jfree/ui/tabbedui/RootPanel.java0000644000175000017500000000641611172030703023324 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------- * RootPanel.java * -------------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: RootPanel.java,v 1.4 2005/10/18 13:23:37 mungady Exp $ * * Changes * ------------------------- * 16.02.2004 : Initial version * */ package org.jfree.ui.tabbedui; import javax.swing.JComponent; /** * A root panel is a panel implementation of an root editor. * * @author Thomas Morgner */ public abstract class RootPanel extends JComponent implements RootEditor { /**a flag indicating whether this editor is the currently active editor. */ private boolean active; /** * Default constructor. */ public RootPanel() { // nothing required. } /** * Returns a flag that indicates whether the panel is active or not. * * @return A flag. */ public final boolean isActive() { return this.active; } /** * Called when the panel is activated. */ protected void panelActivated() { } /** * Called when the panel is deactivated. */ protected void panelDeactivated() { } /** * Sets the status of the panel to active or inactive. * * @param active the flag. */ public final void setActive(final boolean active) { if (this.active == active) { return; } this.active = active; if (active) { panelActivated(); } else { panelDeactivated(); } } /** * Returns the main panel. Returns the self reference, as this panel * implements all necessary methods. * * @return The main panel. */ public JComponent getMainPanel() { return this; } /** * Returns the toolbar. This default implementation return null, to indicate * that no toolbar is used. * * @return The toolbar. */ public JComponent getToolbar() { return null; } } jcommon-1.0.16/source/org/jfree/ui/LocalizationBundle_fr.properties0000644000175000017500000000063111172030703025357 0ustar twernertwerner# org.jfree.ui.ui ResourceBundle properties file - french version # # Changes (from 31-Aug-2003) # -------------------------- # 31-Aug-2003 : Initial version (AL); # Attributes=Attributs : B=B : Bold=Gras Bottom=Bas Font=Police : Insets=Position : Italic=Italique L=G : Left=Gauche No_Font_Selected=Aucune police n'a \u00E9t\u00E9 s\u00E9lectionn\u00E9e. R=D : Right=Droite Size=Taille : T=H : Top=Haut jcommon-1.0.16/source/org/jfree/ui/OverlayLayout.java0000644000175000017500000001440711172030703022460 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------ * OverlayLayout.java * ------------------------------ * (C)opyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): -; * * $Id: OverlayLayout.java,v 1.5 2005/10/18 13:18:34 mungady Exp $ * * Changes * ------------------------- * 09-12-2003 : Initial version * */ package org.jfree.ui; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.Rectangle; /** * A simple layoutmanager to overlay all components of a parent. *

* This layout manager acts similiar to the card layout, but all * childs of the parent band have the same size and all childs can * be visible at the same time. * * @author Thomas Morgner */ public final class OverlayLayout implements LayoutManager { /** * A flag that defines, whether invisible components should be ignored when * computing the layout. */ private boolean ignoreInvisible; /** * Creates a new instance. * * @param ignoreInvisible whether to ignore invisible components when computing the layout. */ public OverlayLayout(final boolean ignoreInvisible) { this.ignoreInvisible = ignoreInvisible; } /** * DefaultConstructor. */ public OverlayLayout() { } /** * If the layout manager uses a per-component string, * adds the component comp to the layout, * associating it * with the string specified by name. * * @param name the string to be associated with the component * @param comp the component to be added */ public void addLayoutComponent(final String name, final Component comp) { } /** * Removes the specified component from the layout. * * @param comp the component to be removed */ public void removeLayoutComponent(final Component comp) { } /** * Lays out the specified container. * * @param parent the container to be laid out */ public void layoutContainer(final Container parent) { synchronized (parent.getTreeLock()) { final Insets ins = parent.getInsets(); final Rectangle bounds = parent.getBounds(); final int width = bounds.width - ins.left - ins.right; final int height = bounds.height - ins.top - ins.bottom; final Component[] comps = parent.getComponents(); for (int i = 0; i < comps.length; i++) { final Component c = comps[i]; if ((comps[i].isVisible() == false) && this.ignoreInvisible) { continue; } c.setBounds(ins.left, ins.top, width, height); } } } /** * Calculates the minimum size dimensions for the specified * container, given the components it contains. * * @param parent the component to be laid out * @return the minimum size computed for the parent. * @see #preferredLayoutSize */ public Dimension minimumLayoutSize(final Container parent) { synchronized (parent.getTreeLock()) { final Insets ins = parent.getInsets(); final Component[] comps = parent.getComponents(); int height = 0; int width = 0; for (int i = 0; i < comps.length; i++) { if ((comps[i].isVisible() == false) && this.ignoreInvisible) { continue; } final Dimension pref = comps[i].getMinimumSize(); if (pref.height > height) { height = pref.height; } if (pref.width > width) { width = pref.width; } } return new Dimension(width + ins.left + ins.right, height + ins.top + ins.bottom); } } /** * Calculates the preferred size dimensions for the specified * container, given the components it contains. * * @param parent the container to be laid out * @return the preferred size computed for the parent. * @see #minimumLayoutSize */ public Dimension preferredLayoutSize(final Container parent) { synchronized (parent.getTreeLock()) { final Insets ins = parent.getInsets(); final Component[] comps = parent.getComponents(); int height = 0; int width = 0; for (int i = 0; i < comps.length; i++) { if ((comps[i].isVisible() == false) && this.ignoreInvisible) { continue; } final Dimension pref = comps[i].getPreferredSize(); if (pref.height > height) { height = pref.height; } if (pref.width > width) { width = pref.width; } } return new Dimension(width + ins.left + ins.right, height + ins.top + ins.bottom); } } } jcommon-1.0.16/source/org/jfree/ui/Drawable.java0000644000175000017500000000402211172030703021352 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------- * Drawable.java * ------------- * (C) Copyright 2002-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: Drawable.java,v 1.4 2005/11/16 15:58:41 taqua Exp $ * * Changes (from 30-May-2002) * -------------------------- * 25-Jun-2002 : Version 1 (DG); * */ package org.jfree.ui; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; /** * An interface for an object that can draw itself within an area on a Graphics2D. * * @author David Gilbert */ public interface Drawable { /** * Draws the object. * * @param g2 the graphics device. * @param area the area inside which the object should be drawn. */ public void draw(Graphics2D g2, Rectangle2D area); } jcommon-1.0.16/source/org/jfree/ui/FilesystemFilter.java0000644000175000017500000001160311172030703023126 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * ExtensionFileFilter.java * ------------------------ * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: FilesystemFilter.java,v 1.6 2008/09/10 09:26:11 mungady Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 01-Jun-2005 : Updated javadoc. */ package org.jfree.ui; import java.io.File; import java.io.FilenameFilter; import javax.swing.filechooser.FileFilter; /** * A filesystem filter. * * @author David Gilbert */ public class FilesystemFilter extends FileFilter implements FilenameFilter { /** The file extension, which should be accepted. */ private String[] fileext; /** The filter description. */ private String descr; /** A flag indicating whether to accept directories. */ private boolean accDirs; /** * Creates a new filter. * * @param fileext the file extension. * @param descr the description. */ public FilesystemFilter(final String fileext, final String descr) { this(fileext, descr, true); } /** * Creates a new filter. * * @param fileext the file extension. * @param descr the description. * @param accDirs accept directories? */ public FilesystemFilter(final String fileext, final String descr, final boolean accDirs) { this(new String[]{fileext}, descr, accDirs); } /** * Creates a new filter. * * @param fileext the file extension. * @param descr the description. * @param accDirs accept directories? * @throws NullPointerException if the file extensions are null. */ public FilesystemFilter(final String[] fileext, final String descr, final boolean accDirs) { this.fileext = (String[]) fileext.clone(); this.descr = descr; this.accDirs = accDirs; } /** * Returns true if the file is accepted, and false otherwise. * * @param dir the directory. * @param name the file name. * @return A boolean. */ public boolean accept(final File dir, final String name) { final File f = new File(dir, name); if (f.isDirectory() && acceptsDirectories()) { return true; } for (int i = 0; i < this.fileext.length; i++) { if (name.endsWith(this.fileext[i])) { return true; } } return false; } /** * Returns true if the specified file matches the requirements of this * filter, and false otherwise. * * @param dir the file or directory. * @return A boolean. */ public boolean accept(final File dir) { if (dir.isDirectory() && acceptsDirectories()) { return true; } for (int i = 0; i < this.fileext.length; i++) { if (dir.getName().endsWith(this.fileext[i])) { return true; } } return false; } /** * Returns the filter description. * * @return The filter description. */ public String getDescription() { return this.descr; } /** * Sets the flag that controls whether or not the filter accepts directories. * * @param b a boolean. */ public void acceptDirectories(final boolean b) { this.accDirs = b; } /** * Returns the flag that indicates whether or not the filter accepts directories. * * @return A boolean. */ public boolean acceptsDirectories() { return this.accDirs; } } jcommon-1.0.16/source/org/jfree/ui/SortButtonRenderer.java0000644000175000017500000002343511172030703023454 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * SortButtonRenderer.java * ----------------------- * (C) Copyright 2000-2004, by Nobuo Tamemasa and Contributors. * * Original Author: Nobuo Tamemasa; * Contributor(s): David Gilbert (for Object Refinery Limited); * Gareth Davis; * * $Id: SortButtonRenderer.java,v 1.7 2008/09/10 09:26:11 mungady Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.* (DG); * 26-Jun-2002 : Removed unnecessary import (DG); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.awt.Component; import java.awt.Insets; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; /** * A table cell renderer for table headings - uses one of three JButton instances to indicate the * sort order for the table column. *

* This class (and also BevelArrowIcon) is adapted from original code by Nobuo Tamemasa (version * 1.0, 26-Feb-1999) posted on www.codeguru.com. * * @author David Gilbert */ public class SortButtonRenderer implements TableCellRenderer { /** * Useful constant indicating NO sorting. */ public static final int NONE = 0; /** * Useful constant indicating ASCENDING (that is, arrow pointing down) sorting in the table. */ public static final int DOWN = 1; /** * Useful constant indicating DESCENDING (that is, arrow pointing up) sorting in the table. */ public static final int UP = 2; /** * The current pressed column (-1 for no column). */ private int pressedColumn = -1; /** * The three buttons that are used to render the table header cells. */ private JButton normalButton; /** * The three buttons that are used to render the table header cells. */ private JButton ascendingButton; /** * The three buttons that are used to render the table header cells. */ private JButton descendingButton; /** * Used to allow the class to work out whether to use the buttuns * or labels. Labels are required when using the aqua look and feel cos the * buttons won't fit. */ private boolean useLabels; /** * The normal label (only used with MacOSX). */ private JLabel normalLabel; /** * The ascending label (only used with MacOSX). */ private JLabel ascendingLabel; /** * The descending label (only used with MacOSX). */ private JLabel descendingLabel; /** * Creates a new button renderer. */ public SortButtonRenderer() { this.pressedColumn = -1; this.useLabels = UIManager.getLookAndFeel().getID().equals("Aqua"); final Border border = UIManager.getBorder("TableHeader.cellBorder"); if (this.useLabels) { this.normalLabel = new JLabel(); this.normalLabel.setHorizontalAlignment(SwingConstants.LEADING); this.ascendingLabel = new JLabel(); this.ascendingLabel.setHorizontalAlignment(SwingConstants.LEADING); this.ascendingLabel.setHorizontalTextPosition(SwingConstants.LEFT); this.ascendingLabel.setIcon(new BevelArrowIcon(BevelArrowIcon.DOWN, false, false)); this.descendingLabel = new JLabel(); this.descendingLabel.setHorizontalAlignment(SwingConstants.LEADING); this.descendingLabel.setHorizontalTextPosition(SwingConstants.LEFT); this.descendingLabel.setIcon(new BevelArrowIcon(BevelArrowIcon.UP, false, false)); this.normalLabel.setBorder(border); this.ascendingLabel.setBorder(border); this.descendingLabel.setBorder(border); } else { this.normalButton = new JButton(); this.normalButton.setMargin(new Insets(0, 0, 0, 0)); this.normalButton.setHorizontalAlignment(SwingConstants.LEADING); this.ascendingButton = new JButton(); this.ascendingButton.setMargin(new Insets(0, 0, 0, 0)); this.ascendingButton.setHorizontalAlignment(SwingConstants.LEADING); this.ascendingButton.setHorizontalTextPosition(SwingConstants.LEFT); this.ascendingButton.setIcon(new BevelArrowIcon(BevelArrowIcon.DOWN, false, false)); this.ascendingButton.setPressedIcon(new BevelArrowIcon(BevelArrowIcon.DOWN, false, true)); this.descendingButton = new JButton(); this.descendingButton.setMargin(new Insets(0, 0, 0, 0)); this.descendingButton.setHorizontalAlignment(SwingConstants.LEADING); this.descendingButton.setHorizontalTextPosition(SwingConstants.LEFT); this.descendingButton.setIcon(new BevelArrowIcon(BevelArrowIcon.UP, false, false)); this.descendingButton.setPressedIcon(new BevelArrowIcon(BevelArrowIcon.UP, false, true)); this.normalButton.setBorder(border); this.ascendingButton.setBorder(border); this.descendingButton.setBorder(border); } } /** * Returns the renderer component. * * @param table the table. * @param value the value. * @param isSelected selected? * @param hasFocus focussed? * @param row the row. * @param column the column. * @return the renderer. */ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { if (table == null) { throw new NullPointerException("Table must not be null."); } final JComponent component; final SortableTableModel model = (SortableTableModel) table.getModel(); final int cc = table.convertColumnIndexToModel(column); final boolean isSorting = (model.getSortingColumn() == cc); final boolean isAscending = model.isAscending(); final JTableHeader header = table.getTableHeader(); final boolean isPressed = (cc == this.pressedColumn); if (this.useLabels) { final JLabel label = getRendererLabel(isSorting, isAscending); label.setText((value == null) ? "" : value.toString()); component = label; } else { final JButton button = getRendererButton(isSorting, isAscending); button.setText((value == null) ? "" : value.toString()); button.getModel().setPressed(isPressed); button.getModel().setArmed(isPressed); component = button; } if (header != null) { component.setForeground(header.getForeground()); component.setBackground(header.getBackground()); component.setFont(header.getFont()); } return component; } /** * Returns the correct button component. * * @param isSorting whether the render component represents the sort column. * @param isAscending whether the model is ascending. * @return either the ascending, descending or normal button. */ private JButton getRendererButton(final boolean isSorting, final boolean isAscending) { if (isSorting) { if (isAscending) { return this.ascendingButton; } else { return this.descendingButton; } } else { return this.normalButton; } } /** * Returns the correct label component. * * @param isSorting whether the render component represents the sort column. * @param isAscending whether the model is ascending. * @return either the ascending, descending or normal label. */ private JLabel getRendererLabel(final boolean isSorting, final boolean isAscending) { if (isSorting) { if (isAscending) { return this.ascendingLabel; } else { return this.descendingLabel; } } else { return this.normalLabel; } } /** * Sets the pressed column. * * @param column the column. */ public void setPressedColumn(final int column) { this.pressedColumn = column; } } jcommon-1.0.16/source/org/jfree/ui/FontChooserPanel.java0000644000175000017500000001722011172030703023046 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * FontChooserPanel.java * --------------------- * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Arnaud Lelievre; * * $Id: FontChooserPanel.java,v 1.6 2008/12/18 09:57:32 mungady Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 08-Sep-2003 : Added internationalization via use of properties resourceBundle (RFE 690236) (AL); * 21-Feb-2004 : The FontParameter of the constructor was never used (TM); * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.ui; import java.awt.BorderLayout; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.GridLayout; import java.util.ResourceBundle; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListModel; import org.jfree.util.ResourceBundleWrapper; /** * A panel for choosing a font from the available system fonts - still a bit of * a hack at the moment, but good enough for demonstration applications. * * @author David Gilbert */ public class FontChooserPanel extends JPanel { /** The font sizes that can be selected. */ public static final String[] SIZES = {"9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "28", "36", "48", "72"}; /** The list of fonts. */ private JList fontlist; /** The list of sizes. */ private JList sizelist; /** The checkbox that indicates whether the font is bold. */ private JCheckBox bold; /** The checkbox that indicates whether or not the font is italic. */ private JCheckBox italic; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle("org.jfree.ui.LocalizationBundle"); /** * Standard constructor - builds a FontChooserPanel initialised with the * specified font. * * @param font the initial font to display. */ public FontChooserPanel(final Font font) { final GraphicsEnvironment g = GraphicsEnvironment.getLocalGraphicsEnvironment(); final String[] fonts = g.getAvailableFontFamilyNames(); setLayout(new BorderLayout()); final JPanel right = new JPanel(new BorderLayout()); final JPanel fontPanel = new JPanel(new BorderLayout()); fontPanel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), localizationResources.getString("Font"))); this.fontlist = new JList(fonts); final JScrollPane fontpane = new JScrollPane(this.fontlist); fontpane.setBorder(BorderFactory.createEtchedBorder()); fontPanel.add(fontpane); add(fontPanel); final JPanel sizePanel = new JPanel(new BorderLayout()); sizePanel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), localizationResources.getString("Size"))); this.sizelist = new JList(SIZES); final JScrollPane sizepane = new JScrollPane(this.sizelist); sizepane.setBorder(BorderFactory.createEtchedBorder()); sizePanel.add(sizepane); final JPanel attributes = new JPanel(new GridLayout(1, 2)); this.bold = new JCheckBox(localizationResources.getString("Bold")); this.italic = new JCheckBox(localizationResources.getString("Italic")); attributes.add(this.bold); attributes.add(this.italic); attributes.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), localizationResources.getString("Attributes"))); right.add(sizePanel, BorderLayout.CENTER); right.add(attributes, BorderLayout.SOUTH); add(right, BorderLayout.EAST); setSelectedFont(font); } /** * Returns a Font object representing the selection in the panel. * * @return the font. */ public Font getSelectedFont() { return new Font(getSelectedName(), getSelectedStyle(), getSelectedSize()); } /** * Returns the selected name. * * @return the name. */ public String getSelectedName() { return (String) this.fontlist.getSelectedValue(); } /** * Returns the selected style. * * @return the style. */ public int getSelectedStyle() { if (this.bold.isSelected() && this.italic.isSelected()) { return Font.BOLD + Font.ITALIC; } if (this.bold.isSelected()) { return Font.BOLD; } if (this.italic.isSelected()) { return Font.ITALIC; } else { return Font.PLAIN; } } /** * Returns the selected size. * * @return the size. */ public int getSelectedSize() { final String selected = (String) this.sizelist.getSelectedValue(); if (selected != null) { return Integer.parseInt(selected); } else { return 10; } } /** * Initializes the contents of the dialog from the given font * object. * * @param font the font from which to read the properties. */ public void setSelectedFont (final Font font) { if (font == null) { throw new NullPointerException(); } this.bold.setSelected(font.isBold()); this.italic.setSelected(font.isItalic()); final String fontName = font.getName(); ListModel model = this.fontlist.getModel(); this.fontlist.clearSelection(); for (int i = 0; i < model.getSize(); i++) { if (fontName.equals(model.getElementAt(i))) { this.fontlist.setSelectedIndex(i); break; } } final String fontSize = String.valueOf(font.getSize()); model = this.sizelist.getModel(); this.sizelist.clearSelection(); for (int i = 0; i < model.getSize(); i++) { if (fontSize.equals(model.getElementAt(i))) { this.sizelist.setSelectedIndex(i); break; } } } } jcommon-1.0.16/source/org/jfree/ui/RefineryUtilities.java0000644000175000017500000002564111172030703023322 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * RefineryUtilities.java * ---------------------- * (C) Copyright 2000-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Jon Iles; * * $Id: RefineryUtilities.java,v 1.11 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 26-Nov-2001 : Changed name to SwingRefinery.java to make it obvious that this is not part of * the Java APIs (DG); * 10-Dec-2001 : Changed name (again) to JRefineryUtilities.java (DG); * 28-Feb-2002 : Moved system properties classes into com.jrefinery.ui.about (DG); * 19-Apr-2002 : Renamed JRefineryUtilities-->RefineryUtilities. Added drawRotatedString() * method (DG); * 21-May-2002 : Changed frame positioning methods to accept Window parameters, as suggested by * Laurence Vanhelsuwe (DG); * 27-May-2002 : Added getPointInRectangle method (DG); * 26-Jun-2002 : Removed unnecessary imports (DG); * 12-Jul-2002 : Added workaround for rotated text (JI); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 08-May-2003 : Added a new drawRotatedString() method (DG); * 09-May-2003 : Added a drawRotatedShape() method (DG); * 10-Jun-2003 : Updated aligned and rotated string methods (DG); * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG); * 07-Nov-2003 : Added rotateShape() method (DG); * 16-Mar-2004 : Moved rotateShape() method to ShapeUtils.java (DG); * 07-Apr-2004 : Modified text bounds calculation with TextUtilities.getTextBounds() (DG); * 21-May-2004 : Fixed bug 951870 - precision in drawAlignedString() method (DG); * 30-Sep-2004 : Deprecated and moved a number of methods to the TextUtilities class (DG); * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG); * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 release (DG); * */ package org.jfree.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Window; import java.lang.reflect.Method; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; /** * A collection of utility methods relating to user interfaces. * * @author David Gilbert */ public class RefineryUtilities { private RefineryUtilities() { } /** Access to logging facilities. */ // private static final LogContext logger = Log.createContext(RefineryUtilities.class); /** * Computes the center point of the current screen device. If this method is called on JDK 1.4, Xinerama-aware * results are returned. (See Sun-Bug-ID 4463949 for details). * * @return the center point of the current screen. */ public static Point getCenterPoint () { final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment(); try { final Method method = GraphicsEnvironment.class.getMethod("getCenterPoint", (Class[]) null); return (Point) method.invoke(localGraphicsEnvironment, (Object[]) null); } catch(Exception e) { // ignore ... will fail if this is not a JDK 1.4 .. } final Dimension s = Toolkit.getDefaultToolkit().getScreenSize(); return new Point (s.width / 2, s.height / 2); } /** * Computes the maximum bounds of the current screen device. If this method is called on JDK 1.4, Xinerama-aware * results are returned. (See Sun-Bug-ID 4463949 for details). * * @return the maximum bounds of the current screen. */ public static Rectangle getMaximumWindowBounds () { final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment(); try { final Method method = GraphicsEnvironment.class.getMethod("getMaximumWindowBounds", (Class[]) null); return (Rectangle) method.invoke(localGraphicsEnvironment, (Object[]) null); } catch(Exception e) { // ignore ... will fail if this is not a JDK 1.4 .. } final Dimension s = Toolkit.getDefaultToolkit().getScreenSize(); return new Rectangle (0, 0, s.width, s.height); } /** * Positions the specified frame in the middle of the screen. * * @param frame the frame to be centered on the screen. */ public static void centerFrameOnScreen(final Window frame) { positionFrameOnScreen(frame, 0.5, 0.5); } /** * Positions the specified frame at a relative position in the screen, where 50% is considered * to be the center of the screen. * * @param frame the frame. * @param horizontalPercent the relative horizontal position of the frame (0.0 to 1.0, * where 0.5 is the center of the screen). * @param verticalPercent the relative vertical position of the frame (0.0 to 1.0, where * 0.5 is the center of the screen). */ public static void positionFrameOnScreen(final Window frame, final double horizontalPercent, final double verticalPercent) { final Rectangle s = getMaximumWindowBounds(); final Dimension f = frame.getSize(); final int w = Math.max(s.width - f.width, 0); final int h = Math.max(s.height - f.height, 0); final int x = (int) (horizontalPercent * w) + s.x; final int y = (int) (verticalPercent * h) + s.y; frame.setBounds(x, y, f.width, f.height); } /** * Positions the specified frame at a random location on the screen while ensuring that the * entire frame is visible (provided that the frame is smaller than the screen). * * @param frame the frame. */ public static void positionFrameRandomly(final Window frame) { positionFrameOnScreen(frame, Math.random(), Math.random()); } /** * Positions the specified dialog within its parent. * * @param dialog the dialog to be positioned on the screen. */ public static void centerDialogInParent(final Dialog dialog) { positionDialogRelativeToParent(dialog, 0.5, 0.5); } /** * Positions the specified dialog at a position relative to its parent. * * @param dialog the dialog to be positioned. * @param horizontalPercent the relative location. * @param verticalPercent the relative location. */ public static void positionDialogRelativeToParent(final Dialog dialog, final double horizontalPercent, final double verticalPercent) { final Dimension d = dialog.getSize(); final Container parent = dialog.getParent(); final Dimension p = parent.getSize(); final int baseX = parent.getX() - d.width; final int baseY = parent.getY() - d.height; final int w = d.width + p.width; final int h = d.height + p.height; int x = baseX + (int) (horizontalPercent * w); int y = baseY + (int) (verticalPercent * h); // make sure the dialog fits completely on the screen... final Rectangle s = getMaximumWindowBounds(); x = Math.min(x, (s.width - d.width)); x = Math.max(x, 0); y = Math.min(y, (s.height - d.height)); y = Math.max(y, 0); dialog.setBounds(x + s.x, y + s.y, d.width, d.height); } /** * Creates a panel that contains a table based on the specified table model. * * @param model the table model to use when constructing the table. * * @return The panel. */ public static JPanel createTablePanel(final TableModel model) { final JPanel panel = new JPanel(new BorderLayout()); final JTable table = new JTable(model); for (int columnIndex = 0; columnIndex < model.getColumnCount(); columnIndex++) { final TableColumn column = table.getColumnModel().getColumn(columnIndex); final Class c = model.getColumnClass(columnIndex); if (c.equals(Number.class)) { column.setCellRenderer(new NumberCellRenderer()); } } panel.add(new JScrollPane(table)); return panel; } /** * Creates a label with a specific font. * * @param text the text for the label. * @param font the font. * * @return The label. */ public static JLabel createJLabel(final String text, final Font font) { final JLabel result = new JLabel(text); result.setFont(font); return result; } /** * Creates a label with a specific font and color. * * @param text the text for the label. * @param font the font. * @param color the color. * * @return The label. */ public static JLabel createJLabel(final String text, final Font font, final Color color) { final JLabel result = new JLabel(text); result.setFont(font); result.setForeground(color); return result; } /** * Creates a {@link JButton}. * * @param label the label. * @param font the font. * * @return The button. */ public static JButton createJButton(final String label, final Font font) { final JButton result = new JButton(label); result.setFont(font); return result; } } jcommon-1.0.16/source/org/jfree/ui/DrawablePanel.java0000644000175000017500000001354311172030703022342 0ustar twernertwerner/** * ======================================== * JCommon : a free Java report library * ======================================== * * Project Info: http://www.jfree.org/jcommon/ * Project Lead: Thomas Morgner; * * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------ * DrawablePanel.java * ------------ * (C) Copyright 2002-2006, by Object Refinery Limited. * * Original Author: Thomas Morgner; * Contributor(s): -; * * $Id: DrawablePanel.java,v 1.4 2008/09/10 09:25:09 mungady Exp $ * * Changes * ------- * * */ package org.jfree.ui; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import javax.swing.JPanel; /** * A component, that accepts a drawable and which draws that drawable. * * @author Thomas Morgner */ public class DrawablePanel extends JPanel { private Drawable drawable; /** * Creates a new instance. */ public DrawablePanel() { setOpaque(false); } /** * Returns the drawable item. * * @return The drawable item. */ public Drawable getDrawable() { return this.drawable; } /** * Sets the drawable item. * * @param drawable the drawable item. */ public void setDrawable(final Drawable drawable) { this.drawable = drawable; revalidate(); repaint(); } /** * If the preferredSize has been set to a non-null * value just returns it. If the UI delegate's getPreferredSize * method returns a non null value then return that; otherwise * defer to the component's layout manager. * * @return the value of the preferredSize property * @see #setPreferredSize * @see javax.swing.plaf.ComponentUI */ public Dimension getPreferredSize() { if (this.drawable instanceof ExtendedDrawable) { final ExtendedDrawable ed = (ExtendedDrawable) this.drawable; return ed.getPreferredSize(); } return super.getPreferredSize(); } /** * If the minimum size has been set to a non-null value just * returns it. If the UI delegate's getMinimumSize method * returns a non-null value then return that; otherwise defer to * the component's layout manager. * * @return the value of the minimumSize property * @see #setMinimumSize * @see javax.swing.plaf.ComponentUI */ public Dimension getMinimumSize() { if (this.drawable instanceof ExtendedDrawable) { final ExtendedDrawable ed = (ExtendedDrawable) this.drawable; return ed.getPreferredSize(); } return super.getMinimumSize(); } /** * Returns true if this component is completely opaque. *

* An opaque component paints every pixel within its rectangular bounds. A * non-opaque component paints only a subset of its pixels or none at all, * allowing the pixels underneath it to "show through". Therefore, a * component that does not fully paint its pixels provides a degree of * transparency. *

* Subclasses that guarantee to always completely paint their contents should * override this method and return true. * * @return true if this component is completely opaque * @see #setOpaque */ public boolean isOpaque() { if (this.drawable == null) { return false; } return super.isOpaque(); } /** * Calls the UI delegate's paint method, if the UI delegate is * non-null. We pass the delegate a copy of the * Graphics object to protect the rest of the paint code from * irrevocable changes (for example, Graphics.translate). *

* If you override this in a subclass you should not make permanent changes to * the passed in Graphics. For example, you should not alter the * clip Rectangle or modify the transform. If you need to do * these operations you may find it easier to create a new * Graphics from the passed in Graphics and * manipulate it. Further, if you do not invoker super's implementation you * must honor the opaque property, that is if this component is opaque, you * must completely fill in the background in a non-opaque color. If you do not * honor the opaque property you will likely see visual artifacts. *

* The passed in Graphics object might have a transform other * than the identify transform installed on it. In this case, you might get * unexpected results if you cumulatively apply another transform. * * @param g the Graphics object to protect * @see #paint * @see javax.swing.plaf.ComponentUI */ protected void paintComponent(Graphics g) { super.paintComponent(g); if (this.drawable == null) { return; } final Graphics2D g2 = (Graphics2D) g.create (0, 0, getWidth(), getHeight()); this.drawable.draw(g2, new Rectangle2D.Double(0, 0, getWidth(), getHeight())); g2.dispose(); } } jcommon-1.0.16/source/org/jfree/ui/JTextObserver.java0000644000175000017500000000723111172030703022404 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * JTextObserver.java * ------------------ * (C) Copyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: JTextObserver.java,v 1.6 2007/11/02 17:50:36 taqua Exp $ * * Changes * ------- * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.ui; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import javax.swing.text.JTextComponent; /** * An observer that selects all the text when a field gains the focus. * * @author Thomas Morgner */ public final class JTextObserver implements FocusListener { /** The singleton instance. */ private static JTextObserver singleton; /** * Creates a new instance. */ private JTextObserver() { // nothing required } /** * Returns the single instance. * * @return The single instance. */ public static JTextObserver getInstance() { if (singleton == null) { singleton = new JTextObserver(); } return singleton; } /** * Selects all the text when a field gains the focus. * * @param e the focus event. */ public void focusGained(final FocusEvent e) { if (e.getSource() instanceof JTextComponent) { final JTextComponent tex = (JTextComponent) e.getSource(); tex.selectAll(); } } /** * Deselects the text when a field loses the focus. * * @param e the event. */ public void focusLost(final FocusEvent e) { if (e.getSource() instanceof JTextComponent) { final JTextComponent tex = (JTextComponent) e.getSource(); tex.select(0, 0); } } /** * Adds this instance as a listener for the specified text component. * * @param t the text component. */ public static void addTextComponent(final JTextComponent t) { if (singleton == null) { singleton = new JTextObserver(); } t.addFocusListener(singleton); } /** * Removes this instance as a listener for the specified text component. * * @param t the text component. */ public static void removeTextComponent(final JTextComponent t) { if (singleton == null) { singleton = new JTextObserver(); } t.removeFocusListener(singleton); } } jcommon-1.0.16/source/org/jfree/ui/GradientPaintTransformType.java0000644000175000017500000001136711172030703025132 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------- * GradientPaintTransformType.java * ------------------------------- * (C) Copyright 2003-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: GradientPaintTransformType.java,v 1.4 2005/10/18 13:18:34 mungady Exp $ * * Changes: * -------- * 21-Oct-2003 (DG); * */ package org.jfree.ui; import java.io.ObjectStreamException; import java.io.Serializable; /** * Represents a type of transform for a GradientPaint. * * @author David Gilbert */ public final class GradientPaintTransformType implements Serializable { /** For serialization. */ private static final long serialVersionUID = 8331561784933982450L; /** Vertical. */ public static final GradientPaintTransformType VERTICAL = new GradientPaintTransformType("GradientPaintTransformType.VERTICAL"); /** Horizontal. */ public static final GradientPaintTransformType HORIZONTAL = new GradientPaintTransformType( "GradientPaintTransformType.HORIZONTAL"); /** Center/vertical. */ public static final GradientPaintTransformType CENTER_VERTICAL = new GradientPaintTransformType( "GradientPaintTransformType.CENTER_VERTICAL"); /** Center/horizontal. */ public static final GradientPaintTransformType CENTER_HORIZONTAL = new GradientPaintTransformType( "GradientPaintTransformType.CENTER_HORIZONTAL"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private GradientPaintTransformType(final String name) { this.name = name; } /** * Returns a string representing the object. * * @return The string. */ public String toString() { return this.name; } /** * Returns true if this object is equal to the specified * object, and false otherwise. * * @param o the other object. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof GradientPaintTransformType)) { return false; } final GradientPaintTransformType t = (GradientPaintTransformType) o; if (!this.name.equals(t.name)) { return false; } return true; } /** * Returns a hash code value for the object. * * @return the hashcode */ public int hashCode() { return this.name.hashCode(); } /** * Ensures that serialization returns the unique instances. * * @return The object. * * @throws ObjectStreamException if there is a problem. */ private Object readResolve() throws ObjectStreamException { GradientPaintTransformType result = null; if (this.equals(GradientPaintTransformType.HORIZONTAL)) { result = GradientPaintTransformType.HORIZONTAL; } else if (this.equals(GradientPaintTransformType.VERTICAL)) { result = GradientPaintTransformType.VERTICAL; } else if (this.equals(GradientPaintTransformType.CENTER_HORIZONTAL)) { result = GradientPaintTransformType.CENTER_HORIZONTAL; } else if (this.equals(GradientPaintTransformType.CENTER_VERTICAL)) { result = GradientPaintTransformType.CENTER_VERTICAL; } return result; } } jcommon-1.0.16/source/org/jfree/ui/FloatingButtonEnabler.java0000644000175000017500000000775211172030703024076 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * DetailEditor.java * ----------------- * (C) Copyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: FloatingButtonEnabler.java,v 1.4 2007/11/02 17:50:36 taqua Exp $ * * Changes * ------- * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.ui; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.AbstractButton; /** * Enables a button to have a simple floating effect. The border of the button is only visible, * when the mouse pointer is floating over the button. * * @author Thomas Morgner */ public final class FloatingButtonEnabler extends MouseAdapter { /** A single instance. */ private static FloatingButtonEnabler singleton; /** * Default constructor. */ private FloatingButtonEnabler() { // nothing required } /** * Returns a default instance of this enabler. * * @return a shared instance of this class. */ public static FloatingButtonEnabler getInstance() { if (singleton == null) { singleton = new FloatingButtonEnabler(); } return singleton; } /** * Adds a button to this enabler. * * @param button the button. */ public void addButton(final AbstractButton button) { button.addMouseListener(this); button.setBorderPainted(false); } /** * Removes a button from the enabler. * * @param button the button. */ public void removeButton(final AbstractButton button) { button.addMouseListener(this); button.setBorderPainted(true); } /** * Triggers the drawing of the border when the mouse entered the button area. * * @param e the mouse event. */ public void mouseEntered(final MouseEvent e) { if (e.getSource() instanceof AbstractButton) { final AbstractButton button = (AbstractButton) e.getSource(); if (button.isEnabled()) { button.setBorderPainted(true); } } } /** * Disables the drawing of the border when the mouse leaves the button area. * * @param e the mouse event. */ public void mouseExited(final MouseEvent e) { if (e.getSource() instanceof AbstractButton) { final AbstractButton button = (AbstractButton) e.getSource(); button.setBorderPainted(false); if (button.getParent() != null) { // button.getParent().repaint(button.getX(), button.getY(), // button.getWidth(), button.getHeight()); button.getParent().repaint(); } } } } jcommon-1.0.16/source/org/jfree/ui/LocalizationBundle_de.properties0000644000175000017500000000067111172030703025344 0ustar twernertwerner# org.jfree.ui.ui ResourceBundle properties file - german version # # Changes (from 31-Aug-2003) # -------------------------- # 15-Mar-2004 : Initial version (Christian W. Zuckschwerdt); # Attributes=Attribute: B=U: Bold=Fett Bottom=Unten Font=Schrift: Insets=R\u00e4nder: Italic=Kursiv L=L: Left=Links No_Font_Selected=Keine Schrift gew\u00e4hlt. R=R: Right=Rechts Size=Gr\u00f6\u00dfe: T=O: Top=Oben Help=Hilfe OK=OK Cancel=Abbrechen jcommon-1.0.16/source/org/jfree/ui/NumberCellRenderer.java0000644000175000017500000000671211172030703023360 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * NumberCellRenderer.java * ----------------------- * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: NumberCellRenderer.java,v 1.7 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 11-Mar-2002 : Updated import statements (DG); * */ package org.jfree.ui; import java.awt.Component; import java.text.NumberFormat; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; /** * A table cell renderer that formats numbers with right alignment in each cell. * * @author David Gilbert */ public class NumberCellRenderer extends DefaultTableCellRenderer { /** * Default constructor - builds a renderer that right justifies the * contents of a table cell. */ public NumberCellRenderer() { super(); setHorizontalAlignment(SwingConstants.RIGHT); } /** * Returns itself as the renderer. Supports the TableCellRenderer interface. * * @param table the table. * @param value the data to be rendered. * @param isSelected a boolean that indicates whether or not the cell is * selected. * @param hasFocus a boolean that indicates whether or not the cell has * the focus. * @param row the (zero-based) row index. * @param column the (zero-based) column index. * * @return the component that can render the contents of the cell. */ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { setFont(null); final NumberFormat nf = NumberFormat.getNumberInstance(); if (value != null) { setText(nf.format(value)); } else { setText(""); } if (isSelected) { setBackground(table.getSelectionBackground()); } else { setBackground(null); } return this; } } jcommon-1.0.16/source/org/jfree/ui/FontDisplayField.java0000644000175000017500000000723011172030703023035 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * FontDisplayField.java * --------------------- * (C) Copyright 2000-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Arnaud Lelievre; * * $Id: FontDisplayField.java,v 1.6 2008/12/18 09:57:32 mungady Exp $ * * Changes (from 26-Oct-2001) * ---------------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 08-Sep-2003 : Added internationalization via use of properties * resourceBundle (RFE 690236) (AL); * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.ui; import java.awt.Font; import java.util.ResourceBundle; import javax.swing.JTextField; import org.jfree.util.ResourceBundleWrapper; /** * A field for displaying a font selection. The display field itself is * read-only, to the developer must provide another mechanism to allow the * user to change the font. * * @author David Gilbert */ public class FontDisplayField extends JTextField { /** The current font. */ private Font displayFont; /** The resourceBundle for the localization. */ protected static final ResourceBundle localizationResources = ResourceBundleWrapper.getBundle("org.jfree.ui.LocalizationBundle"); /** * Standard constructor - builds a FontDescriptionField initialised with * the specified font. * * @param font the font. */ public FontDisplayField(final Font font) { super(""); setDisplayFont(font); setEnabled(false); } /** * Returns the current font. * * @return the font. */ public Font getDisplayFont() { return this.displayFont; } /** * Sets the font. * * @param font the font. */ public void setDisplayFont(final Font font) { this.displayFont = font; setText(fontToString(this.displayFont)); } /** * Returns a string representation of the specified font. * * @param font the font. * * @return a string describing the font. */ private String fontToString(final Font font) { if (font != null) { return font.getFontName() + ", " + font.getSize(); } else { return localizationResources.getString("No_Font_Selected"); } } } jcommon-1.0.16/source/org/jfree/ui/Size2D.java0000644000175000017500000001127411172030703020740 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------- * Size2D.java * ----------- * (C) Copyright 2000-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: Size2D.java,v 1.8 2005/11/16 15:58:41 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 10-Nov-2004 : Added default constructor, added setWidth() and setHeight() * methods, added equals() method, implemented Cloneable, * PublicCloneable and Serializable (DG); * 02-Feb-2005 : Added toString() method (DG); * */ package org.jfree.ui; import java.io.Serializable; import org.jfree.util.PublicCloneable; /** * A simple class for representing the dimensions of an object. It would be * better to use Dimension2D, but this class is broken on various * JDK releases (particularly JDK 1.3.1, refer to bugs 4189446 and 4976448 on * the Java bug parade). * * @author David Gilbert */ public class Size2D implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 2558191683786418168L; /** The width. */ public double width; /** The height. */ public double height; /** * Creates a new instance with zero width and height. */ public Size2D() { this(0.0, 0.0); } /** * Creates a new instance with the specified width and height. * * @param width the width. * @param height the height. */ public Size2D(final double width, final double height) { this.width = width; this.height = height; } /** * Returns the width. * * @return The width. */ public double getWidth() { return this.width; } /** * Sets the width. * * @param width the width. */ public void setWidth(final double width) { this.width = width; } /** * Returns the height. * * @return The height. */ public double getHeight() { return this.height; } /** * Sets the height. * * @param height the height. */ public void setHeight(final double height) { this.height = height; } /** * Returns a string representation of this instance, mostly used for * debugging purposes. * * @return A string. */ public String toString() { return "Size2D[width=" + this.width + ", height=" + this.height + "]"; } /** * Compares this instance for equality with an arbitrary object. * * @param obj the object (null permitted). * * @return A boolean. */ public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof Size2D)) { return false; } final Size2D that = (Size2D) obj; if (this.width != that.width) { return false; } if (this.height != that.height) { return false; } return true; } /** * Returns a clone of this object. * * @return A clone. * * @throws CloneNotSupportedException if the object cannot be cloned. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } } jcommon-1.0.16/source/org/jfree/ui/SortableTableHeaderListener.java0000644000175000017500000001437111172030703025203 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------------- * SortableTableHeaderListener.java * -------------------------------- * (C) Copyright 2000-2004, by Nabuo Tamemasa and Contributors. * * Original Author: Nabuo Tamemasa; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: SortableTableHeaderListener.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.table.JTableHeader; /** * Captures mouse clicks on a table header, with the intention of triggering a sort. Adapted from * code by Nabuo Tamemasa posted on http://www.codeguru.com. * * @author Nabuo Tamemasa */ public class SortableTableHeaderListener implements MouseListener, MouseMotionListener { /** A reference to the table model. */ private SortableTableModel model; /** The header renderer. */ private SortButtonRenderer renderer; /** The index of the column that is sorted - used to determine the state of the renderer. */ private int sortColumnIndex; /** * Standard constructor. * * @param model the model. * @param renderer the renderer. */ public SortableTableHeaderListener(final SortableTableModel model, final SortButtonRenderer renderer) { this.model = model; this.renderer = renderer; } /** * Sets the table model for the listener. * * @param model the model. */ public void setTableModel(final SortableTableModel model) { this.model = model; } /** * Handle a mouse press event - if the user is NOT resizing a column and NOT dragging a column * then give visual feedback that the column header has been pressed. * * @param e the mouse event. */ public void mousePressed(final MouseEvent e) { final JTableHeader header = (JTableHeader) e.getComponent(); if (header.getResizingColumn() == null) { // resizing takes precedence over sorting if (header.getDraggedDistance() < 1) { // dragging also takes precedence over sorting final int columnIndex = header.columnAtPoint(e.getPoint()); final int modelColumnIndex = header.getTable().convertColumnIndexToModel(columnIndex); if (this.model.isSortable(modelColumnIndex)) { this.sortColumnIndex = header.getTable().convertColumnIndexToModel(columnIndex); this.renderer.setPressedColumn(this.sortColumnIndex); header.repaint(); if (header.getTable().isEditing()) { header.getTable().getCellEditor().stopCellEditing(); } } else { this.sortColumnIndex = -1; } } } } /** * If the user is dragging or resizing, then we clear the sort column. * * @param e the mouse event. */ public void mouseDragged(final MouseEvent e) { final JTableHeader header = (JTableHeader) e.getComponent(); if ((header.getDraggedDistance() > 0) || (header.getResizingColumn() != null)) { this.renderer.setPressedColumn(-1); this.sortColumnIndex = -1; } } /** * This event is ignored (not required). * * @param e the mouse event. */ public void mouseEntered(final MouseEvent e) { // not required } /** * This event is ignored (not required). * * @param e the mouse event. */ public void mouseClicked(final MouseEvent e) { // not required } /** * This event is ignored (not required). * * @param e the mouse event. */ public void mouseMoved(final MouseEvent e) { // not required } /** * This event is ignored (not required). * * @param e the mouse event. */ public void mouseExited(final MouseEvent e) { // not required } /** * When the user releases the mouse button, we attempt to sort the table. * * @param e the mouse event. */ public void mouseReleased(final MouseEvent e) { final JTableHeader header = (JTableHeader) e.getComponent(); if (header.getResizingColumn() == null) { // resizing takes precedence over sorting if (this.sortColumnIndex != -1) { final SortableTableModel model = (SortableTableModel) header.getTable().getModel(); final boolean ascending = !model.isAscending(); model.setAscending(ascending); model.sortByColumn(this.sortColumnIndex, ascending); this.renderer.setPressedColumn(-1); // clear header.repaint(); } } } } jcommon-1.0.16/source/org/jfree/ui/LocalizationBundle_es.properties0000644000175000017500000000112311172030703025354 0ustar twernertwerner# org.jfree.ui.ui ResourceBundle properties file spanish # # Changes (from 31-Aug-2003) # -------------------------- # 14-Oct-2004 : Initial version: Leopoldo Federico P�rtile (Grupo de Procesamiento Digital de Im�genes) # Universidad Tecnol�gica Nacional - Facultad Regional Resistencia, Argentina Attributes=Atributos: B=Inf: Bold=Negrita Bottom=Inferior Font=Fuente: Insets=M�rgenes: Italic=Cursiva L=Izq: Left=Izquierda No_Font_Selected=No se seleccion\00F3 ninguna fuente. R=Der: Right=Derecha Size=Tama\u00f1o: T=Sup: Top=Superior Help=Ayuda OK=Aceptar Cancel=Cancelar jcommon-1.0.16/source/org/jfree/ui/UIUtilities.java0000644000175000017500000000701311172030703022045 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * UIUtilities.java * ---------------- * (C) Copyright 2002-2005, by Object Refinery Limited. * * Original Author: Thomas Morgner (for Object Refinery Limited); * Contributor(s): -; * * $Id: UIUtilities.java,v 1.7 2007/11/02 17:50:36 taqua Exp $ * * Changes: * -------- * 25-Jul-2002 : Version 1 (TM); */ package org.jfree.ui; import java.awt.Color; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import javax.swing.border.MatteBorder; import javax.swing.plaf.BorderUIResource; /** * A utility class to tune the Metal look and feel. * * @author Thomas Morgner */ public class UIUtilities { /** * Private constructor prevents object creation. */ private UIUtilities() { } /** * Set up the user interface. */ public static void setupUI() { try { final String classname = UIManager.getSystemLookAndFeelClassName(); UIManager.setLookAndFeel(classname); } catch (Exception e) { e.printStackTrace(); } final UIDefaults defaults = UIManager.getDefaults(); defaults.put( "PopupMenu.border", new BorderUIResource.EtchedBorderUIResource( EtchedBorder.RAISED, defaults.getColor("controlShadow"), defaults.getColor("controlLtHighlight") ) ); final MatteBorder matteborder = new MatteBorder(1, 1, 1, 1, Color.black); final EmptyBorder emptyborder = new MatteBorder(2, 2, 2, 2, defaults.getColor("control")); final BorderUIResource.CompoundBorderUIResource compBorder = new BorderUIResource.CompoundBorderUIResource(emptyborder, matteborder); final BorderUIResource.EmptyBorderUIResource emptyBorderUI = new BorderUIResource.EmptyBorderUIResource(0, 0, 0, 0); defaults.put("SplitPane.border", emptyBorderUI); defaults.put("Table.scrollPaneBorder", emptyBorderUI); defaults.put("ComboBox.border", compBorder); defaults.put("TextField.border", compBorder); defaults.put("TextArea.border", compBorder); defaults.put("CheckBox.border", compBorder); defaults.put("ScrollPane.border", emptyBorderUI); } } jcommon-1.0.16/source/org/jfree/ui/PaintSample.java0000644000175000017500000000727411172030703022062 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * PaintSample.java * ---------------- * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: PaintSample.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Paint; import java.awt.geom.Rectangle2D; import javax.swing.JComponent; /** * A panel that displays a paint sample. * * @author David Gilbert */ public class PaintSample extends JComponent { /** The paint. */ private Paint paint; /** The preferred size of the component. */ private Dimension preferredSize; /** * Standard constructor - builds a paint sample. * * @param paint the paint to display. */ public PaintSample(final Paint paint) { this.paint = paint; this.preferredSize = new Dimension(80, 12); } /** * Returns the current Paint object being displayed in the panel. * * @return the paint. */ public Paint getPaint() { return this.paint; } /** * Sets the Paint object being displayed in the panel. * * @param paint the paint. */ public void setPaint(final Paint paint) { this.paint = paint; repaint(); } /** * Returns the preferred size of the component. * * @return the preferred size. */ public Dimension getPreferredSize() { return this.preferredSize; } /** * Fills the component with the current Paint. * * @param g the graphics device. */ public void paintComponent(final Graphics g) { final Graphics2D g2 = (Graphics2D) g; final Dimension size = getSize(); final Insets insets = getInsets(); final double xx = insets.left; final double yy = insets.top; final double ww = size.getWidth() - insets.left - insets.right - 1; final double hh = size.getHeight() - insets.top - insets.bottom - 1; final Rectangle2D area = new Rectangle2D.Double(xx, yy, ww, hh); g2.setPaint(this.paint); g2.fill(area); g2.setPaint(Color.black); g2.draw(area); } } jcommon-1.0.16/source/org/jfree/ui/SortableTableModel.java0000644000175000017500000000733711172030703023351 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * SortableTableModel.java * ----------------------- * (C) Copyright 2000-2005, by Object Refinery Limited; * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SortableTableModel.java,v 1.6 2008/09/10 09:26:11 mungady Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.* (DG); * 20-Nov-2001 : Made constructor protected (DG); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import javax.swing.table.AbstractTableModel; /** * The base class for a sortable table model. * * @author David Gilbert */ public abstract class SortableTableModel extends AbstractTableModel { /** The column on which the data is sorted (-1 for no sorting). */ private int sortingColumn; /** Indicates ascending (true) or descending (false) order. */ private boolean ascending; /** * Constructs a sortable table model. */ public SortableTableModel() { this.sortingColumn = -1; this.ascending = true; } /** * Returns the index of the sorting column, or -1 if the data is not sorted * on any column. * * @return the column used for sorting. */ public int getSortingColumn() { return this.sortingColumn; } /** * Returns true if the data is sorted in ascending order, and * false otherwise. * * @return true if the data is sorted in ascending order, and * false otherwise. */ public boolean isAscending() { return this.ascending; } /** * Sets the flag that determines whether the sort order is ascending or * descending. * * @param flag the flag. */ public void setAscending(final boolean flag) { this.ascending = flag; } /** * Sorts the table. * * @param column the column to sort on (zero-based index). * @param ascending a flag to indicate ascending order or descending order. */ public void sortByColumn(final int column, final boolean ascending) { if (isSortable(column)) { this.sortingColumn = column; } } /** * Returns a flag indicating whether or not a column is sortable. * * @param column the column (zero-based index). * * @return boolean. */ public boolean isSortable(final int column) { return false; } } jcommon-1.0.16/source/org/jfree/ui/LengthAdjustmentType.java0000644000175000017500000001016111172030703023754 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * LengthAdjustmentType.java * ------------------------- * (C) Copyright 2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: LengthAdjustmentType.java,v 1.5 2005/11/03 09:55:27 mungady Exp $ * * Changes: * -------- * 21-Jan-2005 : Version 1 (DG); * */ package org.jfree.ui; import java.io.ObjectStreamException; import java.io.Serializable; /** * Represents the three options for adjusting a length: expand, contract, and * no change. * * @author David Gilbert */ public final class LengthAdjustmentType implements Serializable { /** For serialization. */ private static final long serialVersionUID = -6097408511380545010L; /** NO_CHANGE. */ public static final LengthAdjustmentType NO_CHANGE = new LengthAdjustmentType("NO_CHANGE"); /** EXPAND. */ public static final LengthAdjustmentType EXPAND = new LengthAdjustmentType("EXPAND"); /** CONTRACT. */ public static final LengthAdjustmentType CONTRACT = new LengthAdjustmentType("CONTRACT"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private LengthAdjustmentType(final String name) { this.name = name; } /** * Returns a string representing the object. * * @return The string. */ public String toString() { return this.name; } /** * Returns true if this object is equal to the specified * object, and false otherwise. * * @param obj the other object (null permitted). * * @return A boolean. */ public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof LengthAdjustmentType)) { return false; } final LengthAdjustmentType that = (LengthAdjustmentType) obj; if (!this.name.equals(that.name)) { return false; } return true; } /** * Returns a hash code value for the object. * * @return The hashcode */ public int hashCode() { return this.name.hashCode(); } /** * Ensures that serialization returns the unique instances. * * @return The object. * * @throws ObjectStreamException if there is a problem. */ private Object readResolve() throws ObjectStreamException { if (this.equals(LengthAdjustmentType.NO_CHANGE)) { return LengthAdjustmentType.NO_CHANGE; } else if (this.equals(LengthAdjustmentType.EXPAND)) { return LengthAdjustmentType.EXPAND; } else if (this.equals(LengthAdjustmentType.CONTRACT)) { return LengthAdjustmentType.CONTRACT; } return null; } } jcommon-1.0.16/source/org/jfree/ui/Layer.java0000644000175000017500000000715311172030703020715 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------- * Layer.java * ---------- * (C) Copyright 2003, 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: Layer.java,v 1.4 2005/10/18 13:18:34 mungady Exp $ * * Changes: * -------- * 17-Sep-2003 (DG); * */ package org.jfree.ui; import java.io.ObjectStreamException; import java.io.Serializable; /** * Used to indicate either the foreground or background layer. * * @author David Gilbert */ public final class Layer implements Serializable { /** For serialization. */ private static final long serialVersionUID = -1470104570733183430L; /** Foreground. */ public static final Layer FOREGROUND = new Layer("Layer.FOREGROUND"); /** Background. */ public static final Layer BACKGROUND = new Layer("Layer.BACKGROUND"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private Layer(final String name) { this.name = name; } /** * Returns a string representing the object. * * @return The string. */ public String toString() { return this.name; } /** * Returns true if this object is equal to the specified * object, and false otherwise. * * @param o the other object. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Layer)) { return false; } final Layer layer = (Layer) o; if (!this.name.equals(layer.name)) { return false; } return true; } /** * Returns a hash code value for the object. * * @return the hashcode */ public int hashCode() { return this.name.hashCode(); } /** * Ensures that serialization returns the unique instances. * * @return The object. * * @throws ObjectStreamException if there is a problem. */ private Object readResolve() throws ObjectStreamException { Layer result = null; if (this.equals(Layer.FOREGROUND)) { result = Layer.FOREGROUND; } else if (this.equals(Layer.BACKGROUND)) { result = Layer.BACKGROUND; } return result; } } jcommon-1.0.16/source/org/jfree/ui/InsetsTextField.java0000644000175000017500000000676111172030703022723 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * InsetsTextField.java * -------------------- * (C) Copyright 2000-2008, by Andrzej Porebski. * * Original Author: Andrzej Porebski; * Contributor(s): Arnaud Lelievre; * * $Id: InsetsTextField.java,v 1.4 2008/12/18 09:57:32 mungady Exp $ * * Changes (from 7-Nov-2001) * ------------------------- * 07-Nov-2001 : Added to com.jrefinery.ui package (DG); * 08-Sep-2003 : Added internationalization via use of properties * resourceBundle (RFE 690236) (AL); * 18-Dec-2008 : Use ResourceBundleWrapper - see JFreeChart patch 1607918 by * Jess Thrysoee (DG); * */ package org.jfree.ui; import java.awt.Insets; import java.util.ResourceBundle; import javax.swing.JTextField; import org.jfree.util.ResourceBundleWrapper; /** * A JTextField for displaying insets. * * @author Andrzej Porebski */ public class InsetsTextField extends JTextField { /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.ui.LocalizationBundle"); /** * Default constructor. Initializes this text field with formatted string * describing provided insets. * * @param insets the insets. */ public InsetsTextField(final Insets insets) { super(); setInsets(insets); setEnabled(false); } /** * Returns a formatted string describing provided insets. * * @param insets the insets. * * @return the string. */ public String formatInsetsString(Insets insets) { insets = (insets == null) ? new Insets(0, 0, 0, 0) : insets; return localizationResources.getString("T") + insets.top + ", " + localizationResources.getString("L") + insets.left + ", " + localizationResources.getString("B") + insets.bottom + ", " + localizationResources.getString("R") + insets.right; } /** * Sets the text of this text field to the formatted string * describing provided insets. If insets is null, empty insets * (0,0,0,0) are used. * * @param insets the insets. */ public void setInsets(final Insets insets) { setText(formatInsetsString(insets)); } } jcommon-1.0.16/source/org/jfree/ui/ExtendedDrawable.java0000644000175000017500000000450711172030703023043 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * ExtendedDrawable.java * --------------------- * (C) Copyright 2002-2005, by Object Refinery Limited. * * Original Author: Thomas Morgner; * Contributor(s): -; * * $Id: ExtendedDrawable.java,v 1.4 2005/10/18 13:18:34 mungady Exp $ * * Changes * ------- * 27-Apr-2005: Initial version. * */ package org.jfree.ui; import java.awt.Dimension; /** * A drawable that has a preferred size and aspect ratio. Implement this interface to gain * some control over the rendering and layouting process for the drawable. * * @author Thomas Morgner */ public interface ExtendedDrawable extends Drawable { /** * Returns the preferred size of the drawable. If the drawable is aspect ratio aware, * these bounds should be used to compute the preferred aspect ratio for this drawable. * * @return the preferred size. */ public Dimension getPreferredSize (); /** * Returns true, if this drawable will preserve an aspect ratio during the drawing. * * @return true, if an aspect ratio is preserved, false otherwise. */ public boolean isPreserveAspectRatio (); } jcommon-1.0.16/source/org/jfree/ui/BevelArrowIcon.java0000644000175000017500000002153311172030703022520 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * BevelArrowIcon.java * ------------------- * (C) Copyright 2000-2004, by Nobuo Tamemasa and Contributors. * * Original Author: Nobuo Tamemasa; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: BevelArrowIcon.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 13-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import javax.swing.Icon; import javax.swing.UIManager; /** * An arrow icon that can point up or down (usually used to indicate the sort direction in a table). *

* This class (and also SortButtonRenderer) is based on original code by Nobuo Tamemasa (version * 1.0, 26-Feb-1999) posted on www.codeguru.com. * * @author Nobuo Tamemasa */ public class BevelArrowIcon implements Icon { /** Constant indicating that the arrow is pointing up. */ public static final int UP = 0; /** Constant indicating that the arrow is pointing down. */ public static final int DOWN = 1; /** The default arrow size. */ private static final int DEFAULT_SIZE = 11; /** Edge color 1. */ private Color edge1; /** Edge color 2. */ private Color edge2; /** The fill color for the arrow icon. */ private Color fill; /** The size of the icon. */ private int size; /** The direction that the arrow is pointing (UP or DOWN). */ private int direction; /** * Standard constructor - builds an icon with the specified attributes. * * @param direction . * @param isRaisedView . * @param isPressedView . */ public BevelArrowIcon(final int direction, final boolean isRaisedView, final boolean isPressedView) { if (isRaisedView) { if (isPressedView) { init(UIManager.getColor("controlLtHighlight"), UIManager.getColor("controlDkShadow"), UIManager.getColor("controlShadow"), DEFAULT_SIZE, direction); } else { init(UIManager.getColor("controlHighlight"), UIManager.getColor("controlShadow"), UIManager.getColor("control"), DEFAULT_SIZE, direction); } } else { if (isPressedView) { init(UIManager.getColor("controlDkShadow"), UIManager.getColor("controlLtHighlight"), UIManager.getColor("controlShadow"), DEFAULT_SIZE, direction); } else { init(UIManager.getColor("controlShadow"), UIManager.getColor("controlHighlight"), UIManager.getColor("control"), DEFAULT_SIZE, direction); } } } /** * Standard constructor - builds an icon with the specified attributes. * * @param edge1 the color of edge1. * @param edge2 the color of edge2. * @param fill the fill color. * @param size the size of the arrow icon. * @param direction the direction that the arrow points. */ public BevelArrowIcon(final Color edge1, final Color edge2, final Color fill, final int size, final int direction) { init(edge1, edge2, fill, size, direction); } /** * Paints the icon at the specified position. Supports the Icon interface. * * @param c . * @param g . * @param x . * @param y . */ public void paintIcon(final Component c, final Graphics g, final int x, final int y) { switch (this.direction) { case DOWN: drawDownArrow(g, x, y); break; case UP: drawUpArrow(g, x, y); break; } } /** * Returns the width of the icon. Supports the Icon interface. * * @return the icon width. */ public int getIconWidth() { return this.size; } /** * Returns the height of the icon. Supports the Icon interface. * @return the icon height. */ public int getIconHeight() { return this.size; } /** * Initialises the attributes of the arrow icon. * * @param edge1 the color of edge1. * @param edge2 the color of edge2. * @param fill the fill color. * @param size the size of the arrow icon. * @param direction the direction that the arrow points. */ private void init(final Color edge1, final Color edge2, final Color fill, final int size, final int direction) { this.edge1 = edge1; this.edge2 = edge2; this.fill = fill; this.size = size; this.direction = direction; } /** * Draws the arrow pointing down. * * @param g the graphics device. * @param xo ?? * @param yo ?? */ private void drawDownArrow(final Graphics g, final int xo, final int yo) { g.setColor(this.edge1); g.drawLine(xo, yo, xo + this.size - 1, yo); g.drawLine(xo, yo + 1, xo + this.size - 3, yo + 1); g.setColor(this.edge2); g.drawLine(xo + this.size - 2, yo + 1, xo + this.size - 1, yo + 1); int x = xo + 1; int y = yo + 2; int dx = this.size - 6; while (y + 1 < yo + this.size) { g.setColor(this.edge1); g.drawLine(x, y, x + 1, y); g.drawLine(x, y + 1, x + 1, y + 1); if (0 < dx) { g.setColor(this.fill); g.drawLine(x + 2, y, x + 1 + dx, y); g.drawLine(x + 2, y + 1, x + 1 + dx, y + 1); } g.setColor(this.edge2); g.drawLine(x + dx + 2, y, x + dx + 3, y); g.drawLine(x + dx + 2, y + 1, x + dx + 3, y + 1); x += 1; y += 2; dx -= 2; } g.setColor(this.edge1); g.drawLine( xo + (this.size / 2), yo + this.size - 1, xo + (this.size / 2), yo + this.size - 1 ); } /** * Draws the arrow pointing up. * * @param g the graphics device. * @param xo ?? * @param yo ?? */ private void drawUpArrow(final Graphics g, final int xo, final int yo) { g.setColor(this.edge1); int x = xo + (this.size / 2); g.drawLine(x, yo, x, yo); x--; int y = yo + 1; int dx = 0; while (y + 3 < yo + this.size) { g.setColor(this.edge1); g.drawLine(x, y, x + 1, y); g.drawLine(x, y + 1, x + 1, y + 1); if (0 < dx) { g.setColor(this.fill); g.drawLine(x + 2, y, x + 1 + dx, y); g.drawLine(x + 2, y + 1, x + 1 + dx, y + 1); } g.setColor(this.edge2); g.drawLine(x + dx + 2, y, x + dx + 3, y); g.drawLine(x + dx + 2, y + 1, x + dx + 3, y + 1); x -= 1; y += 2; dx += 2; } g.setColor(this.edge1); g.drawLine(xo, yo + this.size - 3, xo + 1, yo + this.size - 3); g.setColor(this.edge2); g.drawLine(xo + 2, yo + this.size - 2, xo + this.size - 1, yo + this.size - 2); g.drawLine(xo, yo + this.size - 1, xo + this.size, yo + this.size - 1); } } jcommon-1.0.16/source/org/jfree/ui/ExtensionFileFilter.java0000644000175000017500000000626311172030703023564 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * ExtensionFileFilter.java * ------------------------ * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ExtensionFileFilter.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.* (DG); * 26-Jun-2002 : Updated imports (DG); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.io.File; import javax.swing.filechooser.FileFilter; /** * A filter for JFileChooser that filters files by extension. * * @author David Gilbert */ public class ExtensionFileFilter extends FileFilter { /** A description for the file type. */ private String description; /** The extension (for example, "png" for *.png files). */ private String extension; /** * Standard constructor. * * @param description a description of the file type; * @param extension the file extension; */ public ExtensionFileFilter(final String description, final String extension) { this.description = description; this.extension = extension; } /** * Returns true if the file ends with the specified extension. * * @param file the file to test. * * @return A boolean that indicates whether or not the file is accepted by the filter. */ public boolean accept(final File file) { if (file.isDirectory()) { return true; } final String name = file.getName().toLowerCase(); if (name.endsWith(this.extension)) { return true; } else { return false; } } /** * Returns the description of the filter. * * @return a description of the filter. */ public String getDescription() { return this.description; } } jcommon-1.0.16/source/org/jfree/ui/KeyedComboBoxModel.java0000644000175000017500000002775611172030703023327 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * KeyedComboBoxModel.java * ------------------ * (C) Copyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: KeyedComboBoxModel.java,v 1.8 2008/09/10 09:26:11 mungady Exp $ * * Changes * ------- * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.ui; import java.util.ArrayList; import javax.swing.ComboBoxModel; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; /** * The KeyedComboBox model allows to define an internal key (the data element) * for every entry in the model. *

* This class is usefull in all cases, where the public text differs from the * internal view on the data. A separation between presentation data and * processing data is a prequesite for localizing combobox entries. This model * does not allow selected elements, which are not in the list of valid * elements. * * @author Thomas Morgner */ public class KeyedComboBoxModel implements ComboBoxModel { /** * The internal data carrier to map keys to values and vice versa. */ private static class ComboBoxItemPair { /** * The key. */ private Object key; /** * The value for the key. */ private Object value; /** * Creates a new item pair for the given key and value. The value can be * changed later, if needed. * * @param key the key * @param value the value */ public ComboBoxItemPair(final Object key, final Object value) { this.key = key; this.value = value; } /** * Returns the key. * * @return the key. */ public Object getKey() { return this.key; } /** * Returns the value. * * @return the value for this key. */ public Object getValue() { return this.value; } /** * Redefines the value stored for that key. * * @param value the new value. */ public void setValue(final Object value) { this.value = value; } } /** * The index of the selected item. */ private int selectedItemIndex; private Object selectedItemValue; /** * The data (contains ComboBoxItemPairs). */ private ArrayList data; /** * The listeners. */ private ArrayList listdatalistener; /** * The cached listeners as array. */ private transient ListDataListener[] tempListeners; private boolean allowOtherValue; /** * Creates a new keyed combobox model. */ public KeyedComboBoxModel() { this.data = new ArrayList(); this.listdatalistener = new ArrayList(); } /** * Creates a new keyed combobox model for the given keys and values. Keys * and values must have the same number of items. * * @param keys the keys * @param values the values */ public KeyedComboBoxModel(final Object[] keys, final Object[] values) { this(); setData(keys, values); } /** * Replaces the data in this combobox model. The number of keys must be * equals to the number of values. * * @param keys the keys * @param values the values */ public void setData(final Object[] keys, final Object[] values) { if (values.length != keys.length) { throw new IllegalArgumentException("Values and text must have the same length."); } this.data.clear(); this.data.ensureCapacity(keys.length); for (int i = 0; i < values.length; i++) { add(keys[i], values[i]); } this.selectedItemIndex = -1; final ListDataEvent evt = new ListDataEvent (this, ListDataEvent.CONTENTS_CHANGED, 0, this.data.size() - 1); fireListDataEvent(evt); } /** * Notifies all registered list data listener of the given event. * * @param evt the event. */ protected synchronized void fireListDataEvent(final ListDataEvent evt) { if (this.tempListeners == null) { this.tempListeners = (ListDataListener[]) this.listdatalistener.toArray (new ListDataListener[this.listdatalistener.size()]); } final ListDataListener[] listeners = this.tempListeners; for (int i = 0; i < listeners.length; i++) { final ListDataListener l = listeners[i]; l.contentsChanged(evt); } } /** * Returns the selected item. * * @return The selected item or null if there is no selection */ public Object getSelectedItem() { return this.selectedItemValue; } /** * Defines the selected key. If the object is not in the list of values, no * item gets selected. * * @param anItem the new selected item. */ public void setSelectedKey(final Object anItem) { if (anItem == null) { this.selectedItemIndex = -1; this.selectedItemValue = null; } else { final int newSelectedItem = findDataElementIndex(anItem); if (newSelectedItem == -1) { this.selectedItemIndex = -1; this.selectedItemValue = null; } else { this.selectedItemIndex = newSelectedItem; this.selectedItemValue = getElementAt(this.selectedItemIndex); } } fireListDataEvent(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, -1, -1)); } /** * Set the selected item. The implementation of this method should notify * all registered ListDataListeners that the contents have * changed. * * @param anItem the list object to select or null to clear the * selection */ public void setSelectedItem(final Object anItem) { if (anItem == null) { this.selectedItemIndex = -1; this.selectedItemValue = null; } else { final int newSelectedItem = findElementIndex(anItem); if (newSelectedItem == -1) { if (isAllowOtherValue()) { this.selectedItemIndex = -1; this.selectedItemValue = anItem; } else { this.selectedItemIndex = -1; this.selectedItemValue = null; } } else { this.selectedItemIndex = newSelectedItem; this.selectedItemValue = getElementAt(this.selectedItemIndex); } } fireListDataEvent(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, -1, -1)); } private boolean isAllowOtherValue() { return this.allowOtherValue; } /** * @param allowOtherValue */ public void setAllowOtherValue(final boolean allowOtherValue) { this.allowOtherValue = allowOtherValue; } /** * Adds a listener to the list that's notified each time a change to the data * model occurs. * * @param l the ListDataListener to be added */ public synchronized void addListDataListener(final ListDataListener l) { if (l == null) { throw new NullPointerException(); } this.listdatalistener.add(l); this.tempListeners = null; } /** * Returns the value at the specified index. * * @param index the requested index * @return the value at index */ public Object getElementAt(final int index) { if (index >= this.data.size()) { return null; } final ComboBoxItemPair datacon = (ComboBoxItemPair) this.data.get(index); if (datacon == null) { return null; } return datacon.getValue(); } /** * Returns the key from the given index. * * @param index the index of the key. * @return the the key at the specified index. */ public Object getKeyAt(final int index) { if (index >= this.data.size()) { return null; } if (index < 0) { return null; } final ComboBoxItemPair datacon = (ComboBoxItemPair) this.data.get(index); if (datacon == null) { return null; } return datacon.getKey(); } /** * Returns the selected data element or null if none is set. * * @return the selected data element. */ public Object getSelectedKey() { return getKeyAt(this.selectedItemIndex); } /** * Returns the length of the list. * * @return the length of the list */ public int getSize() { return this.data.size(); } /** * Removes a listener from the list that's notified each time a change to * the data model occurs. * * @param l the ListDataListener to be removed */ public void removeListDataListener(final ListDataListener l) { this.listdatalistener.remove(l); this.tempListeners = null; } /** * Searches an element by its data value. This method is called by the * setSelectedItem method and returns the first occurence of the element. * * @param anItem the item * @return the index of the item or -1 if not found. */ private int findDataElementIndex(final Object anItem) { if (anItem == null) { throw new NullPointerException("Item to find must not be null"); } for (int i = 0; i < this.data.size(); i++) { final ComboBoxItemPair datacon = (ComboBoxItemPair) this.data.get(i); if (anItem.equals(datacon.getKey())) { return i; } } return -1; } /** * Tries to find the index of element with the given key. The key must not * be null. * * @param key the key for the element to be searched. * @return the index of the key, or -1 if not found. */ public int findElementIndex(final Object key) { if (key == null) { throw new NullPointerException("Item to find must not be null"); } for (int i = 0; i < this.data.size(); i++) { final ComboBoxItemPair datacon = (ComboBoxItemPair) this.data.get(i); if (key.equals(datacon.getValue())) { return i; } } return -1; } /** * Removes an entry from the model. * * @param key the key */ public void removeDataElement(final Object key) { final int idx = findDataElementIndex(key); if (idx == -1) { return; } this.data.remove(idx); final ListDataEvent evt = new ListDataEvent (this, ListDataEvent.INTERVAL_REMOVED, idx, idx); fireListDataEvent(evt); } /** * Adds a new entry to the model. * * @param key the key * @param cbitem the display value. */ public void add(final Object key, final Object cbitem) { final ComboBoxItemPair con = new ComboBoxItemPair(key, cbitem); this.data.add(con); final ListDataEvent evt = new ListDataEvent (this, ListDataEvent.INTERVAL_ADDED, this.data.size() - 2, this.data.size() - 2); fireListDataEvent(evt); } /** * Removes all entries from the model. */ public void clear() { final int size = getSize(); this.data.clear(); final ListDataEvent evt = new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, 0, size - 1); fireListDataEvent(evt); } } jcommon-1.0.16/source/org/jfree/ui/SortableTable.java0000644000175000017500000000662111172030703022363 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * SortableTable.java * ------------------ * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SortableTable.java,v 1.5 2005/11/16 15:58:41 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import javax.swing.JTable; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumnModel; /** * A simple extension of JTable that supports the use of a SortableTableModel. * * @author David Gilbert */ public class SortableTable extends JTable { /** A listener for sorting. */ private SortableTableHeaderListener headerListener; /** * Standard constructor - builds a table for the specified model. * * @param model the data. */ public SortableTable(final SortableTableModel model) { super(model); final SortButtonRenderer renderer = new SortButtonRenderer(); final TableColumnModel cm = getColumnModel(); for (int i = 0; i < cm.getColumnCount(); i++) { cm.getColumn(i).setHeaderRenderer(renderer); } final JTableHeader header = getTableHeader(); this.headerListener = new SortableTableHeaderListener(model, renderer); header.addMouseListener(this.headerListener); header.addMouseMotionListener(this.headerListener); model.sortByColumn(0, true); } /** * Changes the model for the table. Takes care of updating the header listener at the * same time. * * @param model the table model. * */ public void setSortableModel(final SortableTableModel model) { super.setModel(model); this.headerListener.setTableModel(model); final SortButtonRenderer renderer = new SortButtonRenderer(); final TableColumnModel cm = getColumnModel(); for (int i = 0; i < cm.getColumnCount(); i++) { cm.getColumn(i).setHeaderRenderer(renderer); } model.sortByColumn(0, true); } } jcommon-1.0.16/source/org/jfree/ui/ApplicationFrame.java0000644000175000017500000001013111172030703023045 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * ApplicationFrame.java * --------------------- * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ApplicationFrame.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 30-May-2002) * -------------------------- * 30-May-2002 : Added title (DG); * 13-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; /** * A base class for creating the main frame for simple applications. The frame listens for * window closing events, and responds by shutting down the JVM. This is OK for small demo * applications...for more serious applications, you'll want to use something more robust. * * @author David Gilbert */ public class ApplicationFrame extends JFrame implements WindowListener { /** * Constructs a new application frame. * * @param title the frame title. */ public ApplicationFrame(final String title) { super(title); addWindowListener(this); } /** * Listens for the main window closing, and shuts down the application. * * @param event information about the window event. */ public void windowClosing(final WindowEvent event) { if (event.getWindow() == this) { dispose(); System.exit(0); } } /** * Required for WindowListener interface, but not used by this class. * * @param event information about the window event. */ public void windowClosed(final WindowEvent event) { // ignore } /** * Required for WindowListener interface, but not used by this class. * * @param event information about the window event. */ public void windowActivated(final WindowEvent event) { // ignore } /** * Required for WindowListener interface, but not used by this class. * * @param event information about the window event. */ public void windowDeactivated(final WindowEvent event) { // ignore } /** * Required for WindowListener interface, but not used by this class. * * @param event information about the window event. */ public void windowDeiconified(final WindowEvent event) { // ignore } /** * Required for WindowListener interface, but not used by this class. * * @param event information about the window event. */ public void windowIconified(final WindowEvent event) { // ignore } /** * Required for WindowListener interface, but not used by this class. * * @param event information about the window event. */ public void windowOpened(final WindowEvent event) { // ignore } } jcommon-1.0.16/source/org/jfree/ui/Align.java0000644000175000017500000001150211172030703020664 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------- * Align.java * ---------- * (C) Copyright 2000-2004, by Object Refinery Limited and Contributors. * * Original Author: Christian W. Zuckschwerdt; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Align.java,v 1.5 2005/10/18 13:18:34 mungady Exp $ * * Changes (from 30-May-2002) * -------------------------- * 30-May-2002 : Added title (DG); * 13-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.awt.geom.Rectangle2D; /** * A utility class for aligning rectangles. * * @author David Gilbert */ public final class Align { /** Center alignment. */ public static final int CENTER = 0x00; /** Top alignment. */ public static final int TOP = 0x01; /** Bottom alignment. */ public static final int BOTTOM = 0x02; /** Left alignment. */ public static final int LEFT = 0x04; /** Right alignment. */ public static final int RIGHT = 0x08; /** Top/Left alignment. */ public static final int TOP_LEFT = TOP | LEFT; /** Top/Right alignment. */ public static final int TOP_RIGHT = TOP | RIGHT; /** Bottom/Left alignment. */ public static final int BOTTOM_LEFT = BOTTOM | LEFT; /** Bottom/Right alignment. */ public static final int BOTTOM_RIGHT = BOTTOM | RIGHT; /** Horizontal fit. */ public static final int FIT_HORIZONTAL = LEFT | RIGHT; /** Vertical fit. */ public static final int FIT_VERTICAL = TOP | BOTTOM; /** Complete fit. */ public static final int FIT = FIT_HORIZONTAL | FIT_VERTICAL; /** North alignment (same as TOP). */ public static final int NORTH = TOP; /** South alignment (same as BOTTOM). */ public static final int SOUTH = BOTTOM; /** West alignment (same as LEFT). */ public static final int WEST = LEFT; /** East alignment (same as RIGHT). */ public static final int EAST = RIGHT; /** North/West alignment (same as TOP_LEFT). */ public static final int NORTH_WEST = NORTH | WEST; /** North/East alignment (same as TOP_RIGHT). */ public static final int NORTH_EAST = NORTH | EAST; /** South/West alignment (same as BOTTOM_LEFT). */ public static final int SOUTH_WEST = SOUTH | WEST; /** South/East alignment (same as BOTTOM_RIGHT). */ public static final int SOUTH_EAST = SOUTH | EAST; /** * Private constructor. */ private Align() { super(); } /** * Aligns one rectangle (rect) relative to another rectangle (frame). * * @param rect the rectangle to be aligned (null not permitted). * @param frame the reference frame (null not permitted). * @param align the alignment code. */ public static void align(final Rectangle2D rect, final Rectangle2D frame, final int align) { double x = frame.getCenterX() - rect.getWidth() / 2.0; double y = frame.getCenterY() - rect.getHeight() / 2.0; double w = rect.getWidth(); double h = rect.getHeight(); if ((align & FIT_VERTICAL) == FIT_VERTICAL) { h = frame.getHeight(); } if ((align & FIT_HORIZONTAL) == FIT_HORIZONTAL) { w = frame.getWidth(); } if ((align & TOP) == TOP) { y = frame.getMinY(); } if ((align & BOTTOM) == BOTTOM) { y = frame.getMaxY() - h; } if ((align & LEFT) == LEFT) { x = frame.getX(); } if ((align & RIGHT) == RIGHT) { x = frame.getMaxX() - w; } rect.setRect(x, y, w, h); } } jcommon-1.0.16/source/org/jfree/ui/junit/0000755000175000017500000000000011351753320020127 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/ui/junit/GradientPaintTransformTypeTests.java0000644000175000017500000000704211172030703027301 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------------------- * GradientPaintTransformerTypeTests.java * -------------------------------------- * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: GradientPaintTransformTypeTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 08-Jan-2004 : Version 1 (DG); * */ package org.jfree.ui.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.ui.GradientPaintTransformType; /** * Tests for the {@link GradientPaintTransformType} class. */ public class GradientPaintTransformTypeTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(GradientPaintTransformTypeTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public GradientPaintTransformTypeTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { assertTrue( GradientPaintTransformType.HORIZONTAL.equals(GradientPaintTransformType.HORIZONTAL) ); } /** * Serialize an instance, restore it, and check for identity. */ public void testSerialization() { final GradientPaintTransformType t1 = GradientPaintTransformType.VERTICAL; GradientPaintTransformType t2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(t1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); t2 = (GradientPaintTransformType) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(t1 == t2); } } jcommon-1.0.16/source/org/jfree/ui/junit/RectangleInsetsTests.java0000644000175000017500000002712611172030703025111 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * RectangleInsetsTests.java * ------------------------- * (C) Copyright 2004, 2005, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: RectangleInsetsTests.java,v 1.7 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 14-Jun-2004 : Version 1 (DG); * 03-May-2005 : Fixed tests for changes to RectangleInsets constructor (DG); * */ package org.jfree.ui.junit; import java.awt.geom.Rectangle2D; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.ui.LengthAdjustmentType; import org.jfree.ui.RectangleInsets; import org.jfree.util.UnitType; /** * Tests for the {@link RectangleInsets} class. */ public class RectangleInsetsTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(RectangleInsetsTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public RectangleInsetsTests(final String name) { super(name); } /** * Some checks for the createAdjustedRectangle() method. */ public void testCreateAdjustedRectangleAbsolute() { RectangleInsets i1 = new RectangleInsets( UnitType.ABSOLUTE, 1.0, 2.0, 3.0, 4.0 ); Rectangle2D base = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); // no adjustment Rectangle2D adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.NO_CHANGE, LengthAdjustmentType.NO_CHANGE ); assertEquals(new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0), adjusted); // expand height adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.NO_CHANGE, LengthAdjustmentType.EXPAND ); assertEquals(new Rectangle2D.Double(10.0, 19.0, 30.0, 44.0), adjusted); // contract height adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.NO_CHANGE, LengthAdjustmentType.CONTRACT ); assertEquals(new Rectangle2D.Double(10.0, 21.0, 30.0, 36.0), adjusted); // expand width adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.EXPAND, LengthAdjustmentType.NO_CHANGE ); assertEquals(new Rectangle2D.Double(8.0, 20.0, 36.0, 40.0), adjusted); // contract width adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.CONTRACT, LengthAdjustmentType.NO_CHANGE ); assertEquals(new Rectangle2D.Double(12.0, 20.0, 24.0, 40.0), adjusted); // expand both adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.EXPAND, LengthAdjustmentType.EXPAND ); assertEquals(new Rectangle2D.Double(8.0, 19.0, 36.0, 44.0), adjusted); // expand width contract height adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.EXPAND, LengthAdjustmentType.CONTRACT ); assertEquals(new Rectangle2D.Double(8.0, 21.0, 36.0, 36.0), adjusted); // contract both adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.CONTRACT, LengthAdjustmentType.CONTRACT ); assertEquals(new Rectangle2D.Double(12.0, 21.0, 24.0, 36.0), adjusted); // contract width expand height adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.CONTRACT, LengthAdjustmentType.EXPAND ); assertEquals(new Rectangle2D.Double(12.0, 19.0, 24.0, 44.0), adjusted); } private static final double EPSILON = 0.0000001; /** * Some checks for the createAdjustedRectangle() method. */ public void testCreateAdjustedRectangleRelative() { RectangleInsets i1 = new RectangleInsets( UnitType.RELATIVE, 0.04, 0.03, 0.02, 0.01 ); Rectangle2D base = new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0); // no adjustment Rectangle2D adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.NO_CHANGE, LengthAdjustmentType.NO_CHANGE ); assertEquals(new Rectangle2D.Double(10.0, 20.0, 30.0, 40.0), adjusted); // expand height adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.NO_CHANGE, LengthAdjustmentType.EXPAND ); assertEquals(10.0, adjusted.getX(), EPSILON); assertEquals(18.2978723404, adjusted.getY(), EPSILON); assertEquals(30.0, adjusted.getWidth(), EPSILON); assertEquals(42.553191489, adjusted.getHeight(), EPSILON); // contract height adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.NO_CHANGE, LengthAdjustmentType.CONTRACT ); assertEquals(10.0, adjusted.getX(), EPSILON); assertEquals(21.6, adjusted.getY(), EPSILON); assertEquals(30.0, adjusted.getWidth(), EPSILON); assertEquals(37.6, adjusted.getHeight(), EPSILON); // expand width adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.EXPAND, LengthAdjustmentType.NO_CHANGE ); assertEquals(9.0625, adjusted.getX(), EPSILON); assertEquals(20.0, adjusted.getY(), EPSILON); assertEquals(31.25, adjusted.getWidth(), EPSILON); assertEquals(40.0, adjusted.getHeight(), EPSILON); // contract width adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.CONTRACT, LengthAdjustmentType.NO_CHANGE ); assertEquals(10.9, adjusted.getX(), EPSILON); assertEquals(20.0, adjusted.getY(), EPSILON); assertEquals(28.8, adjusted.getWidth(), EPSILON); assertEquals(40.0, adjusted.getHeight(), EPSILON); // expand both adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.EXPAND, LengthAdjustmentType.EXPAND ); assertEquals(9.0625, adjusted.getX(), EPSILON); assertEquals(18.2978723404, adjusted.getY(), EPSILON); assertEquals(31.25, adjusted.getWidth(), EPSILON); assertEquals(42.553191489, adjusted.getHeight(), EPSILON); // expand width contract height adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.EXPAND, LengthAdjustmentType.CONTRACT ); assertEquals(9.0625, adjusted.getX(), EPSILON); assertEquals(21.6, adjusted.getY(), EPSILON); assertEquals(31.25, adjusted.getWidth(), EPSILON); assertEquals(37.6, adjusted.getHeight(), EPSILON); // contract both adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.CONTRACT, LengthAdjustmentType.CONTRACT ); assertEquals(10.9, adjusted.getX(), EPSILON); assertEquals(21.6, adjusted.getY(), EPSILON); assertEquals(28.8, adjusted.getWidth(), EPSILON); assertEquals(37.6, adjusted.getHeight(), EPSILON); // contract width expand height adjusted = i1.createAdjustedRectangle( base, LengthAdjustmentType.CONTRACT, LengthAdjustmentType.EXPAND ); assertEquals(10.9, adjusted.getX(), EPSILON); assertEquals(18.2978723404, adjusted.getY(), EPSILON); assertEquals(28.8, adjusted.getWidth(), EPSILON); assertEquals(42.553191489, adjusted.getHeight(), EPSILON); } /** * Test the equals() method. */ public void testEquals() { RectangleInsets i1 = new RectangleInsets( UnitType.ABSOLUTE, 1.0, 2.0, 3.0, 4.0 ); RectangleInsets i2 = new RectangleInsets( UnitType.ABSOLUTE, 1.0, 2.0, 3.0, 4.0 ); assertTrue(i1.equals(i2)); assertTrue(i2.equals(i1)); i1 = new RectangleInsets(UnitType.RELATIVE, 1.0, 2.0, 3.0, 4.0); assertFalse(i1.equals(i2)); i2 = new RectangleInsets(UnitType.RELATIVE, 1.0, 2.0, 3.0, 4.0); assertTrue(i1.equals(i2)); i1 = new RectangleInsets(UnitType.RELATIVE, 0.0, 2.0, 3.0, 4.0); assertFalse(i1.equals(i2)); i2 = new RectangleInsets(UnitType.RELATIVE, 0.0, 2.0, 3.0, 4.0); assertTrue(i1.equals(i2)); i1 = new RectangleInsets(UnitType.RELATIVE, 0.0, 0.0, 3.0, 4.0); assertFalse(i1.equals(i2)); i2 = new RectangleInsets(UnitType.RELATIVE, 0.0, 0.0, 3.0, 4.0); assertTrue(i1.equals(i2)); i1 = new RectangleInsets(UnitType.RELATIVE, 0.0, 0.0, 0.0, 4.0); assertFalse(i1.equals(i2)); i2 = new RectangleInsets(UnitType.RELATIVE, 0.0, 0.0, 0.0, 4.0); assertTrue(i1.equals(i2)); i1 = new RectangleInsets(UnitType.RELATIVE, 0.0, 0.0, 0.0, 0.0); assertFalse(i1.equals(i2)); i2 = new RectangleInsets(UnitType.RELATIVE, 0.0, 0.0, 0.0, 0.0); assertTrue(i1.equals(i2)); } /** * Serialize an instance, restore it, and check for identity. */ public void testSerialization() { final RectangleInsets i1 = new RectangleInsets( UnitType.ABSOLUTE, 1.0, 2.0, 3.0, 4.0 ); RectangleInsets i2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(i1); out.close(); final ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); i2 = (RectangleInsets) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(i1.equals(i2)); } /** * Runs the test suite using the JUnit text-based runner. * * @param args ignored. */ public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } } jcommon-1.0.16/source/org/jfree/ui/junit/StandardGradientPaintTransformerTests.java0000644000175000017500000001007211172030703030444 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------------------ * StandardGradientPaintTransformerTests.java * ------------------------------------------ * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: StandardGradientPaintTransformerTests.java,v 1.5 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 19-Mar-2004 : Version 1 (DG); * */ package org.jfree.ui.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.ui.GradientPaintTransformType; import org.jfree.ui.StandardGradientPaintTransformer; /** * Tests for the {@link StandardGradientPaintTransformer} class. */ public class StandardGradientPaintTransformerTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(StandardGradientPaintTransformerTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public StandardGradientPaintTransformerTests(final String name) { super(name); } /** * Test that the equals() method distinguishes all fields. */ public void testEquals() { StandardGradientPaintTransformer t1 = new StandardGradientPaintTransformer(); StandardGradientPaintTransformer t2 = new StandardGradientPaintTransformer(); assertTrue(t1.equals(t2)); assertTrue(t2.equals(t1)); t1 = new StandardGradientPaintTransformer(GradientPaintTransformType.CENTER_VERTICAL); assertFalse(t1.equals(t2)); t2 = new StandardGradientPaintTransformer(GradientPaintTransformType.CENTER_VERTICAL); assertTrue(t1.equals(t2)); } /** * Serialize an instance, restore it, and check for identity. */ public void testSerialization() { final StandardGradientPaintTransformer t1 = new StandardGradientPaintTransformer(); StandardGradientPaintTransformer t2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(t1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); t2 = (StandardGradientPaintTransformer) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(t1.equals(t2)); } } jcommon-1.0.16/source/org/jfree/ui/junit/TextAnchorTests.java0000644000175000017500000000643711172030703024100 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * TextAnchorTests.java * -------------------- * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: TextAnchorTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 08-Jan-2004 : Version 1 (DG); * */ package org.jfree.ui.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.ui.TextAnchor; /** * Tests for the {@link TextAnchor} class. */ public class TextAnchorTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TextAnchorTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TextAnchorTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { assertTrue(TextAnchor.BOTTOM_LEFT.equals(TextAnchor.BOTTOM_LEFT)); } /** * Serialize an instance, restore it, and check for identity. */ public void testSerialization() { final TextAnchor a1 = TextAnchor.BASELINE_CENTER; TextAnchor a2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(a1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); a2 = (TextAnchor) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(a1 == a2); } } jcommon-1.0.16/source/org/jfree/ui/junit/UIPackageTests.java0000644000175000017500000000550511172030703023605 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * UIPackageTests.java * ------------------- * (C) Copyright 2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: UIPackageTests.java,v 1.4 2005/11/02 16:30:23 mungady Exp $ * * Changes: * -------- * 08-Jan-2004 : Version 1 (DG); * */ package org.jfree.ui.junit; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * A collection of tests for the org.jfree.ui package. These tests can be run using * JUnit (http://www.junit.org). */ public class UIPackageTests extends TestCase { /** * Returns a test suite to the JUnit test runner. * * @return The test suite. */ public static Test suite() { final TestSuite suite = new TestSuite("org.jfree.ui"); suite.addTestSuite(GradientPaintTransformTypeTests.class); suite.addTestSuite(HorizontalAlignmentTests.class); suite.addTestSuite(LayerTests.class); suite.addTestSuite(RectangleAnchorTests.class); suite.addTestSuite(RectangleEdgeTests.class); suite.addTestSuite(RectangleInsetsTests.class); suite.addTestSuite(Size2DTests.class); suite.addTestSuite(StandardGradientPaintTransformerTests.class); suite.addTestSuite(TextAnchorTests.class); suite.addTestSuite(VerticalAlignmentTests.class); return suite; } /** * Constructs the test suite. * * @param name the suite name. */ public UIPackageTests(final String name) { super(name); } } jcommon-1.0.16/source/org/jfree/ui/junit/RectangleEdgeTests.java0000644000175000017500000000700111172030703024476 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * RectangleEdgeTests.java * ----------------------- * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: RectangleEdgeTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 08-Jan-2004 : Version 1 (DG); * */ package org.jfree.ui.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.ui.RectangleEdge; /** * Tests for the {@link RectangleEdge} class. */ public class RectangleEdgeTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(RectangleEdgeTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public RectangleEdgeTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { assertTrue(RectangleEdge.TOP.equals(RectangleEdge.TOP)); assertTrue(RectangleEdge.BOTTOM.equals(RectangleEdge.BOTTOM)); assertTrue(RectangleEdge.LEFT.equals(RectangleEdge.LEFT)); assertTrue(RectangleEdge.RIGHT.equals(RectangleEdge.RIGHT)); } /** * Serialize an instance, restore it, and check for identity. */ public void testSerialization() { final RectangleEdge e1 = RectangleEdge.RIGHT; RectangleEdge e2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(e1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); e2 = (RectangleEdge) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(e1 == e2); } } jcommon-1.0.16/source/org/jfree/ui/junit/RectangleAnchorTests.java0000644000175000017500000000652011172030703025051 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * RectangleAnchorTests.java * ------------------------- * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: RectangleAnchorTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 08-Jan-2004 : Version 1 (DG); * */ package org.jfree.ui.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.ui.RectangleAnchor; /** * Tests for the {@link RectangleAnchor} class. */ public class RectangleAnchorTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(RectangleAnchorTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public RectangleAnchorTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { assertTrue(RectangleAnchor.TOP.equals(RectangleAnchor.TOP)); } /** * Serialize an instance, restore it, and check for identity. */ public void testSerialization() { final RectangleAnchor a1 = RectangleAnchor.RIGHT; RectangleAnchor a2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(a1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); a2 = (RectangleAnchor) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(a1 == a2); } } jcommon-1.0.16/source/org/jfree/ui/junit/LayerTests.java0000644000175000017500000000651411172030703023071 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * LayerTests.java * --------------- * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: LayerTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 08-Jan-2004 : Version 1 (DG); * */ package org.jfree.ui.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.ui.Layer; /** * Tests for the {@link Layer} class. */ public class LayerTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(LayerTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public LayerTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { assertTrue(Layer.FOREGROUND.equals(Layer.FOREGROUND)); assertTrue(Layer.BACKGROUND.equals(Layer.BACKGROUND)); assertFalse(Layer.FOREGROUND.equals(Layer.BACKGROUND)); } /** * Serialize an instance, restore it, and check for identity. */ public void testSerialization() { final Layer l1 = Layer.FOREGROUND; Layer l2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(l1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); l2 = (Layer) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(l1 == l2); } } jcommon-1.0.16/source/org/jfree/ui/junit/Size2DTests.java0000644000175000017500000001020011172030703023100 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * Size2DTests.java * ---------------- * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: Size2DTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 10-Nov-2004 : Version 1 (DG); * */ package org.jfree.ui.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.ui.Size2D; /** * Tests for the {@link Size2D} class. */ public class Size2DTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(Size2DTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public Size2DTests(final String name) { super(name); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { Size2D s1 = new Size2D(1.0, 2.0); Size2D s2 = new Size2D(1.0, 2.0); assertTrue(s1.equals(s2)); assertTrue(s2.equals(s1)); s1 = new Size2D(2.0, 2.0); assertFalse(s1.equals(s2)); s2 = new Size2D(2.0, 2.0); assertTrue(s1.equals(s2)); s1 = new Size2D(2.0, 3.0); assertFalse(s1.equals(s2)); s2 = new Size2D(2.0, 3.0); assertTrue(s1.equals(s2)); } /** * Confirm that cloning works. */ public void testCloning() { Size2D s1 = new Size2D(1.0, 2.0); Size2D s2 = null; try { s2 = (Size2D) s1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); System.err.println("Failed to clone."); } assertTrue(s1 != s2); assertTrue(s1.getClass() == s2.getClass()); assertTrue(s1.equals(s2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { final Size2D s1 = new Size2D(3.0, 4.0); Size2D s2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); s2 = (Size2D) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(s1.equals(s2)); } } jcommon-1.0.16/source/org/jfree/ui/junit/HorizontalAlignmentTests.java0000644000175000017500000000711311172030703026001 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------------- * HorizontalAlignmentTests.java * ----------------------------- * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: HorizontalAlignmentTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 08-Jan-2004 : Version 1 (DG); * */ package org.jfree.ui.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.ui.HorizontalAlignment; /** * Tests for the {@link HorizontalAlignment} class. */ public class HorizontalAlignmentTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(RectangleEdgeTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public HorizontalAlignmentTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { assertTrue(HorizontalAlignment.LEFT.equals(HorizontalAlignment.LEFT)); assertTrue(HorizontalAlignment.RIGHT.equals(HorizontalAlignment.RIGHT)); assertTrue(HorizontalAlignment.CENTER.equals(HorizontalAlignment.CENTER)); } /** * Serialize an instance, restore it, and check for identity. */ public void testSerialization() { final HorizontalAlignment a1 = HorizontalAlignment.CENTER; HorizontalAlignment a2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(a1); out.close(); final ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); a2 = (HorizontalAlignment) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(a1 == a2); } } jcommon-1.0.16/source/org/jfree/ui/junit/VerticalAlignmentTests.java0000644000175000017500000000701511172030703025422 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------- * VerticalAlignmentTests.java * --------------------------- * (C) Copyright 2004, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: VerticalAlignmentTests.java,v 1.3 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 08-Jan-2004 : Version 1 (DG); * */ package org.jfree.ui.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.ui.VerticalAlignment; /** * Tests for the {@link VerticalAlignment} class. */ public class VerticalAlignmentTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(VerticalAlignmentTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public VerticalAlignmentTests(final String name) { super(name); } /** * Tests the equals() method. */ public void testEquals() { assertTrue(VerticalAlignment.TOP.equals(VerticalAlignment.TOP)); assertTrue(VerticalAlignment.BOTTOM.equals(VerticalAlignment.BOTTOM)); assertTrue(VerticalAlignment.CENTER.equals(VerticalAlignment.CENTER)); } /** * Serialize an instance, restore it, and check for identity. */ public void testSerialization() { final VerticalAlignment a1 = VerticalAlignment.CENTER; VerticalAlignment a2 = null; try { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(a1); out.close(); final ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); a2 = (VerticalAlignment) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertTrue(a1 == a2); } } jcommon-1.0.16/source/org/jfree/ui/junit/FontChooserDialogTest.java0000644000175000017500000000462211172030703025201 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * FontChooserDialogTest.java * -------------------------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: FontChooserDialogTest.java,v 1.4 2007/11/02 17:50:37 taqua Exp $ * * Changes * ------- * 21-Feb-2004 : Initial version * */ package org.jfree.ui.junit; import java.awt.Font; import java.awt.Frame; import junit.framework.TestCase; import org.jfree.ui.FontChooserDialog; /** * A test for the {@link FontChooserDialog} class. */ public class FontChooserDialogTest extends TestCase { /** * Creates a new test. * * @param s the test name. */ public FontChooserDialogTest(final String s) { super(s); } /** * Checks that it is possible to create a dialog. */ public void testCreateDialog () { try { new FontChooserDialog (new Frame(), "Title", false, new Font("Serif", Font.PLAIN, 10)); } catch (UnsupportedOperationException use) { // Headless mode exception is instance of this ex. } } } jcommon-1.0.16/source/org/jfree/ui/L1R3ButtonPanel.java0000644000175000017500000001052511172030703022473 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * L1R3ButtonPanel.java * -------------------- * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: L1R3ButtonPanel.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.* (DG); * 26-Jun-2002 : Removed unnecessary import (DG); * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JPanel; /** * A 'ready-made' panel that has one button on the left and three buttons on the right - nested * panels and layout managers take care of resizing. * * @author David Gilbert */ public class L1R3ButtonPanel extends JPanel { /** The left button. */ private JButton left; /** The first button on the right of the panel. */ private JButton right1; /** The second button on the right of the panel. */ private JButton right2; /** The third button on the right of the panel. */ private JButton right3; /** * Standard constructor - creates panel with the specified button labels. * * @param label1 the label for button 1. * @param label2 the label for button 2. * @param label3 the label for button 3. * @param label4 the label for button 4. */ public L1R3ButtonPanel(final String label1, final String label2, final String label3, final String label4) { setLayout(new BorderLayout()); // create the pieces... final JPanel panel = new JPanel(new BorderLayout()); final JPanel panel2 = new JPanel(new BorderLayout()); this.left = new JButton(label1); this.right1 = new JButton(label2); this.right2 = new JButton(label3); this.right3 = new JButton(label4); // ...and put them together panel.add(this.left, BorderLayout.WEST); panel2.add(this.right1, BorderLayout.EAST); panel.add(panel2, BorderLayout.CENTER); panel.add(this.right2, BorderLayout.EAST); add(panel, BorderLayout.CENTER); add(this.right3, BorderLayout.EAST); } /** * Returns a reference to button 1, allowing the caller to set labels, action-listeners etc. * * @return the left button. */ public JButton getLeftButton() { return this.left; } /** * Returns a reference to button 2, allowing the caller to set labels, action-listeners etc. * * @return the right button 1. */ public JButton getRightButton1() { return this.right1; } /** * Returns a reference to button 3, allowing the caller to set labels, action-listeners etc. * * @return the right button 2. */ public JButton getRightButton2() { return this.right2; } /** * Returns a reference to button 4, allowing the caller to set labels, action-listeners etc. * * @return the right button 3. */ public JButton getRightButton3() { return this.right3; } } jcommon-1.0.16/source/org/jfree/ui/GradientPaintTransformer.java0000644000175000017500000000452311172030703024613 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2007, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------------- * GradientPaintTransformer.java * ----------------------------- * (C) Copyright 2003-2007, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: GradientPaintTransformer.java,v 1.4 2007/04/03 12:34:13 mungady Exp $ * * Changes * ------- * 28-Oct-2003 : Version 1 (DG); * */ package org.jfree.ui; import java.awt.GradientPaint; import java.awt.Shape; /** * The interface for a class that can transform a GradientPaint to * fit an arbitrary shape. * * @author David Gilbert */ public interface GradientPaintTransformer { /** * Transforms a GradientPaint instance to fit some target * shape. Classes that implement this method typically return a new * instance of GradientPaint. * * @param paint the original paint (not null). * @param target the reference area (not null). * * @return A transformed paint. */ public GradientPaint transform(GradientPaint paint, Shape target); } jcommon-1.0.16/source/org/jfree/ui/FontChooserDialog.java0000644000175000017500000001012511172030703023203 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * FontChooserDialog.java * ---------------------- * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: FontChooserDialog.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui; import java.awt.BorderLayout; import java.awt.Dialog; import java.awt.Font; import java.awt.Frame; import javax.swing.BorderFactory; import javax.swing.JPanel; /** * A dialog for choosing a font from the available system fonts. * * @author David Gilbert */ public class FontChooserDialog extends StandardDialog { /** The panel within the dialog that contains the font selection controls. */ private FontChooserPanel fontChooserPanel; /** * Standard constructor - builds a font chooser dialog owned by another dialog. * * @param owner the dialog that 'owns' this dialog. * @param title the title for the dialog. * @param modal a boolean that indicates whether or not the dialog is modal. * @param font the initial font displayed. */ public FontChooserDialog(final Dialog owner, final String title, final boolean modal, final Font font) { super(owner, title, modal); setContentPane(createContent(font)); } /** * Standard constructor - builds a font chooser dialog owned by a frame. * * @param owner the frame that 'owns' this dialog. * @param title the title for the dialog. * @param modal a boolean that indicates whether or not the dialog is modal. * @param font the initial font displayed. */ public FontChooserDialog(final Frame owner, final String title, final boolean modal, final Font font) { super(owner, title, modal); setContentPane(createContent(font)); } /** * Returns the selected font. * * @return the font. */ public Font getSelectedFont() { return this.fontChooserPanel.getSelectedFont(); } /** * Returns the panel that is the user interface. * * @param font the font. * * @return the panel. */ private JPanel createContent(Font font) { final JPanel content = new JPanel(new BorderLayout()); content.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); if (font == null) { font = new Font("Dialog", 10, Font.PLAIN); } this.fontChooserPanel = new FontChooserPanel(font); content.add(this.fontChooserPanel); final JPanel buttons = createButtonPanel(); buttons.setBorder(BorderFactory.createEmptyBorder(4, 0, 0, 0)); content.add(buttons, BorderLayout.SOUTH); return content; } } jcommon-1.0.16/source/org/jfree/ui/RectangleAnchor.java0000644000175000017500000002352011172030703022674 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * RectangleAnchor.java * -------------------- * (C) Copyright 2003-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: RectangleAnchor.java,v 1.6 2005/10/18 13:18:34 mungady Exp $ * * Changes: * -------- * 31-Oct-2003 (DG); * 01-Apr-2004 : Changed java.awt.geom.Dimension2D to org.jfree.ui.Size2D * because of JDK bug 4976448 which persists on JDK 1.3.1 (DG); * 21-Jan-2005 : Changed return type of coordinates() method (DG); * */ package org.jfree.ui; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.ObjectStreamException; import java.io.Serializable; /** * Used to indicate an anchor point for a rectangle. * * @author David Gilbert */ public final class RectangleAnchor implements Serializable { /** For serialization. */ private static final long serialVersionUID = -2457494205644416327L; /** Center. */ public static final RectangleAnchor CENTER = new RectangleAnchor("RectangleAnchor.CENTER"); /** Top. */ public static final RectangleAnchor TOP = new RectangleAnchor("RectangleAnchor.TOP"); /** Top-Left. */ public static final RectangleAnchor TOP_LEFT = new RectangleAnchor("RectangleAnchor.TOP_LEFT"); /** Top-Right. */ public static final RectangleAnchor TOP_RIGHT = new RectangleAnchor("RectangleAnchor.TOP_RIGHT"); /** Bottom. */ public static final RectangleAnchor BOTTOM = new RectangleAnchor("RectangleAnchor.BOTTOM"); /** Bottom-Left. */ public static final RectangleAnchor BOTTOM_LEFT = new RectangleAnchor("RectangleAnchor.BOTTOM_LEFT"); /** Bottom-Right. */ public static final RectangleAnchor BOTTOM_RIGHT = new RectangleAnchor("RectangleAnchor.BOTTOM_RIGHT"); /** Left. */ public static final RectangleAnchor LEFT = new RectangleAnchor("RectangleAnchor.LEFT"); /** Right. */ public static final RectangleAnchor RIGHT = new RectangleAnchor("RectangleAnchor.RIGHT"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private RectangleAnchor(final String name) { this.name = name; } /** * Returns a string representing the object. * * @return The string. */ public String toString() { return this.name; } /** * Returns true if this object is equal to the specified * object, and false otherwise. * * @param obj the other object (null permitted). * * @return A boolean. */ public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof RectangleAnchor)) { return false; } final RectangleAnchor order = (RectangleAnchor) obj; if (!this.name.equals(order.name)) { return false; } return true; } /** * Returns a hash code value for the object. * * @return The hashcode */ public int hashCode() { return this.name.hashCode(); } /** * Returns the (x, y) coordinates of the specified anchor. * * @param rectangle the rectangle. * @param anchor the anchor. * * @return The (x, y) coordinates. */ public static Point2D coordinates(final Rectangle2D rectangle, final RectangleAnchor anchor) { Point2D result = new Point2D.Double(); if (anchor == RectangleAnchor.CENTER) { result.setLocation(rectangle.getCenterX(), rectangle.getCenterY()); } else if (anchor == RectangleAnchor.TOP) { result.setLocation(rectangle.getCenterX(), rectangle.getMinY()); } else if (anchor == RectangleAnchor.BOTTOM) { result.setLocation(rectangle.getCenterX(), rectangle.getMaxY()); } else if (anchor == RectangleAnchor.LEFT) { result.setLocation(rectangle.getMinX(), rectangle.getCenterY()); } else if (anchor == RectangleAnchor.RIGHT) { result.setLocation(rectangle.getMaxX(), rectangle.getCenterY()); } else if (anchor == RectangleAnchor.TOP_LEFT) { result.setLocation(rectangle.getMinX(), rectangle.getMinY()); } else if (anchor == RectangleAnchor.TOP_RIGHT) { result.setLocation(rectangle.getMaxX(), rectangle.getMinY()); } else if (anchor == RectangleAnchor.BOTTOM_LEFT) { result.setLocation(rectangle.getMinX(), rectangle.getMaxY()); } else if (anchor == RectangleAnchor.BOTTOM_RIGHT) { result.setLocation(rectangle.getMaxX(), rectangle.getMaxY()); } return result; } /** * Creates a new rectangle with the specified dimensions that is aligned to * the given anchor point (anchorX, anchorY). * * @param dimensions the dimensions (null not permitted). * @param anchorX the x-anchor. * @param anchorY the y-anchor. * @param anchor the anchor (null not permitted). * * @return A rectangle. */ public static Rectangle2D createRectangle(final Size2D dimensions, final double anchorX, final double anchorY, final RectangleAnchor anchor) { Rectangle2D result = null; final double w = dimensions.getWidth(); final double h = dimensions.getHeight(); if (anchor == RectangleAnchor.CENTER) { result = new Rectangle2D.Double( anchorX - w / 2.0, anchorY - h / 2.0, w, h ); } else if (anchor == RectangleAnchor.TOP) { result = new Rectangle2D.Double( anchorX - w / 2.0, anchorY - h / 2.0, w, h ); } else if (anchor == RectangleAnchor.BOTTOM) { result = new Rectangle2D.Double( anchorX - w / 2.0, anchorY - h / 2.0, w, h ); } else if (anchor == RectangleAnchor.LEFT) { result = new Rectangle2D.Double( anchorX, anchorY - h / 2.0, w, h ); } else if (anchor == RectangleAnchor.RIGHT) { result = new Rectangle2D.Double( anchorX - w, anchorY - h / 2.0, w, h ); } else if (anchor == RectangleAnchor.TOP_LEFT) { result = new Rectangle2D.Double( anchorX - w / 2.0, anchorY - h / 2.0, w, h ); } else if (anchor == RectangleAnchor.TOP_RIGHT) { result = new Rectangle2D.Double( anchorX - w / 2.0, anchorY - h / 2.0, w, h ); } else if (anchor == RectangleAnchor.BOTTOM_LEFT) { result = new Rectangle2D.Double( anchorX - w / 2.0, anchorY - h / 2.0, w, h ); } else if (anchor == RectangleAnchor.BOTTOM_RIGHT) { result = new Rectangle2D.Double( anchorX - w / 2.0, anchorY - h / 2.0, w, h ); } return result; } /** * Ensures that serialization returns the unique instances. * * @return The object. * * @throws ObjectStreamException if there is a problem. */ private Object readResolve() throws ObjectStreamException { RectangleAnchor result = null; if (this.equals(RectangleAnchor.CENTER)) { result = RectangleAnchor.CENTER; } else if (this.equals(RectangleAnchor.TOP)) { result = RectangleAnchor.TOP; } else if (this.equals(RectangleAnchor.BOTTOM)) { result = RectangleAnchor.BOTTOM; } else if (this.equals(RectangleAnchor.LEFT)) { result = RectangleAnchor.LEFT; } else if (this.equals(RectangleAnchor.RIGHT)) { result = RectangleAnchor.RIGHT; } else if (this.equals(RectangleAnchor.TOP_LEFT)) { result = RectangleAnchor.TOP_LEFT; } else if (this.equals(RectangleAnchor.TOP_RIGHT)) { result = RectangleAnchor.TOP_RIGHT; } else if (this.equals(RectangleAnchor.BOTTOM_LEFT)) { result = RectangleAnchor.BOTTOM_LEFT; } else if (this.equals(RectangleAnchor.BOTTOM_RIGHT)) { result = RectangleAnchor.BOTTOM_RIGHT; } return result; } } jcommon-1.0.16/source/org/jfree/ui/LengthLimitingDocument.java0000644000175000017500000001001211172030703024242 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------- * LengthLimitingDocument.java * --------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: LengthLimitingDocument.java,v 1.3 2005/10/18 13:18:34 mungady Exp $ * * Changes * ------- * 22-Jan-2003 : Initial version * 05-Feb-2003 : Documentation * */ package org.jfree.ui; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; /** * This Document restricts the size of the contained plain text to the given number of * characters. * * @author Thomas Morgner */ public class LengthLimitingDocument extends PlainDocument { /** The maximum length. */ private int maxlen; /** * Creates a new LengthLimitingDocument, with no limitation. */ public LengthLimitingDocument() { this(-1); } /** * Creates a new LengthLimitingDocument with the given limitation. No more than * maxlen characters can be added to the document. If maxlen is negative, then * no length check is performed. * * @param maxlen the maximum number of elements in this document */ public LengthLimitingDocument(final int maxlen) { super(); this.maxlen = maxlen; } /** * Sets the maximum number of characters for this document. Existing characters * are not removed. * * @param maxlen the maximum number of characters in this document. */ public void setMaxLength(final int maxlen) { this.maxlen = maxlen; } /** * Returns the defined maximum number characters for this document. * @return the maximum number of characters */ public int getMaxLength() { return this.maxlen; } /** * Inserts the string into the document. If the length of the document would * violate the maximum characters restriction, then the string is cut down so * that * @param offs the offset, where the string should be inserted into the document * @param str the string that should be inserted * @param a the attribute set assigned for the document * @throws javax.swing.text.BadLocationException if the offset is not correct */ public void insertString(final int offs, final String str, final AttributeSet a) throws BadLocationException { if (str == null) { return; } if (this.maxlen < 0) { super.insertString(offs, str, a); } final char[] numeric = str.toCharArray(); final StringBuffer b = new StringBuffer(); b.append(numeric, 0, Math.min(this.maxlen, numeric.length)); super.insertString(offs, b.toString(), a); } } jcommon-1.0.16/source/org/jfree/ui/HorizontalAlignment.java0000644000175000017500000001033511172030703023625 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * HorizontalAlignment.java * ------------------------ * (C) Copyright 2004, 2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: HorizontalAlignment.java,v 1.5 2005/10/18 13:18:34 mungady Exp $ * * Changes: * -------- * 08-Jan-2004 : Version 1 (DG); * */ package org.jfree.ui; import java.io.ObjectStreamException; import java.io.Serializable; /** * An enumeration of the horizontal alignment types (LEFT, * RIGHT and CENTER). * * @author David Gilbert */ public final class HorizontalAlignment implements Serializable { /** For serialization. */ private static final long serialVersionUID = -8249740987565309567L; /** Left alignment. */ public static final HorizontalAlignment LEFT = new HorizontalAlignment("HorizontalAlignment.LEFT"); /** Right alignment. */ public static final HorizontalAlignment RIGHT = new HorizontalAlignment("HorizontalAlignment.RIGHT"); /** Center alignment. */ public static final HorizontalAlignment CENTER = new HorizontalAlignment("HorizontalAlignment.CENTER"); /** The name. */ private String name; /** * Private constructor. * * @param name the name. */ private HorizontalAlignment(final String name) { this.name = name; } /** * Returns a string representing the object. * * @return The string. */ public String toString() { return this.name; } /** * Returns true if this object is equal to the specified * object, and false otherwise. * * @param obj the object (null permitted). * * @return A boolean. */ public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof HorizontalAlignment)) { return false; } final HorizontalAlignment that = (HorizontalAlignment) obj; if (!this.name.equals(that.name)) { return false; } return true; } /** * Returns a hash code value for the object. * * @return The hashcode */ public int hashCode() { return this.name.hashCode(); } /** * Ensures that serialization returns the unique instances. * * @return The object. * * @throws ObjectStreamException if there is a problem. */ private Object readResolve() throws ObjectStreamException { HorizontalAlignment result = null; if (this.equals(HorizontalAlignment.LEFT)) { result = HorizontalAlignment.LEFT; } else if (this.equals(HorizontalAlignment.RIGHT)) { result = HorizontalAlignment.RIGHT; } else if (this.equals(HorizontalAlignment.CENTER)) { result = HorizontalAlignment.CENTER; } return result; } } jcommon-1.0.16/source/org/jfree/xml/0000755000175000017500000000000011351753320017161 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/xml/generator/0000755000175000017500000000000011351753320021147 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/xml/generator/SourceCollector.java0000644000175000017500000000363111172030703025116 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * SourceCollector.java * -------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: SourceCollector.java,v 1.2 2005/10/18 13:32:20 mungady Exp $ * * Changes * ------- * 21.06.2003 : Initial version * */ package org.jfree.xml.generator; /** * A source collector returns a collection of {@link Class} objects. */ public interface SourceCollector { /** * Returns the classes that fall within the scope of the source collector. * * @return The classes. */ public Class[] getClasses(); } jcommon-1.0.16/source/org/jfree/xml/generator/ModelBuilder.java0000644000175000017500000004116711172030703024364 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * ModelBuilder.java * ----------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ModelBuilder.java,v 1.3 2005/10/18 13:32:20 mungady Exp $ * * Changes * ------- * 21-Jun-2003 : Initial version (TM); * 26-Nov-2003 : Updated header and Javadocs (DG); * */ package org.jfree.xml.generator; import java.beans.BeanInfo; import java.beans.IndexedPropertyDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.Properties; import org.jfree.util.HashNMap; import org.jfree.xml.generator.model.ClassDescription; import org.jfree.xml.generator.model.DescriptionModel; import org.jfree.xml.generator.model.MultiplexMappingInfo; import org.jfree.xml.generator.model.PropertyInfo; import org.jfree.xml.generator.model.PropertyType; import org.jfree.xml.generator.model.TypeInfo; import org.jfree.xml.util.BasicTypeSupport; /** * A model builder. This class performs the work of creating a class description model from * a set of source files. */ public final class ModelBuilder { /** The single instance. */ private static ModelBuilder instance; /** * Returns the single instance of this class. * * @return the single instance of this class. */ public static ModelBuilder getInstance() { if (instance == null) { instance = new ModelBuilder(); } return instance; } /** The handler mapping. */ private Properties handlerMapping; /** * Creates a single instance. */ private ModelBuilder() { this.handlerMapping = new Properties(); } /** * Adds attribute handlers. * * @param p the handlers. */ public void addAttributeHandlers(final Properties p) { this.handlerMapping.putAll(p); } /** * Builds a model from the classes provided by the {@link SourceCollector}. *

* The {@link DescriptionGenerator} class invokes this. * * @param c the source collector. * @param model the model under construction (null permitted). * * @return The completed model. */ public DescriptionModel buildModel(final SourceCollector c, DescriptionModel model) { Class[] classes = c.getClasses(); if (model == null) { model = new DescriptionModel(); } while (classes.length != 0) { classes = fillModel(classes, model); } fillSuperClasses(model); // search for multiplexer classes // first search all classes used in parameters and add them to // our list of possible base classes final Class[] baseClasses = findElementTypes(model); final HashNMap classMap = new HashNMap(); for (int i = 0; i < baseClasses.length; i++) { final Class base = baseClasses[i]; for (int j = 0; j < baseClasses.length; j++) { final Class child = baseClasses[j]; if (Modifier.isAbstract(child.getModifiers())) { continue; } if (base.isAssignableFrom(child)) { classMap.add(base, child); } } } // at this point, the keys of 'classMap' represent all required // multiplexers, while the values assigned to these keys define the // possible childs final Iterator keys = classMap.keys(); while (keys.hasNext()) { final Class base = (Class) keys.next(); final Class[] childs = (Class[]) classMap.toArray(base, new Class[0]); if (childs.length < 2) { continue; } boolean isNew = false; MultiplexMappingInfo mmi = model.getMappingModel().lookupMultiplexMapping(base); final ArrayList typeInfoList; if (mmi == null) { mmi = new MultiplexMappingInfo(base); typeInfoList = new ArrayList(); isNew = true; } else { typeInfoList = new ArrayList(Arrays.asList(mmi.getChildClasses())); } for (int i = 0; i < childs.length; i++) { // the generic information is only added, if no other information // is already present ... final TypeInfo typeInfo = new TypeInfo(childs[i].getName(), childs[i]); if (!typeInfoList.contains(typeInfo)) { typeInfoList.add(typeInfo); } } mmi.setChildClasses((TypeInfo[]) typeInfoList.toArray(new TypeInfo[0])); if (isNew) { model.getMappingModel().addMultiplexMapping(mmi); } } // when resolving a class to an handler, the resolver first has to // search for an multiplexer before searching for handlers. Otherwise // non-abstract baseclasses will be found before the multiplexer can // resolve the situation. return model; } private Class[] findElementTypes(final DescriptionModel model) { final ArrayList baseClasses = new ArrayList(); for (int i = 0; i < model.size(); i++) { final ClassDescription cd = model.get(i); if (!baseClasses.contains(cd.getObjectClass())) { baseClasses.add(cd.getObjectClass()); } final PropertyInfo[] properties = cd.getProperties(); for (int p = 0; p < properties.length; p++) { // filter primitive types ... they cannot form a generalization // relation if (!properties[p].getPropertyType().equals(PropertyType.ELEMENT)) { continue; } final Class type = properties[p].getType(); if (baseClasses.contains(type)) { continue; } // filter final classes, they too cannot have derived classes if (Modifier.isFinal(type.getModifiers())) { continue; } baseClasses.add(type); } } return (Class[]) baseClasses.toArray(new Class[baseClasses.size()]); } /** * Fills the super class for all object descriptions of the model. The * super class is only filled, if the object's super class is contained * in the model. * * @param model the model which should get its superclasses updated. */ private void fillSuperClasses(final DescriptionModel model) { // Fill superclasses for (int i = 0; i < model.size(); i++) { final ClassDescription cd = model.get(i); final Class parent = cd.getObjectClass().getSuperclass(); if (parent == null) { continue; } final ClassDescription superCD = model.get(parent); if (superCD != null) { cd.setSuperClass(superCD.getObjectClass()); } } } /** * Updates the model to contain the given classes. * * @param classes a list of classes which should be part of the model. * @param model the model which is updated * * @return A list of super classes which should also be contained in the model. */ private Class[] fillModel(final Class[] classes, final DescriptionModel model) { // first check all direct matches from the source collector. // but make sure that we also detect external superclasses - // we have to get all properties ... final ArrayList superClasses = new ArrayList(); for (int i = 0; i < classes.length; i++) { Class superClass = classes[i].getSuperclass(); if (superClass != null) { if (!Object.class.equals(superClass) && !contains(classes, superClass) && !superClasses.contains(superClass)) { superClasses.add(superClass); } } else { superClass = Object.class; } try { final BeanInfo bi = Introspector.getBeanInfo(classes[i], superClass); final ClassDescription parent = model.get(classes[i]); final ClassDescription cd = createClassDescription(bi, parent); if (cd != null) { model.addClassDescription(cd); } } catch (IntrospectionException ie) { // swallowed.... } } return (Class[]) superClasses.toArray(new Class[0]); } /** * Creates a {@link ClassDescription} object for the specified bean info. * * @param beanInfo the bean info. * @param parent the parent class description. * * @return The class description. */ private ClassDescription createClassDescription (final BeanInfo beanInfo, final ClassDescription parent) { final PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); final ArrayList properties = new ArrayList(); for (int i = 0; i < props.length; i++) { final PropertyDescriptor propertyDescriptor = props[i]; PropertyInfo pi; if (parent != null) { pi = parent.getProperty(propertyDescriptor.getName()); if (pi != null) { // Property already found, don't touch it // Log.info (new Log.SimpleMessage // ("Ignore predefined property: ", propertyDescriptor.getName())); properties.add(pi); continue; } } if (props[i] instanceof IndexedPropertyDescriptor) { // this would handle lists and array access. We don't support // this in the direct approach. We will need some cheating: // // // // // pi = createIndexedPropertyInfo((IndexedPropertyDescriptor) props[i]); } else { pi = createSimplePropertyInfo(props[i]); if (pi != null) { properties.add(pi); } } } final PropertyInfo[] propArray = (PropertyInfo[]) properties.toArray(new PropertyInfo[properties.size()]); final ClassDescription cd; if (parent != null) { cd = parent; } else { cd = new ClassDescription(beanInfo.getBeanDescriptor().getBeanClass()); cd.setDescription(beanInfo.getBeanDescriptor().getShortDescription()); } cd.setProperties(propArray); return cd; } /** * Checks, whether the given method can be called from the generic object factory. * * @param method the method descriptor * @return true, if the method is not null and public, false otherwise. */ public static boolean isValidMethod(final Method method) { if (method == null) { return false; } if (!Modifier.isPublic(method.getModifiers())) { return false; } return true; } /** * Creates a {@link PropertyInfo} object from a {@link PropertyDescriptor}. * * @param pd the property descriptor. * * @return the property info (null possible). */ public PropertyInfo createSimplePropertyInfo(final PropertyDescriptor pd) { final boolean readMethod = isValidMethod(pd.getReadMethod()); final boolean writeMethod = isValidMethod(pd.getWriteMethod()); if (!writeMethod || !readMethod) { // a property is useless for our purposes without having a read or write method. return null; } final PropertyInfo pi = new PropertyInfo(pd.getName(), pd.getPropertyType()); pi.setConstrained(pd.isConstrained()); pi.setDescription(pd.getShortDescription()); pi.setNullable(true); pi.setPreserve(false); pi.setReadMethodAvailable(readMethod); pi.setWriteMethodAvailable(writeMethod); pi.setXmlName(pd.getName()); if (isAttributeProperty(pd.getPropertyType())) { pi.setPropertyType(PropertyType.ATTRIBUTE); pi.setXmlHandler(getHandlerClass(pd.getPropertyType())); } else { pi.setPropertyType(PropertyType.ELEMENT); } return pi; } /** * Checks, whether the given class can be handled as attribute. * All primitive types can be attributes as well as all types which have * a custom attribute handler defined. * * @param c the class which should be checked * @return true, if the class can be handled as attribute, false otherwise. */ private boolean isAttributeProperty(final Class c) { if (BasicTypeSupport.isBasicDataType(c)) { return true; } return this.handlerMapping.containsKey(c.getName()); } /** * Returns the class name for the attribute handler for a property of the specified class. * * @param c the class for which to search an attribute handler * @return the handler class or null, if this class cannot be handled * as attribute. */ private String getHandlerClass(final Class c) { if (BasicTypeSupport.isBasicDataType(c)) { final String handler = BasicTypeSupport.getHandlerClass(c); if (handler != null) { return handler; } } return this.handlerMapping.getProperty(c.getName()); } /** * Checks, whether the class c is contained in the given * class array. * * @param cAll the list of all classes * @param c the class to be searched * @return true, if the class is contained in the array, false otherwise. */ private boolean contains(final Class[] cAll, final Class c) { for (int i = 0; i < cAll.length; i++) { if (cAll[i].equals(c)) { return true; } } return false; } // private PropertyInfo createIndexedPropertyInfo(IndexedPropertyDescriptor prop) // { // // MethodInfo readMethod = createMethodInfo(prop.getIndexedReadMethod()); // MethodInfo writeMethod = createMethodInfo(prop.getIndexedWriteMethod()); // if (writeMethod == null) // { // return null; // } // IndexedPropertyInfo pi = new IndexedPropertyInfo(prop.getName()); // pi.setConstrained(prop.isConstrained()); // pi.setDescription(prop.getShortDescription()); // pi.setNullable(true); // pi.setPreserve(false); // pi.setType(prop.getIndexedPropertyType()); // pi.setReadMethod(readMethod); // pi.setWriteMethod(writeMethod); // // TypeInfo keyInfo = new TypeInfo("index"); // keyInfo.setType(Integer.TYPE); // keyInfo.setNullable(false); // keyInfo.setConstrained(true); // throws indexoutofboundsexception // keyInfo.setDescription("Generic index value"); // KeyDescription kd = new KeyDescription(new TypeInfo[]{keyInfo}); // pi.setKey(kd); // return pi; // } } jcommon-1.0.16/source/org/jfree/xml/generator/DescriptionGenerator.java0000644000175000017500000001477311172030703026152 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * DescriptionGenerator.java * ------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DescriptionGenerator.java,v 1.4 2005/10/18 13:32:20 mungady Exp $ * * Changes * ------------------------- * 21.06.2003 : Initial version * */ package org.jfree.xml.generator; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.net.URL; import java.util.Iterator; import java.util.Properties; import org.jfree.util.Log; import org.jfree.util.PrintStreamLogTarget; import org.jfree.util.ObjectUtilities; import org.jfree.xml.generator.model.DescriptionModel; /** * A utility application for generating class descriptions. */ public final class DescriptionGenerator { /** * Loads a property set from the specified URL. * * @param propertyURL the URL. * * @return The properties. */ private static Properties loadProperties(final URL propertyURL) { final Properties p = new Properties(); try { final InputStream in = new BufferedInputStream(propertyURL.openStream()); p.load(in); in.close(); } catch (Exception e) { System.err.println("Unable to load properties from " + propertyURL); } return p; } /** * Runs the generator, using the 'generator.properties' file for configuration info. * * @param args command line arguments. * * @throws Exception if something goes wrong! */ public static void main(final String[] args) throws Exception { Log.getInstance().addTarget(new PrintStreamLogTarget()); URL propertyURL = ObjectUtilities.getResourceRelative ("generator.properties", DescriptionGenerator.class); if (args.length > 0) { final File f = new File(args[0]); propertyURL = f.toURL(); } final Properties p = loadProperties(propertyURL); final String handlerSource = p.getProperty("attributedefinition"); if (handlerSource != null) { final Properties handlers = loadProperties(new URL(propertyURL, handlerSource)); ModelBuilder.getInstance().addAttributeHandlers(handlers); } final String source = p.getProperty("sourcedirectory", "."); final String target = p.getProperty("targetfile", "model.xml"); DescriptionModel model = null; try { model = new DefaultModelReader().load(target); } catch (Exception e) { Log.debug("Unable to load default model. Ignoring..."); } // Log.debug (model.getModelComments()); model = generate(source, p, model); model.prune(); writeMultiFile(target, model); System.exit(0); } /** * Generates a {@link DescriptionModel} from the specified source. * * @param source the source directory. * @param configuration the configuration properties. * @param model the model (null permitted). * * @return A class description model. */ public static DescriptionModel generate(final String source, final Properties configuration, final DescriptionModel model) { final JavaSourceCollector jsc = new JavaSourceCollector(new File(source)); final Iterator it = configuration.keySet().iterator(); while (it.hasNext()) { final String pName = (String) it.next(); if (pName.startsWith("ignore.baseclass.")) { jsc.addIgnoredBaseClass(configuration.getProperty(pName)); } else if (pName.startsWith("ignore.package.")) { jsc.addIgnoredPackage(configuration.getProperty(pName)); } } jsc.collectFiles(); return ModelBuilder.getInstance().buildModel(jsc, model); } /** * Writes the class description model to a single file. * * @param target the target file name. * @param model the class description model. * * @throws IOException if there is an I/O problem. */ public static void writeSingleFile(final String target, final DescriptionModel model) throws IOException { Log.debug ("Writing ..."); final ModelWriter writer = new ModelWriter(); writer.setModel(model); final Writer w = new BufferedWriter(new FileWriter(target)); writer.write(w); w.close(); } /** * Writes the class description model to multiple files. * * @param target the target file name. * @param model the class description model. * * @throws IOException if there is an I/O problem. */ public static void writeMultiFile(final String target, final DescriptionModel model) throws IOException { Log.debug ("Writing multiple files ..."); final SplittingModelWriter writer = new SplittingModelWriter(); writer.setModel(model); writer.write(target); } } jcommon-1.0.16/source/org/jfree/xml/generator/package.html0000644000175000017500000000021511172030703023420 0ustar twernertwerner XML generatorBeanInfoBeanInfoBeanInfo. jcommon-1.0.16/source/org/jfree/xml/generator/model.dtd0000644000175000017500000000542111172030703022740 0ustar twernertwerner jcommon-1.0.16/source/org/jfree/xml/generator/JavaSourceCollector.java0000644000175000017500000002134211172030703025717 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * JavaSourceCollector.java * ------------------------ * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: JavaSourceCollector.java,v 1.3 2005/10/18 13:32:20 mungady Exp $ * * Changes * ------------------------- * 21.06.2003 : Initial version * */ package org.jfree.xml.generator; import java.io.File; import java.io.FileFilter; import java.lang.reflect.Modifier; import java.util.ArrayList; import org.jfree.ui.ExtensionFileFilter; import org.jfree.util.Log; import org.jfree.util.ObjectUtilities; /** * The class collects all class-files and loads the class objects named * by these files. */ public class JavaSourceCollector implements SourceCollector { /** * A file filter. */ private static class CollectorFileFilter extends ExtensionFileFilter implements FileFilter { /** * Creates a new instance. * * @param description the file description. * @param extension the file extension. */ public CollectorFileFilter(final String description, final String extension) { super(description, extension); } } /** A file filter. */ private CollectorFileFilter eff; /** The file list. */ private ArrayList fileList; /** A list of ignored packages. */ private ArrayList ignoredPackages; /** A list of ignored base classes. */ private ArrayList ignoredBaseClasses; /** The start directory. */ private File startDirectory; /** The initial package name. */ private String initialPackageName; /** * Creates a new source collector. * * @param startDirectory the start directory. */ public JavaSourceCollector(final File startDirectory) { this(startDirectory, ""); } /** * Creates a new source collector. * * @param startDirectory the base directory. * @param packageName the base package name. */ public JavaSourceCollector(final File startDirectory, final String packageName) { this.eff = new CollectorFileFilter("", ".java"); this.fileList = new ArrayList(); this.startDirectory = startDirectory; this.initialPackageName = packageName; this.ignoredPackages = new ArrayList(); this.ignoredBaseClasses = new ArrayList(); } /** * Adds a package that should be ignored. * * @param pkg the package name. */ public void addIgnoredPackage(final String pkg) { Log.debug (new Log.SimpleMessage("Added IgnPackage: " , pkg)); this.ignoredPackages.add(pkg); } /** * Adds a base class that should be ignored. * * @param baseClass the base class name. */ public void addIgnoredBaseClass(final String baseClass) { final Class loadedClass = loadClass(baseClass); if (loadedClass != null) { Log.debug (new Log.SimpleMessage("Added IgnClass: " , baseClass)); this.ignoredBaseClasses.add(loadedClass); } } /** * Adds a class to the list of ignored base classes. * * @param baseClass the class. */ public void addIgnoredBaseClass(final Class baseClass) { this.ignoredBaseClasses.add(baseClass); } /** * Returns true if the named class is being ignored (because of the package that * it belongs to), and false otherwise. * * @param classname the name of the class to test. * * @return A boolean. */ protected boolean isIgnoredPackage(final String classname) { for (int i = 0; i < this.ignoredPackages.size(); i++) { final String ignoredPackage = (String) this.ignoredPackages.get(i); if (classname.startsWith(ignoredPackage)) { return true; } } return false; } /** * Returns true if the named class is being ignored (because it is a descendant * of an ignored base class), and false otherwise. * * @param c the class name. * * @return A boolean. */ protected boolean isIgnoredBaseClass(final Class c) { for (int i = 0; i < this.ignoredBaseClasses.size(); i++) { final Class ignoredClass = (Class) this.ignoredBaseClasses.get(i); if (ignoredClass.isAssignableFrom(c)) { return true; } } return false; } /** * Collects the files/classes. */ public void collectFiles() { collectFiles(this.startDirectory, this.initialPackageName); } /** * Collects the files/classes. * * @param directory the starting directory. * @param packageName the initial package name. */ protected void collectFiles(final File directory, final String packageName) { final File[] files = directory.listFiles(this.eff); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { collectFiles(files[i], buildJavaName(packageName, files[i].getName())); } else { final String fname = files[i].getName(); final String className = fname.substring(0, fname.length() - 5); final String fullName = buildJavaName(packageName, className); if (isIgnoredPackage(fullName)) { Log.debug (new Log.SimpleMessage("Do not process: Ignored: ", className)); continue; } final Class jclass = loadClass(fullName); if (jclass == null || isIgnoredBaseClass(jclass)) { continue; } if (jclass.isInterface() || Modifier.isAbstract(jclass.getModifiers())) { Log.debug (new Log.SimpleMessage("Do not process: Abstract: ", className)); continue; } if (!Modifier.isPublic(jclass.getModifiers())) { Log.debug (new Log.SimpleMessage("Do not process: Not public: ", className)); continue; } this.fileList.add(jclass); } } } /** * Loads a class by its fully qualified name. * * @param name the class name. * * @return The class (or null if there was a problem loading the class). */ protected Class loadClass(final String name) { try { return ObjectUtilities.getClassLoader(JavaSourceCollector.class).loadClass(name); } catch (Exception e) { Log.warn (new Log.SimpleMessage("Do not process: Failed to load class:", name)); return null; } } /** * Creates a fully qualified Java class or package name. * * @param packageName the base package name. * @param newPackage the class/package name. * * @return The fully qualified package/class name. */ protected String buildJavaName(final String packageName, final String newPackage) { if (packageName.length() == 0) { return newPackage; } else { return packageName + "." + newPackage; } } /** * Returns the list of classes as an array. * * @return The list of classes. */ public Class[] getClasses() { return (Class[]) this.fileList.toArray(new Class[0]); } } jcommon-1.0.16/source/org/jfree/xml/generator/model/0000755000175000017500000000000011351753320022247 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/xml/generator/model/Comments.java0000644000175000017500000000712711172030703024700 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------- * Comments.java * ------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Comments.java,v 1.2 2005/10/18 13:32:37 mungady Exp $ * * Changes * ------- * 03-Dec-2003 : Initial version (TM); * 04-Feb-2004 : Added Javadocs (DG); * */ package org.jfree.xml.generator.model; /** * A set of comments for a model. */ public class Comments { /** Open tag comments. */ private String[] openTagComment; /** Close tag comments. */ private String[] closeTagComment; /** * Creates a new set of comments. * * @param openTagComment the open tag comment. * @param closeTagComment the close tag comment. */ public Comments(final String[] openTagComment, final String[] closeTagComment) { this.openTagComment = openTagComment; this.closeTagComment = closeTagComment; } /** * Returns the open tag comments. * * @return The open tag comments. */ public String[] getOpenTagComment() { return this.openTagComment; } /** * Returns the close tag comments. * * @return The close tag comments. */ public String[] getCloseTagComment() { return this.closeTagComment; } /** * Returns a string representation of the set of comments. * * @return A string. */ public String toString() { final StringBuffer b = new StringBuffer(); b.append ("Comments:={open="); if (this.openTagComment == null) { b.append("null"); } else { b.append("{"); for (int i = 0; i < this.openTagComment.length; i++) { b.append("["); b.append(this.openTagComment[i]); b.append("]"); } b.append("}"); } b.append(", close="); if (this.closeTagComment == null) { b.append("null"); } else { b.append("{"); for (int i = 0; i < this.closeTagComment.length; i++) { b.append("["); b.append(this.closeTagComment[i]); b.append("]"); } b.append("}"); } b.append("}"); return b.toString(); } } jcommon-1.0.16/source/org/jfree/xml/generator/model/IgnoredPropertyInfo.java0000644000175000017500000000371711172030703027064 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * IgnoredPropertyInfo.java * ------------------------ * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: IgnoredPropertyInfo.java,v 1.2 2005/10/18 13:32:37 mungady Exp $ * * Changes * ------------------------- * 21.06.2003 : Initial version * */ package org.jfree.xml.generator.model; /** * Represents an ignored property. */ public class IgnoredPropertyInfo extends PropertyInfo { /** * Creates a new instance. * * @param name the property name. */ public IgnoredPropertyInfo(final String name) { super(name, Object.class); } } jcommon-1.0.16/source/org/jfree/xml/generator/model/PropertyInfo.java0000644000175000017500000001230611172030703025546 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * PropertyInfo.java * ----------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: PropertyInfo.java,v 1.2 2005/10/18 13:32:37 mungady Exp $ * * Changes * ------- * 21-Jun-2003 : Initial version (TM) * */ package org.jfree.xml.generator.model; /** * Information about a property. */ public class PropertyInfo extends TypeInfo { /** Preserve? */ private boolean preserve; /** Is there a read method available? */ private boolean readMethodAvailable; /** Is there a write method available? */ private boolean writeMethodAvailable; /** The property type - indicates how the property is described in XML. */ private PropertyType propertyType; /** The XML name. */ private String xmlName; /** The XML handler. */ private String xmlHandler; /** * Creates a new info object for a property. * * @param name the property name. * @param type the class. */ public PropertyInfo(final String name, final Class type) { super(name, type); this.propertyType = PropertyType.ELEMENT; } /** * Returns the preserve flag. * * @return the preserve flag. */ public boolean isPreserve() { return this.preserve; } /** * Sets the preserve flag. * * @param preserve the preserve flag. */ public void setPreserve(final boolean preserve) { this.preserve = preserve; } /** * Returns the property type. This describes how the property is handled in XML. * * @return the property type. */ public PropertyType getPropertyType() { return this.propertyType; } /** * Sets the property type. * * @param propertyType the type (null not permitted). */ public void setPropertyType(final PropertyType propertyType) { if (propertyType == null) { throw new NullPointerException(); } this.propertyType = propertyType; } /** * Returns the XML handler. * * @return the XML handler. */ public String getXmlHandler() { return this.xmlHandler; } /** * Sets the XML handler. * * @param xmlHandler the fully qualified class name for the attribute handler. */ public void setXmlHandler(final String xmlHandler) { this.xmlHandler = xmlHandler; } /** * Returns the XML name. * * @return the XML name. */ public String getXmlName() { return this.xmlName; } /** * Sets the XML name. * * @param xmlName the XML name. */ public void setXmlName(final String xmlName) { this.xmlName = xmlName; } /** * Returns true if there is a read method available, and false * otherwise. * * @return a boolean. */ public boolean isReadMethodAvailable() { return this.readMethodAvailable; } /** * Sets a flag indicating whether or not there is a read method for this property. * * @param readMethodAvailable the new value of the flag. */ public void setReadMethodAvailable(final boolean readMethodAvailable) { this.readMethodAvailable = readMethodAvailable; } /** * Returns true if there is a write method available, and false * otherwise. * * @return a boolean. */ public boolean isWriteMethodAvailable() { return this.writeMethodAvailable; } /** * Sets a flag indicating whether or not there is a write method for this property. * * @param writeMethodAvailable the new value of the flag. */ public void setWriteMethodAvailable(final boolean writeMethodAvailable) { this.writeMethodAvailable = writeMethodAvailable; } } jcommon-1.0.16/source/org/jfree/xml/generator/model/DescriptionModel.java0000644000175000017500000001354511172030703026360 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * DescriptionModel.java * --------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DescriptionModel.java,v 1.3 2005/10/18 13:32:37 mungady Exp $ * * Changes * ------- * 21-Jun-2003 : Initial version (TM); * */ package org.jfree.xml.generator.model; import java.util.ArrayList; import java.util.HashMap; import org.jfree.util.Log; /** * A model containing class descriptions. */ public class DescriptionModel { /** The sources. */ private ArrayList sources; /** The classes. */ private ArrayList classes; /** Maps classes to class descriptions. */ private HashMap classesMap; /** The mapping model. */ private MappingModel mappingModel; /** Model comments. */ private Comments modelComments; /** Include comments. */ private HashMap includeComments; /** * Creates a new class description model. */ public DescriptionModel() { this.classes = new ArrayList(); this.classesMap = new HashMap(); this.mappingModel = new MappingModel(); this.sources = new ArrayList(); this.includeComments = new HashMap(); } /** * Adds a class description to the model. * * @param cd the class description. */ public void addClassDescription(final ClassDescription cd) { this.classesMap.put(cd.getObjectClass(), cd); if (!this.classes.contains(cd)) { this.classes.add(cd); } } /** * Removes a class description from the model. * * @param cd the class description. */ public void removeClassDescription(final ClassDescription cd) { this.classesMap.remove(cd.getObjectClass()); this.classes.remove(cd); } /** * Returns a class description. * * @param index the description index (zero-based). * * @return a class description. */ public ClassDescription get(final int index) { return (ClassDescription) this.classes.get(index); } /** * Returns a class description for the given class name. * * @param key the class name. * * @return the class description. */ public ClassDescription get(final Class key) { return (ClassDescription) this.classesMap.get(key); } /** * Returns the number of classes in the model. * * @return the number of classes in the model. */ public int size() { return this.classes.size(); } /** * Returns the mapping model. * * @return the mapping model. */ public MappingModel getMappingModel() { return this.mappingModel; } /** * Adds a source to the model description. * * @param source the source. */ public void addSource(final String source) { this.sources.add(source); } /** * Returns the sources for the model description. * * @return The sources. */ public String[] getSources() { return (String[]) this.sources.toArray(new String[this.sources.size()]); } /** * Removes any class descriptions that are not fully defined. */ public void prune() { final ClassDescription[] cds = (ClassDescription[]) this.classes.toArray(new ClassDescription[0]); for (int i = 0; i < cds.length; i++) { if (cds[i].isUndefined()) { removeClassDescription(cds[i]); Log.debug("Pruned: " + cds[i].getName()); } } } /** * Adds an include comment. * * @param source the source. * @param comments the comments. */ public void addIncludeComment(final String source, final Comments comments) { this.includeComments.put(source, comments); } /** * Returns the include comment for the specified source. * * @param source the source. * * @return The include comment. */ public Comments getIncludeComment(final String source) { return (Comments) this.includeComments.get(source); } /** * Returns the model comments. * * @return The model comments. */ public Comments getModelComments() { return this.modelComments; } /** * Sets the model comments. * * @param modelComments the model comments. */ public void setModelComments(final Comments modelComments) { Log.debug ("Model: Comment set: " + modelComments); this.modelComments = modelComments; } } jcommon-1.0.16/source/org/jfree/xml/generator/model/package.html0000644000175000017500000000030411172030703024517 0ustar twernertwerner Contains the classes describing the class model used in the JFreeChart XML-parser and writer. jcommon-1.0.16/source/org/jfree/xml/generator/model/TypeInfo.java0000644000175000017500000001237511172030703024651 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------- * TypeInfo.java * ------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: TypeInfo.java,v 1.2 2005/10/18 13:32:37 mungady Exp $ * * Changes * ------- * 21.06.2003 : Initial version * */ package org.jfree.xml.generator.model; /** * Retains information about a type. */ public class TypeInfo { /** The type name. */ private String name; /** The class. */ private Class type; /** A flag indicating whether or not the type can take a null value. */ private boolean nullable; /** ??. */ private boolean constrained; /** A description. */ private String description; /** Comments. */ private Comments comments; /** * Creates a new instance. * * @param name the type name (null not permitted). * @param type the class. */ public TypeInfo(final String name, final Class type) { if (name == null) { throw new NullPointerException("Name"); } this.name = name; this.type = type; } /** * Returns the class. * * @return The class. */ public Class getType() { return this.type; } /** * Returns the nullable status. * * @return A boolean. */ public boolean isNullable() { return this.nullable; } /** * Sets the nullable flag. * * @param nullable the flag. */ public void setNullable(final boolean nullable) { this.nullable = nullable; } /** * Returns true if the type is constrained, and false otherwise. * * @return A boolean. */ public boolean isConstrained() { return this.constrained; } /** * Sets the flag that indicates whether or not the type is constrained. * * @param constrained the flag. */ public void setConstrained(final boolean constrained) { this.constrained = constrained; } /** * Returns the type description. * * @return The type description. */ public String getDescription() { return this.description; } /** * Sets the type description. * * @param description the description. */ public void setDescription(final String description) { this.description = description; } /** * Returns the type name. * * @return The type name. */ public String getName() { return this.name; } /** * Returns the comments for this type info. * * @return The comments. */ public Comments getComments() { return this.comments; } /** * Sets the comments for this type info. * * @param comments the comments. */ public void setComments(final Comments comments) { this.comments = comments; } /** * Tests this object for equality with another object. * * @param o the other object. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof TypeInfo)) { return false; } final TypeInfo typeInfo = (TypeInfo) o; if (!this.name.equals(typeInfo.name)) { return false; } if (!this.type.equals(typeInfo.type)) { return false; } return true; } /** * Returns a hash code for this object. * * @return A hash code. */ public int hashCode() { int result; result = this.name.hashCode(); result = 29 * result + this.type.hashCode(); result = 29 * result + (this.nullable ? 1 : 0); result = 29 * result + (this.constrained ? 1 : 0); result = 29 * result + (this.description != null ? this.description.hashCode() : 0); return result; } } jcommon-1.0.16/source/org/jfree/xml/generator/model/ClassDescription.java0000644000175000017500000001626311172030703026365 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * ClassDescription.java * --------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ClassDescription.java,v 1.2 2005/10/18 13:32:37 mungady Exp $ * * Changes * ------- * 21-Jun-2003 : Initial version (TM); * 26-Nov-2003 : Updated header and Javadocs (DG); * */ package org.jfree.xml.generator.model; /** * A description of a Java class. */ public class ClassDescription { /** Storage for info about properties. */ private PropertyInfo[] properties; /** Constructor descriptions. */ private TypeInfo[] constructorDescription; /** The class. */ private Class objectClass; /** A description. */ private String description; /** The register key. */ private String registerKey; /** The super class. */ private Class superClass; /** ??. */ private boolean preserve; /** The comments. */ private Comments comments; /** The source. */ private String source; /** * Creates a new class description. * * @param objectClass the class. */ public ClassDescription(final Class objectClass) { if (objectClass == null) { throw new NullPointerException(); } this.objectClass = objectClass; } /** * Returns the info about properties. * * @return the info about properties. */ public PropertyInfo[] getProperties() { return this.properties; } /** * Sets the info about the class properties. * * @param properties the properties. */ public void setProperties(final PropertyInfo[] properties) { this.properties = properties; } /** * Returns the object's class. * * @return the object's class. */ public Class getObjectClass() { return this.objectClass; } /** * Returns the description. * * @return the description. */ public String getDescription() { return this.description; } /** * Sets the description for the object. * * @param description the description. */ public void setDescription(final String description) { this.description = description; } /** * Returns the class name. * * @return the class name. */ public String getName() { if (getObjectClass() == null) { return null; } return getObjectClass().getName(); } /** * Returns the super class. * * @return the super class. */ public Class getSuperClass() { return this.superClass; } /** * Sets the super class. * * @param superClass the super class. */ public void setSuperClass(final Class superClass) { this.superClass = superClass; } /** * Returns the preserve flag. * * @return a boolean. */ public boolean isPreserve() { return this.preserve; } /** * Sets the preserve flag. * * @param preserve the new value of the flag. */ public void setPreserve(final boolean preserve) { this.preserve = preserve; } /** * Returns the register key. * * @return the register key. */ public String getRegisterKey() { return this.registerKey; } /** * Sets the register key. * * @param registerKey the register key. */ public void setRegisterKey(final String registerKey) { this.registerKey = registerKey; } /** * Returns the constructor descriptions. * * @return the constructor descriptions. */ public TypeInfo[] getConstructorDescription() { return this.constructorDescription; } /** * Sets the constructor description. * * @param constructorDescription the constructor description. */ public void setConstructorDescription(final TypeInfo[] constructorDescription) { this.constructorDescription = constructorDescription; } /** * Returns a property. * * @param name the property name. * * @return a property. */ public PropertyInfo getProperty (final String name) { if (this.properties == null) { return null; } for (int i = 0; i < this.properties.length; i++) { if (this.properties[i].getName().equals(name)) { return this.properties[i]; } } return null; } /** * Returns true if the description is undefined. * * @return a boolean. */ public boolean isUndefined() { if (this.properties != null) { if (this.properties.length > 0) { return false; } } if (isPreserve()) { return false; } if (getRegisterKey() != null) { return false; } if (getConstructorDescription() != null) { if (getConstructorDescription().length > 0) { return false; } } return true; } /** * Returns the comments for the class description. * * @return The comments. */ public Comments getComments() { return this.comments; } /** * Sets the comments for the class description. * * @param comments the comments. */ public void setComments(final Comments comments) { this.comments = comments; } /** * Returns the source for the class description. * * @return The source. */ public String getSource() { return this.source; } /** * Sets the source for the class description. * * @param source the source. */ public void setSource(final String source) { this.source = source; } } jcommon-1.0.16/source/org/jfree/xml/generator/model/KeyDescription.java0000644000175000017500000000504211172030703026041 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * KeyDescription.java * ------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: KeyDescription.java,v 1.2 2005/10/18 13:32:37 mungady Exp $ * * Changes * ------------------------- * 21.06.2003 : Initial version * */ package org.jfree.xml.generator.model; /** * A key description. */ public class KeyDescription { /** The parameters. */ private TypeInfo[] parameters; /** The comments. */ private Comments comments; /** * Creates a new key description instance. * * @param parameters the parameters. */ public KeyDescription(final TypeInfo[] parameters) { this.parameters = parameters; } /** * Returns the parameters. * * @return The parameters. */ public TypeInfo[] getParameters() { return this.parameters; } /** * Returns the comments. * * @return The comments. */ public Comments getComments() { return this.comments; } /** * Sets the comments. * * @param comments the comments. */ public void setComments(final Comments comments) { this.comments = comments; } } jcommon-1.0.16/source/org/jfree/xml/generator/model/ManualMappingInfo.java0000644000175000017500000001002511172030703026447 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * ManualMappingInfo.java * ---------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ManualMappingInfo.java,v 1.2 2005/10/18 13:32:37 mungady Exp $ * * Changes * ------------------------- * 12.11.2003 : Initial version * */ package org.jfree.xml.generator.model; /** * The manual mapping describes, how a certain class is handled in the parser. * This defines the read and write handler implementations to be used to handle * the instantiation or serialisation of the described type. *

* Manual mappings will not be created by the generator, they have to be defined * manually. The parser will print warnings, if the definitions are invalid. *

* Manual mappings will always override automatic mappings. */ public class ManualMappingInfo { /** The base class. */ private Class baseClass; /** The read handler. */ private Class readHandler; /** The write handler. */ private Class writeHandler; /** The comments. */ private Comments comments; /** The source. */ private String source; /** * Creates a new manual mapping instance. * * @param baseClass the base class. * @param readHandler the read handler class. * @param writeHandler the write handler class. */ public ManualMappingInfo(final Class baseClass, final Class readHandler, final Class writeHandler) { this.baseClass = baseClass; this.readHandler = readHandler; this.writeHandler = writeHandler; } /** * Returns the base class. * * @return The base class. */ public Class getBaseClass() { return this.baseClass; } /** * Returns the read handler class. * * @return The read handler class. */ public Class getReadHandler() { return this.readHandler; } /** * Returns the write handler class. * * @return The write handler class. */ public Class getWriteHandler() { return this.writeHandler; } /** * Returns the comments. * * @return The comments. */ public Comments getComments() { return this.comments; } /** * Sets the comments. * * @param comments the comments. */ public void setComments(final Comments comments) { this.comments = comments; } /** * Returns the source. * * @return The source. */ public String getSource() { return this.source; } /** * Sets the source. * * @param source the source. */ public void setSource(final String source) { this.source = source; } } jcommon-1.0.16/source/org/jfree/xml/generator/model/PrintBeanInfo.java0000644000175000017500000001017111172030703025602 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * PrintBeanInfo.java * ------------------ * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: PrintBeanInfo.java,v 1.3 2005/10/18 13:32:37 mungady Exp $ * * Changes * ------- * 21.06.2003 : Initial version (TM); * */ package org.jfree.xml.generator.model; import java.beans.BeanInfo; import java.beans.IndexedPropertyDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; /** * A utility class for printing information about a class. */ public class PrintBeanInfo { private PrintBeanInfo () { } /** * Prints the information for a class. * * @param c the class. */ public static void print (final Class c) { try { System.out.println("Class: " + c.getName()); System.out.println( "========================================================================" ); final BeanInfo bi = Introspector.getBeanInfo(c, c.getSuperclass()); final PropertyDescriptor[] pd = bi.getPropertyDescriptors(); for (int i = 0; i < pd.length; i++) { System.out.println ("Property: " + pd[i].getDisplayName()); System.out.println( "---------------------------------------------------------------------" ); System.out.println (" ( " + pd[i].getShortDescription() + ")"); if (pd[i] instanceof IndexedPropertyDescriptor) { final IndexedPropertyDescriptor id = (IndexedPropertyDescriptor) pd[i]; System.out.println (" - idx-type : " + id.getIndexedPropertyType()); System.out.println (" - idx-read : " + id.getIndexedReadMethod()); System.out.println (" - idx-write : " + id.getIndexedWriteMethod()); } else { System.out.println (" - type : " + pd[i].getPropertyType()); System.out.println (" - read : " + pd[i].getReadMethod()); System.out.println (" - write : " + pd[i].getWriteMethod()); } System.out.println (" - bound : " + pd[i].isBound()); System.out.println (" - constrained: " + pd[i].isConstrained()); } } catch (IntrospectionException ie) { ie.printStackTrace(); } } /** * Entry point for this utility application. * * @param args the class names. * * @throws Exception if there is a problem. */ public static void main(final String[] args) throws Exception { for (int i = 0; i < args.length; i++) { print(Class.forName(args[i])); } } } jcommon-1.0.16/source/org/jfree/xml/generator/model/IndexedPropertyInfo.java0000644000175000017500000000445011172030703027050 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * IndexedPropertyInfo.java * ------------------------ * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: IndexedPropertyInfo.java,v 1.2 2005/10/18 13:32:37 mungady Exp $ * * Changes * ------- * 21.06.2003 : Initial version * */ package org.jfree.xml.generator.model; /** * Indexed property info. */ public class IndexedPropertyInfo extends PropertyInfo { /** The key. */ private KeyDescription key; /** * Creates a new instance. * * @param name the name. * @param type the type. */ public IndexedPropertyInfo(final String name, final Class type) { super(name, type); } /** * Returns the key. * * @return the key. */ public KeyDescription getKey() { return this.key; } /** * Sets the key. * * @param key the key. */ public void setKey(final KeyDescription key) { this.key = key; } } jcommon-1.0.16/source/org/jfree/xml/generator/model/PropertyType.java0000644000175000017500000000575311172030703025604 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * PropertyType.java * ----------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: PropertyType.java,v 1.2 2005/10/18 13:32:37 mungady Exp $ * * Changes * ------- * 12-Nov-2003 : Initial version (TM); * 26-Nov-2003 : Updated header and Javadocs (DG); * */ package org.jfree.xml.generator.model; /** * An enumeration over the defined property types. *

* Attribute types are mapped into xml attributes - this is used for * primitive data or enumeration classes. *

* Element types are used to define complex classes, a new xml tag will * be introduced for every element type. *

* The lookup properties are defined elsewhere and are referenced using * the defined name during the class building process. */ public final class PropertyType { /** A property that is described using an attribute in the XML. */ public static final PropertyType ATTRIBUTE = new PropertyType("ATTRIBUTE"); /** A property that is described using an XML element. */ public static final PropertyType ELEMENT = new PropertyType("ELEMENT"); /** A property that is... */ public static final PropertyType LOOKUP = new PropertyType("LOOKUP"); /** The property type name. */ private final String myName; // for debug only /** * Private constructor prevents new types being created. * * @param name the type name. */ private PropertyType(final String name) { this.myName = name; } /** * Returns a string representing the type. * * @return a string. */ public String toString() { return this.myName; } } jcommon-1.0.16/source/org/jfree/xml/generator/model/MultiplexMappingInfo.java0000644000175000017500000001301011172030703027212 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * MultiplexMappingInfo.java * ------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: MultiplexMappingInfo.java,v 1.2 2005/10/18 13:32:37 mungady Exp $ * * Changes * ------- * 16-Nov-2003 : Initial version * */ package org.jfree.xml.generator.model; import java.util.Arrays; /** * Defines the multiplex entries for a certain base class. Multiplexers are * used to select a specific handler if more than one class will match the * property type. *

* Multiplexers override automatic mappings and can be redefined using manual * mappings. */ public class MultiplexMappingInfo { /** The base class. */ private Class baseClass; /** The type attribute. */ private String typeAttribute; /** The child classes. */ private TypeInfo[] childClasses; /** The comments. */ private Comments comments; /** The source. */ private String source; /** * Creates a new instance for the specified class. * * @param baseClass the base class. */ public MultiplexMappingInfo(final Class baseClass) { this(baseClass, "type"); } /** * Creates a new instance for the specified class. * * @param baseClass the base class (null not permitted). * @param typeAttribute the type attribute (null not permitted). */ public MultiplexMappingInfo(final Class baseClass, final String typeAttribute) { if (baseClass == null) { throw new NullPointerException("BaseClass"); } if (typeAttribute == null) { throw new NullPointerException("TypeAttribute"); } this.baseClass = baseClass; this.typeAttribute = typeAttribute; } /** * Returns the base class. * * @return The base class. */ public Class getBaseClass() { return this.baseClass; } /** * Returns the type attribute. * * @return The type attribute. */ public String getTypeAttribute() { return this.typeAttribute; } /** * Returns the child classes. * * @return The child classes. */ public TypeInfo[] getChildClasses() { return this.childClasses; } /** * Sets the child classes. * * @param childClasses the child classes. */ public void setChildClasses(final TypeInfo[] childClasses) { this.childClasses = childClasses; } /** * Returns the comments. * * @return The comments. */ public Comments getComments() { return this.comments; } /** * Sets the comments. * * @param comments the comments. */ public void setComments(final Comments comments) { this.comments = comments; } /** * Returns the source. * * @return The source. */ public String getSource() { return this.source; } /** * Sets the source. * * @param source the source. */ public void setSource(final String source) { this.source = source; } /** * Tests this object for equality with another object. * * @param o the other object. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof MultiplexMappingInfo)) { return false; } final MultiplexMappingInfo multiplexMappingInfo = (MultiplexMappingInfo) o; if (!this.baseClass.equals(multiplexMappingInfo.baseClass)) { return false; } if (!Arrays.equals(this.childClasses, multiplexMappingInfo.childClasses)) { return false; } if (!this.typeAttribute.equals(multiplexMappingInfo.typeAttribute)) { return false; } return true; } /** * Returns a hash code for this object. * * @return A hash code. */ public int hashCode() { int result; result = this.baseClass.hashCode(); result = 29 * result + this.typeAttribute.hashCode(); return result; } } jcommon-1.0.16/source/org/jfree/xml/generator/model/MappingModel.java0000644000175000017500000001153411172030703025464 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * MappingModel.java * ----------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: MappingModel.java,v 1.3 2005/10/18 13:32:37 mungady Exp $ * * Changes * ------- * 20-Nov-2003 : Initial version * */ package org.jfree.xml.generator.model; import java.util.ArrayList; import java.util.HashMap; import org.jfree.util.Log; /** * A mapping model. */ public class MappingModel { /** Mapping infos. */ private HashMap mappingInfos; /** The manual mappings. */ private ArrayList manualMappings; /** The multiplex mappings. */ private ArrayList multiplexMappings; /** * Creates a new instance. */ public MappingModel() { this.mappingInfos = new HashMap(); this.manualMappings = new ArrayList(); this.multiplexMappings = new ArrayList(); } /** * Returns the multiplex mapping info. * * @return The multiplex mapping info. */ public MultiplexMappingInfo[] getMultiplexMapping() { return (MultiplexMappingInfo[]) this.multiplexMappings.toArray( new MultiplexMappingInfo[this.multiplexMappings.size()] ); } /** * Returns the manual mapping info. * * @return The manual mapping info. */ public ManualMappingInfo[] getManualMapping() { return (ManualMappingInfo[]) this.manualMappings.toArray( new ManualMappingInfo[this.manualMappings.size()] ); } /** * Adds a manual mapping. * * @param mappingInfo the mapping. */ public void addManualMapping(final ManualMappingInfo mappingInfo) { if (!this.mappingInfos.containsKey(mappingInfo.getBaseClass())) { this.manualMappings.add(mappingInfo); this.mappingInfos.put(mappingInfo.getBaseClass(), mappingInfo); } else { final Object o = this.mappingInfos.get(mappingInfo.getBaseClass()); if (o instanceof ManualMappingInfo) { Log.info ("Duplicate manual mapping: " + mappingInfo.getBaseClass()); } else { throw new IllegalArgumentException ("This mapping is already a multiplex mapping."); } } } /** * Adds a multiplex mapping. * * @param mappingInfo the mapping. */ public void addMultiplexMapping(final MultiplexMappingInfo mappingInfo) { if (!this.mappingInfos.containsKey(mappingInfo.getBaseClass())) { this.multiplexMappings.add(mappingInfo); this.mappingInfos.put(mappingInfo.getBaseClass(), mappingInfo); } else { final Object o = this.mappingInfos.get(mappingInfo.getBaseClass()); if (o instanceof ManualMappingInfo) { throw new IllegalArgumentException ("This mapping is already a manual mapping."); } else { Log.info( "Duplicate Multiplex mapping: " + mappingInfo.getBaseClass(), new Exception() ); } } } /** * Returns a multiplex mapping for the specified class. * * @param baseClass the base class. * * @return The mapping. */ public MultiplexMappingInfo lookupMultiplexMapping(final Class baseClass) { final Object o = this.mappingInfos.get(baseClass); if (o instanceof MultiplexMappingInfo) { return (MultiplexMappingInfo) o; } return null; } } jcommon-1.0.16/source/org/jfree/xml/generator/attributehandler.properties0000644000175000017500000000073211172030703026622 0ustar twernertwerner# # Maps the attribute type class to the handler implementation # org.jfree.chart.axis.AxisLocation=org.jfree.chart.xml.attributehandlers.AxisLocationAttributeHandler org.jfree.chart.renderer.ItemLabelAnchor=org.jfree.chart.xml.attributehandlers.ItemLabelAnchorAttributeHandler org.jfree.chart.plot.PlotOrientation=org.jfree.chart.xml.attributehandlers.PlotOrientationAttributeHandler org.jfree.ui.TextAnchor=org.jfree.chart.xml.attributehandlers.TextAnchorAttributeHandler jcommon-1.0.16/source/org/jfree/xml/generator/generator.properties0000644000175000017500000000300711172030703025245 0ustar twernertwerner# # Specifies the directory containing the sources ... sourcedirectory=C:\\Documents and Settings\\sony\\My Documents\\eclipse-SDK-3.0M6-win32\\eclipse\\workspace\\jfreechart-cvs\\ # # Where to generate the definition files ... targetfile=C:\\model.xml # # From where to load the attribute handler definitions... attributedefinition=attributehandler.properties # # The list of base classes we ignore when collecting the sources. # Use this to remove unnecessary references. ignore.baseclass.0=junit.framework.TestCase ignore.baseclass.1=java.util.ResourceBundle ignore.baseclass.2=java.awt.Component ignore.baseclass.3=org.jfree.chart.ChartColor ignore.baseclass.4=org.jfree.chart.ChartFactory ignore.baseclass.5=org.jfree.chart.ChartUtilities ignore.baseclass.6=java.lang.Throwable ignore.baseclass.7=java.util.EventObject ignore.baseclass.8=javax.swing.text.AbstractDocument # # The list of packages we ignore. ignore.package.0=com.keypoint ignore.package.1=org.jfree.xml ignore.package.2=org.jfree.threads ignore.package.3=org.jfree.resources ignore.package.4=org.jfree.util ignore.package.5=org.jfree.layout ignore.package.6=org.jfree.io ignore.package.7=org.jfree.demo ignore.package.8=org.jfree.chart.demo ignore.package.9=org.jfree.chart.event ignore.package.10=org.jfree.chart.junit ignore.package.11=org.jfree.chart.resources ignore.package.12=org.jfree.chart.ui ignore.package.13=org.jfree.data.xml ignore.package.14=org.jfree.chart.servlet ignore.package.15=org.jfree.chart.renderer.junit ignore.package.16=org.jfree.chart.xml jcommon-1.0.16/source/org/jfree/xml/generator/SplittingModelWriter.java0000644000175000017500000002552711172030703026152 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * SplittingModelWriter.java * ------------------------- * (C)opyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: SplittingModelWriter.java,v 1.2 2005/10/18 13:32:20 mungady Exp $ * * Changes * ------------------------- * 12.11.2003 : Initial version * */ package org.jfree.xml.generator; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import org.jfree.io.IOUtils; import org.jfree.util.HashNMap; import org.jfree.util.Log; import org.jfree.xml.generator.model.ClassDescription; import org.jfree.xml.generator.model.DescriptionModel; import org.jfree.xml.generator.model.ManualMappingInfo; import org.jfree.xml.generator.model.MappingModel; import org.jfree.xml.generator.model.MultiplexMappingInfo; import org.jfree.xml.util.ClassModelTags; /** * A model writer that writes to multiple files. */ public class SplittingModelWriter extends ModelWriter { /** ??. */ private HashNMap classDescriptionByPackage; /** The sources. */ private ArrayList sources; /** The target file. */ private File targetFile; /** The file extension. */ private String extension; /** The plain file name. */ private String plainFileName; /** ??. */ private HashNMap manualMappingByPackage; /** ??. */ private HashNMap multiplexMappingByPackage; /** * Creates a new instance. */ public SplittingModelWriter() { super(); } /** * Writes the model to the specified target. * * @param target the target file name. * * @throws IOException if there is an I/O problem. */ public synchronized void write(final String target) throws IOException { final DescriptionModel model = getModel(); this.sources = new ArrayList(Arrays.asList(model.getSources())); this.targetFile = new File(target); this.plainFileName = IOUtils.getInstance().stripFileExtension(this.targetFile.getName()); this.extension = IOUtils.getInstance().getFileExtension(target); // split into classDescriptionByPackage ... this.classDescriptionByPackage = new HashNMap(); for (int i = 0; i < model.size(); i++) { final ClassDescription cd = model.get(i); if (cd.getSource() == null) { final String packageName = getPackage(cd.getObjectClass()); final String includeFileName = this.plainFileName + "-" + packageName + this.extension; this.classDescriptionByPackage.add(includeFileName, cd); } else { this.classDescriptionByPackage.add(cd.getSource(), cd); } } final MappingModel mappingModel = model.getMappingModel(); // split manual mappings into packages ... final ManualMappingInfo[] manualMappings = mappingModel.getManualMapping(); this.manualMappingByPackage = new HashNMap(); for (int i = 0; i < manualMappings.length; i++) { final ManualMappingInfo mapping = manualMappings[i]; if (mapping.getSource() == null) { this.manualMappingByPackage.add("", mapping); } else { this.manualMappingByPackage.add(mapping.getSource(), mapping); } } // split manual mappings into packages ... final MultiplexMappingInfo[] multiplexMappings = mappingModel.getMultiplexMapping(); this.multiplexMappingByPackage = new HashNMap(); for (int i = 0; i < multiplexMappings.length; i++) { final MultiplexMappingInfo mapping = multiplexMappings[i]; if (mapping.getSource() == null) { this.multiplexMappingByPackage.add("", mapping); } else { this.multiplexMappingByPackage.add(mapping.getSource(), mapping); } } final Object[] keys = this.classDescriptionByPackage.keySet().toArray(); for (int i = 0; i < keys.length; i++) { final String includeFileName = (String) keys[i]; // write if not contained in the master file ... if (!includeFileName.equals("")) { writePackageFile(includeFileName); } } writeMasterFile(); this.manualMappingByPackage = null; this.multiplexMappingByPackage = null; this.classDescriptionByPackage = null; this.sources = null; } /** * Writes a file for a package. * * @param includeFileName the name of the file. * * @throws IOException if there is an I/O problem. */ private void writePackageFile(final String includeFileName) throws IOException { final Iterator values = this.classDescriptionByPackage.getAll(includeFileName); final Iterator manualMappings = this.manualMappingByPackage.getAll(includeFileName); final Iterator multiplexMappings = this.multiplexMappingByPackage.getAll(includeFileName); if (!values.hasNext() && !manualMappings.hasNext() && !multiplexMappings.hasNext()) { return; } Log.debug ("Writing included file: " + includeFileName); // the current file need no longer be included manually ... this.sources.remove(includeFileName); final BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( new File(this.targetFile.getParentFile(), includeFileName) ), "UTF-8" ) ); writeXMLHeader(writer); writeStandardComment(writer, getModel().getModelComments()); getWriterSupport().writeTag(writer, ClassModelTags.OBJECTS_TAG); while (values.hasNext()) { final ClassDescription cd = (ClassDescription) values.next(); writeClassDescription(writer, cd); } while (manualMappings.hasNext()) { final ManualMappingInfo mi = (ManualMappingInfo) manualMappings.next(); writeManualMapping(writer, mi); } while (multiplexMappings.hasNext()) { final MultiplexMappingInfo mi = (MultiplexMappingInfo) multiplexMappings.next(); writeMultiplexMapping(writer, mi); } writeCloseComment(writer, getModel().getModelComments()); getWriterSupport().writeCloseTag(writer, ClassModelTags.OBJECTS_TAG); writer.close(); } /** * Returns the name of the package for the given class. This is a * workaround for the classloader behaviour of JDK1.2.2 where no * package objects are created. * * @param c the class for which we search the package. * * @return the name of the package, never null. */ public static String getPackage(final Class c) { final String className = c.getName(); final int idx = className.lastIndexOf('.'); if (idx <= 0) { // the default package return ""; } else { return className.substring(0, idx); } } /** * Writes the master file. * * @throws IOException if there is an I/O problem. */ private void writeMasterFile() throws IOException { Log.debug ("Writing master file: " + this.targetFile); final BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(this.targetFile), "UTF-8") ); writeXMLHeader(writer); writeStandardComment(writer, getModel().getModelComments()); getWriterSupport().writeTag(writer, ClassModelTags.OBJECTS_TAG); for (int i = 0; i < this.sources.size(); i++) { final String includeFileName = (String) this.sources.get(i); if (!includeFileName.equals("")) { writeTag(writer, ClassModelTags.INCLUDE_TAG, ClassModelTags.SOURCE_ATTR, includeFileName, getModel().getIncludeComment(includeFileName)); } } final Object[] keys = this.classDescriptionByPackage.keySet().toArray(); Arrays.sort(keys); for (int i = 0; i < keys.length; i++) { final String includeFileName = (String) keys[i]; if (!includeFileName.equals("")) { writeTag(writer, ClassModelTags.INCLUDE_TAG, ClassModelTags.SOURCE_ATTR, includeFileName, getModel().getIncludeComment(includeFileName)); } } final Iterator values = this.classDescriptionByPackage.getAll(""); while (values.hasNext()) { final ClassDescription cd = (ClassDescription) values.next(); writeClassDescription(writer, cd); } final Iterator manualMappings = this.manualMappingByPackage.getAll(""); while (manualMappings.hasNext()) { final ManualMappingInfo mi = (ManualMappingInfo) manualMappings.next(); writeManualMapping(writer, mi); } final Iterator multiplexMappings = this.multiplexMappingByPackage.getAll(""); while (multiplexMappings.hasNext()) { final MultiplexMappingInfo mi = (MultiplexMappingInfo) multiplexMappings.next(); writeMultiplexMapping(writer, mi); } writeCloseComment(writer, getModel().getModelComments()); getWriterSupport().writeCloseTag(writer, ClassModelTags.OBJECTS_TAG); writer.close(); } } jcommon-1.0.16/source/org/jfree/xml/generator/ModelWriter.java0000644000175000017500000004110111172030703024236 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * ModelWriter.java * ---------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ModelWriter.java,v 1.3 2005/10/18 13:32:20 mungady Exp $ * * Changes * ------------------------- * 21.06.2003 : Initial version * */ package org.jfree.xml.generator; import java.io.IOException; import java.io.Writer; import org.jfree.xml.generator.model.ClassDescription; import org.jfree.xml.generator.model.Comments; import org.jfree.xml.generator.model.DescriptionModel; import org.jfree.xml.generator.model.IgnoredPropertyInfo; import org.jfree.xml.generator.model.ManualMappingInfo; import org.jfree.xml.generator.model.MultiplexMappingInfo; import org.jfree.xml.generator.model.PropertyInfo; import org.jfree.xml.generator.model.PropertyType; import org.jfree.xml.generator.model.TypeInfo; import org.jfree.xml.util.ClassModelTags; import org.jfree.xml.writer.AttributeList; import org.jfree.xml.writer.SafeTagList; import org.jfree.xml.writer.XMLWriterSupport; /** * A model writer. */ public class ModelWriter { /** The tags that can be split. */ private static SafeTagList safeTags; /** * Returns the safe tag list. * * @return The safe tag list. */ public static SafeTagList getSafeTags() { if (safeTags == null) { safeTags = new SafeTagList(); safeTags.add(ClassModelTags.OBJECTS_TAG); safeTags.add(ClassModelTags.OBJECT_TAG); safeTags.add(ClassModelTags.CONSTRUCTOR_TAG); safeTags.add(ClassModelTags.ELEMENT_PROPERTY_TAG); safeTags.add(ClassModelTags.LOOKUP_PROPERTY_TAG); safeTags.add(ClassModelTags.ATTRIBUTE_PROPERTY_TAG); safeTags.add(ClassModelTags.PARAMETER_TAG); safeTags.add(ClassModelTags.INCLUDE_TAG); safeTags.add(ClassModelTags.IGNORED_PROPERTY_TAG); safeTags.add(ClassModelTags.MANUAL_TAG); safeTags.add(ClassModelTags.MAPPING_TAG); safeTags.add(ClassModelTags.TYPE_TAG); } return safeTags; } /** A support class for writing XML tags. */ private XMLWriterSupport writerSupport; /** A model containing class descriptions. */ private DescriptionModel model; /** * Creates a new model writer instance. */ public ModelWriter() { this.writerSupport = new XMLWriterSupport(getSafeTags(), 0); } /** * Returns the model. * * @return The model. */ public DescriptionModel getModel() { return this.model; } /** * Sets the model to be written. * * @param model the model. */ public void setModel(final DescriptionModel model) { this.model = model; } /** * Writes an XML header. * * @param writer the writer. * * @throws IOException if there is an I/O problem. */ public static void writeXMLHeader(final Writer writer) throws IOException { writer.write(""); writer.write(XMLWriterSupport.getLineSeparator()); } /** * Writes a set of comments. * * @param writer the writer. * @param comments a set of comments. * * @throws IOException if there is an I/O problem. */ protected void writeStandardComment(final Writer writer, final Comments comments) throws IOException { if ((comments == null) || (comments.getOpenTagComment() == null)) { writer.write( "" ); writer.write(XMLWriterSupport.getLineSeparator()); } else { writeComment(writer, comments.getOpenTagComment()); } } /** * Writes a sequence of comments. * * @param writer the writer. * @param comments the comments (null ignored). * * @throws IOException if there is an I/O problem. */ protected void writeComment(final Writer writer, final String[] comments) throws IOException { if (comments == null) { return; } for (int i = 0; i < comments.length; i++) { this.writerSupport.indent(writer, XMLWriterSupport.INDENT_ONLY); writer.write(""); writer.write(XMLWriterSupport.getLineSeparator()); } } /** * Writes the open comments from a set of comments. * * @param writer the writer. * @param comments the set of comments. * * @throws IOException if there is an I/O problem. */ protected void writeOpenComment(final Writer writer, final Comments comments) throws IOException { if (comments == null) { return; } if (comments.getOpenTagComment() == null) { return; } writeComment(writer, comments.getOpenTagComment()); } /** * Writes the close comments from a set of comments. * * @param writer the writer. * @param comments the set of comments. * * @throws IOException if there is an I/O problem. */ protected void writeCloseComment(final Writer writer, final Comments comments) throws IOException { if (comments == null) { return; } if (comments.getCloseTagComment() == null) { return; } writeComment(writer, comments.getCloseTagComment()); } /** * Writes a closed (short) tag with eventually nested comments. * * @param writer the writer. * @param tagName the tag name. * @param attributes the attributes. * @param comments the comments. * * @throws IOException if there is an I/O problem. */ protected void writeTag(final Writer writer, final String tagName, final AttributeList attributes, final Comments comments) throws IOException { if (comments == null) { this.writerSupport.writeTag(writer, tagName, attributes, XMLWriterSupport.CLOSE); } else { writeOpenComment(writer, comments); if (comments.getCloseTagComment() != null) { this.writerSupport.writeTag(writer, tagName, attributes, XMLWriterSupport.OPEN); writeCloseComment(writer, comments); this.writerSupport.writeCloseTag(writer, tagName); } else { this.writerSupport.writeTag(writer, tagName, attributes, XMLWriterSupport.CLOSE); } } } /** * Writes a closed (short) tag with eventually nested comments. * * @param writer the writer. * @param tagName the tag name. * @param attribute the attribute name. * @param value the attribute value. * @param comments the comments. * * @throws IOException if there is an I/O problem. */ protected void writeTag(final Writer writer, final String tagName, final String attribute, final String value, final Comments comments) throws IOException { if (comments == null) { this.writerSupport.writeTag(writer, tagName, attribute, value , XMLWriterSupport.CLOSE); } else { writeOpenComment(writer, comments); if (comments.getCloseTagComment() != null) { this.writerSupport.writeTag( writer, tagName, attribute, value, XMLWriterSupport.OPEN ); writeCloseComment(writer, comments); this.writerSupport.writeCloseTag(writer, tagName); } else { this.writerSupport.writeTag( writer, tagName, attribute, value, XMLWriterSupport.CLOSE ); } } } /** * Writes a model to the specified writer. * * @param writer the writer. * * @throws IOException if there is an I/O problem. */ public void write(final Writer writer) throws IOException { writeStandardComment(writer, this.model.getModelComments()); this.writerSupport.writeTag(writer, ClassModelTags.OBJECTS_TAG); final String[] sources = this.model.getSources(); for (int i = 0; i < sources.length; i++) { final Comments comments = this.model.getIncludeComment(sources[i]); writeTag( writer, ClassModelTags.INCLUDE_TAG, ClassModelTags.SOURCE_ATTR, sources[i], comments ); } for (int i = 0; i < this.model.size(); i++) { final ClassDescription cd = this.model.get(i); writeClassDescription(writer, cd); } final ManualMappingInfo[] mappings = getModel().getMappingModel().getManualMapping(); for (int i = 0; i < mappings.length; i++) { final ManualMappingInfo mi = mappings[i]; writeManualMapping(writer, mi); } final MultiplexMappingInfo[] mmappings = getModel().getMappingModel().getMultiplexMapping(); for (int i = 0; i < mmappings.length; i++) { final MultiplexMappingInfo mi = mmappings[i]; writeMultiplexMapping(writer, mi); } writeCloseComment(writer, this.model.getModelComments()); this.writerSupport.writeCloseTag(writer, ClassModelTags.OBJECTS_TAG); } /** * Writes a manual mapping to the XML output. * * @param writer the writer. * @param mi the mapping info. * * @throws IOException if there is an I/O problem. */ protected void writeManualMapping(final Writer writer, final ManualMappingInfo mi) throws IOException { final AttributeList al = new AttributeList(); al.setAttribute(ClassModelTags.CLASS_ATTR, mi.getBaseClass().getName()); al.setAttribute(ClassModelTags.READ_HANDLER_ATTR, mi.getReadHandler().getName()); al.setAttribute(ClassModelTags.WRITE_HANDLER_ATTR, mi.getWriteHandler().getName()); writeTag(writer, ClassModelTags.MANUAL_TAG, al, mi.getComments()); } /** * Writes a multiplex mapping to the XML output. * * @param writer the writer. * @param mi the mapping info. * * @throws IOException if there is an I/O problem. */ protected void writeMultiplexMapping(final Writer writer, final MultiplexMappingInfo mi) throws IOException { final TypeInfo[] tis = mi.getChildClasses(); final AttributeList al = new AttributeList(); al.setAttribute(ClassModelTags.BASE_CLASS_ATTR, mi.getBaseClass().getName()); al.setAttribute(ClassModelTags.TYPE_ATTR, mi.getTypeAttribute()); getWriterSupport().writeTag(writer, ClassModelTags.MAPPING_TAG, al, XMLWriterSupport.OPEN); for (int j = 0; j < tis.length; j++) { final AttributeList tiAttr = new AttributeList(); tiAttr.setAttribute(ClassModelTags.NAME_ATTR, tis[j].getName()); tiAttr.setAttribute(ClassModelTags.CLASS_ATTR, tis[j].getType().getName()); writeTag(writer, ClassModelTags.TYPE_TAG, tiAttr, tis[j].getComments()); } getWriterSupport().writeCloseTag(writer, ClassModelTags.MAPPING_TAG); } /** * Writes a class description. * * @param writer the writer. * @param cd the class description. * * @throws IOException if there is an I/O problem. */ protected void writeClassDescription(final Writer writer, final ClassDescription cd) throws IOException { if (cd.isUndefined()) { return; } final AttributeList al = new AttributeList(); al.setAttribute(ClassModelTags.CLASS_ATTR, cd.getName()); if (cd.getRegisterKey() != null) { al.setAttribute(ClassModelTags.REGISTER_NAMES_ATTR, cd.getRegisterKey()); } if (cd.isPreserve()) { al.setAttribute(ClassModelTags.IGNORE_ATTR, "true"); } this.writerSupport.writeTag(writer, ClassModelTags.OBJECT_TAG, al, XMLWriterSupport.OPEN); final TypeInfo[] constructorInfo = cd.getConstructorDescription(); if (constructorInfo != null && constructorInfo.length != 0) { this.writerSupport.writeTag(writer, ClassModelTags.CONSTRUCTOR_TAG); for (int i = 0; i < constructorInfo.length; i++) { final AttributeList constructorList = new AttributeList(); constructorList.setAttribute( ClassModelTags.CLASS_ATTR, constructorInfo[i].getType().getName() ); constructorList.setAttribute( ClassModelTags.PROPERTY_ATTR, constructorInfo[i].getName() ); writeTag(writer, ClassModelTags.PARAMETER_TAG, constructorList, constructorInfo[i].getComments()); } this.writerSupport.writeCloseTag(writer, ClassModelTags.CONSTRUCTOR_TAG); } final PropertyInfo[] properties = cd.getProperties(); for (int i = 0; i < properties.length; i++) { writePropertyInfo(writer, properties[i]); } this.writerSupport.writeCloseTag(writer, ClassModelTags.OBJECT_TAG); } /** * Writes a property info element. * * @param writer the writer. * @param ipi the property info. * * @throws IOException if there is an I/O problem. */ private void writePropertyInfo(final Writer writer, final PropertyInfo ipi) throws IOException { final AttributeList props = new AttributeList(); props.setAttribute(ClassModelTags.NAME_ATTR, ipi.getName()); if (ipi instanceof IgnoredPropertyInfo) { writeTag(writer, ClassModelTags.IGNORED_PROPERTY_TAG, props, ipi.getComments()); return; } if (ipi.getPropertyType().equals(PropertyType.ATTRIBUTE)) { props.setAttribute(ClassModelTags.ATTRIBUTE_ATTR, ipi.getXmlName()); props.setAttribute(ClassModelTags.ATTRIBUTE_HANDLER_ATTR, ipi.getXmlHandler()); writeTag(writer, ClassModelTags.ATTRIBUTE_PROPERTY_TAG, props, ipi.getComments()); } else if (ipi.getPropertyType().equals(PropertyType.ELEMENT)) { if (ipi.getComments() == null || ipi.getComments().getOpenTagComment() == null) { this.writerSupport.indent(writer, XMLWriterSupport.INDENT_ONLY); writer.write(""); writer.write(System.getProperty("line.separator", "\n")); } props.setAttribute(ClassModelTags.ELEMENT_ATTR, ipi.getXmlName()); writeTag(writer, ClassModelTags.ELEMENT_PROPERTY_TAG, props, ipi.getComments()); } else { props.setAttribute(ClassModelTags.LOOKUP_ATTR, ipi.getXmlName()); writeTag(writer, ClassModelTags.LOOKUP_PROPERTY_TAG, props, ipi.getComments()); } } /** * Returns the writer support object. * * @return The writer support object. */ public XMLWriterSupport getWriterSupport() { return this.writerSupport; } } jcommon-1.0.16/source/org/jfree/xml/generator/DefaultModelReader.java0000644000175000017500000003554511172030703025510 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * DefaultModelReader.java * ----------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DefaultModelReader.java,v 1.2 2005/10/18 13:32:20 mungady Exp $ * * Changes * ------- * 12-Nov-2003 : Initial version (TM); * 26-Nov-2003 : Updated header and Javadocs (DG); * */ package org.jfree.xml.generator; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import org.jfree.io.IOUtils; import org.jfree.xml.generator.model.ClassDescription; import org.jfree.xml.generator.model.Comments; import org.jfree.xml.generator.model.DescriptionModel; import org.jfree.xml.generator.model.IgnoredPropertyInfo; import org.jfree.xml.generator.model.ManualMappingInfo; import org.jfree.xml.generator.model.MultiplexMappingInfo; import org.jfree.xml.generator.model.PropertyInfo; import org.jfree.xml.generator.model.PropertyType; import org.jfree.xml.generator.model.TypeInfo; import org.jfree.xml.util.AbstractModelReader; import org.jfree.xml.util.ObjectDescriptionException; /** * A reader for the class model. */ public class DefaultModelReader extends AbstractModelReader { /** A model containing classes and the corresponding class descriptions. */ private DescriptionModel model; /** The class description under construction. */ private ClassDescription currentClassDescription; /** Information about the class being processed. */ private BeanInfo currentBeanInfo; /** The base URL. */ private URL baseURL; /** The source. */ private String source; /** The multiplex mapping info. */ private MultiplexMappingInfo multiplexInfo; /** The multiplex type info.*/ private ArrayList multiplexTypeInfos; /** Storage for the properties of the current class. */ private ArrayList propertyList; /** Storage for the constructors of the current class. */ private ArrayList constructorList; /** * Creates a new model reader. */ public DefaultModelReader() { super(); } /** * Loads a description model. * * @param file the file name. * * @return A description model. * * @throws IOException if there is an I/O problem. * @throws ObjectDescriptionException if there is a problem reading the object descriptions. */ public synchronized DescriptionModel load(final String file) throws IOException, ObjectDescriptionException { this.model = new DescriptionModel(); this.baseURL = new File (file).toURL(); parseXml(this.baseURL); fillSuperClasses(); return this.model; } /** * Iterates through all the class descriptions in the model, setting the superclass * attribute in all cases where the superclass definitions are contained in the model. */ protected void fillSuperClasses() { for (int i = 0; i < this.model.size(); i++) { final ClassDescription cd = this.model.get(i); final Class parent = cd.getObjectClass().getSuperclass(); if (parent == null) { continue; } final ClassDescription superCD = this.model.get(parent); if (superCD != null) { cd.setSuperClass(superCD.getObjectClass()); } } } /** * Begin processing an object definition element. * * @param className the class name. * @param register the register name (null permitted). * @param ignore ?? * * @return true if the class is available, and false otherwise. */ protected boolean startObjectDefinition(final String className, final String register, final boolean ignore) { final Class c = loadClass(className); if (c == null) { return false; } this.currentClassDescription = new ClassDescription(c); this.currentClassDescription.setPreserve(ignore); this.currentClassDescription.setRegisterKey(register); try { this.currentBeanInfo = Introspector.getBeanInfo(c, Object.class); } catch (IntrospectionException ie) { return false; } this.propertyList = new java.util.ArrayList(); this.constructorList = new java.util.ArrayList(); return true; } /** * Finishes processing an object definition (sets the constructor and property info for the * class description, and adds the class description to the model). * * @throws ObjectDescriptionException if there is a problem with the object description. */ protected void endObjectDefinition() throws ObjectDescriptionException { final PropertyInfo[] pis = (PropertyInfo[]) this.propertyList.toArray(new PropertyInfo[this.propertyList.size()]); this.currentClassDescription.setProperties(pis); final TypeInfo[] tis = (TypeInfo[]) this.constructorList.toArray(new TypeInfo[this.constructorList.size()]); this.currentClassDescription.setConstructorDescription(tis); this.currentClassDescription.setComments (new Comments(getOpenComment(), getCloseComment())); this.currentClassDescription.setSource(this.source); this.model.addClassDescription(this.currentClassDescription); this.propertyList = null; this.currentBeanInfo = null; this.currentClassDescription = null; } /** * Handles the description of an attribute within an object definition. * * @param name the name. * @param attribName the attribute name. * @param handlerClass the fully qualified class name for the attribute handler. * * @throws ObjectDescriptionException if there is a problem with the object description. */ protected void handleAttributeDefinition(final String name, final String attribName, final String handlerClass) throws ObjectDescriptionException { final PropertyInfo propertyInfo = ModelBuilder.getInstance().createSimplePropertyInfo (getPropertyDescriptor(name)); if (propertyInfo == null) { throw new ObjectDescriptionException("Unable to load property " + name); } propertyInfo.setComments(new Comments(getOpenComment(), getCloseComment())); propertyInfo.setPropertyType(PropertyType.ATTRIBUTE); propertyInfo.setXmlName(attribName); propertyInfo.setXmlHandler(handlerClass); this.propertyList.add(propertyInfo); } /** * Handles the constructor definition. * * @param tagName the tag name. * @param parameterClass the parameter class. * * @throws ObjectDescriptionException if there is a problem with the object description. */ protected void handleConstructorDefinition(final String tagName, final String parameterClass) throws ObjectDescriptionException { final Class c = loadClass(parameterClass); if (c == null) { throw new ObjectDescriptionException("Failed to load class " + parameterClass); } final TypeInfo ti = new TypeInfo(tagName, c); ti.setComments(new Comments(getOpenComment(), getCloseComment())); this.constructorList.add (ti); } /** * Handles the description of an element within an object definition. * * @param name the property name. * @param element the element name. * * @throws ObjectDescriptionException if there is a problem with the object description. */ protected void handleElementDefinition(final String name, final String element) throws ObjectDescriptionException { final PropertyInfo propertyInfo = ModelBuilder.getInstance().createSimplePropertyInfo (getPropertyDescriptor(name)); if (propertyInfo == null) { throw new ObjectDescriptionException("Unable to load property " + name); } propertyInfo.setComments(new Comments(getOpenComment(), getCloseComment())); propertyInfo.setPropertyType(PropertyType.ELEMENT); propertyInfo.setXmlName(element); propertyInfo.setXmlHandler(null); this.propertyList.add(propertyInfo); } /** * Handles a lookup definition. * * @param name the name. * @param lookupKey the lookup key. * * @throws ObjectDescriptionException if there is a problem with the object description. */ protected void handleLookupDefinition(final String name, final String lookupKey) throws ObjectDescriptionException { final PropertyInfo propertyInfo = ModelBuilder.getInstance().createSimplePropertyInfo (getPropertyDescriptor(name)); if (propertyInfo == null) { throw new ObjectDescriptionException("Unable to load property " + name); } propertyInfo.setComments(new Comments(getOpenComment(), getCloseComment())); propertyInfo.setPropertyType(PropertyType.LOOKUP); propertyInfo.setXmlName(lookupKey); propertyInfo.setXmlHandler(null); this.propertyList.add(propertyInfo); } /** * Returns a property descriptor for the named property, or null if there is * no descriptor with the given name. * * @param propertyName the property name. * * @return a property descriptor. */ protected PropertyDescriptor getPropertyDescriptor(final String propertyName) { final PropertyDescriptor[] pds = this.currentBeanInfo.getPropertyDescriptors(); for (int i = 0; i < pds.length; i++) { if (pds[i].getName().equals(propertyName)) { return pds[i]; } } return null; } /** * Handles an ignored property. * * @param name the name. */ protected void handleIgnoredProperty(final String name) { final IgnoredPropertyInfo propertyInfo = new IgnoredPropertyInfo(name); propertyInfo.setComments(new Comments(getOpenComment(), getCloseComment())); this.propertyList.add(propertyInfo); } /** * Handles a manual mapping. * * @param className the class name. * @param readHandler the read handler. * @param writeHandler the write handler. * * @return A boolean. * * @throws ObjectDescriptionException if there is a problem with the object description. */ protected boolean handleManualMapping(final String className, final String readHandler, final String writeHandler) throws ObjectDescriptionException { final ManualMappingInfo manualMappingInfo = new ManualMappingInfo(loadClass(className), loadClass(readHandler), loadClass(writeHandler)); manualMappingInfo.setComments(new Comments(getOpenComment(), getCloseComment())); manualMappingInfo.setSource(this.source); this.model.getMappingModel().addManualMapping(manualMappingInfo); return true; } /** * Start a multiplex mapping. * * @param className the class name. * @param typeAttr the type. */ protected void startMultiplexMapping(final String className, final String typeAttr) { this.multiplexInfo = new MultiplexMappingInfo(loadClass(className), typeAttr); this.multiplexInfo.setSource(this.source); this.multiplexTypeInfos = new ArrayList(); } /** * Handles a multiplex mapping. * * @param typeName the type name. * @param className the class name. * * @throws ObjectDescriptionException if there is a problem with the object description. */ protected void handleMultiplexMapping(final String typeName, final String className) throws ObjectDescriptionException { final TypeInfo info = new TypeInfo(typeName, loadClass(className)); info.setComments(new Comments(getOpenComment(), getCloseComment())); this.multiplexTypeInfos.add (info); } /** * Ends a multiplex mapping. * * @throws ObjectDescriptionException if there is a problem with the object description. */ protected void endMultiplexMapping() throws ObjectDescriptionException { final TypeInfo[] typeInfos = (TypeInfo[]) this.multiplexTypeInfos.toArray( new TypeInfo[this.multiplexTypeInfos.size()] ); this.multiplexInfo.setComments(new Comments(getOpenComment(), getCloseComment())); this.multiplexInfo.setChildClasses(typeInfos); this.model.getMappingModel().addMultiplexMapping(this.multiplexInfo); this.multiplexInfo = null; } /** * Starts include handling. * * @param resource the URL. */ protected void startIncludeHandling(final URL resource) { this.source = IOUtils.getInstance().createRelativeURL(resource, this.baseURL); this.model.addSource(this.source); this.model.addIncludeComment( this.source, new Comments(getOpenComment(), getCloseComment()) ); } /** * Ends include handling. */ protected void endIncludeHandling() { this.source = ""; } /** * Starts the root document. */ protected void startRootDocument() { this.source = ""; } /** * Ends the root document. */ protected void endRootDocument() { this.model.setModelComments(new Comments(getOpenComment(), getCloseComment())); } } jcommon-1.0.16/source/org/jfree/xml/ElementDefinitionHandler.java0000644000175000017500000000652311172030703024724 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------- * ElementDefinitionHandler.java * ---------------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ElementDefinitionHandler.java,v 1.4 2005/11/14 10:57:22 mungady Exp $ * * Changes * ------- * 21-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A element definition handler. The element definition handler is used to * represent a certain parser state. The current state is set in the parser * using the pushFactory() method. The parser forwards any incoming SAXEvent * to the current handler, until the handler is removed with popFactory(). * * @author Thomas Morgner */ public interface ElementDefinitionHandler { /** * Callback to indicate that an XML element start tag has been read by the parser. * * @param tagName the tag name. * @param attrs the attributes. * * @throws SAXException if a parser error occurs or the validation failed. */ public void startElement(String tagName, Attributes attrs) throws SAXException; /** * Callback to indicate that some character data has been read. * * @param ch the character array. * @param start the start index for the characters. * @param length the length of the character sequence. * @throws SAXException if a parser error occurs or the validation failed. */ public void characters(char[] ch, int start, int length) throws SAXException; /** * Callback to indicate that an XML element end tag has been read by the parser. * * @param tagName the tag name. * * @throws SAXException if a parser error occurs or the validation failed. */ public void endElement(String tagName) throws SAXException; /** * Returns the parser. * * @return The parser. */ public Parser getParser(); } jcommon-1.0.16/source/org/jfree/xml/AbstractElementDefinitionHandler.java0000644000175000017500000000675711172030703026421 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------------- * AbstractElementDefinitionHandler.java * ------------------------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AbstractElementDefinitionHandler.java,v 1.3 2005/10/18 13:25:44 mungady Exp $ * * Changes * ------------------------- * 23.06.2003 : Initial version * */ package org.jfree.xml; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * An abstract element definition handler. * * @author Thomas Morgner */ public abstract class AbstractElementDefinitionHandler implements ElementDefinitionHandler { /** A parser. */ private Parser parser; /** * Creates a new handler. * * @param parser the parser. */ public AbstractElementDefinitionHandler(final Parser parser) { this.parser = parser; } /** * Callback to indicate that an XML element start tag has been read by the parser. * * @param tagName the tag name. * @param attrs the attributes. * * @throws SAXException if a parser error occurs or the validation failed. */ public void startElement(final String tagName, final Attributes attrs) throws SAXException { // nothing required } /** * Callback to indicate that some character data has been read. * * @param ch the character array. * @param start the start index for the characters. * @param length the length of the character sequence. * @throws SAXException if a parser error occurs or the validation failed. */ public void characters(final char[] ch, final int start, final int length) throws SAXException { // nothing required } /** * Callback to indicate that an XML element end tag has been read by the parser. * * @param tagName the tag name. * * @throws SAXException if a parser error occurs or the validation failed. */ public void endElement(final String tagName) throws SAXException { // nothing required } /** * Returns the parser. * * @return The parser. */ public Parser getParser() { return this.parser; } } jcommon-1.0.16/source/org/jfree/xml/writer/0000755000175000017500000000000011351753320020475 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/xml/writer/coretypes/0000755000175000017500000000000011351753320022512 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/xml/writer/coretypes/GenericWriteHandler.java0000644000175000017500000001225711172030703027243 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * GenericWriteHandler.java * ------------------------ * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: GenericWriteHandler.java,v 1.6 2005/11/16 15:58:41 taqua Exp $ * * Changes * ------- * 23-Sep-2003 : Initial version (TM); * 23-Dec-2003 : Added missing Javadocs (DG); * */ package org.jfree.xml.writer.coretypes; import java.io.IOException; import java.util.ArrayList; import org.jfree.util.Log; import org.jfree.xml.util.AttributeDefinition; import org.jfree.xml.util.GenericObjectFactory; import org.jfree.xml.util.ObjectDescriptionException; import org.jfree.xml.util.PropertyDefinition; import org.jfree.xml.writer.AbstractXmlWriteHandler; import org.jfree.xml.writer.AttributeList; import org.jfree.xml.writer.RootXmlWriteHandler; import org.jfree.xml.writer.XMLWriter; import org.jfree.xml.writer.XMLWriterException; /** * A handler for writing generic objects. */ public class GenericWriteHandler extends AbstractXmlWriteHandler { private GenericObjectFactory factory; /** * Creates a new handler. * * @param factory the object factory. */ public GenericWriteHandler(final GenericObjectFactory factory) { this.factory = factory; } /** * Performs the writing of a generic object. * * @param tagName the tag name. * @param object the generic object. * @param writer the writer. * @param mPlexAttribute ??. * @param mPlexValue ??. * * @throws IOException if there is an I/O error. * @throws XMLWriterException if there is a writer error. */ public void write(final String tagName, final Object object, final XMLWriter writer, final String mPlexAttribute, final String mPlexValue) throws IOException, XMLWriterException { try { this.factory.readProperties(object); final AttributeList attributes = new AttributeList(); if (mPlexAttribute != null) { attributes.setAttribute(mPlexAttribute, mPlexValue); } final AttributeDefinition[] attribDefs = this.factory.getAttributeDefinitions(); final ArrayList properties = new ArrayList(); for (int i = 0; i < attribDefs.length; i++) { final AttributeDefinition adef = attribDefs[i]; final String pName = adef.getAttributeName(); final Object propValue = this.factory.getProperty(adef.getPropertyName()); if (propValue != null) { Log.debug( "Here: " + this.factory.getBaseClass() + " -> " + adef.getPropertyName() ); final String value = adef.getHandler().toAttributeValue(propValue); if (value != null) { attributes.setAttribute(pName, value); } } properties.add(adef.getPropertyName()); } writer.writeTag(tagName, attributes, false); writer.startBlock(); final PropertyDefinition[] propertyDefs = this.factory.getPropertyDefinitions(); final RootXmlWriteHandler rootHandler = getRootHandler(); for (int i = 0; i < propertyDefs.length; i++) { final PropertyDefinition pDef = propertyDefs[i]; final String elementName = pDef.getElementName(); rootHandler.write (elementName, this.factory.getProperty(pDef.getPropertyName()), this.factory.getTypeForTagName(elementName), writer); } writer.endBlock(); writer.writeCloseTag(tagName); } catch (ObjectDescriptionException ode) { Log.warn ("Unable to write element", ode); throw new IOException(ode.getMessage()); } } } jcommon-1.0.16/source/org/jfree/xml/writer/coretypes/ColorWriteHandler.java0000644000175000017500000000714111172030703026741 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * ColorWriteHandler.java * ---------------------- * (C) Copyright 2003-2005, by Object Refinery Limited and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ColorWriteHandler.java,v 1.3 2005/10/18 13:35:21 mungady Exp $ * * Changes (from 23-Dec-2003) * -------------------------- * 23-Dec-2003 : Added standard header and Javadocs (DG); * */ package org.jfree.xml.writer.coretypes; import java.awt.Color; import java.io.IOException; import org.jfree.xml.writer.AbstractXmlWriteHandler; import org.jfree.xml.writer.AttributeList; import org.jfree.xml.writer.XMLWriter; import org.jfree.xml.writer.XMLWriterException; /** * A handler for writing a {@link Color} object. */ public class ColorWriteHandler extends AbstractXmlWriteHandler { /** * Default constructor. */ public ColorWriteHandler() { super(); } /** * Performs the writing of a {@link Color} object. * * @param tagName the tag name. * @param object the {@link Color} object. * @param writer the writer. * @param mPlexAttribute ??. * @param mPlexValue ??. * * @throws IOException if there is an I/O error. * @throws XMLWriterException if there is a writer error. */ public void write(final String tagName, final Object object, final XMLWriter writer, final String mPlexAttribute, final String mPlexValue) throws IOException, XMLWriterException { final Color color = (Color) object; final AttributeList attribs = new AttributeList(); if (mPlexAttribute != null) { attribs.setAttribute(mPlexAttribute, mPlexValue); } attribs.setAttribute("value", encodeColor(color)); if (color.getAlpha() != 255) { attribs.setAttribute("alpha", String.valueOf(color.getAlpha())); } writer.writeTag(tagName, attribs, true); } private String encodeColor(final Color color) { return "#" + encodeInt(color.getRed()) + encodeInt(color.getGreen()) + encodeInt(color.getBlue()); } private String encodeInt(final int i) { final String retVal = Integer.toHexString(i); if (retVal.length() == 1) { return "0" + retVal; } else { return retVal; } } } jcommon-1.0.16/source/org/jfree/xml/writer/coretypes/Point2DWriteHandler.java0000644000175000017500000000631411172030703027143 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * Point2DWriteHandler.java * ------------------------ * (C) Copyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Point2DWriteHandler.java,v 1.3 2005/10/18 13:35:21 mungady Exp $ * * Changes (from 25-Nov-2003) * -------------------------- * 25-Nov-2003 : Added standard header (DG); * */ package org.jfree.xml.writer.coretypes; import java.awt.geom.Point2D; import java.io.IOException; import org.jfree.xml.writer.AbstractXmlWriteHandler; import org.jfree.xml.writer.AttributeList; import org.jfree.xml.writer.XMLWriter; import org.jfree.xml.writer.XMLWriterException; /** * A handler for writing a {@link Point2D} object. */ public class Point2DWriteHandler extends AbstractXmlWriteHandler { /** * Default constructor. */ public Point2DWriteHandler() { super(); } /** * Performs the writing of a {@link Point2D} object. * * @param tagName the tag name. * @param object the {@link Point2D} object. * @param writer the writer. * @param mPlexAttribute ??. * @param mPlexValue ??. * * @throws IOException if there is an I/O error. * @throws XMLWriterException if there is a writer error. */ public void write(final String tagName, final Object object, final XMLWriter writer, final String mPlexAttribute, final String mPlexValue) throws IOException, XMLWriterException { final Point2D point = (Point2D) object; final double x = point.getX(); final double y = point.getY(); final AttributeList attribs = new AttributeList(); if (mPlexAttribute != null) { attribs.setAttribute(mPlexAttribute, mPlexValue); } attribs.setAttribute("x", String.valueOf(x)); attribs.setAttribute("y", String.valueOf(y)); writer.writeTag(tagName, attribs, true); } } jcommon-1.0.16/source/org/jfree/xml/writer/coretypes/InsetsWriteHandler.java0000644000175000017500000000646711172030703027142 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * InsetsWriteHandler.java * ----------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: InsetsWriteHandler.java,v 1.5 2005/10/18 13:35:21 mungady Exp $ * * Changes * ------- * 22-Nov-2003 : Initial version (TM); * 23-Dec-2003 : Added missing Javadocs (DG); * */ package org.jfree.xml.writer.coretypes; import java.awt.Insets; import java.io.IOException; import org.jfree.xml.writer.AbstractXmlWriteHandler; import org.jfree.xml.writer.AttributeList; import org.jfree.xml.writer.XMLWriter; import org.jfree.xml.writer.XMLWriterException; import org.jfree.xml.writer.XMLWriterSupport; /** * A handler for writing an {@link Insets} object. */ public class InsetsWriteHandler extends AbstractXmlWriteHandler { /** * Default constructor. */ public InsetsWriteHandler() { super(); } /** * Performs the writing of a {@link Insets} object. * * @param tagName the tag name. * @param object the {@link Insets} object. * @param writer the writer. * @param mPlexAttribute ??. * @param mPlexValue ??. * * @throws IOException if there is an I/O error. * @throws XMLWriterException if there is a writer error. */ public void write(final String tagName, final Object object, final XMLWriter writer, final String mPlexAttribute, final String mPlexValue) throws IOException, XMLWriterException { final AttributeList attribs = new AttributeList(); if (mPlexAttribute != null) { attribs.setAttribute(mPlexAttribute, mPlexValue); } final Insets i = (Insets) object; attribs.setAttribute("top", String.valueOf(i.top)); attribs.setAttribute("left", String.valueOf(i.left)); attribs.setAttribute("bottom", String.valueOf(i.bottom)); attribs.setAttribute("right", String.valueOf(i.right)); writer.writeTag(tagName, attribs, XMLWriterSupport.CLOSE); } } jcommon-1.0.16/source/org/jfree/xml/writer/coretypes/FontWriteHandler.java0000644000175000017500000000675611172030703026604 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * FontWriteHandler.java * --------------------- * (C) Copyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: FontWriteHandler.java,v 1.3 2005/10/18 13:35:21 mungady Exp $ * * Changes (from 25-Nov-2003) * -------------------------- * 25-Nov-2003 : Added standard header (DG); * */ package org.jfree.xml.writer.coretypes; import java.awt.Font; import java.io.IOException; import org.jfree.xml.writer.AbstractXmlWriteHandler; import org.jfree.xml.writer.AttributeList; import org.jfree.xml.writer.XMLWriter; import org.jfree.xml.writer.XMLWriterException; /** * A handler for writing {@link Font} objects. */ public class FontWriteHandler extends AbstractXmlWriteHandler { /** * Default constructor. */ public FontWriteHandler() { super(); } /** * Performs the writing of a {@link Font} object. * * @param tagName the tag name. * @param object the {@link Font} object. * @param writer the writer. * @param mPlexAttribute ??. * @param mPlexValue ??. * * @throws IOException if there is an I/O error. * @throws XMLWriterException if there is a writer error. */ public void write(final String tagName, final Object object, final XMLWriter writer, final String mPlexAttribute, final String mPlexValue) throws IOException, XMLWriterException { final Font font = (Font) object; final AttributeList attribs = new AttributeList(); if (mPlexAttribute != null) { attribs.setAttribute(mPlexAttribute, mPlexValue); } attribs.setAttribute("family", font.getFamily()); attribs.setAttribute("size", String.valueOf(font.getSize())); attribs.setAttribute("style", String.valueOf(getFontStyle(font))); writer.writeTag(tagName, attribs, true); } private String getFontStyle(final Font font) { if (font.isBold() && font.isItalic()) { return "bold-italic"; } if (font.isBold()) { return "bold"; } if (font.isItalic()) { return "italic"; } return "plain"; } } jcommon-1.0.16/source/org/jfree/xml/writer/coretypes/package.html0000644000175000017500000000020511172030703024762 0ustar twernertwerner Writers for some core classes. jcommon-1.0.16/source/org/jfree/xml/writer/coretypes/GradientPaintWriteHandler.java0000644000175000017500000000706411172030703030420 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------ * GradientPaintWriteHandler.java * ------------------------------ * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: GradientPaintWriteHandler.java,v 1.4 2005/10/18 13:35:21 mungady Exp $ * * Changes * ------- * 12-Nov-2003 : Initial version (TM); * 23-Dec-2003 : Updated header (DG); * */ package org.jfree.xml.writer.coretypes; import java.awt.Color; import java.awt.GradientPaint; import java.awt.geom.Point2D; import java.io.IOException; import org.jfree.xml.writer.AbstractXmlWriteHandler; import org.jfree.xml.writer.RootXmlWriteHandler; import org.jfree.xml.writer.XMLWriter; import org.jfree.xml.writer.XMLWriterException; /** * A handler for writing {@link GradientPaint} objects. */ public class GradientPaintWriteHandler extends AbstractXmlWriteHandler { /** * Default constructor. */ public GradientPaintWriteHandler() { super(); } /** * Performs the writing of a {@link GradientPaint} object. * * @param tagName the tag name. * @param object the {@link GradientPaint} object. * @param writer the writer. * @param mPlexAttribute ??. * @param mPlexValue ??. * * @throws IOException if there is an I/O error. * @throws XMLWriterException if there is a writer error. */ public void write(final String tagName, final Object object, final XMLWriter writer, final String mPlexAttribute, final String mPlexValue) throws IOException, XMLWriterException { final GradientPaint paint = (GradientPaint) object; writer.writeTag(tagName, mPlexAttribute, mPlexValue, false); writer.startBlock(); final RootXmlWriteHandler rootHandler = getRootHandler(); rootHandler.write("color1", paint.getColor1(), Color.class, writer); writer.allowLineBreak(); rootHandler.write("color2", paint.getColor2(), Color.class, writer); writer.allowLineBreak(); rootHandler.write("point1", paint.getPoint1(), Point2D.class, writer); writer.allowLineBreak(); rootHandler.write("point2", paint.getPoint2(), Point2D.class, writer); writer.endBlock(); writer.writeCloseTag(tagName); } } jcommon-1.0.16/source/org/jfree/xml/writer/coretypes/Rectangle2DWriteHandler.java0000644000175000017500000000666711172030703027771 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------- * Rectangle2DWriteHandler.java * ---------------------------- * (C) Copyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Rectangle2DWriteHandler.java,v 1.3 2005/10/18 13:35:21 mungady Exp $ * * Changes (from 25-Nov-2003) * -------------------------- * 25-Nov-2003 : Added standard header (DG); * */ package org.jfree.xml.writer.coretypes; import java.awt.geom.Rectangle2D; import java.io.IOException; import org.jfree.xml.writer.AbstractXmlWriteHandler; import org.jfree.xml.writer.AttributeList; import org.jfree.xml.writer.XMLWriter; import org.jfree.xml.writer.XMLWriterException; /** * A handler for writing a {@link Rectangle2D} object. */ public class Rectangle2DWriteHandler extends AbstractXmlWriteHandler { /** * Default constructor. */ public Rectangle2DWriteHandler() { super(); } /** * Performs the writing of a single object. * * @param tagName the tag name. * @param object the {@link Rectangle2D} object. * @param writer the writer. * @param mPlexAttribute ??. * @param mPlexValue ??. * * @throws IOException if there is an I/O error. * @throws XMLWriterException if there is a writer error. */ public void write(final String tagName, final Object object, final XMLWriter writer, final String mPlexAttribute, final String mPlexValue) throws IOException, XMLWriterException { final Rectangle2D rect = (Rectangle2D) object; final double x = rect.getX(); final double y = rect.getY(); final double w = rect.getWidth(); final double h = rect.getHeight(); final AttributeList attribs = new AttributeList(); if (mPlexAttribute != null) { attribs.setAttribute(mPlexAttribute, mPlexValue); } attribs.setAttribute("x", String.valueOf(x)); attribs.setAttribute("y", String.valueOf(y)); attribs.setAttribute("width", String.valueOf(w)); attribs.setAttribute("height", String.valueOf(h)); writer.writeTag(tagName, attribs, true); } } jcommon-1.0.16/source/org/jfree/xml/writer/coretypes/RenderingHintsWriteHandler.java0000644000175000017500000001075611172030703030614 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * RenderingHintsHandler.java * -------------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: RenderingHintsWriteHandler.java,v 1.5 2005/10/18 13:35:21 mungady Exp $ * * Changes * ------------------------- * 22.11.2003 : Initial version * */ package org.jfree.xml.writer.coretypes; import java.awt.RenderingHints; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Iterator; import org.jfree.util.Log; import org.jfree.xml.writer.AbstractXmlWriteHandler; import org.jfree.xml.writer.AttributeList; import org.jfree.xml.writer.XMLWriter; import org.jfree.xml.writer.XMLWriterException; import org.jfree.xml.writer.XMLWriterSupport; /** * A handler for writing a {@link RenderingHints} object. */ public class RenderingHintsWriteHandler extends AbstractXmlWriteHandler { /** * Default constructor. */ public RenderingHintsWriteHandler() { super(); } /** * Performs the writing of a single object. * * @param tagName the tag name. * @param object the object. * @param writer the writer. * @param mPlexAttribute ??. * @param mPlexValue ??. * * @throws IOException if there is an I/O error. * @throws XMLWriterException if there is a writer problem. */ public void write(final String tagName, final Object object, final XMLWriter writer, final String mPlexAttribute, final String mPlexValue) throws IOException, XMLWriterException { writer.writeTag(tagName, mPlexAttribute, mPlexValue, XMLWriterSupport.OPEN); writer.allowLineBreak(); final RenderingHints hints = (RenderingHints) object; final Iterator it = hints.keySet().iterator(); while (it.hasNext()) { final RenderingHints.Key key = (RenderingHints.Key) it.next(); final String keyname = hintFieldToString(key); final String value = hintFieldToString(hints.get(key)); final AttributeList attribs = new AttributeList(); attribs.setAttribute("key", keyname); attribs.setAttribute("value", value); writer.writeTag("entry", attribs, XMLWriterSupport.CLOSE); writer.allowLineBreak(); } writer.writeCloseTag(tagName); writer.allowLineBreak(); } private String hintFieldToString(final Object o) { final Field[] fields = RenderingHints.class.getFields(); for (int i = 0; i < fields.length; i++) { final Field f = fields[i]; if (Modifier.isFinal(f.getModifiers()) && Modifier.isPublic(f.getModifiers()) && Modifier.isStatic(f.getModifiers())) { try { final Object value = f.get(null); if (o.equals(value)) { return f.getName(); } } catch (Exception e) { Log.info ("Unable to write RenderingHint", e); } } } throw new IllegalArgumentException("Invalid value given"); } } jcommon-1.0.16/source/org/jfree/xml/writer/coretypes/ListWriteHandler.java0000644000175000017500000000616711172030703026605 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * ListWriteHandler.java * --------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ListWriteHandler.java,v 1.4 2005/10/18 13:35:21 mungady Exp $ * * Changes * ------- * 22-Nov-2003 : Initial version * */ package org.jfree.xml.writer.coretypes; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.jfree.xml.writer.AbstractXmlWriteHandler; import org.jfree.xml.writer.XMLWriter; import org.jfree.xml.writer.XMLWriterException; import org.jfree.xml.writer.XMLWriterSupport; /** * A handler for writing a {@link List} object. */ public class ListWriteHandler extends AbstractXmlWriteHandler { /** * Performs the writing of a {@link List} object. * * @param tagName the tag name. * @param object the {@link List} object. * @param writer the writer. * @param mPlexAttribute ??. * @param mPlexValue ??. * * @throws IOException if there is an I/O error. * @throws XMLWriterException if there is a writer error. */ public void write(final String tagName, final Object object, final XMLWriter writer, final String mPlexAttribute, final String mPlexValue) throws IOException, XMLWriterException { writer.writeTag(tagName, mPlexAttribute, mPlexValue, XMLWriterSupport.OPEN); final List list = (List) object; final Iterator it = list.iterator(); while (it.hasNext()) { final Object value = it.next(); if (value == null) { writer.writeTag("null", XMLWriterSupport.CLOSE); } else { getRootHandler().write("object", value, Object.class, writer); } } writer.writeCloseTag(tagName); } } jcommon-1.0.16/source/org/jfree/xml/writer/coretypes/BasicStrokeWriteHandler.java0000644000175000017500000001100011172030703030061 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------- * BasicStrokeWriteHandler.java * ---------------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: BasicStrokeWriteHandler.java,v 1.3 2005/10/18 13:35:21 mungady Exp $ * * Changes * ------- * 12-Nov-2003 : Initial version (TM); * 25-Nov-2003 : Updated header (DG); * */ package org.jfree.xml.writer.coretypes; import java.awt.BasicStroke; import java.io.IOException; import org.jfree.xml.writer.AbstractXmlWriteHandler; import org.jfree.xml.writer.AttributeList; import org.jfree.xml.writer.XMLWriter; import org.jfree.xml.writer.XMLWriterException; /** * A handler that can write the XML description for a {@link BasicStroke} object. */ public class BasicStrokeWriteHandler extends AbstractXmlWriteHandler { /** * Creates a new handler. */ public BasicStrokeWriteHandler() { super(); } /** * Performs the writing of a single object. * * @param tagName the tag name. * @param object the object ({@link BasicStroke} expected). * @param writer the writer. * @param mPlexAttribute ?? * @param mPlexValue ?? * * @throws IOException if there is an I/O problem. * @throws XMLWriterException if there is a problem with the writer. */ public void write(final String tagName, final Object object, final XMLWriter writer, final String mPlexAttribute, final String mPlexValue) throws IOException, XMLWriterException { final BasicStroke stroke = (BasicStroke) object; final float[] dashArray = stroke.getDashArray(); final float dashPhase = stroke.getDashPhase(); final int endCap = stroke.getEndCap(); final int lineJoin = stroke.getLineJoin(); final float lineWidth = stroke.getLineWidth(); final float miterLimit = stroke.getMiterLimit(); final AttributeList attribs = new AttributeList(); if (mPlexAttribute != null) { attribs.setAttribute(mPlexAttribute, mPlexValue); } attribs.setAttribute("type", "basic"); attribs.setAttribute("endCap", String.valueOf(endCap)); attribs.setAttribute("lineJoin", String.valueOf(lineJoin)); attribs.setAttribute("lineWidth", String.valueOf(lineWidth)); attribs.setAttribute("miterLimit", String.valueOf(miterLimit)); if (dashArray != null) { attribs.setAttribute("dashArray", toString(dashArray)); attribs.setAttribute("dashPhase", String.valueOf(dashPhase)); } writer.writeTag(tagName, attribs, true); } /** * A utility method that converts a dash array (from a {@link BasicStroke} object) to * a {@link String}. * * @param dashArray the dash array. * * @return a {@link String} representing the dash array. */ private String toString(final float[] dashArray) { final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < dashArray.length; i++) { final float f = dashArray[i]; if (i != 0) { buffer.append(','); } buffer.append(f); } return buffer.toString(); } } jcommon-1.0.16/source/org/jfree/xml/writer/AbstractXmlWriteHandler.java0000644000175000017500000000474711172030703026103 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------- * AbstractXmlWriteHandler.java * ---------------------------- * (C) Copyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AbstractXmlWriteHandler.java,v 1.3 2005/10/18 13:35:06 mungady Exp $ * * Changes (from 26-Nov-2003) * -------------------------- * 26-Nov-2003 : Added standard header and Javadocs (DG); * */ package org.jfree.xml.writer; /** * A base class for implementing a handler that writes the XML for an object of a particular * class. */ public abstract class AbstractXmlWriteHandler implements XmlWriteHandler { /** The root handler. */ private RootXmlWriteHandler rootHandler; /** * Creates a new handler. */ public AbstractXmlWriteHandler() { super(); } /** * Returns the root handler. * * @return the root handler. */ public RootXmlWriteHandler getRootHandler() { return this.rootHandler; } /** * Sets the root handler. * * @param rootHandler the root handler. */ public void setRootHandler(final RootXmlWriteHandler rootHandler) { this.rootHandler = rootHandler; } } jcommon-1.0.16/source/org/jfree/xml/writer/XMLWriterSupport.java0000644000175000017500000003124311172030703024567 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * XMLWriterSupport.java * --------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: XMLWriterSupport.java,v 1.6 2005/11/08 14:35:52 mungady Exp $ * * Changes * ------- * 21-Jun-2003 : Initial version (TM); * 26-Nov-2003 : Updated Javadocs (DG); * */ package org.jfree.xml.writer; import java.io.IOException; import java.io.Writer; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; /** * A support class for writing XML files. * * @author Thomas Morgner */ public class XMLWriterSupport { /** A constant for controlling the indent function. */ public static final int OPEN_TAG_INCREASE = 1; /** A constant for controlling the indent function. */ public static final int CLOSE_TAG_DECREASE = 2; /** A constant for controlling the indent function. */ public static final int INDENT_ONLY = 3; /** A constant for close. */ public static final boolean CLOSE = true; /** A constant for open. */ public static final boolean OPEN = false; /** The line separator. */ private static String lineSeparator; /** A list of safe tags. */ private SafeTagList safeTags; /** The indent level for that writer. */ private int indentLevel; /** The indent string. */ private String indentString; /** * A flag indicating whether to force a linebreak before printing the next * tag. */ private boolean newLineOk; /** * Default Constructor. The created XMLWriterSupport will not have no safe * tags and starts with an indention level of 0. */ public XMLWriterSupport() { this(new SafeTagList(), 0); } /** * Creates a new support instance. * * @param safeTags tags that are safe for line breaks. * @param indentLevel the index level. */ public XMLWriterSupport(final SafeTagList safeTags, final int indentLevel) { this(safeTags, indentLevel, " "); } /** * Creates a new support instance. * * @param safeTags the tags that are safe for line breaks. * @param indentLevel the indent level. * @param indentString the indent string. */ public XMLWriterSupport(final SafeTagList safeTags, final int indentLevel, final String indentString) { if (indentString == null) { throw new NullPointerException("IndentString must not be null"); } this.safeTags = safeTags; this.indentLevel = indentLevel; this.indentString = indentString; } /** * Starts a new block by increasing the indent level. * * @throws IOException if an IO error occurs. */ public void startBlock() throws IOException { this.indentLevel++; allowLineBreak(); } /** * Ends the current block by decreasing the indent level. * * @throws IOException if an IO error occurs. */ public void endBlock() throws IOException { this.indentLevel--; allowLineBreak(); } /** * Forces a linebreak on the next call to writeTag or writeCloseTag. * * @throws IOException if an IO error occurs. */ public void allowLineBreak() throws IOException { this.newLineOk = true; } /** * Returns the line separator. * * @return the line separator. */ public static String getLineSeparator() { if (lineSeparator == null) { try { lineSeparator = System.getProperty("line.separator", "\n"); } catch (SecurityException se) { lineSeparator = "\n"; } } return lineSeparator; } /** * Writes an opening XML tag that has no attributes. * * @param w the writer. * @param name the tag name. * * @throws java.io.IOException if there is an I/O problem. */ public void writeTag(final Writer w, final String name) throws IOException { if (this.newLineOk) { w.write(getLineSeparator()); } indent(w, OPEN_TAG_INCREASE); w.write("<"); w.write(name); w.write(">"); if (getSafeTags().isSafeForOpen(name)) { w.write(getLineSeparator()); } } /** * Writes a closing XML tag. * * @param w the writer. * @param tag the tag name. * * @throws java.io.IOException if there is an I/O problem. */ public void writeCloseTag(final Writer w, final String tag) throws IOException { // check whether the tag contains CData - we ma not indent such tags if (this.newLineOk || getSafeTags().isSafeForOpen(tag)) { if (this.newLineOk) { w.write(getLineSeparator()); } indent(w, CLOSE_TAG_DECREASE); } else { decreaseIndent(); } w.write(""); if (getSafeTags().isSafeForClose(tag)) { w.write(getLineSeparator()); } this.newLineOk = false; } /** * Writes an opening XML tag with an attribute/value pair. * * @param w the writer. * @param name the tag name. * @param attributeName the attribute name. * @param attributeValue the attribute value. * @param close controls whether the tag is closed. * * @throws java.io.IOException if there is an I/O problem. */ public void writeTag(final Writer w, final String name, final String attributeName, final String attributeValue, final boolean close) throws IOException { final AttributeList attr = new AttributeList(); if (attributeName != null) { attr.setAttribute(attributeName, attributeValue); } writeTag(w, name, attr, close); } /** * Writes an opening XML tag along with a list of attribute/value pairs. * * @param w the writer. * @param name the tag name. * @param attributes the attributes. * @param close controls whether the tag is closed. * * @throws java.io.IOException if there is an I/O problem. * @deprecated use the attribute list instead of the properties. */ public void writeTag(final Writer w, final String name, final Properties attributes, final boolean close) throws IOException { final AttributeList attList = new AttributeList(); final Enumeration keys = attributes.keys(); while (keys.hasMoreElements()) { final String key = (String) keys.nextElement(); attList.setAttribute(key, attributes.getProperty(key)); } writeTag(w, name, attList, close); } /** * Writes an opening XML tag along with a list of attribute/value pairs. * * @param w the writer. * @param name the tag name. * @param attributes the attributes. * @param close controls whether the tag is closed. * * @throws java.io.IOException if there is an I/O problem. */ public void writeTag(final Writer w, final String name, final AttributeList attributes, final boolean close) throws IOException { if (this.newLineOk) { w.write(getLineSeparator()); this.newLineOk = false; } indent(w, OPEN_TAG_INCREASE); w.write("<"); w.write(name); final Iterator keys = attributes.keys(); while (keys.hasNext()) { final String key = (String) keys.next(); final String value = attributes.getAttribute(key); w.write(" "); w.write(key); w.write("=\""); w.write(normalize(value)); w.write("\""); } if (close) { w.write("/>"); if (getSafeTags().isSafeForClose(name)) { w.write(getLineSeparator()); } decreaseIndent(); } else { w.write(">"); if (getSafeTags().isSafeForOpen(name)) { w.write(getLineSeparator()); } } } /** * Normalises a string, replacing certain characters with their escape * sequences so that the XML text is not corrupted. * * @param s the string. * * @return the normalised string. */ public static String normalize(final String s) { if (s == null) { return ""; } final StringBuffer str = new StringBuffer(); final int len = s.length(); for (int i = 0; i < len; i++) { final char ch = s.charAt(i); switch (ch) { case '<': { str.append("<"); break; } case '>': { str.append(">"); break; } case '&': { str.append("&"); break; } case '"': { str.append("""); break; } case '\n': { if (i > 0) { final char lastChar = str.charAt(str.length() - 1); if (lastChar != '\r') { str.append(getLineSeparator()); } else { str.append('\n'); } } else { str.append(getLineSeparator()); } break; } default : { str.append(ch); } } } return (str.toString()); } /** * Indent the line. Called for proper indenting in various places. * * @param writer the writer which should receive the indentention. * @param increase the current indent level. * @throws java.io.IOException if writing the stream failed. */ public void indent(final Writer writer, final int increase) throws IOException { if (increase == CLOSE_TAG_DECREASE) { decreaseIndent(); } for (int i = 0; i < this.indentLevel; i++) { writer.write(this.indentString); // 4 spaces, we could also try tab, // but I do not know whether this works // with our XML edit pane } if (increase == OPEN_TAG_INCREASE) { increaseIndent(); } } /** * Returns the current indent level. * * @return the current indent level. */ public int getIndentLevel() { return this.indentLevel; } /** * Increases the indention by one level. */ protected void increaseIndent() { this.indentLevel++; } /** * Decreates the indention by one level. */ protected void decreaseIndent() { this.indentLevel--; } /** * Returns the list of safe tags. * * @return The list. */ public SafeTagList getSafeTags() { return this.safeTags; } } jcommon-1.0.16/source/org/jfree/xml/writer/package.html0000644000175000017500000000021211172030703022743 0ustar twernertwerner Core classes for writing XML files. jcommon-1.0.16/source/org/jfree/xml/writer/XMLWriter.java0000644000175000017500000001416511172030703023176 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------- * XMLWriter.java * -------------- * (C) Copyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: XMLWriter.java,v 1.5 2005/11/08 14:42:42 mungady Exp $ * * Changes (from 26-Nov-2003) * -------------------------- * 26-Nov-2003 : Added standard header and Javadocs (DG); * */ package org.jfree.xml.writer; import java.io.IOException; import java.io.Writer; import java.util.Properties; /** * A class for writing XML to a character stream. */ public class XMLWriter extends XMLWriterSupport { /** * The character stream. */ private Writer writer; /** * Creates a new XML writer for the specified character stream. By * default, four spaces are used for indentation. * * @param writer the character stream. */ public XMLWriter(final Writer writer) { this(writer, " "); } /** * Creates a new XML writer for the specified character stream. * * @param writer the character stream. * @param indentString the string used for indentation (should contain * white space, for example four spaces). */ public XMLWriter(final Writer writer, final String indentString) { super(new SafeTagList(), 0, indentString); if (writer == null) { throw new NullPointerException("Writer must not be null."); } this.writer = writer; } /** * Writes the XML declaration that usually appears at the top of every XML * file. * * @throws IOException if there is a problem writing to the character * stream. */ public void writeXmlDeclaration() throws IOException { this.writer.write(""); this.writer.write(getLineSeparator()); } /** * Writes an opening XML tag that has no attributes. * * @param name the tag name. * @param close a flag that controls whether or not the tag is closed * immediately. * @throws java.io.IOException if there is an I/O problem. */ public void writeTag(final String name, final boolean close) throws IOException { if (close) { writeTag(this.writer, name, new AttributeList(), close); } else { writeTag(this.writer, name); } } /** * Writes a closing XML tag. * * @param tag the tag name. * @throws java.io.IOException if there is an I/O problem. */ public void writeCloseTag(final String tag) throws IOException { writeCloseTag(this.writer, tag); } /** * Writes an opening XML tag with an attribute/value pair. * * @param name the tag name. * @param attributeName the attribute name. * @param attributeValue the attribute value. * @param close controls whether the tag is closed. * @throws java.io.IOException if there is an I/O problem. */ public void writeTag(final String name, final String attributeName, final String attributeValue, final boolean close) throws IOException { writeTag(this.writer, name, attributeName, attributeValue, close); } /** * Writes an opening XML tag along with a list of attribute/value pairs. * * @param name the tag name. * @param attributes the attributes. * @param close controls whether the tag is closed. * @throws java.io.IOException if there is an I/O problem. */ public void writeTag(final String name, final AttributeList attributes, final boolean close) throws IOException { writeTag(this.writer, name, attributes, close); } /** * Writes an opening XML tag along with a list of attribute/value pairs. * * @param name the tag name. * @param attributes the attributes. * @param close controls whether the tag is closed. * @throws java.io.IOException if there is an I/O problem. * @deprecated use the attribute list instead ... */ public void writeTag(final String name, final Properties attributes, final boolean close) throws IOException { writeTag(this.writer, name, attributes, close); } /** * Writes some text to the character stream. * * @param text the text. * @throws IOException if there is a problem writing to the character * stream. */ public void writeText(final String text) throws IOException { this.writer.write(text); } /** * Closes the underlying character stream. * * @throws IOException if there is a problem closing the character stream. */ public void close() throws IOException { this.writer.close(); } } jcommon-1.0.16/source/org/jfree/xml/writer/RootXmlWriteHandler.java0000644000175000017500000003252011172030703025251 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * RootXmlWriteHandler.java * ------------------------ * (C) Copyright 2002-2005, by Object Refinery Limited. * * Original Author: Peter Becker; * Contributor(s): -; * * $Id: RootXmlWriteHandler.java,v 1.5 2005/10/18 13:35:06 mungady Exp $ * * Changes * ------- * 23-Dec-2003 : Added missing Javadocs (DG); * */ package org.jfree.xml.writer; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Insets; import java.awt.Paint; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Stack; import java.util.Vector; import org.jfree.util.ObjectUtilities; import org.jfree.xml.util.ManualMappingDefinition; import org.jfree.xml.util.MultiplexMappingDefinition; import org.jfree.xml.util.MultiplexMappingEntry; import org.jfree.xml.util.ObjectFactory; import org.jfree.xml.util.SimpleObjectFactory; import org.jfree.xml.writer.coretypes.BasicStrokeWriteHandler; import org.jfree.xml.writer.coretypes.ColorWriteHandler; import org.jfree.xml.writer.coretypes.FontWriteHandler; import org.jfree.xml.writer.coretypes.GenericWriteHandler; import org.jfree.xml.writer.coretypes.GradientPaintWriteHandler; import org.jfree.xml.writer.coretypes.InsetsWriteHandler; import org.jfree.xml.writer.coretypes.ListWriteHandler; import org.jfree.xml.writer.coretypes.Point2DWriteHandler; import org.jfree.xml.writer.coretypes.Rectangle2DWriteHandler; import org.jfree.xml.writer.coretypes.RenderingHintsWriteHandler; /** * A root handler for writing objects to XML format. */ public abstract class RootXmlWriteHandler { /** A map containg the manual mappings. */ private SimpleObjectFactory classToHandlerMapping; /** * Creates a new RootXmlWrite handler with the default mappings enabled. */ public RootXmlWriteHandler() { this.classToHandlerMapping = new SimpleObjectFactory(); // set up handling for Paint objects final MultiplexMappingEntry[] paintEntries = new MultiplexMappingEntry[2]; paintEntries[0] = new MultiplexMappingEntry("color", Color.class.getName()); paintEntries[1] = new MultiplexMappingEntry("gradientPaint", GradientPaint.class.getName()); addMultiplexMapping(Paint.class, "type", paintEntries); addManualMapping(GradientPaint.class, GradientPaintWriteHandler.class); addManualMapping(Color.class, ColorWriteHandler.class); // set up handling for Point2D objects final MultiplexMappingEntry[] point2DEntries = new MultiplexMappingEntry[2]; point2DEntries[0] = new MultiplexMappingEntry("float", Point2D.Float.class.getName()); point2DEntries[1] = new MultiplexMappingEntry("double", Point2D.Double.class.getName()); addMultiplexMapping(Point2D.class, "type", point2DEntries); addManualMapping(Point2D.Float.class, Point2DWriteHandler.class); addManualMapping(Point2D.Double.class, Point2DWriteHandler.class); // set up handling for Stroke objects final MultiplexMappingEntry[] strokeEntries = new MultiplexMappingEntry[1]; strokeEntries[0] = new MultiplexMappingEntry("basic", BasicStroke.class.getName()); addMultiplexMapping(Stroke.class, "type", strokeEntries); addManualMapping(BasicStroke.class, BasicStrokeWriteHandler.class); // set up handling for Rectangle2D objects final MultiplexMappingEntry[] rectangle2DEntries = new MultiplexMappingEntry[2]; rectangle2DEntries[0] = new MultiplexMappingEntry( "float", Rectangle2D.Float.class.getName() ); rectangle2DEntries[1] = new MultiplexMappingEntry( "double", Rectangle2D.Double.class.getName() ); addMultiplexMapping(Rectangle2D.class, "type", rectangle2DEntries); addManualMapping(Rectangle2D.Float.class, Rectangle2DWriteHandler.class); addManualMapping(Rectangle2D.Double.class, Rectangle2DWriteHandler.class); // set up handling for List objects final MultiplexMappingEntry[] listEntries = new MultiplexMappingEntry[4]; listEntries[0] = new MultiplexMappingEntry("array-list", ArrayList.class.getName()); listEntries[1] = new MultiplexMappingEntry("linked-list", LinkedList.class.getName()); listEntries[2] = new MultiplexMappingEntry("vector", Vector.class.getName()); listEntries[3] = new MultiplexMappingEntry("stack", Stack.class.getName()); addMultiplexMapping(List.class, "type", listEntries); addManualMapping(LinkedList.class, ListWriteHandler.class); addManualMapping(Vector.class, ListWriteHandler.class); addManualMapping(ArrayList.class, ListWriteHandler.class); addManualMapping(Stack.class, ListWriteHandler.class); // handle all other direct mapping types addManualMapping(RenderingHints.class, RenderingHintsWriteHandler.class); addManualMapping(Insets.class, InsetsWriteHandler.class); addManualMapping(Font.class, FontWriteHandler.class); } /** * Returns the object factory. * * @return the object factory. */ protected abstract ObjectFactory getFactoryLoader(); /** * Adds a new manual mapping to this handler. * * This method provides support for the manual mapping. The manual mapping * will become active before the multiplexers were queried. This facility * could be used to override the model definition. * * @param classToWrite the class, which should be handled * @param handler the write handler implementation for that class. */ protected void addManualMapping(final Class classToWrite, final Class handler) { if (handler == null) { throw new NullPointerException("handler must not be null."); } if (classToWrite == null) { throw new NullPointerException("classToWrite must not be null."); } if (!XmlWriteHandler.class.isAssignableFrom(handler)) { throw new IllegalArgumentException("The given handler is no XmlWriteHandler."); } this.classToHandlerMapping.addManualMapping (new ManualMappingDefinition(classToWrite, null, handler.getName())); } /** * Adds a multiplex mapping. * * @param baseClass the base class. * @param typeAttr the type attribute. * @param mdef the mapping entries. */ protected void addMultiplexMapping(final Class baseClass, final String typeAttr, final MultiplexMappingEntry[] mdef) { this.classToHandlerMapping.addMultiplexMapping( new MultiplexMappingDefinition(baseClass, typeAttr, mdef) ); } /** * Tries to find the mapping for the given class. This will first check * the manual mapping and then try to use the object factory to resolve * the class parameter into a write handler. * * @param classToWrite the class for which to find a handler. * @return the write handler, never null. * @throws XMLWriterException if no handler could be found for the given class. */ protected XmlWriteHandler getMapping(final Class classToWrite) throws XMLWriterException { if (classToWrite == null) { throw new NullPointerException("ClassToWrite is null."); } // search direct matches, first the direct definitions ... ManualMappingDefinition manualMapping = this.classToHandlerMapping.getManualMappingDefinition(classToWrite); if (manualMapping == null) { // search the manual mappings from the xml file. manualMapping = getFactoryLoader().getManualMappingDefinition(classToWrite); } if (manualMapping != null) { return loadHandlerClass(manualMapping.getWriteHandler()); } // multiplexer definitions can be safely ignored here, as they are used to // map parent classes to more specific child classes. In this case, we already // know the child class and can look up the handler directly. // of course we have to check for multiplexers later, so that we can apply // the mutiplex-attributes. // and finally try the generic handler matches ... if (this.classToHandlerMapping.isGenericHandler(classToWrite)) { return new GenericWriteHandler( this.classToHandlerMapping.getFactoryForClass(classToWrite) ); } if (getFactoryLoader().isGenericHandler(classToWrite)) { return new GenericWriteHandler(getFactoryLoader().getFactoryForClass(classToWrite)); } throw new XMLWriterException("Unable to handle " + classToWrite); } /** * Writes the given object with the specified tagname. This method will * do nothing, if the given object is null. * * @param tagName the tagname for the xml-element containing the object * definition. The tagname must not be null. * @param object the object which should be written. * @param baseClass the base class. * @param writer the xml writer used to write the content, never null. * * @throws IOException if an IOException occures. * @throws XMLWriterException if an object model related error occures during * the writing. */ public void write(final String tagName, final Object object, final Class baseClass, final XMLWriter writer) throws IOException, XMLWriterException { if (object == null) { return; } if (tagName == null) { throw new NullPointerException("RootXmlWriteHandler.write(..) : tagName is null"); } if (writer == null) { throw new NullPointerException("RootXmlWriteHandler.write(..) : writer is null"); } if (!baseClass.isInstance(object)) { throw new ClassCastException("Object is no instance of " + baseClass); } final Class classToWrite = object.getClass(); final XmlWriteHandler handler = getMapping(classToWrite); handler.setRootHandler(this); String attributeName = null; String attributeValue = null; // find multiplexer for this class... MultiplexMappingDefinition mplex = getFactoryLoader().getMultiplexDefinition(baseClass); if (mplex == null) { mplex = this.classToHandlerMapping.getMultiplexDefinition(baseClass); } if (mplex != null) { final MultiplexMappingEntry entry = mplex.getEntryForClass(classToWrite.getName()); if (entry != null) { attributeName = mplex.getAttributeName(); attributeValue = entry.getAttributeValue(); } else { throw new XMLWriterException( "Unable to find child mapping for multiplexer " + baseClass + " to child " + classToWrite ); } } handler.write(tagName, object, writer, attributeName, attributeValue); writer.allowLineBreak(); } /** * Loads the given class, and ignores all exceptions which may occur * during the loading. If the class was invalid, null is returned instead. * * @param className the name of the class to be loaded. * @return the class or null. * * @throws XMLWriterException if there is a writer exception. */ protected XmlWriteHandler loadHandlerClass(final String className) throws XMLWriterException { if (className == null) { throw new XMLWriterException("LoadHanderClass: Class name not defined"); } try { final Class c = ObjectUtilities.getClassLoader(getClass()).loadClass(className); return (XmlWriteHandler) c.newInstance(); } catch (Exception e) { // ignore buggy classes for now .. throw new XMLWriterException("LoadHanderClass: Unable to instantiate " + className, e); } } } jcommon-1.0.16/source/org/jfree/xml/writer/SafeTagList.java0000644000175000017500000001103611172030703023501 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * SafeTagList.java * ---------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: SafeTagList.java,v 1.3 2005/10/18 13:35:06 mungady Exp $ * * Changes * ------- * 21-Feb-2003 : Added standard header and Javadocs (DG); * */ package org.jfree.xml.writer; import java.util.HashMap; /** * A container for information relating to the tags in the JFreeReport XML report files. Some tags * cannot be spread across multiple lines, because it causes problems for the parser. * * @author Thomas Morgner. */ public class SafeTagList { /** Storage for the tag information. */ private HashMap safeTags; /** * A tag description. */ private static class SafeDescription { /** A flag indicating whether or not it is safe to put a new line after the open tag. */ private boolean open; /** A flag indicating whether or not it is safe to put a new line before the close tag. */ private boolean close; /** * Creates a new tag description. * * @param open the 'open' flag. * @param close the 'close' flag. */ public SafeDescription(final boolean open, final boolean close) { this.open = open; this.close = close; } /** * Returns the 'open' flag. * * @return true or false. */ public boolean isOpen() { return this.open; } /** * Returns the 'close' flag. * * @return true or false. */ public boolean isClose() { return this.close; } } /** * Creates a new list. */ public SafeTagList() { this.safeTags = new HashMap(); } /** * Adds a tag with both the 'open' and 'close' flags set to true. * * @param tag the tag name. */ public void add (final String tag) { this.safeTags.put(tag, new SafeDescription(true, true)); } /** * Adds a tag. * * @param tag the tag name. * @param open the 'open' flag. * @param closed the 'close' flag. */ public void add (final String tag, final boolean open, final boolean closed) { this.safeTags.put(tag, new SafeDescription(open, closed)); } /** * Returns true if it is safe to start a new line * immediately after an open tag. * * @param tag the tag name. * * @return A boolean. */ public boolean isSafeForOpen (final String tag) { final SafeDescription sd = (SafeDescription) this.safeTags.get(tag); if (sd == null) { return false; } return sd.isOpen(); } /** * Returns true if it is safe to start a new * line immediately after a close tag. * * @param tag the tag name. * * @return A boolean. */ public boolean isSafeForClose (final String tag) { final SafeDescription sd = (SafeDescription) this.safeTags.get(tag); if (sd == null) { return false; } return sd.isClose(); } } jcommon-1.0.16/source/org/jfree/xml/writer/XmlWriteHandler.java0000644000175000017500000000562411172030703024412 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * XmlWriteHandler.java * -------------------- * (C) Copyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: XmlWriteHandler.java,v 1.3 2005/10/18 13:35:06 mungady Exp $ * * Changes (from 26-Nov-2003) * -------------------------- * 26-Nov-2003 : Added standard header and Javadocs (DG); * */ package org.jfree.xml.writer; import java.io.IOException; /** * The interface that must be supported by all XML write handlers. */ public interface XmlWriteHandler { /** * Returns the root handler for this write handler. The root handler * will be used to resolve the child handlers. * * @return the root handler. */ public RootXmlWriteHandler getRootHandler(); /** * Sets the root handler. * * @param rootHandler the root handler. */ public void setRootHandler(RootXmlWriteHandler rootHandler); /** * Performs the writing of a single object. * * @param tagName the tag name for the generated xml element. * @param object the object to be written. * @param writer the writer. * @param mPlexAttribute the multiplexer selector attribute name. * @param mPlexValue the multiplexers attribute value corresponding to this * object type. * * @throws IOException if an IOError occured. * @throws XMLWriterException if an XmlDefinition error occured. */ public void write(String tagName, Object object, XMLWriter writer, String mPlexAttribute, String mPlexValue) throws IOException, XMLWriterException; } jcommon-1.0.16/source/org/jfree/xml/writer/XMLWriterException.java0000644000175000017500000000470211172030703025051 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * XMLWriterException.java * ----------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: XMLWriterException.java,v 1.3 2005/10/18 13:35:06 mungady Exp $ * * Changes * ------- * 21-Nov-2003 : Initial version (TM); * 26-Nov-2003 : Header and Javadoc updates (DG); * */ package org.jfree.xml.writer; import org.jfree.xml.util.ObjectDescriptionException; /** * An exception that can be thrown by the {@link XMLWriter} class. */ public class XMLWriterException extends ObjectDescriptionException { /** * Creates a new exception with no message or parent. */ public XMLWriterException() { super(); } /** * Creates an exception. * * @param message the exception message. */ public XMLWriterException(final String message) { super(message); } /** * Creates an exception. * * @param message the exception message. * @param ex the parent exception. */ public XMLWriterException(final String message, final Exception ex) { super(message, ex); } } jcommon-1.0.16/source/org/jfree/xml/writer/AttributeList.java0000644000175000017500000002127111172030703024134 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * AttributeList.java * ------------------ * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AttributeList.java,v 1.3 2005/10/18 13:35:06 mungady Exp $ * * Changes * ------- * 25-Sep-2003 : Initial version (TM); * 26-Nov-2003 : Javadoc updates (DG); * */ package org.jfree.xml.writer; import java.util.Iterator; import java.util.List; /** * The attribute list is used by a writer to specify the attributes * of an XML element in a certain order. * * @author Thomas Morgner */ public class AttributeList { /** * A name/value pair of the attribute list. */ private static class AttributeEntry { /** The name of the attribute entry. */ private String name; /** The value of the attribute entry. */ private String value; /** * Creates a new attribute entry for the given name and value. * * @param name the attribute name (null not permitted). * @param value the attribute value (null not permitted). */ public AttributeEntry(final String name, final String value) { if (name == null) { throw new NullPointerException("Name must not be null. [" + name + ", " + value + "]"); } if (value == null) { throw new NullPointerException("Value must not be null. [" + name + ", " + value + "]"); } this.name = name; this.value = value; } /** * Returns the attribute name. * * @return the name. */ public String getName() { return this.name; } /** * Returns the value of this attribute entry. * * @return the value of the entry. */ public String getValue() { return this.value; } /** * Checks whether the given object is an attribute entry with the same name. * * @param o the suspected other attribute entry. * * @return true if the given object is equal, false otherwise. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof AttributeEntry)) { return false; } final AttributeEntry attributeEntry = (AttributeEntry) o; if (!this.name.equals(attributeEntry.name)) { return false; } return true; } /** * Computes an hashcode for this entry. * * @return the hashcode. */ public int hashCode() { return this.name.hashCode(); } } /** * An iterator over the attribute names of this list. */ private static class AttributeIterator implements Iterator { /** The backend is an iterator over the attribute entries. */ private Iterator backend; /** * Creates a new attribute iterator using the given iterator as backend. * * @param backend an iterator over the attribute entries (null not permitted). */ public AttributeIterator(final Iterator backend) { if (backend == null) { throw new NullPointerException(); } this.backend = backend; } /** * Returns true if the iteration has more elements. (In other * words, returns true if next would return an element * rather than throwing an exception.) * * @return true if the iterator has more elements. */ public boolean hasNext() { return this.backend.hasNext(); } /** * Returns the next element in the iteration. * * @return the next element in the iteration. */ public Object next() { final AttributeEntry entry = (AttributeEntry) this.backend.next(); if (entry != null) { return entry.getName(); } return entry; } /** * * Removes from the underlying collection the last element returned by the * iterator (optional operation). This method can be called only once per * call to next. The behavior of an iterator is unspecified if * the underlying collection is modified while the iteration is in * progress in any way other than by calling this method. */ public void remove() { this.backend.remove(); } } /** The storage for all entries of this list. */ private List entryList; /** * Creates an empty attribute list with no default values. */ public AttributeList() { this.entryList = new java.util.ArrayList(); } /** * Returns an iterator over all attribute names. The names are returned * in their oder of addition to the list. The iterator contains strings. * * @return the iterator over all attribute names. */ public Iterator keys() { return new AttributeIterator(this.entryList.iterator()); } /** * Defines an attribute. * * @param name the name of the attribute to be defined * @param value the value of the attribute. */ public synchronized void setAttribute(final String name, final String value) { final AttributeEntry entry = new AttributeEntry(name, value); final int pos = this.entryList.indexOf(entry); if (pos != -1) { this.entryList.remove(pos); } this.entryList.add(entry); } /** * Returns the attribute value for the given attribute name or null, * if the attribute is not defined in this list. * * @param name the name of the attribute * @return the attribute value or null. */ public synchronized String getAttribute(final String name) { return getAttribute(name, null); } /** * Returns the attribute value for the given attribute name or the given * defaultvalue, if the attribute is not defined in this list. * * @param name the name of the attribute. * @param defaultValue the default value. * * @return the attribute value or the defaultValue. */ public synchronized String getAttribute(final String name, final String defaultValue) { for (int i = 0; i < this.entryList.size(); i++) { final AttributeEntry ae = (AttributeEntry) this.entryList.get(i); if (ae.getName().equals(name)) { return ae.getValue(); } } return defaultValue; } /** * Removes the attribute with the given name from the list. * * @param name the name of the attribute which should be removed.. */ public synchronized void removeAttribute(final String name) { for (int i = 0; i < this.entryList.size(); i++) { final AttributeEntry ae = (AttributeEntry) this.entryList.get(i); if (ae.getName().equals(name)) { this.entryList.remove(ae); return; } } } } jcommon-1.0.16/source/org/jfree/xml/ElementDefinitionException.java0000644000175000017500000001232411172030703025301 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------ * ElementDefinitionException.java * ------------------------------ * (C)opyright 2002-2004, by Object Refinery Limited. * * $Id: ElementDefinitionException.java,v 1.3 2005/10/18 13:25:44 mungady Exp $ * * Changes * ------- * 24-Apr-2002 : Initial version * 31-Aug-2002 : Documentation; changed PrintStackTrace for better tracing * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon */ package org.jfree.xml; import java.io.PrintStream; import java.io.PrintWriter; import org.xml.sax.Locator; /** * A reportdefinition exception is thrown when the parsing of the report definition * failed because invalid or missing attributes are encountered. * * @author Thomas Morgner */ public class ElementDefinitionException extends ParseException { /** The parent exception. */ private Exception parent; /** * Creates a new ElementDefinitionException without an parent exception and with the given * message as explanation. * * @param message a detail message explaining the reasons for this exception. */ public ElementDefinitionException(final String message) { super(message); } /** * Creates a new ElementDefinitionException with an parent exception and with the parents * message as explaination. * * @param e the parentException that caused this exception */ public ElementDefinitionException(final Exception e) { this(e, e.getMessage()); } /** * Creates a new ElementDefinitionException with an parent exception and with the given * message as explaination. * * @param e the parentException that caused this exception * @param message a detail message explaining the reasons for this exception */ public ElementDefinitionException(final Exception e, final String message) { this(message); this.parent = e; } /** * Creates a new ParseException with the given root exception * and the locator. * * @param e the exception * @param locator the locator of the parser */ public ElementDefinitionException(final Exception e, final Locator locator) { super(e, locator); this.parent = e; } /** * Creates a new ParseException with the given message and the locator. * * @param message the message * @param locator the locator of the parser */ public ElementDefinitionException(final String message, final Locator locator) { super(message, locator); } /** * Creates a new ParseException with the given message, root exception * and the locator. * * @param s the message * @param e the exception * @param locator the locator of the parser */ public ElementDefinitionException(final String s, final Exception e, final Locator locator) { super(s, e, locator); this.parent = e; } /** * Returns the parent exception. * * @return the parent exception. */ public Exception getParentException() { return this.parent; } /** * Prints the stack trace. If an inner exception exists, use * its stack trace. * * @param s the stream for writing to. */ public void printStackTrace(final PrintStream s) { super.printStackTrace(s); if (this.parent != null) { s.print("ParentException:"); this.parent.printStackTrace(s); } else { s.println("ParentException: "); } } /** * Prints the stack trace. If an inner exception exists, use * its stack trace. * * @param s the stream for writing to. */ public void printStackTrace(final PrintWriter s) { super.printStackTrace(s); if (this.parent != null) { s.print("ParentException:"); this.parent.printStackTrace(s); } else { s.println("ParentException: "); } } } jcommon-1.0.16/source/org/jfree/xml/package.html0000644000175000017500000000016211172030703021433 0ustar twernertwerner XML parser. jcommon-1.0.16/source/org/jfree/xml/factory/0000755000175000017500000000000011172030703020622 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/xml/factory/objects/0000755000175000017500000000000011351753320022261 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/xml/factory/objects/Point2DObjectDescription.java0000644000175000017500000000722111172030703027732 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------------- * Point2DObjectDescription.java * ----------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Point2DObjectDescription.java,v 1.3 2005/11/14 11:03:35 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import java.awt.geom.Point2D; /** * An object-description for a Point2D object. * * @author Thomas Morgner */ public class Point2DObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public Point2DObjectDescription() { super(Point2D.class); setParameterDefinition("x", Float.class); setParameterDefinition("y", Float.class); } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { final Point2D point = new Point2D.Float(); final float x = getFloatParameter("x"); final float y = getFloatParameter("y"); point.setLocation(x, y); return point; } /** * Returns a parameter value as a float. * * @param param the parameter name. * * @return The float value. */ private float getFloatParameter(final String param) { final Float p = (Float) getParameter(param); if (p == null) { return 0; } return p.floatValue(); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Point2D). * * @throws ObjectFactoryException if the object is not an instance of Point2D. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Point2D)) { throw new ObjectFactoryException("The given object is no java.awt.geom.Point2D."); } final Point2D point = (Point2D) o; final float x = (float) point.getX(); final float y = (float) point.getY(); setParameter("x", new Float(x)); setParameter("y", new Float(y)); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/ShortObjectDescription.java0000644000175000017500000000735711172030703027564 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------- * ShortObjectDescription.java * --------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ShortObjectDescription.java,v 1.3 2005/11/14 11:04:00 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; /** * An object-description for a Short object. * * @author Thomas Morgner */ public class ShortObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public ShortObjectDescription() { super(Short.class); setParameterDefinition("value", String.class); } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { final String o = (String) getParameter("value"); return Short.valueOf(o); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Short). * * @throws ObjectFactoryException if the object is not an instance of Short. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Short)) { throw new ObjectFactoryException("The given object is no java.lang.Short."); } setParameter("value", String.valueOf(o)); } /** * Tests for equality. * * @param o the object to test. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof AbstractObjectDescription)) { return false; } final AbstractObjectDescription abstractObjectDescription = (AbstractObjectDescription) o; if (Short.TYPE.equals(abstractObjectDescription.getObjectClass())) { return true; } if (Short.class.equals(abstractObjectDescription.getObjectClass())) { return true; } return false; } /** * Returns a hash code. * * @return A hash code. */ public int hashCode() { return getObjectClass().hashCode(); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/CollectionObjectDescription.java0000644000175000017500000001312111172030703030542 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * ObjectDescription.java * ---------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: CollectionObjectDescription.java,v 1.2 2005/10/18 13:31:58 mungady Exp $ * * Changes * ------------------------- * 06-May-2003 : Initial version */ package org.jfree.xml.factory.objects; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.jfree.util.Log; /** * An object description for simple collection objects, like java.util.List * or java.util.Set. * * @author Thomas Morgner */ public class CollectionObjectDescription extends AbstractObjectDescription { /** * Creates a list object description for the given collection class. *

* Throws ClassCastException if the given class is no collection instance. * * @param c the class of the collection implementation. */ public CollectionObjectDescription(final Class c) { super(c); if (!Collection.class.isAssignableFrom(c)) { throw new ClassCastException("The given class is no Collection instance"); } } /** * Tries to parse the given parameter string into a positive integer. * Returns -1 if the parsing failed for some reason. * * @param name the name of the parameter. * @return the parsed int value or -1 on errors. */ private int parseParameterName(final String name) { try { return Integer.parseInt(name); } catch (Exception e) { return -1; } } /** * Returns a parameter definition. If the parameter is invalid, this * function returns null. * * @param name the definition name. * * @return The parameter class or null, if the parameter is not defined. */ public Class getParameterDefinition(final String name) { if (name.equals("size")) { return Integer.TYPE; } final int par = parseParameterName(name); if (par < 0) { return null; } return Object.class; } /** * Returns an iterator for the parameter names. * * @return The iterator. */ public Iterator getParameterNames() { final Integer size = (Integer) getParameter("size"); if (size == null) { return getDefinedParameterNames(); } else { final ArrayList l = new ArrayList(); l.add("size"); for (int i = 0; i < size.intValue(); i++) { l.add(String.valueOf(i)); } return l.iterator(); } } /** * Creates an object based on the description. * * @return The object. */ public Object createObject() { try { final Collection l = (Collection) getObjectClass().newInstance(); int counter = 0; while (getParameterDefinition(String.valueOf(counter)) != null) { final Object value = getParameter(String.valueOf(counter)); if (value == null) { break; } l.add(value); counter += 1; } return l; } catch (Exception ie) { Log.warn("Unable to instantiate Object", ie); return null; } } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object. * * @throws ObjectFactoryException if there is a problem while reading the * properties of the given object. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (o == null) { throw new NullPointerException("Given object is null"); } final Class c = getObjectClass(); if (!c.isInstance(o)) { throw new ObjectFactoryException("Object is no instance of " + c + "(is " + o.getClass() + ")"); } final Collection l = (Collection) o; final Iterator it = l.iterator(); int counter = 0; while (it.hasNext()) { final Object ob = it.next(); setParameter(String.valueOf(counter), ob); counter++; } } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/ClassFactoryCollector.java0000644000175000017500000001540111172030703027363 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * ClassFactoryCollector.java * -------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ClassFactoryCollector.java,v 1.6 2005/11/14 11:00:23 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * 03-Jun-2003 : Adding factories configures the new factory. * 29-Jul-2004 : Replaced 'enum' variable name (reserved word in JDK 1.5) (DG); */ package org.jfree.xml.factory.objects; import java.util.ArrayList; import java.util.Iterator; import org.jfree.util.Configuration; /** * A class factory collector. * * @author Thomas Morgner */ public class ClassFactoryCollector extends ClassFactoryImpl { /** Storage for the class factories. */ private ArrayList factories; /** * Creates a new class factory collector. */ public ClassFactoryCollector() { this.factories = new ArrayList(); } /** * Adds a class factory to the collection. * * @param factory the factory. */ public void addFactory(final ClassFactory factory) { this.factories.add(factory); if (getConfig() != null) { factory.configure(getConfig()); } } /** * Returns an iterator the provides access to all the factories in the collection. * * @return The iterator. */ public Iterator getFactories() { return this.factories.iterator(); } /** * Returns an object description for a class. * * @param c the class. * * @return The object description. */ public ObjectDescription getDescriptionForClass(final Class c) { for (int i = 0; i < this.factories.size(); i++) { final ClassFactory f = (ClassFactory) this.factories.get(i); final ObjectDescription od = f.getDescriptionForClass(c); if (od != null) { return od; } } return super.getDescriptionForClass(c); } /** * Returns an object-description for the super class of a class. * * @param d the class. * @param knownSuperClass the last known super class or null. * @return The object description. */ public ObjectDescription getSuperClassObjectDescription (final Class d, ObjectDescription knownSuperClass) { for (int i = 0; i < this.factories.size(); i++) { final ClassFactory f = (ClassFactory) this.factories.get(i); final ObjectDescription od = f.getSuperClassObjectDescription(d, knownSuperClass); if (od != null) { if (knownSuperClass == null) { knownSuperClass = od; } else { if (getComparator().isComparable(knownSuperClass.getObjectClass(), od.getObjectClass())) { if (getComparator().compare(knownSuperClass.getObjectClass(), od.getObjectClass()) < 0) { knownSuperClass = od; } } } } } return super.getSuperClassObjectDescription(d, knownSuperClass); } /** * Returns an iterator that provices access to the registered classes. * * @return The iterator. */ public Iterator getRegisteredClasses() { final ArrayList list = new ArrayList(); for (int i = 0; i < this.factories.size(); i++) { final ClassFactory f = (ClassFactory) this.factories.get(i); final Iterator iterator = f.getRegisteredClasses(); while (iterator.hasNext()) { list.add(iterator.next()); } } return list.iterator(); } /** * Configures this factory. The configuration contains several keys and * their defined values. The given reference to the configuration object * will remain valid until the report parsing or writing ends. *

* The configuration contents may change during the reporting. * * @param config the configuration, never null */ public void configure(final Configuration config) { if (getConfig() != null) { // already configured ... return; } super.configure(config); final Iterator it = this.factories.iterator(); while (it.hasNext()) { final ClassFactory od = (ClassFactory) it.next(); od.configure(config); } } /** * Tests for equality. * * @param o the object to test. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof ClassFactoryCollector)) { return false; } if (!super.equals(o)) { return false; } final ClassFactoryCollector classFactoryCollector = (ClassFactoryCollector) o; if (!this.factories.equals(classFactoryCollector.factories)) { return false; } return true; } /** * Returns a hash code for the object. * * @return The hash code. */ public int hashCode() { int result = super.hashCode(); result = 29 * result + this.factories.hashCode(); return result; } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/URLClassFactory.java0000644000175000017500000000407311172030703026102 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * URLClassFactory.java * -------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: URLClassFactory.java,v 1.3 2005/11/14 11:04:33 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import java.net.URL; /** * A URL class factory. * * @author Thomas Morgner */ public class URLClassFactory extends ClassFactoryImpl { /** * Creates a new URL class factory. */ public URLClassFactory() { registerClass(URL.class, new URLObjectDescription()); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/ByteObjectDescription.java0000644000175000017500000000746511172030703027370 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * ByteObjectDescription.java * -------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ByteObjectDescription.java,v 1.3 2005/11/14 10:59:30 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; /** * An object-description for a Byte object. * * @author Thomas Morgner */ public class ByteObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public ByteObjectDescription() { super(Byte.class); setParameterDefinition("value", String.class); } /** * Creates a new object (Byte) based on this description object. * * @return The Byte object. */ public Object createObject() { final String o = (String) getParameter("value"); return Byte.valueOf(o); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Byte. * @throws ObjectFactoryException if there is a problem * while reading the properties of the given object. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Byte)) { throw new ObjectFactoryException("The given object is no java.lang.Byte."); } setParameter("value", String.valueOf(o)); } /** * Tests for equality. * * @param o the object to test. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof AbstractObjectDescription)) { return false; } final AbstractObjectDescription abstractObjectDescription = (AbstractObjectDescription) o; if (Byte.TYPE.equals(abstractObjectDescription.getObjectClass())) { return true; } if (Byte.class.equals(abstractObjectDescription.getObjectClass())) { return true; } return false; } /** * Returns a hash code for the object. * * @return The hash code. */ public int hashCode() { return getObjectClass().hashCode(); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/DimensionObjectDescription.java0000644000175000017500000000717711172030703030412 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------- * DimensionObjectDescription.java * ------------------------------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DimensionObjectDescription.java,v 1.2 2005/10/18 13:31:58 mungady Exp $ * * Changes * ------- * 13-Jan-2004 : Initial version * */ package org.jfree.xml.factory.objects; import java.awt.Dimension; import java.awt.geom.Dimension2D; /** * An object-description for a java.awt.Dimension object. * * @author Thomas Morgner */ public class DimensionObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public DimensionObjectDescription() { super(Dimension.class); setParameterDefinition("width", Float.class); setParameterDefinition("height", Float.class); } /** * Creates an object based on the description. * * @return The object. */ public Object createObject() { final Dimension2D dim = new Dimension(); final float width = getFloatParameter("width"); final float height = getFloatParameter("height"); dim.setSize(width, height); return dim; } /** * Returns a parameter value as a float. * * @param param the parameter name. * * @return The float value. */ private float getFloatParameter(final String param) { final Float p = (Float) getParameter(param); if (p == null) { return 0; } return p.floatValue(); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Dimension2D). * * @throws ObjectFactoryException if the object is not an instance of Point2D. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Dimension)) { throw new ObjectFactoryException("The given object is no java.awt.geom.Dimension2D."); } final Dimension dim = (Dimension) o; final float width = (float) dim.getWidth(); final float height = (float) dim.getHeight(); setParameter("width", new Float(width)); setParameter("height", new Float(height)); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/SimpleDateFormatObjectDescription.java0000644000175000017500000001064011172030703031652 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * LongObjectDescription.java * -------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: SimpleDateFormatObjectDescription.java,v 1.3 2005/11/14 11:04:12 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import java.text.DateFormatSymbols; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * An object-description for a SimpleDateFormat object. * * @author Thomas Morgner */ public class SimpleDateFormatObjectDescription extends BeanObjectDescription { /** * Creates a new object description. */ public SimpleDateFormatObjectDescription() { this(SimpleDateFormat.class); } /** * Creates a new object description. * * @param className the class. */ public SimpleDateFormatObjectDescription(final Class className) { this(className, true); } /** * Creates a new object description. * * @param className the class. * @param init initialise? */ public SimpleDateFormatObjectDescription(final Class className, final boolean init) { super(className, false); setParameterDefinition("2DigitYearStart", Date.class); setParameterDefinition("calendar", Calendar.class); setParameterDefinition("dateFormatSymbols", DateFormatSymbols.class); setParameterDefinition("lenient", Boolean.TYPE); setParameterDefinition("numberFormat", NumberFormat.class); // setParameterDefinition("timeZone", TimeZone.class); setParameterDefinition("localizedPattern", String.class); setParameterDefinition("pattern", String.class); ignoreParameter("localizedPattern"); ignoreParameter("pattern"); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object. * * @throws ObjectFactoryException if there is a problem while reading the * properties of the given object. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { super.setParameterFromObject(o); final SimpleDateFormat format = (SimpleDateFormat) o; setParameter("localizedPattern", format.toLocalizedPattern()); setParameter("pattern", format.toPattern()); } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { final SimpleDateFormat format = (SimpleDateFormat) super.createObject(); if (getParameter("pattern") != null) { format.applyPattern((String) getParameter("pattern")); } if (getParameter("localizedPattern") != null) { format.applyLocalizedPattern((String) getParameter("localizedPattern")); } return format; } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/CharacterObjectDescription.java0000644000175000017500000001004311172030703030343 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------- * CharacterObjectDescription.java * ------------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: CharacterObjectDescription.java,v 1.3 2005/11/14 10:59:44 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; /** * An object-description for a Character object. * * @author Thomas Morgner */ public class CharacterObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public CharacterObjectDescription() { super(Character.class); setParameterDefinition("value", String.class); } /** * Creates a new object (Character) based on this description object. * * @return The Character object. */ public Object createObject() { final String o = (String) getParameter("value"); if (o == null) { return null; } if (o.length() > 0) { return new Character(o.charAt(0)); } else { return null; } } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Character). * @throws ObjectFactoryException if there is a * problem while reading the properties of the given object. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Character)) { throw new ObjectFactoryException("The given object is no java.lang.Character."); } setParameter("value", String.valueOf(o)); } /** * Tests for equality. * * @param o the object to test. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof AbstractObjectDescription)) { return false; } final AbstractObjectDescription abstractObjectDescription = (AbstractObjectDescription) o; if (Character.TYPE.equals(abstractObjectDescription.getObjectClass())) { return true; } if (Character.class.equals(abstractObjectDescription.getObjectClass())) { return true; } return false; } /** * Returns a hash code for the object. * * @return The hash code. */ public int hashCode() { return getObjectClass().hashCode(); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/JavaBaseClassFactory.java0000644000175000017500000001705111172030703027114 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * JavaBaseClassFactory.java * ------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner (taquera@sherito.org); * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: JavaBaseClassFactory.java,v 1.3 2005/11/14 11:02:34 mungady Exp $ * * Changes * ------- * 14-Apr-2003 : Initial version * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * 13-Jan-2004 : Did not handle java.awt.Dimension objects correctly. */ package org.jfree.xml.factory.objects; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.geom.Dimension2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.Format; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.Vector; import org.jfree.ui.FloatDimension; /** * A default factory for all commonly used java base classes from java.lang, java.awt * etc. * * @author Thomas Morgner */ public class JavaBaseClassFactory extends ClassFactoryImpl { /** * DefaultConstructor. Creates the object factory for all java base classes. */ public JavaBaseClassFactory() { registerClass(Dimension.class, new DimensionObjectDescription()); registerClass(Dimension2D.class, new Dimension2DObjectDescription()); registerClass(FloatDimension.class, new BeanObjectDescription(FloatDimension.class)); registerClass(Date.class, new DateObjectDescription()); registerClass(Boolean.TYPE, new BooleanObjectDescription()); registerClass(Byte.TYPE, new ByteObjectDescription()); registerClass(Double.TYPE, new DoubleObjectDescription()); registerClass(Float.TYPE, new FloatObjectDescription()); registerClass(Integer.TYPE, new IntegerObjectDescription()); registerClass(Long.TYPE, new LongObjectDescription()); registerClass(Short.TYPE, new ShortObjectDescription()); registerClass(Character.TYPE, new CharacterObjectDescription()); registerClass(Character.class, new CharacterObjectDescription()); registerClass(Boolean.class, new BooleanObjectDescription()); registerClass(Byte.class, new ByteObjectDescription()); registerClass(Double.class, new DoubleObjectDescription()); registerClass(Float.class, new FloatObjectDescription()); registerClass(Integer.class, new IntegerObjectDescription()); registerClass(Long.class, new LongObjectDescription()); registerClass(Short.class, new ShortObjectDescription()); registerClass(Line2D.class, new Line2DObjectDescription()); registerClass(Point2D.class, new Point2DObjectDescription()); registerClass(Rectangle2D.class, new Rectangle2DObjectDescription()); registerClass(String.class, new StringObjectDescription()); registerClass(Color.class, new ColorObjectDescription()); registerClass(BasicStroke.class, new BasicStrokeObjectDescription()); registerClass(Object.class, new ClassLoaderObjectDescription()); registerClass(Format.class, new ClassLoaderObjectDescription()); registerClass(NumberFormat.class, createNumberFormatDescription()); registerClass(DecimalFormat.class, new DecimalFormatObjectDescription()); registerClass(DecimalFormatSymbols.class, createDecimalFormatSymbols()); registerClass(DateFormat.class, new ClassLoaderObjectDescription()); registerClass(SimpleDateFormat.class, new SimpleDateFormatObjectDescription()); registerClass(DateFormatSymbols.class, new ClassLoaderObjectDescription()); registerClass(ArrayList.class, new CollectionObjectDescription(ArrayList.class)); registerClass(Vector.class, new CollectionObjectDescription(Vector.class)); registerClass(HashSet.class, new CollectionObjectDescription(HashSet.class)); registerClass(TreeSet.class, new CollectionObjectDescription(TreeSet.class)); registerClass(Set.class, new CollectionObjectDescription(HashSet.class)); registerClass(List.class, new CollectionObjectDescription(ArrayList.class)); registerClass(Collection.class, new CollectionObjectDescription(ArrayList.class)); } private ObjectDescription createNumberFormatDescription () { final BeanObjectDescription nfDesc = new BeanObjectDescription(NumberFormat.class, false); nfDesc.setParameterDefinition("groupingUsed", Boolean.TYPE); nfDesc.setParameterDefinition("maximumFractionDigits", Integer.TYPE); nfDesc.setParameterDefinition("minimumFractionDigits", Integer.TYPE); nfDesc.setParameterDefinition("maximumIntegerDigits", Integer.TYPE); nfDesc.setParameterDefinition("minimumIntegerDigits", Integer.TYPE); nfDesc.setParameterDefinition("parseIntegerOnly", Boolean.TYPE); return nfDesc; } private ObjectDescription createDecimalFormatSymbols() { final BeanObjectDescription dfsDesc = new BeanObjectDescription(DecimalFormatSymbols.class, false); dfsDesc.setParameterDefinition("currencySymbol", String.class); dfsDesc.setParameterDefinition("decimalSeparator", Character.TYPE); dfsDesc.setParameterDefinition("digit", Character.TYPE); dfsDesc.setParameterDefinition("groupingSeparator", Character.TYPE); dfsDesc.setParameterDefinition("infinity", String.class); dfsDesc.setParameterDefinition("internationalCurrencySymbol", String.class); dfsDesc.setParameterDefinition("minusSign", Character.TYPE); dfsDesc.setParameterDefinition("monetaryDecimalSeparator", Character.TYPE); dfsDesc.setParameterDefinition("naN", String.class); dfsDesc.setParameterDefinition("patternSeparator", Character.TYPE); dfsDesc.setParameterDefinition("perMill", Character.TYPE); dfsDesc.setParameterDefinition("percent", Character.TYPE); dfsDesc.setParameterDefinition("zeroDigit", Character.TYPE); return dfsDesc; } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/DecimalFormatObjectDescription.java0000644000175000017500000001210411172030703031156 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------------------- * DecimalFormatObjectDescription.java * ----------------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DecimalFormatObjectDescription.java,v 1.5 2005/11/14 11:01:44 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; /** * An object-description for a DecimalFormat object. * * @author Thomas Morgner */ public class DecimalFormatObjectDescription extends BeanObjectDescription { /** * Creates a new object description. */ public DecimalFormatObjectDescription() { this(DecimalFormat.class); } /** * Creates a new object description. * * @param className the class. */ public DecimalFormatObjectDescription(final Class className) { super(className, false); setParameterDefinition("localizedPattern", String.class); setParameterDefinition("pattern", String.class); setParameterDefinition("decimalFormatSymbols", DecimalFormatSymbols.class); setParameterDefinition("decimalSeparatorAlwaysShown", Boolean.TYPE); setParameterDefinition("groupingSize", Integer.TYPE); setParameterDefinition("groupingUsed", Boolean.TYPE); setParameterDefinition("maximumFractionDigits", Integer.TYPE); setParameterDefinition("maximumIntegerDigits", Integer.TYPE); setParameterDefinition("minimumFractionDigits", Integer.TYPE); setParameterDefinition("minimumIntegerDigits", Integer.TYPE); setParameterDefinition("multiplier", Integer.TYPE); setParameterDefinition("negativePrefix", String.class); setParameterDefinition("negativeSuffix", String.class); // setParameterDefinition("parseBigDecimal", Boolean.TYPE); setParameterDefinition("parseIntegerOnly", Boolean.TYPE); setParameterDefinition("positivePrefix", String.class); setParameterDefinition("positiveSuffix", String.class); ignoreParameter("localizedPattern"); ignoreParameter("pattern"); } /** * Creates a new object description. * * @param className the class. * @param init initialise * @deprecated should no longer be used... */ public DecimalFormatObjectDescription(final Class className, final boolean init) { this(className); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of DecimalFormat). * * @throws ObjectFactoryException if there is a problem while reading the * properties of the given object. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { super.setParameterFromObject(o); final DecimalFormat format = (DecimalFormat) o; setParameter("localizedPattern", format.toLocalizedPattern()); setParameter("pattern", format.toPattern()); } /** * Creates an object (DecimalFormat) based on this description. * * @return The object. */ public Object createObject() { final DecimalFormat format = (DecimalFormat) super.createObject(); if (getParameter("pattern") != null) { format.applyPattern((String) getParameter("pattern")); } if (getParameter("localizedPattern") != null) { format.applyLocalizedPattern((String) getParameter("localizedPattern")); } return format; } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/AbstractObjectDescription.java0000644000175000017500000002261011172030703030215 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------ * AbstractObjectDescription.java * ------------------------------ * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AbstractObjectDescription.java,v 1.3 2005/11/14 10:58:37 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import org.jfree.util.Configuration; import org.jfree.util.Log; import org.jfree.util.ReadOnlyIterator; /** * An abstract base class for object descriptions. * * @author Thomas Morgner. */ public abstract class AbstractObjectDescription implements ObjectDescription, Cloneable { /** The class. */ private Class className; /** Storage for parameters. */ private HashMap parameters; /** Storage for parameter definitions. */ private HashMap parameterDefs; /** The configuration for the object description. */ private Configuration config; /** * Creates a new object description. * * @param className the class. */ public AbstractObjectDescription(final Class className) { this.className = className; this.parameters = new HashMap(); this.parameterDefs = new HashMap(); } /** * Returns a parameter class. * * @param name the parameter definition. * * @return The class. */ public Class getParameterDefinition(final String name) { return (Class) this.parameterDefs.get(name); } /** * Sets the class for a parameter. * * @param name the parameter name. * @param obj the parameter class. */ public void setParameterDefinition(final String name, final Class obj) { if (obj == null) { this.parameterDefs.remove(name); } else { this.parameterDefs.put(name, obj); } } /** * Converts primitives to corresponding object class. * * @param obj the class. * * @return The class. */ public static Class convertPrimitiveClass(final Class obj) { if (!obj.isPrimitive()) { return obj; } if (obj == Boolean.TYPE) { return Boolean.class; } if (obj == Byte.TYPE) { return Byte.class; } if (obj == Character.TYPE) { return Character.class; } if (obj == Short.TYPE) { return Short.class; } if (obj == Integer.TYPE) { return Integer.class; } if (obj == Long.TYPE) { return Long.class; } if (obj == Float.TYPE) { return Float.class; } if (obj == Double.TYPE) { return Double.class; } throw new IllegalArgumentException("Class 'void' is not allowed here"); } /** * Sets a parameter. * * @param name the name. * @param value the value. */ public void setParameter(final String name, final Object value) { if (getParameterDefinition(name) == null) { throw new IllegalArgumentException("No such Parameter defined: " + name + " in class " + getObjectClass()); } final Class parameterClass = convertPrimitiveClass(getParameterDefinition(name)); if (!parameterClass.isAssignableFrom(value.getClass())) { throw new ClassCastException("In Object " + getObjectClass() + ": Value is not assignable: " + value.getClass() + " is not assignable from " + parameterClass); } this.parameters.put(name, value); } /** * Returns an iterator for the parameter names. * * @return The iterator. */ public synchronized Iterator getParameterNames() { final ArrayList parameterNames = new ArrayList(this.parameterDefs.keySet()); Collections.sort(parameterNames); return new ReadOnlyIterator (parameterNames.iterator()); } /** * Returns an iterator for the parameter names. * * @return The iterator. */ protected Iterator getDefinedParameterNames() { return new ReadOnlyIterator (this.parameters.keySet().iterator()); } /** * Returns a parameter value. * * @param name the parameter name. * * @return The parameter value. */ public Object getParameter(final String name) { return this.parameters.get(name); } /** * Returns the class for the object. * * @return The class. */ public Class getObjectClass() { return this.className; } /** * Returns a cloned instance of the object description. The contents * of the parameter objects collection are cloned too, so that any * already defined parameter value is copied to the new instance. *

* Parameter definitions are not cloned, as they are considered read-only. *

* The newly instantiated object description is not configured. If it * need to be configured, then you have to call configure on it. * * @return A cloned instance. */ public ObjectDescription getInstance() { try { final AbstractObjectDescription c = (AbstractObjectDescription) super.clone(); c.parameters = (HashMap) this.parameters.clone(); return c; } catch (Exception e) { Log.error("Should not happen: Clone Error: ", e); return null; } } /** * Returns a cloned instance of the object description. The contents * of the parameter objects collection are cloned too, so that any * already defined parameter value is copied to the new instance. *

* Parameter definitions are not cloned, as they are considered read-only. *

* The newly instantiated object description is not configured. If it * need to be configured, then you have to call configure on it. * * @return A cloned instance. */ public ObjectDescription getUnconfiguredInstance() { try { final AbstractObjectDescription c = (AbstractObjectDescription) super.clone(); c.parameters = (HashMap) this.parameters.clone(); c.config = null; return c; } catch (Exception e) { Log.error("Should not happen: Clone Error: ", e); return null; } } /** * Configures this factory. The configuration contains several keys and * their defined values. The given reference to the configuration object * will remain valid until the report parsing or writing ends. *

* The configuration contents may change during the reporting. * * @param config the configuration, never null */ public void configure(final Configuration config) { if (config == null) { throw new NullPointerException("The given configuration is null"); } this.config = config; } /** * Returns the configuration for that object description. * * @return the configuration or null, if not yet set. */ public Configuration getConfig() { return this.config; } /** * Tests for equality. * * @param o the object to test. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof AbstractObjectDescription)) { return false; } final AbstractObjectDescription abstractObjectDescription = (AbstractObjectDescription) o; if (!this.className.equals(abstractObjectDescription.className)) { return false; } return true; } /** * Returns a hash code for the object. * * @return The hash code. */ public int hashCode() { return this.className.hashCode(); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/package.html0000644000175000017500000000021211172030703024527 0ustar twernertwerner Object descriptions for the parser. jcommon-1.0.16/source/org/jfree/xml/factory/objects/ColorObjectDescription.java0000644000175000017500000000610111172030703027525 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------- * ColorObjectDescription.java * --------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ColorObjectDescription.java,v 1.4 2005/11/14 11:01:17 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon */ package org.jfree.xml.factory.objects; import java.awt.Color; import org.jfree.util.PaintUtilities; /** * An object-description for a Color object. * * @author Thomas Morgner */ public class ColorObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public ColorObjectDescription() { super(Color.class); setParameterDefinition("value", String.class); } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { final String value = (String) getParameter("value"); return PaintUtilities.stringToColor(value); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Color). * * @throws ObjectFactoryException if there is a problem while reading the * properties of the given object. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Color)) { throw new ObjectFactoryException("Is no instance of java.awt.Color"); } final Color c = (Color) o; setParameter("value", PaintUtilities.colorToString(c)); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/DateObjectDescription.java0000644000175000017500000000771311172030703027336 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * DateObjectDescription.java * -------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DateObjectDescription.java,v 1.4 2005/11/14 11:01:31 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * An object-description for a Date object. * * @author Thomas Morgner */ public class DateObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public DateObjectDescription() { super(Date.class); setParameterDefinition("year", Integer.class); setParameterDefinition("month", Integer.class); setParameterDefinition("day", Integer.class); } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { final int y = getIntParameter("year"); final int m = getIntParameter("month"); final int d = getIntParameter("day"); return new GregorianCalendar(y, m, d).getTime(); } /** * Returns a parameter value as an int. * * @param param the parameter name. * * @return The parameter value. */ private int getIntParameter(final String param) { final Integer p = (Integer) getParameter(param); if (p == null) { return 0; } return p.intValue(); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Date). * * @throws ObjectFactoryException if the object is not an instance of Date. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (o instanceof Date) { final GregorianCalendar gc = new GregorianCalendar(); gc.setTime((Date) o); final int year = gc.get(Calendar.YEAR); final int month = gc.get(Calendar.MONTH); final int day = gc.get(Calendar.DAY_OF_MONTH); setParameter("year", new Integer(year)); setParameter("month", new Integer(month)); setParameter("day", new Integer(day)); } else { throw new ObjectFactoryException("Is no instance of java.util.Date"); } } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/ClassLoaderObjectDescription.java0000644000175000017500000000722611172030703030654 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------------- * ClassLoaderObjectDescription.java * --------------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ClassLoaderObjectDescription.java,v 1.5 2005/11/14 11:01:04 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import org.jfree.util.ObjectUtilities; /** * An object-description for a class loader. * * @author Thomas Morgner */ public class ClassLoaderObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public ClassLoaderObjectDescription() { super(Object.class); setParameterDefinition("class", String.class); } /** * Creates an object based on this object description. * * @return The object. */ public Object createObject() { try { final String o = (String) getParameter("class"); return ObjectUtilities.getClassLoader(getClass()).loadClass(o).newInstance(); } catch (Exception e) { return null; } } /** * Sets the parameters of the object description to match the supplied object. * * @param o the object. * * @throws ObjectFactoryException if there is a problem while reading the * properties of the given object. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (o == null) { throw new ObjectFactoryException("The Object is null."); } try { final Constructor c = o.getClass().getConstructor(new Class[0]); if (!Modifier.isPublic(c.getModifiers())) { throw new ObjectFactoryException ("The given object has no public default constructor. [" + o.getClass() + "]"); } setParameter("class", o.getClass().getName()); } catch (Exception e) { throw new ObjectFactoryException ("The given object has no default constructor. [" + o.getClass() + "]", e); } } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/BooleanObjectDescription.java0000644000175000017500000000752411172030703030040 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------------- * BooleanObjectDescription.java * ----------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: BooleanObjectDescription.java,v 1.3 2005/11/14 10:59:16 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; /** * An object-description for a Boolean object. * * @author Thomas Morgner */ public class BooleanObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public BooleanObjectDescription() { super(Boolean.class); setParameterDefinition("value", String.class); } /** * Creates a new Boolean based on the settings of this description object. * * @return A Boolean. */ public Object createObject() { final String o = (String) getParameter("value"); return Boolean.valueOf(o); } /** * Sets the description object parameters to match the supplied object * (which should be an instance of Boolean. * * @param o the object. * @throws ObjectFactoryException if there is a problem while reading the * properties of the given object. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Boolean)) { throw new ObjectFactoryException("The given object is no java.lang.Boolean. "); } setParameter("value", String.valueOf(o)); } /** * Tests for equality. * * @param o the object to test. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof AbstractObjectDescription)) { return false; } final AbstractObjectDescription abstractObjectDescription = (AbstractObjectDescription) o; if (Boolean.TYPE.equals(abstractObjectDescription.getObjectClass())) { return true; } if (Boolean.class.equals(abstractObjectDescription.getObjectClass())) { return true; } return false; } /** * Returns a hash code. * * @return A hash code. */ public int hashCode() { return getObjectClass().hashCode(); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/Dimension2DObjectDescription.java0000644000175000017500000000723311172030703030571 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------------- * Dimension2DObjectDescription.java * --------------------------------- * (C)opyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Dimension2DObjectDescription.java,v 1.2 2005/10/18 13:31:58 mungady Exp $ * * Changes * ------- * 13-Jan-2004 : Initial version * */ package org.jfree.xml.factory.objects; import java.awt.geom.Dimension2D; import org.jfree.ui.FloatDimension; /** * An object-description for a Dimension2D object. * * @author Thomas Morgner */ public class Dimension2DObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public Dimension2DObjectDescription() { super(Dimension2D.class); setParameterDefinition("width", Float.class); setParameterDefinition("height", Float.class); } /** * Creates an object based on the description. * * @return The object. */ public Object createObject() { final Dimension2D dim = new FloatDimension(); final float width = getFloatParameter("width"); final float height = getFloatParameter("height"); dim.setSize(width, height); return dim; } /** * Returns a parameter value as a float. * * @param param the parameter name. * * @return The float value. */ private float getFloatParameter(final String param) { final Float p = (Float) getParameter(param); if (p == null) { return 0; } return p.floatValue(); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Dimension2D). * * @throws ObjectFactoryException if the object is not an instance of Point2D. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Dimension2D)) { throw new ObjectFactoryException("The given object is no java.awt.geom.Dimension2D."); } final Dimension2D dim = (Dimension2D) o; final float width = (float) dim.getWidth(); final float height = (float) dim.getHeight(); setParameter("width", new Float(width)); setParameter("height", new Float(height)); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/ClassFactory.java0000644000175000017500000000752311172030703025522 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * ClassFactory.java * ----------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ClassFactory.java,v 1.3 2005/11/14 10:59:58 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import java.io.Serializable; import java.util.Iterator; import org.jfree.util.Configuration; /** * A class factory. * * @author Thomas Morgner */ public interface ClassFactory extends Serializable { /** * Returns an object description for a class. * * @param c the class. * * @return The object description. */ public ObjectDescription getDescriptionForClass(Class c); /** * Returns an object description for the super class of a class. * * @param d the class. * @param knownSuperClass the last known super class or null. * * @return The object description. */ public ObjectDescription getSuperClassObjectDescription (Class d, ObjectDescription knownSuperClass); /** * Returns an iterator for the registered classes. This returns a list * of pre-registered classes known to this ClassFactory. A class may be able * to handle more than the registered classes. *

* This method exists to support query tools for UI design, do not rely on it * for day to day work. * * @return The iterator. */ public Iterator getRegisteredClasses(); /** * Configures this factory. The configuration contains several keys and * their defined values. The given reference to the configuration object * will remain valid until the report parsing or writing ends. *

* The configuration contents may change during the reporting. * * @param config the configuration, never null */ public void configure(Configuration config); /** * Compares whether two object factories are equal. This method must be * implemented! * * @param o the other object. * @return true, if both object factories describe the same objects, false otherwise. */ public boolean equals (Object o); /** * Computes the hashCode for this ClassFactory. As equals() must be implemented, * a corresponding hashCode() should be implemented as well. * * @return the hashcode. */ public int hashCode(); } jcommon-1.0.16/source/org/jfree/xml/factory/objects/ArrayClassFactory.java0000644000175000017500000001114311172030703026512 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * ArrayClassFactory.java * ---------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ArrayClassFactory.java,v 1.2 2005/10/18 13:31:58 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 06-May-2003 : Initial version */ package org.jfree.xml.factory.objects; import java.util.ArrayList; import java.util.Iterator; import org.jfree.util.Configuration; /** * An class that implements the {@link ClassFactory} interface to * create Arrays of objects. The object descriptions are created on * demand. * * @author Thomas Morgner. */ public class ArrayClassFactory implements ClassFactory { /** * Default constructor. */ public ArrayClassFactory() { super(); } /** * Returns an object description for a class. * * @param c the class. * * @return The object description. */ public ObjectDescription getDescriptionForClass(final Class c) { if (!c.isArray()) { return null; } else { return new ArrayObjectDescription(c); } } /** * Returns an object description for the super class of a class. * This method always returns null. * * @param d the class. * @param knownSuperClass the last known super class or null. * * @return The object description. */ public ObjectDescription getSuperClassObjectDescription (final Class d, final ObjectDescription knownSuperClass) { return null; } /** * Returns an iterator for the registered classes. This returns a list * of pre-registered classes known to this ClassFactory. A class may be able * to handle more than the registered classes. *

* This method exists to support query tools for UI design, do not rely on it * for day to day work. * * @return The iterator. */ public Iterator getRegisteredClasses() { final ArrayList l = new ArrayList(); l.add(Object[].class); return l.iterator(); } /** * Configures this factory. The configuration contains several keys and * their defined values. The given reference to the configuration object * will remain valid until the report parsing or writing ends. *

* The configuration contents may change during the reporting. * * @param config the configuration, never null */ public void configure(final Configuration config) { // nothing required } /** * ArrayClassFactories are always equal, there is nothing that could * not be equal :) * * @param o the other object. * @return true, if both object factories describe the same objects, false otherwise. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof ArrayClassFactory)) { return false; } return true; } /** * Returns a hash code value for the object. This method is * supported for the benefit of hashtables such as those provided by * java.util.Hashtable. * * @return the computed hashcode. */ public int hashCode() { return getClass().hashCode(); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/LongObjectDescription.java0000644000175000017500000000734511172030703027361 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * LongObjectDescription.java * -------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: LongObjectDescription.java,v 1.3 2005/11/14 11:03:00 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; /** * An object-description for a Long object. * * @author Thomas Morgner */ public class LongObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public LongObjectDescription() { super(Long.class); setParameterDefinition("value", String.class); } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { final String o = (String) getParameter("value"); return Long.valueOf(o); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Long). * * @throws ObjectFactoryException if the object is not an instance of Long. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Long)) { throw new ObjectFactoryException("The given object is no java.lang.Long."); } setParameter("value", String.valueOf(o)); } /** * Tests for equality. * * @param o the object to test. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof AbstractObjectDescription)) { return false; } final AbstractObjectDescription abstractObjectDescription = (AbstractObjectDescription) o; if (Long.TYPE.equals(abstractObjectDescription.getObjectClass())) { return true; } if (Long.class.equals(abstractObjectDescription.getObjectClass())) { return true; } return false; } /** * Returns a hash code. * * @return A hash code. */ public int hashCode() { return getObjectClass().hashCode(); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/Rectangle2DObjectDescription.java0000644000175000017500000001014611172030703030545 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------------- * rectangle2DObjectDescription.java * --------------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Rectangle2DObjectDescription.java,v 1.3 2005/11/14 11:03:47 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import java.awt.geom.Rectangle2D; /** * An object-description for a Rectangle2D object. * * @author Thomas Morgner */ public class Rectangle2DObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public Rectangle2DObjectDescription() { super(Rectangle2D.class); setParameterDefinition("width", Float.class); setParameterDefinition("height", Float.class); setParameterDefinition("x", Float.class); setParameterDefinition("y", Float.class); } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { final Rectangle2D rect = new Rectangle2D.Float(); final float w = getFloatParameter("width"); final float h = getFloatParameter("height"); final float x = getFloatParameter("x"); final float y = getFloatParameter("y"); rect.setRect(x, y, w, h); return rect; } /** * Returns a parameter value as a float. * * @param param the parameter name. * * @return The float value. */ private float getFloatParameter(final String param) { final Float p = (Float) getParameter(param); if (p == null) { return 0; } return p.floatValue(); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Rectangle2D). * * @throws ObjectFactoryException if the object is not an instance of Rectangle2D. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Rectangle2D)) { throw new ObjectFactoryException("The given object is no java.awt.geom.Rectangle2D."); } final Rectangle2D rect = (Rectangle2D) o; final float x = (float) rect.getX(); final float y = (float) rect.getY(); final float w = (float) rect.getWidth(); final float h = (float) rect.getHeight(); setParameter("x", new Float(x)); setParameter("y", new Float(y)); setParameter("width", new Float(w)); setParameter("height", new Float(h)); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/BasicStrokeObjectDescription.java0000644000175000017500000001043611172030703030666 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------------- * BasicStrokeObjectDescription.java * --------------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: BasicStrokeObjectDescription.java,v 1.4 2006/01/27 18:53:15 taqua Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import java.awt.BasicStroke; /** * An object-description for a BasicStroke object. * * @author Thomas Morgner */ public class BasicStrokeObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public BasicStrokeObjectDescription() { super(BasicStroke.class); setParameterDefinition("value", String.class); setParameterDefinition("width", Float.class); setParameterDefinition("dashes", Float[].class); } /** * Returns a parameter as a float. * * @param param the parameter name. * * @return The float value. */ private float getFloatParameter(final String param) { final String p = (String) getParameter(param); if (p == null) { return 0; } try { return Float.parseFloat(p); } catch (Exception e) { return 0; } } /** * Creates a new BasicStroke object based on this description. * * @return The BasicStroke object. */ public Object createObject() { final float width = getFloatParameter("value"); if (width > 0) { return new BasicStroke(width); } Float realWidth = (Float) getParameter("width"); Float[] dashes = (Float[]) getParameter("dashes"); if (realWidth == null || dashes == null) { return null; } float[] dashesPrimitive = new float[dashes.length]; for (int i = 0; i < dashes.length; i++) { Float dash = dashes[i]; dashesPrimitive[i] = dash.floatValue(); } return new BasicStroke(realWidth.floatValue(), BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 10.0f, dashesPrimitive, 0.0f); } /** * Sets the parameters for this description to match the supplied object. * * @param o the object (instance of BasicStroke required). * * @throws ObjectFactoryException if the supplied object is not an instance of * BasicStroke. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof BasicStroke)) { throw new ObjectFactoryException("Expected object of type BasicStroke"); } final BasicStroke bs = (BasicStroke) o; setParameter("value", String.valueOf(bs.getLineWidth())); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/DoubleObjectDescription.java0000644000175000017500000000737511172030703027677 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * DoubleDescription.java * ---------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DoubleObjectDescription.java,v 1.3 2005/11/14 11:01:56 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; /** * An object-description for a Double object. * * @author Thomas Morgner */ public class DoubleObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public DoubleObjectDescription() { super(Double.class); setParameterDefinition("value", String.class); } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { final String o = (String) getParameter("value"); return Double.valueOf(o); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Double). * * @throws ObjectFactoryException if the object is not an instance of Double. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Double)) { throw new ObjectFactoryException("The given object is no java.lang.Double."); } setParameter("value", String.valueOf(o)); } /** * Tests for equality. * * @param o the object to test. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof AbstractObjectDescription)) { return false; } final AbstractObjectDescription abstractObjectDescription = (AbstractObjectDescription) o; if (Double.TYPE.equals(abstractObjectDescription.getObjectClass())) { return true; } if (Double.class.equals(abstractObjectDescription.getObjectClass())) { return true; } return false; } /** * Returns a hash code for the object. * * @return The hash code. */ public int hashCode() { return getObjectClass().hashCode(); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/FloatObjectDescription.java0000644000175000017500000000735711172030703027532 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------- * FloatObjectDescription.java * --------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: FloatObjectDescription.java,v 1.3 2005/11/14 11:02:08 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; /** * An object-description for a Float object. * * @author Thomas Morgner */ public class FloatObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public FloatObjectDescription() { super(Float.class); setParameterDefinition("value", String.class); } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { final String o = (String) getParameter("value"); return Float.valueOf(o); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Float). * * @throws ObjectFactoryException if the object is not an instance of Float. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Float)) { throw new ObjectFactoryException("The given object is no java.lang.Float."); } setParameter("value", String.valueOf(o)); } /** * Tests for equality. * * @param o the object to test. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof AbstractObjectDescription)) { return false; } final AbstractObjectDescription abstractObjectDescription = (AbstractObjectDescription) o; if (Float.TYPE.equals(abstractObjectDescription.getObjectClass())) { return true; } if (Float.class.equals(abstractObjectDescription.getObjectClass())) { return true; } return false; } /** * Returns a hash code. * * @return A hash code. */ public int hashCode() { return getObjectClass().hashCode(); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/ObjectDescription.java0000644000175000017500000001256511172030703026541 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * ObjectDescription.java * ---------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ObjectDescription.java,v 1.3 2005/11/14 11:03:12 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import java.io.Serializable; import java.util.Iterator; import org.jfree.util.Configuration; /** * An interface for object descriptions. * * @author Thomas Morgner */ public interface ObjectDescription extends Serializable { /** * Returns a parameter definition. If the parameter is invalid, this * function returns null. * * @param name the definition name. * * @return The parameter class or null, if the parameter is not defined. */ public Class getParameterDefinition(String name); /** * Sets the value of a parameter. * * @param name the parameter name. * @param value the parameter value. */ public void setParameter(String name, Object value); /** * Returns the value of a parameter. * * @param name the parameter name. * * @return The value. */ public Object getParameter(String name); /** * Returns an iterator the provides access to the parameter names. This * returns all _known_ parameter names, the object description may accept * additional parameters. * * @return The iterator. */ public Iterator getParameterNames(); /** * Returns the object class. * * @return The Class. */ public Class getObjectClass(); /** * Creates an object based on the description. * * @return The object. */ public Object createObject(); /** * Returns a cloned instance of the object description. The contents * of the parameter objects collection are cloned too, so that any * already defined parameter value is copied to the new instance. *

* Parameter definitions are not cloned, as they are considered read-only. *

* The newly instantiated object description is not configured. If it * need to be configured, then you have to call configure on it. * * @return A cloned instance. */ public ObjectDescription getUnconfiguredInstance(); /** * Returns a cloned instance of the object description. The contents * of the parameter objects collection are cloned too, so that any * already defined parameter value is copied to the new instance. *

* Parameter definitions are not cloned, as they are considered read-only. * * @return A cloned instance. */ public ObjectDescription getInstance(); /** * Sets the parameters of this description object to match the supplied object. * * @param o the object. * * @throws ObjectFactoryException if there is a problem while reading the * properties of the given object. */ public void setParameterFromObject(Object o) throws ObjectFactoryException; /** * Configures this factory. The configuration contains several keys and * their defined values. The given reference to the configuration object * will remain valid until the report parsing or writing ends. *

* The configuration contents may change during the reporting. * * @param config the configuration, never null */ public void configure(Configuration config); /** * Compares whether two object descriptions are equal. * * @param o the other object. * @return true, if both object desciptions describe the same object, false otherwise. */ public boolean equals (Object o); /** * Computes the hashCode for this ClassFactory. As equals() must be implemented, * a corresponding hashCode() should be implemented as well. * * @return the hashcode. */ public int hashCode(); } jcommon-1.0.16/source/org/jfree/xml/factory/objects/ArrayObjectDescription.java0000644000175000017500000001526411172030703027537 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------- * ArrayObjectDescription.java * --------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner (taquera@sherito.org); * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ArrayObjectDescription.java,v 1.4 2006/01/27 18:53:15 taqua Exp $ * * Changes * ------- * 14-Apr-2003 : Initial version * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon */ package org.jfree.xml.factory.objects; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Iterator; import org.jfree.util.Log; /** * Describes an Object- or primitive value array. This object description is * not intended to be created outside the ArrayClassFactory. * * @author Thomas Morgner */ public class ArrayObjectDescription extends AbstractObjectDescription { /** * Constructs a new array objet description for the given array class. *

* Note: throws IllegalArgumentException if the given class is no array. * * @param c the array class object. */ public ArrayObjectDescription(final Class c) { super(c); if (!c.isArray()) { throw new IllegalArgumentException("Need an array class"); } } /** * Creates an object based on the description. * * @return The object. */ public Object createObject() { try { final Integer size = (Integer) getParameter("size"); if (size == null) { final ArrayList l = new ArrayList(); int counter = 0; while (getParameterDefinition(String.valueOf(counter)) != null) { final Object value = getParameter(String.valueOf(counter)); if (value == null) { break; } l.add(value); counter += 1; } final Object o = Array.newInstance (getObjectClass().getComponentType(), l.size()); for (int i = 0; i < l.size(); i++) { Array.set(o, i, l.get(i)); } return o; } else { // a size is given, so we can assume that all values are defined. final Object o = Array.newInstance (getObjectClass().getComponentType(), size.intValue()); for (int i = 0; i < size.intValue(); i++) { Array.set(o, i, getParameter(String.valueOf(i))); } return o; } } catch (Exception ie) { Log.warn("Unable to instantiate Object", ie); return null; } } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object. * * @throws ObjectFactoryException if there is a * problem while reading the properties of the given object. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (o == null) { throw new ObjectFactoryException("Given object is null."); } if (!o.getClass().isArray()) { throw new ObjectFactoryException("Given object is no array"); } if (!getObjectClass().isAssignableFrom(o.getClass())) { throw new ObjectFactoryException("Given object is incompatible with base class"); } final int size = Array.getLength(o); setParameter("size", new Integer(size)); for (int i = 0; i < size; i++) { setParameter(String.valueOf(i), Array.get(o, i)); } } /** * Tries to parse the given parameter string into a positive integer. * Returns -1 if the parsing failed for some reason. * * @param name the name of the parameter. * @return the parsed int value or -1 on errors. */ private int parseParameterName(final String name) { try { return Integer.parseInt(name); } catch (Exception e) { return -1; } } /** * Returns a parameter definition. If the parameter is invalid, this * function returns null. * * @param name the definition name. * * @return The parameter class or null, if the parameter is not defined. */ public Class getParameterDefinition(final String name) { if (name.equals("size")) { return Integer.TYPE; } final int par = parseParameterName(name); if (par < 0) { return null; } return getObjectClass().getComponentType(); } /** * Returns an iterator for the parameter names. * * @return The iterator. */ public Iterator getParameterNames() { final Integer size = (Integer) getParameter("size"); if (size == null) { return getDefinedParameterNames(); } else { final ArrayList l = new ArrayList(); l.add("size"); for (int i = 0; i < size.intValue(); i++) { l.add(String.valueOf(i)); } return l.iterator(); } } /** * Returns a new instance of the object description. * * @return The object description. */ public ObjectDescription getInstance() { return new ArrayObjectDescription(getObjectClass()); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/ClassFactoryImpl.java0000644000175000017500000001571011172030703026341 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * ClassFactoryImpl.java * --------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ClassFactoryImpl.java,v 1.6 2006/01/25 23:15:03 taqua Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * 29-Jul-2004 : Replaced 'enum' variable name (reserved word in JDK 1.5) (DG); * */ package org.jfree.xml.factory.objects; import java.util.HashMap; import java.util.Iterator; import org.jfree.util.Configuration; import org.jfree.util.ClassComparator; /** * An abstract class that implements the {@link ClassFactory} interface. * * @author Thomas Morgner. */ public abstract class ClassFactoryImpl implements ClassFactory { /** Storage for the classes. */ private HashMap classes; /** A class comparator for searching the super class */ private ClassComparator comparator; /** The parser/report configuration */ private Configuration config; /** * Creates a new class factory. */ public ClassFactoryImpl() { this.classes = new HashMap(); this.comparator = new ClassComparator(); } /** * Returns the class comparator used to sort the super classes of an object. * * @return the class comparator. */ public ClassComparator getComparator() { return this.comparator; } /** * Returns an object-description for a class. * * @param c the class. * * @return An object description. */ public ObjectDescription getDescriptionForClass(final Class c) { final ObjectDescription od = (ObjectDescription) this.classes.get(c); if (od == null) { return null; } return od.getInstance(); } /** * Returns the most concrete object-description for the super class of a class. * * @param d the class. * @param knownSuperClass a known supported superclass or null, if no superclass * is known yet. * * @return The object description. */ public ObjectDescription getSuperClassObjectDescription (final Class d, ObjectDescription knownSuperClass) { if (d == null) { throw new NullPointerException("Description class must not be null."); } final Iterator iterator = this.classes.keySet().iterator(); while (iterator.hasNext()) { final Class keyClass = (Class) iterator.next(); if (keyClass.isAssignableFrom(d)) { final ObjectDescription od = (ObjectDescription) this.classes.get(keyClass); if (knownSuperClass == null) { knownSuperClass = od; } else { if (this.comparator.isComparable (knownSuperClass.getObjectClass(), od.getObjectClass())) { if (this.comparator.compare (knownSuperClass.getObjectClass(), od.getObjectClass()) < 0) { knownSuperClass = od; } } } } } if (knownSuperClass == null) { return null; } return knownSuperClass.getInstance(); } /** * Registers an object description with the factory. * * @param key the key. * @param od the object description. */ protected void registerClass(final Class key, final ObjectDescription od) { this.classes.put(key, od); if (this.config != null) { od.configure(this.config); } } /** * Returns an iterator that provides access to the registered object definitions. * * @return The iterator. */ public Iterator getRegisteredClasses() { return this.classes.keySet().iterator(); } /** * Configures this factory. The configuration contains several keys and * their defined values. The given reference to the configuration object * will remain valid until the report parsing or writing ends. *

* The configuration contents may change during the reporting. * * @param config the configuration, never null */ public void configure(final Configuration config) { if (config == null) { throw new NullPointerException("The given configuration is null"); } if (this.config != null) { // already configured ... ignored return; } this.config = config; final Iterator it = this.classes.values().iterator(); while (it.hasNext()) { final ObjectDescription od = (ObjectDescription) it.next(); od.configure(config); } } /** * Returns the currently set configuration or null, if none was set. * * @return the configuration. */ public Configuration getConfig() { return this.config; } /** * Tests for equality. * * @param o the object to test. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof ClassFactoryImpl)) { return false; } final ClassFactoryImpl classFactory = (ClassFactoryImpl) o; if (!this.classes.equals(classFactory.classes)) { return false; } return true; } /** * Returns a hash code. * * @return A hash code. */ public int hashCode() { return this.classes.hashCode(); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/StringObjectDescription.java0000644000175000017500000000567311172030703027732 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------- * StringObjectDescription.java * ---------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: StringObjectDescription.java,v 1.3 2005/11/14 11:04:24 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; /** * An object-description for a String object. * * @author Thomas Morgner */ public class StringObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public StringObjectDescription() { super(String.class); setParameterDefinition("value", String.class); } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { final String o = (String) getParameter("value"); return String.valueOf(o); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of String). * * @throws ObjectFactoryException if the object is not an instance of String. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof String)) { throw new ObjectFactoryException("The given object is no java.lang.String."); } setParameter("value", String.valueOf(o)); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/Line2DObjectDescription.java0000644000175000017500000001001311172030703027521 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------- * Line2DObjectDescription.java * ---------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Line2DObjectDescription.java,v 1.3 2005/11/14 11:02:46 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import java.awt.geom.Line2D; /** * An object-description for a Line2D object. * * @author Thomas Morgner */ public class Line2DObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public Line2DObjectDescription() { super(Line2D.class); setParameterDefinition("x1", Float.class); setParameterDefinition("x2", Float.class); setParameterDefinition("y1", Float.class); setParameterDefinition("y2", Float.class); } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { final Line2D line = new Line2D.Float(); final float x1 = getFloatParameter("x1"); final float x2 = getFloatParameter("x2"); final float y1 = getFloatParameter("y1"); final float y2 = getFloatParameter("y2"); line.setLine(x1, y1, x2, y2); return line; } /** * Returns a parameter value as a float. * * @param param the parameter name. * * @return The float value. */ private float getFloatParameter(final String param) { final Float p = (Float) getParameter(param); if (p == null) { return 0; } return p.floatValue(); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Line2D). * * @throws ObjectFactoryException if the object is not an instance of Line2D. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Line2D)) { throw new ObjectFactoryException("The given object is no java.awt.geom.Line2D."); } final Line2D line = (Line2D) o; final float x1 = (float) line.getX1(); final float x2 = (float) line.getX2(); final float y1 = (float) line.getY1(); final float y2 = (float) line.getY2(); setParameter("x1", new Float(x1)); setParameter("x2", new Float(x2)); setParameter("y1", new Float(y1)); setParameter("y2", new Float(y2)); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/URLObjectDescription.java0000644000175000017500000000735711172030703027127 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * URLClassFactory.java * -------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: URLObjectDescription.java,v 1.3 2005/11/14 11:04:43 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import java.net.URL; import org.jfree.io.IOUtils; import org.jfree.util.Log; import org.jfree.xml.Parser; /** * An object-description for a URL object. * * @author Thomas Morgner */ public class URLObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public URLObjectDescription() { super(URL.class); setParameterDefinition("value", String.class); } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { final String o = (String) getParameter("value"); final String baseURL = getConfig().getConfigProperty(Parser.CONTENTBASE_KEY); try { try { final URL bURL = new URL(baseURL); return new URL(bURL, o); } catch (Exception e) { Log.warn("BaseURL is invalid: ", e); } return new URL(o); } catch (Exception e) { return null; } } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of URL). * * @throws ObjectFactoryException if the object is not an instance of URL. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof URL)) { throw new ObjectFactoryException("Is no instance of java.net.URL"); } final URL comp = (URL) o; final String baseURL = getConfig().getConfigProperty(Parser.CONTENTBASE_KEY); try { final URL bURL = new URL(baseURL); setParameter("value", IOUtils.getInstance().createRelativeURL(comp, bURL)); } catch (Exception e) { Log.warn("BaseURL is invalid: ", e); } setParameter("value", comp.toExternalForm()); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/ObjectFactoryException.java0000644000175000017500000000576411172030703027547 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------- * ObjectFactoryException.java * --------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ObjectFactoryException.java,v 1.3 2005/11/14 11:03:24 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; import org.jfree.util.StackableException; /** * An exception that is thrown, if the creation of an Object failed in the * ObjectFactory implementation. * * @author Thomas Morgner. */ public class ObjectFactoryException extends StackableException { /** * Constructs a new exception with null as its detail message. * The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause}. */ public ObjectFactoryException() { super(); } /** * Constructs a new exception with the specified detail message. The * cause is not initialized, and may subsequently be initialized by * a call to {@link #initCause}. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ public ObjectFactoryException(final String message) { super(message); } /** * Creates a new exception. * * @param message the message. * @param cause the cause of the exception. */ public ObjectFactoryException(final String message, final Exception cause) { super(message, cause); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/ClassComparator.java0000644000175000017500000001131211172030703026211 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * ClassComparator.java * -------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner (taquera@sherito.org); * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ClassComparator.java,v 1.5 2005/11/08 14:22:04 mungady Exp $ * * Changes * ------- * 02-May-2003 : Initial version */ package org.jfree.xml.factory.objects; import java.io.Serializable; import java.util.Comparator; /** * The class comparator can be used to compare and sort classes and their * superclasses. The comparator is not able to compare classes which have * no relation... * * @author Thomas Morgner * @deprecated Moved to org.jfree.util */ public class ClassComparator implements Comparator, Serializable { /** * Defaultconstructor. */ public ClassComparator() { super(); } /** * Compares its two arguments for order. Returns a negative integer, * zero, or a positive integer as the first argument is less than, equal * to, or greater than the second.

*

* Note: throws ClassCastException if the arguments' types prevent them from * being compared by this Comparator. * And IllegalArgumentException if the classes share no relation. * * The implementor must ensure that sgn(compare(x, y)) == * -sgn(compare(y, x)) for all x and y. (This * implies that compare(x, y) must throw an exception if and only * if compare(y, x) throws an exception.)

* * The implementor must also ensure that the relation is transitive: * ((compare(x, y)>0) && (compare(y, z)>0)) implies * compare(x, z)>0.

* * Finally, the implementer must ensure that compare(x, y)==0 * implies that sgn(compare(x, z))==sgn(compare(y, z)) for all * z.

* * It is generally the case, but not strictly required that * (compare(x, y)==0) == (x.equals(y)). Generally speaking, * any comparator that violates this condition should clearly indicate * this fact. The recommended language is "Note: this comparator * imposes orderings that are inconsistent with equals." * * @param o1 the first object to be compared. * @param o2 the second object to be compared. * @return a negative integer, zero, or a positive integer as the * first argument is less than, equal to, or greater than the * second. */ public int compare(final Object o1, final Object o2) { final Class c1 = (Class) o1; final Class c2 = (Class) o2; if (c1.equals(o2)) { return 0; } if (c1.isAssignableFrom(c2)) { return -1; } else { if (!c2.isAssignableFrom(c2)) { throw new IllegalArgumentException("The classes share no relation"); } return 1; } } /** * Checks, whether the given classes are comparable. This method will * return true, if one of the classes is assignable from the other class. * * @param c1 the first class to compare * @param c2 the second class to compare * @return true, if the classes share a direct relation, false otherwise. */ public boolean isComparable(final Class c1, final Class c2) { return (c1.isAssignableFrom(c2) || c2.isAssignableFrom(c1)); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/IntegerObjectDescription.java0000644000175000017500000000741711172030703030057 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------------- * IntegerObjectDescription.java * ----------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: IntegerObjectDescription.java,v 1.3 2005/11/14 11:02:20 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml.factory.objects; /** * An object-description for an Integer object. * * @author Thomas Morgner */ public class IntegerObjectDescription extends AbstractObjectDescription { /** * Creates a new object description. */ public IntegerObjectDescription() { super(Integer.class); setParameterDefinition("value", String.class); } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { final String o = (String) getParameter("value"); return Integer.valueOf(o); } /** * Sets the parameters of this description object to match the supplied object. * * @param o the object (should be an instance of Integer). * * @throws ObjectFactoryException if the object is not an instance of Integer. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (!(o instanceof Integer)) { throw new ObjectFactoryException("The given object is no java.lang.Integer."); } setParameter("value", String.valueOf(o)); } /** * Tests for equality. * * @param o the object to test. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof AbstractObjectDescription)) { return false; } final AbstractObjectDescription abstractObjectDescription = (AbstractObjectDescription) o; if (Integer.TYPE.equals(abstractObjectDescription.getObjectClass())) { return true; } if (Integer.class.equals(abstractObjectDescription.getObjectClass())) { return true; } return false; } /** * Returns a hash code. * * @return A hash code. */ public int hashCode() { return getObjectClass().hashCode(); } } jcommon-1.0.16/source/org/jfree/xml/factory/objects/BeanObjectDescription.java0000644000175000017500000002116311172030703027321 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * BeanObjectDescription.java * -------------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: BeanObjectDescription.java,v 1.6 2005/10/18 13:31:58 mungady Exp $ * * Changes (from 19-Feb-2003) * ------------------------- * 19-Feb-2003 : Added standard header and Javadocs (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into * JCommon (TM); * 18-Aug-2005 : Added casts to suppress compiler warnings, as suggested in * patch 1260622 (DG); * */ package org.jfree.xml.factory.objects; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.TreeSet; import java.util.HashMap; import java.beans.Introspector; import java.beans.IntrospectionException; import java.beans.BeanInfo; import java.beans.PropertyDescriptor; import java.io.ObjectInputStream; import java.io.IOException; import org.jfree.util.Log; /** * An object-description for a bean object. This object description * is very dangerous, if the bean contains properties with undefined * types. * * @author Thomas Morgner */ public class BeanObjectDescription extends AbstractObjectDescription { private TreeSet ignoredParameters; private transient HashMap properties; /** * Creates a new object description. * * @param className the class. */ public BeanObjectDescription(final Class className) { this(className, true); } /** * Creates a new object description. * * @param className the class. * @param init set to true, to autmaoticly initialise the object * description. If set to false, the initialisation is * elsewhere. */ public BeanObjectDescription(final Class className, final boolean init) { super(className); // now create some method descriptions .. this.ignoredParameters = new TreeSet(); readBeanDescription(className, init); } private boolean isValidMethod (final Method method, final int parCount) { if (method == null) { return false; } if (!Modifier.isPublic(method.getModifiers())) { return false; } if (Modifier.isStatic(method.getModifiers())) { return false; } if (method.getParameterTypes().length != parCount) { return false; } return true; } /** * Creates an object based on this description. * * @return The object. */ public Object createObject() { try { final Object o = getObjectClass().newInstance(); // now add the various parameters ... final Iterator it = getParameterNames(); while (it.hasNext()) { final String name = (String) it.next(); if (isParameterIgnored(name)) { continue; } final Method method = findSetMethod(name); final Object parameterValue = getParameter(name); if (parameterValue == null) { // Log.debug ("Parameter: " + name + " is null"); } else { method.invoke(o, new Object[]{parameterValue}); } } return o; } catch (Exception e) { Log.error("Unable to invoke bean method", e); } return null; } /** * Finds a set method in the bean. * * @param parameterName the parameter name. * * @return The method. */ private Method findSetMethod(final String parameterName) { final PropertyDescriptor descriptor = (PropertyDescriptor) this.properties.get(parameterName); return descriptor.getWriteMethod(); } /** * Finds a get method in the bean. * * @param parameterName the paramater name. * @return The method. */ private Method findGetMethod(final String parameterName) { final PropertyDescriptor descriptor = (PropertyDescriptor) this.properties.get(parameterName); return descriptor.getReadMethod(); } /** * Sets the parameters in the description to match the supplied object. * * @param o the object (null not allowed). * * @throws ObjectFactoryException if there is a problem. */ public void setParameterFromObject(final Object o) throws ObjectFactoryException { if (o == null) { throw new NullPointerException("Given object is null"); } final Class c = getObjectClass(); if (!c.isInstance(o)) { throw new ObjectFactoryException("Object is no instance of " + c + "(is " + o.getClass() + ")"); } final Iterator it = getParameterNames(); while (it.hasNext()) { final String propertyName = (String) it.next(); if (isParameterIgnored(propertyName)) { continue; } try { final Method method = findGetMethod(propertyName); final Object retval = method.invoke(o, (Object[]) null); if (retval != null) { setParameter(propertyName, retval); } } catch (Exception e) { Log.info("Exception on method invokation.", e); } } } /** * Adds a parameter to the ignored parameters. * * @param parameter the parameter. */ protected void ignoreParameter(final String parameter) { this.ignoredParameters.add (parameter); } /** * Returns a flag that indicates whether or not the specified parameter is * ignored. * * @param parameter the parameter. * * @return The flag. */ protected boolean isParameterIgnored (final String parameter) { return this.ignoredParameters.contains(parameter); } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); readBeanDescription(getObjectClass(), false); } private void readBeanDescription(final Class className, final boolean init) { try { this.properties = new HashMap(); final BeanInfo bi = Introspector.getBeanInfo(className); final PropertyDescriptor[] propertyDescriptors = bi.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { final PropertyDescriptor propertyDescriptor = propertyDescriptors[i]; final Method readMethod = propertyDescriptor.getReadMethod(); final Method writeMethod = propertyDescriptor.getWriteMethod(); if (isValidMethod(readMethod, 0) && isValidMethod(writeMethod, 1)) { final String name = propertyDescriptor.getName(); this.properties.put(name, propertyDescriptor); if (init) { super.setParameterDefinition(name, propertyDescriptor.getPropertyType()); } } } } catch (IntrospectionException e) { Log.error ("Unable to build bean description", e); } } } jcommon-1.0.16/source/org/jfree/xml/ParserFrontend.java0000644000175000017500000002315611172030703022761 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * ReportGenerator.java * -------------------- * (C)opyright 2002-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner (taquera@sherito.org); * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ParserFrontend.java,v 1.8 2005/11/14 10:58:19 mungady Exp $ * * Changes * ------- * 10-May-2002 : Initial version * 12-Dec-2002 : Fixed issues reported by Checkstyle (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * */ package org.jfree.xml; import java.io.BufferedInputStream; import java.io.IOException; import java.net.URL; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.jfree.util.Log; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * The reportgenerator initializes the parser and provides an interface * the the default parser. * * To create a report from an URL, use * * ReportGenerator.getInstance().parseReport (URL myURl, URL contentBase); * * * @author Thomas Morgner */ public class ParserFrontend { /** The report handler. */ private FrontendDefaultHandler defaulthandler; /** The parser factory. */ private SAXParserFactory factory; /** The DTD. */ private EntityResolver entityResolver; /** A flag indicating whether to use a DTD to validate the xml input. */ private boolean validateDTD; /** * Creates a new report generator. The generator uses the singleton pattern by default, * so use generator.getInstance() to get the generator. * * @param parser the parser that is used to coordinate the parsing process. */ protected ParserFrontend(final FrontendDefaultHandler parser) { if (parser == null) { throw new NullPointerException(); } this.defaulthandler = parser; } /** * Returns true if the report definition should be validated against the * DTD, and false otherwise. * * @return A boolean. */ public boolean isValidateDTD() { return this.validateDTD; } /** * Sets a flag that controls whether or not the report definition is validated * against the DTD. * * @param validateDTD the flag. */ public void setValidateDTD(final boolean validateDTD) { this.validateDTD = validateDTD; } /** * Returns the entity resolver. * * @return The entity resolver. */ public EntityResolver getEntityResolver() { return this.entityResolver; } /** * Sets the entity resolver. * * @param entityResolver the entity resolver. */ public void setEntityResolver(final EntityResolver entityResolver) { this.entityResolver = entityResolver; } /** * Returns a SAX parser. * * @return a SAXParser. * * @throws ParserConfigurationException if there is a problem configuring the parser. * @throws SAXException if there is a problem with the parser initialisation */ protected SAXParser getParser() throws ParserConfigurationException, SAXException { if (this.factory == null) { this.factory = SAXParserFactory.newInstance(); if (isValidateDTD()) { try { // dont touch the validating feature, if not needed .. this.factory.setValidating(true); } catch (Exception ex) { // the parser does not like the idea of validating ... Log.debug("The parser will not validate the xml document.", ex); } } } return this.factory.newSAXParser(); } /** * Sets the default handler used for parsing reports. This handler is used to * initiate parsing. * * @param handler the handler. */ public void setDefaultHandler(final FrontendDefaultHandler handler) { if (handler == null) { throw new NullPointerException(); } this.defaulthandler = handler; } /** * Returns the ElementDefinitionHandler used for parsing reports. * * @return the report handler. */ public FrontendDefaultHandler getDefaultHandler() { return this.defaulthandler; } /** * Creates a new instance of the currently set default handler and sets the contentbase * for the handler to contentBase. * * @param contentBase the content base. * * @return the report handler. */ protected FrontendDefaultHandler createDefaultHandler(final URL contentBase) { final FrontendDefaultHandler handler = getDefaultHandler().newInstance(); if (contentBase != null) { handler.setConfigProperty(Parser.CONTENTBASE_KEY, contentBase.toExternalForm()); } return handler; } /** * Parses an XML report template file. * * @param input the input source. * @param contentBase the content base. * * @return the report. * * @throws ElementDefinitionException if an error occurred. */ protected Object parse(final InputSource input, final URL contentBase) throws ElementDefinitionException { try { final SAXParser parser = getParser(); final XMLReader reader = parser.getXMLReader(); try { reader.setFeature("http://xml.org/sax/features/validation", isValidateDTD()); } catch (SAXException se) { Log.debug("The XMLReader will not validate the xml document.", se); } final FrontendDefaultHandler handler = createDefaultHandler(contentBase); configureReader(reader, handler); try { reader.setContentHandler(handler); reader.setDTDHandler(handler); if (getEntityResolver() != null) { reader.setEntityResolver(getEntityResolver()); } reader.setErrorHandler(handler); reader.parse(input); return handler.getResult(); } catch (IOException e) { throw new ElementDefinitionException(e); } } catch (ParserConfigurationException e) { throw new ElementDefinitionException(e); } catch (SAXException e) { throw new ElementDefinitionException(e); } } /** * Configures the xml reader. Use this to set features or properties * before the documents get parsed. * * @param handler the parser implementation that will handle the SAX-Callbacks. * @param reader the xml reader that should be configured. */ protected void configureReader(final XMLReader reader, final FrontendDefaultHandler handler) { try { reader.setProperty ("http://xml.org/sax/properties/lexical-handler", handler.getCommentHandler()); } catch (SAXException se) { Log.debug("Comments are not supported by this SAX implementation."); } } /** * Parses an XML file which is loaded using the given URL. All * needed relative file- and resourcespecification are loaded * using the URL contentBase as base. *

* After the report is generated, the ReportDefinition-source and the contentbase are * stored as string in the reportproperties. * * @param file the URL for the report template file. * @param contentBase the URL for the report template content base. * * @return the parsed report. * * @throws IOException if an I/O error occurs. * @throws ElementDefinitionException if there is a problem parsing the report template. */ public Object parse(final URL file, final URL contentBase) throws ElementDefinitionException, IOException { if (file == null) { throw new NullPointerException("File may not be null"); } final BufferedInputStream bin = new BufferedInputStream(file.openStream()); final InputSource in = new InputSource(bin); in.setSystemId(file.toString()); final Object result = parse(in, contentBase); bin.close(); return result; } } jcommon-1.0.16/source/org/jfree/xml/util/0000755000175000017500000000000011351753320020136 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/xml/util/BasicTypeSupport.java0000644000175000017500000001335511172030703024262 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * BasicTypeSupport.java * --------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: BasicTypeSupport.java,v 1.4 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 12-Nov-2003 : Initial version (TM); * 26-Nov-2003 : Updated header and Javadocs (DG); * */ package org.jfree.xml.util; import org.jfree.xml.attributehandlers.BooleanAttributeHandler; import org.jfree.xml.attributehandlers.ByteAttributeHandler; import org.jfree.xml.attributehandlers.DoubleAttributeHandler; import org.jfree.xml.attributehandlers.FloatAttributeHandler; import org.jfree.xml.attributehandlers.IntegerAttributeHandler; import org.jfree.xml.attributehandlers.LongAttributeHandler; import org.jfree.xml.attributehandlers.ShortAttributeHandler; import org.jfree.xml.attributehandlers.StringAttributeHandler; /** * A class that contains information about some basic types. */ public class BasicTypeSupport { private BasicTypeSupport () { } /** * Returns the fully qualified class name for the attribute handler for a property of * the specified class. * * @param c the property class. * * @return the attribute handler class name. */ public static String getHandlerClass(final Class c) { if (c.equals(Integer.class) || c.equals(Integer.TYPE)) { return IntegerAttributeHandler.class.getName(); } if (c.equals(Short.class) || c.equals(Short.TYPE)) { return ShortAttributeHandler.class.getName(); } if (c.equals(Long.class) || c.equals(Long.TYPE)) { return LongAttributeHandler.class.getName(); } if (c.equals(Boolean.class) || c.equals(Boolean.TYPE)) { return BooleanAttributeHandler.class.getName(); } if (c.equals(Float.class) || c.equals(Float.TYPE)) { return FloatAttributeHandler.class.getName(); } if (c.equals(Double.class) || c.equals(Double.TYPE)) { return DoubleAttributeHandler.class.getName(); } if (c.equals(Byte.class) || c.equals(Byte.TYPE)) { return ByteAttributeHandler.class.getName(); } // string can also be handled directly ... if (c.equals(String.class)) { return StringAttributeHandler.class.getName(); } throw new IllegalArgumentException("BasicTypeSupport.getHandlerClass(Class): " + "this is no attribute type."); } /** * Returns true if the specified class is a "basic" type, and false * otherwise. Basic types are written as attributes (rather than elements) in XML output. * * @param c the class. * * @return a boolean. */ public static boolean isBasicDataType (final Class c) { if (c.equals(Integer.class) || c.equals(Integer.TYPE)) { return true; } if (c.equals(Short.class) || c.equals(Short.TYPE)) { return true; } if (c.equals(Long.class) || c.equals(Long.TYPE)) { return true; } if (c.equals(Boolean.class) || c.equals(Boolean.TYPE)) { return true; } if (c.equals(Float.class) || c.equals(Float.TYPE)) { return true; } if (c.equals(Double.class) || c.equals(Double.TYPE)) { return true; } if (c.equals(Byte.class) || c.equals(Byte.TYPE)) { return true; } // string can also be handled directly ... if (c.equals(String.class)) { return true; } return false; } /** * Returns the class for a given primitive class type. * * @param className the primitive class name. * * @return a class. */ public static Class getClassRepresentation(final String className) { if (className.equals("::double")) { return Double.TYPE; } if (className.equals("::boolean")) { return Boolean.TYPE; } if (className.equals("::int")) { return Integer.TYPE; } if (className.equals("::short")) { return Short.TYPE; } if (className.equals("::long")) { return Long.TYPE; } if (className.equals("::byte")) { return Byte.TYPE; } throw new IllegalArgumentException("This is none of my primitives."); } } jcommon-1.0.16/source/org/jfree/xml/util/MultiplexMappingDefinition.java0000644000175000017500000000735411172030703026314 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------- * MultiplexMappingDefinition.java * ------------------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: MultiplexMappingDefinition.java,v 1.3 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 22-Nov-2003 : Initial version * */ package org.jfree.xml.util; import java.util.HashMap; /** * Maps a class to ... */ public class MultiplexMappingDefinition { /** The class. */ private Class baseClass; /** The attribute name. */ private String attributeName; /** The forward mappings. */ private HashMap forwardMappings; /** The reverse mappings. */ private HashMap reverseMappings; /** * Creates a new mapping definition. * * @param baseClass the class. * @param attributeName the attribute name. * @param entries the entries. */ public MultiplexMappingDefinition(final Class baseClass, final String attributeName, final MultiplexMappingEntry[] entries) { this.attributeName = attributeName; this.baseClass = baseClass; this.forwardMappings = new HashMap(); this.reverseMappings = new HashMap(); for (int i = 0; i < entries.length; i++) { final MultiplexMappingEntry entry = entries[i]; this.forwardMappings.put(entry.getAttributeValue(), entry); this.reverseMappings.put(entry.getTargetClass(), entry); } } /** * Returns the attribute name. * * @return The attribute name. */ public String getAttributeName() { return this.attributeName; } /** * Returns the class. * * @return The class. */ public Class getBaseClass() { return this.baseClass; } /** * Returns a mapping entry for a type. * * @param type the type. * * @return The mapping entry. */ public MultiplexMappingEntry getEntryForType(final String type) { return (MultiplexMappingEntry) this.forwardMappings.get(type); } /** * Returns a mapping entry for a class. * * @param clazz the class. * * @return The mapping entry. */ public MultiplexMappingEntry getEntryForClass(final String clazz) { return (MultiplexMappingEntry) this.reverseMappings.get(clazz); } } jcommon-1.0.16/source/org/jfree/xml/util/AbstractModelReader.java0000644000175000017500000006010611172030703024645 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * AbstractModelReader.java * ------------------------ * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AbstractModelReader.java,v 1.8 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 12-Nov-2003 : Initial version * 25-Nov-2003 : Updated header (DG); * */ package org.jfree.xml.util; import java.io.BufferedInputStream; import java.io.InputStream; import java.net.URL; import java.util.Stack; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.jfree.util.Log; import org.jfree.util.ObjectUtilities; import org.jfree.xml.CommentHandler; import org.jfree.xml.ElementDefinitionException; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; /** * Loads the class model from an previously written xml file set. * This class provides abstract methods which get called during the parsing * (similiar to the SAX parsing, but slightly easier to code). * * This will need a rewrite in the future, when the structure is finished. */ public abstract class AbstractModelReader { /** The 'START' state. */ private static final int STATE_START = 0; /** The 'IN_OBJECT' state. */ private static final int IN_OBJECT = 1; /** The 'IGNORE_OBJECT' state. */ private static final int IGNORE_OBJECT = 2; /** The 'MAPPING' state. */ private static final int MAPPING_STATE = 3; /** The 'CONSTRUCTOR' state. */ private static final int CONSTRUCTOR_STATE = 4; /** * The SAX2 callback implementation used for parsing the model xml files. */ private class SAXModelHandler extends DefaultHandler { /** The resource URL. */ private URL resource; /** The current state. */ private int state; /** Open comments. */ private Stack openComments; /** Flag to track includes. */ private boolean isInclude; /** * Creates a new SAX handler for parsing the model. * * @param resource the resource URL. * @param isInclude an include? */ public SAXModelHandler(final URL resource, final boolean isInclude) { if (resource == null) { throw new NullPointerException(); } this.resource = resource; this.openComments = new Stack(); this.isInclude = isInclude; } /** * Receive notification of the start of an element. * * @param uri The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. * @param localName The local name (without prefix), or the * empty string if Namespace processing is not being * performed. * @param qName The qualified name (with prefix), or the * empty string if qualified names are not available. * @param attributes The attributes attached to the element. If * there are no attributes, it shall be an empty * Attributes object. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * * @see org.xml.sax.ContentHandler#startElement */ public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { setOpenComment(getCommentHandler().getComments()); this.openComments.push(getOpenComment()); setCloseComment(null); try { if (!this.isInclude && qName.equals(ClassModelTags.OBJECTS_TAG)) { //Log.debug ("Open Comments: " + openComment); startRootDocument(); return; } if (getState() == STATE_START) { startRootElement(qName, attributes); } else if (getState() == IGNORE_OBJECT) { return; } else if (getState() == IN_OBJECT) { startObjectElement(qName, attributes); } else if (getState() == MAPPING_STATE) { if (!qName.equals(ClassModelTags.TYPE_TAG)) { throw new SAXException("Expected 'type' tag"); } final String name = attributes.getValue(ClassModelTags.NAME_ATTR); final String target = attributes.getValue(ClassModelTags.CLASS_ATTR); handleMultiplexMapping(name, target); } else if (getState() == CONSTRUCTOR_STATE) { if (!qName.equals(ClassModelTags.PARAMETER_TAG)) { throw new SAXException("Expected 'parameter' tag"); } final String parameterClass = attributes.getValue(ClassModelTags.CLASS_ATTR); final String tagName = attributes.getValue(ClassModelTags.PROPERTY_ATTR); // optional handleConstructorDefinition(tagName, parameterClass); } } catch (ObjectDescriptionException e) { throw new SAXException(e); } finally { getCommentHandler().clearComments(); } } /** * Receive notification of the end of an element. * * @param uri The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. * @param localName The local name (without prefix), or the * empty string if Namespace processing is not being * performed. * @param qName The qualified name (with prefix), or the * empty string if qualified names are not available. * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#endElement */ public void endElement(final String uri, final String localName, final String qName) throws SAXException { setOpenComment((String[]) this.openComments.pop()); setCloseComment(getCommentHandler().getComments()); try { if (!this.isInclude && qName.equals(ClassModelTags.OBJECTS_TAG)) { endRootDocument(); return; } if (qName.equals(ClassModelTags.OBJECT_TAG)) { if (getState() != IGNORE_OBJECT) { endObjectDefinition(); } setState(STATE_START); } else if (qName.equals(ClassModelTags.MAPPING_TAG)) { setState(STATE_START); endMultiplexMapping(); } else if (qName.equals(ClassModelTags.CONSTRUCTOR_TAG)) { if (getState() != IGNORE_OBJECT) { setState(IN_OBJECT); } } } catch (ObjectDescriptionException e) { throw new SAXException(e); } finally { getCommentHandler().clearComments(); } } /** * Handles the start of an element within an object definition. * * @param qName The qualified name (with prefix), or the * empty string if qualified names are not available. * @param attributes The attributes attached to the element. If * there are no attributes, it shall be an empty * Attributes object. * @throws ObjectDescriptionException if an error occured while * handling this tag */ private void startObjectElement(final String qName, final Attributes attributes) throws ObjectDescriptionException { if (qName.equals(ClassModelTags.CONSTRUCTOR_TAG)) { setState(CONSTRUCTOR_STATE); } else if (qName.equals(ClassModelTags.LOOKUP_PROPERTY_TAG)) { final String name = attributes.getValue(ClassModelTags.NAME_ATTR); final String lookupKey = attributes.getValue(ClassModelTags.LOOKUP_ATTR); handleLookupDefinition(name, lookupKey); } else if (qName.equals(ClassModelTags.IGNORED_PROPERTY_TAG)) { final String name = attributes.getValue(ClassModelTags.NAME_ATTR); handleIgnoredProperty(name); } else if (qName.equals(ClassModelTags.ELEMENT_PROPERTY_TAG)) { final String elementAtt = attributes.getValue(ClassModelTags.ELEMENT_ATTR); final String name = attributes.getValue(ClassModelTags.NAME_ATTR); handleElementDefinition(name, elementAtt); } else if (qName.equals(ClassModelTags.ATTRIBUTE_PROPERTY_TAG)) { final String name = attributes.getValue(ClassModelTags.NAME_ATTR); final String attribName = attributes.getValue(ClassModelTags.ATTRIBUTE_ATTR); final String handler = attributes.getValue(ClassModelTags.ATTRIBUTE_HANDLER_ATTR); handleAttributeDefinition(name, attribName, handler); } } /** * Handles the include or object tag. * * @param qName The qualified name (with prefix), or the * empty string if qualified names are not available. * @param attributes The attributes attached to the element. If * there are no attributes, it shall be an empty * Attributes object. * @throws SAXException if an parser error occured * @throws ObjectDescriptionException if an object model related * error occured. */ private void startRootElement(final String qName, final Attributes attributes) throws SAXException, ObjectDescriptionException { if (qName.equals(ClassModelTags.INCLUDE_TAG)) { if (this.isInclude) { Log.warn("Ignored nested include tag."); return; } final String src = attributes.getValue(ClassModelTags.SOURCE_ATTR); try { final URL url = new URL(this.resource, src); startIncludeHandling(url); parseXmlDocument(url, true); endIncludeHandling(); } catch (Exception ioe) { throw new ElementDefinitionException (ioe, "Unable to include file from " + src); } } else if (qName.equals(ClassModelTags.OBJECT_TAG)) { setState(IN_OBJECT); final String className = attributes.getValue(ClassModelTags.CLASS_ATTR); String register = attributes.getValue(ClassModelTags.REGISTER_NAMES_ATTR); if (register != null && register.length() == 0) { register = null; } final boolean ignored = "true".equals(attributes.getValue(ClassModelTags.IGNORE_ATTR)); if (!startObjectDefinition(className, register, ignored)) { setState(IGNORE_OBJECT); } } else if (qName.equals(ClassModelTags.MANUAL_TAG)) { final String className = attributes.getValue(ClassModelTags.CLASS_ATTR); final String readHandler = attributes.getValue(ClassModelTags.READ_HANDLER_ATTR); final String writeHandler = attributes.getValue(ClassModelTags.WRITE_HANDLER_ATTR); handleManualMapping(className, readHandler, writeHandler); } else if (qName.equals(ClassModelTags.MAPPING_TAG)) { setState(MAPPING_STATE); final String typeAttr = attributes.getValue(ClassModelTags.TYPE_ATTR); final String baseClass = attributes.getValue(ClassModelTags.BASE_CLASS_ATTR); startMultiplexMapping(baseClass, typeAttr); } } /** * Returns the current state. * * @return the state. */ private int getState() { return this.state; } /** * Sets the current state. * * @param state the state. */ private void setState(final int state) { this.state = state; } } /** The comment handler. */ private CommentHandler commentHandler; /** The close comments. */ private String[] closeComment; /** The open comments. */ private String[] openComment; /** * Default Constructor. */ public AbstractModelReader() { this.commentHandler = new CommentHandler(); } /** * Returns the comment handler. * * @return The comment handler. */ protected CommentHandler getCommentHandler() { return this.commentHandler; } /** * Returns the close comment. * * @return The close comment. */ protected String[] getCloseComment() { return this.closeComment; } /** * Returns the open comment. * * @return The open comment. */ protected String[] getOpenComment() { return this.openComment; } /** * Sets the close comment. * * @param closeComment the close comment. */ protected void setCloseComment(final String[] closeComment) { this.closeComment = closeComment; } /** * Sets the open comment. * * @param openComment the open comment. */ protected void setOpenComment(final String[] openComment) { this.openComment = openComment; } /** * Parses an XML document at the given URL. * * @param resource the document URL. * * @throws ObjectDescriptionException ?? */ protected void parseXml(final URL resource) throws ObjectDescriptionException { parseXmlDocument(resource, false); } /** * Parses the given specification and loads all includes specified in the files. * This implementation does not check for loops in the include files. * * @param resource the url of the xml specification. * @param isInclude an include? * * @throws org.jfree.xml.util.ObjectDescriptionException if an error occured which prevented the * loading of the specifications. */ protected void parseXmlDocument(final URL resource, final boolean isInclude) throws ObjectDescriptionException { try { final InputStream in = new BufferedInputStream(resource.openStream()); final SAXParserFactory factory = SAXParserFactory.newInstance(); final SAXParser saxParser = factory.newSAXParser(); final XMLReader reader = saxParser.getXMLReader(); final SAXModelHandler handler = new SAXModelHandler(resource, isInclude); try { reader.setProperty ("http://xml.org/sax/properties/lexical-handler", getCommentHandler()); } catch (SAXException se) { Log.debug("Comments are not supported by this SAX implementation."); } reader.setContentHandler(handler); reader.setDTDHandler(handler); reader.setErrorHandler(handler); reader.parse(new InputSource(in)); in.close(); } catch (Exception e) { // unable to init Log.warn("Unable to load factory specifications", e); throw new ObjectDescriptionException("Unable to load object factory specs.", e); } } /** * Start the root document. */ protected void startRootDocument() { // nothing required } /** * End the root document. */ protected void endRootDocument() { // nothing required } /** * Start handling an include. * * @param resource the URL. */ protected void startIncludeHandling(final URL resource) { // nothing required } /** * End handling an include. */ protected void endIncludeHandling() { // nothing required } /** * Callback method for ignored properties. Such properties get marked so that * the information regarding these properties won't get lost. * * @param name the name of the ignored property. */ protected void handleIgnoredProperty(final String name) { // nothing required } /** * Handles a manual mapping definition. The manual mapping maps specific * read and write handlers to a given base class. Manual mappings always * override any other definition. * * @param className the base class name * @param readHandler the class name of the read handler * @param writeHandler the class name of the write handler * @return true, if the mapping was accepted, false otherwise. * @throws ObjectDescriptionException if an unexpected error occured. */ protected abstract boolean handleManualMapping(String className, String readHandler, String writeHandler) throws ObjectDescriptionException; /** * Starts a object definition. The object definition collects all properties of * an bean-class and defines, which constructor should be used when creating the * class. * * @param className the class name of the defined object * @param register the (optional) register name, to lookup and reference the object * later. * @param ignored ??. * * @return true, if the definition was accepted, false otherwise. * @throws ObjectDescriptionException if an unexpected error occured. */ protected abstract boolean startObjectDefinition(String className, String register, boolean ignored) throws ObjectDescriptionException; /** * Handles an attribute definition. This method gets called after the object definition * was started. The method will be called for every defined attribute property. * * @param name the name of the property * @param attribName the xml-attribute name to use later. * @param handlerClass the attribute handler class. * @throws ObjectDescriptionException if an error occured. */ protected abstract void handleAttributeDefinition(String name, String attribName, String handlerClass) throws ObjectDescriptionException; /** * Handles an element definition. This method gets called after the object definition * was started. The method will be called for every defined element property. Element * properties are used to describe complex objects. * * @param name the name of the property * @param element the xml-tag name for the child element. * @throws ObjectDescriptionException if an error occurs. */ protected abstract void handleElementDefinition(String name, String element) throws ObjectDescriptionException; /** * Handles an lookup definition. This method gets called after the object definition * was started. The method will be called for every defined lookup property. Lookup properties * reference previously created object using the object's registry name. * * @param name the property name of the base object * @param lookupKey the register key of the referenced object * @throws ObjectDescriptionException if an error occured. */ protected abstract void handleLookupDefinition(String name, String lookupKey) throws ObjectDescriptionException; /** * Finializes the object definition. * * @throws ObjectDescriptionException if an error occures. */ protected abstract void endObjectDefinition() throws ObjectDescriptionException; /** * Starts a multiplex mapping. Multiplex mappings are used to define polymorphic * argument handlers. The mapper will collect all derived classes of the given * base class and will select the corresponding mapping based on the given type * attribute. * * @param className the base class name * @param typeAttr the xml-attribute name containing the mapping key */ protected abstract void startMultiplexMapping(String className, String typeAttr); /** * Defines an entry for the multiplex mapping. The new entry will be activated * when the base mappers type attribute contains this typename and * will resolve to the handler for the given classname. * * @param typeName the type value for this mapping. * @param className the class name to which this mapping resolves. * @throws ObjectDescriptionException if an error occurs. */ protected abstract void handleMultiplexMapping(String typeName, String className) throws ObjectDescriptionException; /** * Finializes the multiplexer mapping. * * @throws ObjectDescriptionException if an error occurs. */ protected abstract void endMultiplexMapping() throws ObjectDescriptionException; /** * Handles a constructor definition. Only one constructor can be defined for * a certain object type. The constructor will be filled using the given properties. * * @param propertyName the property name of the referenced local property * @param parameterClass the parameter class for the parameter. * @throws ObjectDescriptionException if an error occured. */ protected abstract void handleConstructorDefinition(String propertyName, String parameterClass) throws ObjectDescriptionException; /** * Loads the given class, and ignores all exceptions which may occur * during the loading. If the class was invalid, null is returned instead. * * @param className the name of the class to be loaded. * @return the class or null. */ protected Class loadClass(final String className) { if (className == null) { return null; } if (className.startsWith("::")) { return BasicTypeSupport.getClassRepresentation(className); } try { return ObjectUtilities.getClassLoader(getClass()).loadClass(className); } catch (Exception e) { // ignore buggy classes for now .. Log.warn("Unable to load class", e); return null; } } } jcommon-1.0.16/source/org/jfree/xml/util/MultiplexMappingEntry.java0000644000175000017500000000503011172030703025312 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * MultiplexMappingEntry.java * -------------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: MultiplexMappingEntry.java,v 1.3 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 22-Nov-2003 : Initial version * */ package org.jfree.xml.util; /** * A multiplex mapping entry. */ public class MultiplexMappingEntry { /** The attribute value. */ private String attributeValue; /** The target class. */ private String targetClass; /** * Creates a new instance. * * @param attributeValue the attribute value. * @param targetClass the target class. */ public MultiplexMappingEntry(final String attributeValue, final String targetClass) { this.attributeValue = attributeValue; this.targetClass = targetClass; } /** * Returns the attribute value. * * @return The attribute value. */ public String getAttributeValue() { return this.attributeValue; } /** * Returns the target class. * * @return The target class. */ public String getTargetClass() { return this.targetClass; } } jcommon-1.0.16/source/org/jfree/xml/util/ObjectFactory.java0000644000175000017500000000601611172030703023534 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * ObjectFactory.java * ------------------ * (C) Copyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ObjectFactory.java,v 1.3 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 22-Nov-2003 : Version 1 (TM); * */ package org.jfree.xml.util; /** * An object factory. */ public interface ObjectFactory { /** * Returns the generic factory for the given class or null, if there is * no handler for this class. The factory will be reinitialized using * getInstance(). * * @param c the class for which we need a producer * @return the factory for this class */ public GenericObjectFactory getFactoryForClass(Class c); /** * Checks, whether a generic handler exists for the given class. This does * not check, whether an mapping exists. * * @param c the class for which to check * @return true, if an generic handler is defined, false otherwise. */ public boolean isGenericHandler(Class c); /** * Returns the multiplex definition for the given class, or null, if no * such definition exists. * * @param c the class for which to check the existence of the multiplexer * @return the multiplexer for the class, or null if no multiplexer exists. */ public MultiplexMappingDefinition getMultiplexDefinition(Class c); /** * Returns the manual mapping definition for the given class, or null, if * not manual definition exists. * * @param c the class for which to check the existence of the definition * @return the manual mapping definition or null. */ public ManualMappingDefinition getManualMappingDefinition(Class c); } jcommon-1.0.16/source/org/jfree/xml/util/ObjectDescriptionException.java0000644000175000017500000000475611172030703026300 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------- * ObjectDescriptionException.java * ------------------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ObjectDescriptionException.java,v 1.3 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 24-Sep-2003 : Initial version * 11-Feb-2004 : Added missing Javadocs (DG); * */ package org.jfree.xml.util; import org.jfree.util.StackableException; /** * An exception that indicates a problem with an object description. */ public class ObjectDescriptionException extends StackableException { /** * Creates a StackableRuntimeException with no message and no parent. */ public ObjectDescriptionException() { super(); } /** * Creates an exception. * * @param message the exception message. * @param ex the parent exception. */ public ObjectDescriptionException(final String message, final Exception ex) { super(message, ex); } /** * Creates an exception. * * @param message the exception message. */ public ObjectDescriptionException(final String message) { super(message); } } jcommon-1.0.16/source/org/jfree/xml/util/package.html0000644000175000017500000000021511172030703022407 0ustar twernertwerner Utility classes for the XML framework. jcommon-1.0.16/source/org/jfree/xml/util/AttributeDefinition.java0000644000175000017500000000573511172030703024761 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * AttributeDefinition.java * ------------------------ * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AttributeDefinition.java,v 1.3 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 24.09.2003 : Initial version * */ package org.jfree.xml.util; import org.jfree.xml.attributehandlers.AttributeHandler; /** * An attribute definition. */ public class AttributeDefinition { /** The attribute name. */ private String attributeName; /** The attribute handler. */ private AttributeHandler handler; /** The property name. */ private String propertyName; /** * Creates a new attribute definition. * * @param propertyName the property name. * @param attributeName the attribute name. * @param handler the handler. */ public AttributeDefinition(final String propertyName, final String attributeName, final AttributeHandler handler) { this.propertyName = propertyName; this.attributeName = attributeName; this.handler = handler; } /** * Returns the property name. * * @return the property name. */ public String getPropertyName() { return this.propertyName; } /** * Returns the attribute name. * * @return the attribute name. */ public String getAttributeName() { return this.attributeName; } /** * Returns the handler. * * @return the handler. */ public AttributeHandler getHandler() { return this.handler; } } jcommon-1.0.16/source/org/jfree/xml/util/Base64.java0000644000175000017500000002611611172030703022025 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------------- * AbstractElementDefinitionHandler.java * ------------------------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Kevin Kelley - * 30718 Rd. 28, La Junta, CO, 81050 USA. * * $Id: Base64.java,v 1.4 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------------------------- * 23.09.2003 : Initial version * */ package org.jfree.xml.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.CharArrayWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; /** * Provides encoding of raw bytes to base64-encoded characters, and * decoding of base64 characters to raw bytes. * date: 06 August 1998 * modified: 14 February 2000 * modified: 22 September 2000 * * @author Kevin Kelley (kelley@ruralnet.net) * @version 1.3 */ public class Base64 { private Base64 () { } /** * returns an array of base64-encoded characters to represent the * passed data array. * * @param data the array of bytes to encode * @return base64-coded character array. */ public static char[] encode(final byte[] data) { final char[] out = new char[((data.length + 2) / 3) * 4]; // // 3 bytes encode to 4 chars. Output is always an even // multiple of 4 characters. // for (int i = 0, index = 0; i < data.length; i += 3, index += 4) { boolean quad = false; boolean trip = false; int val = (0xFF & data[i]); val <<= 8; if ((i + 1) < data.length) { val |= (0xFF & data[i + 1]); trip = true; } val <<= 8; if ((i + 2) < data.length) { val |= (0xFF & data[i + 2]); quad = true; } out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)]; val >>= 6; out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)]; val >>= 6; out[index + 1] = alphabet[val & 0x3F]; val >>= 6; out[index + 0] = alphabet[val & 0x3F]; } return out; } /** * Decodes a BASE-64 encoded stream to recover the original * data. White space before and after will be trimmed away, * but no other manipulation of the input will be performed. * * As of version 1.2 this method will properly handle input * containing junk characters (newlines and the like) rather * than throwing an error. It does this by pre-parsing the * input and generating from that a count of VALID input * characters. * * @param data the character data. * * @return The decoded data. */ public static byte[] decode(final char[] data) { // as our input could contain non-BASE64 data (newlines, // whitespace of any sort, whatever) we must first adjust // our count of USABLE data so that... // (a) we don't misallocate the output array, and // (b) think that we miscalculated our data length // just because of extraneous throw-away junk int tempLen = data.length; for (int ix = 0; ix < data.length; ix++) { if ((data[ix] > 255) || codes[data[ix]] < 0) { --tempLen; // ignore non-valid chars and padding } } // calculate required length: // -- 3 bytes for every 4 valid base64 chars // -- plus 2 bytes if there are 3 extra base64 chars, // or plus 1 byte if there are 2 extra. int len = (tempLen / 4) * 3; if ((tempLen % 4) == 3) { len += 2; } if ((tempLen % 4) == 2) { len += 1; } final byte[] out = new byte[len]; int shift = 0; // # of excess bits stored in accum int accum = 0; // excess bits int index = 0; // we now go through the entire array (NOT using the 'tempLen' value) for (int ix = 0; ix < data.length; ix++) { final int value = (data[ix] > 255) ? -1 : codes[data[ix]]; if (value >= 0) { // skip over non-code accum <<= 6; // bits shift up by 6 each time thru shift += 6; // loop, with new bits being put in accum |= value; // at the bottom. if (shift >= 8) { // whenever there are 8 or more shifted in, shift -= 8; // write them out (from the top, leaving any out[index++] = // excess at the bottom for next iteration. (byte) ((accum >> shift) & 0xff); } } // we will also have skipped processing a padding null byte ('=') here; // these are used ONLY for padding to an even length and do not legally // occur as encoded data. for this reason we can ignore the fact that // no index++ operation occurs in that special case: the out[] array is // initialized to all-zero bytes to start with and that works to our // advantage in this combination. } // if there is STILL something wrong we just have to throw up now! if (index != out.length) { throw new Error("Miscalculated data length (wrote " + index + " instead of " + out.length + ")"); } return out; } // // code characters for values 0..63 // private static char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray(); // // lookup table for converting base64 characters to value in range 0..63 // private static byte[] codes = new byte[256]; static { for (int i = 0; i < 256; i++) { codes[i] = -1; } for (int i = 'A'; i <= 'Z'; i++) { codes[i] = (byte) (i - 'A'); } for (int i = 'a'; i <= 'z'; i++) { codes[i] = (byte) (26 + i - 'a'); } for (int i = '0'; i <= '9'; i++) { codes[i] = (byte) (52 + i - '0'); } codes['+'] = 62; codes['/'] = 63; } /////////////////////////////////////////////////// // remainder (main method and helper functions) is // for testing purposes only, feel free to clip it. /////////////////////////////////////////////////// /** * Entry point. * * @param args the command line arguments. */ public static void main(final String[] args) { boolean decode = false; if (args.length == 0) { System.out.println("usage: java Base64 [-d[ecode]] filename"); System.exit(0); } for (int i = 0; i < args.length; i++) { if ("-decode".equalsIgnoreCase(args[i])) { decode = true; } else if ("-d".equalsIgnoreCase(args[i])) { decode = true; } } final String filename = args[args.length - 1]; final File file = new File(filename); if (!file.exists()) { System.out.println("Error: file '" + filename + "' doesn't exist!"); System.exit(0); } if (decode) { final char[] encoded = readChars(file); final byte[] decoded = decode(encoded); writeBytes(file, decoded); } else { final byte[] decoded = readBytes(file); final char[] encoded = encode(decoded); writeChars(file, encoded); } } private static byte[] readBytes(final File file) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { final InputStream fis = new FileInputStream(file); final InputStream is = new BufferedInputStream(fis); int count; final byte[] buf = new byte[16384]; while ((count = is.read(buf)) != -1) { if (count > 0) { baos.write(buf, 0, count); } } is.close(); } catch (Exception e) { e.printStackTrace(); } return baos.toByteArray(); } private static char[] readChars(final File file) { final CharArrayWriter caw = new CharArrayWriter(); try { final Reader fr = new FileReader(file); final Reader in = new BufferedReader(fr); int count; final char[] buf = new char[16384]; while ((count = in.read(buf)) != -1) { if (count > 0) { caw.write(buf, 0, count); } } in.close(); } catch (Exception e) { e.printStackTrace(); } return caw.toCharArray(); } private static void writeBytes(final File file, final byte[] data) { try { final OutputStream fos = new FileOutputStream(file); final OutputStream os = new BufferedOutputStream(fos); os.write(data); os.close(); } catch (Exception e) { e.printStackTrace(); } } private static void writeChars(final File file, final char[] data) { try { final Writer fos = new FileWriter(file); final Writer os = new BufferedWriter(fos); os.write(data); os.close(); } catch (Exception e) { e.printStackTrace(); } } /////////////////////////////////////////////////// // end of test code. /////////////////////////////////////////////////// } jcommon-1.0.16/source/org/jfree/xml/util/ObjectFactoryLoader.java0000644000175000017500000004236611172030703024673 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * ObjectFactoryLoader.java * ------------------------ * (C) Copyright 2002-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): -; * * $Id: ObjectFactoryLoader.java,v 1.4 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 24-Sep-2003: Initial version * */ package org.jfree.xml.util; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import org.jfree.util.Log; import org.jfree.xml.attributehandlers.AttributeHandler; /** * The object factory loader loads the xml specification for the generic * handlers. The specification may be distributed over multiple files. *

* This class provides the model management for the reader and writer. * The instantiation of the handlers is done elsewhere. * * @author TM */ public class ObjectFactoryLoader extends AbstractModelReader implements ObjectFactory { /** Maps classes to GenericObjectFactory instances. */ private HashMap objectMappings; /** Manual mappings. */ private HashMap manualMappings; /** Multiplex mappings. */ private HashMap multiplexMappings; /** The target class. */ private Class target; /** The register name. */ private String registerName; /** The property definition. */ private ArrayList propertyDefinition; /** The attribute definition. */ private ArrayList attributeDefinition; /** The constructor definition. */ private ArrayList constructorDefinition; /** The lookup definitions. */ private ArrayList lookupDefinitions; /** The ordered names. */ private ArrayList orderedNames; /** The base class. */ private String baseClass; /** The attribute name. */ private String attributeName; /** The multiplex entries. */ private ArrayList multiplexEntries; /** * Creates a new object factory loader for the given base file. * * @param resourceName the URL of the initial specification file. * * @throws ObjectDescriptionException if the file could not be parsed. */ public ObjectFactoryLoader(final URL resourceName) throws ObjectDescriptionException { this.objectMappings = new HashMap(); this.manualMappings = new HashMap(); this.multiplexMappings = new HashMap(); parseXml(resourceName); rebuildSuperClasses(); } private void rebuildSuperClasses() throws ObjectDescriptionException { this.propertyDefinition = new ArrayList(); this.attributeDefinition = new ArrayList(); this.constructorDefinition = new ArrayList(); this.lookupDefinitions = new ArrayList(); this.orderedNames = new ArrayList(); final HashMap newObjectDescriptions = new HashMap(); final Iterator it = this.objectMappings.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final GenericObjectFactory gef = (GenericObjectFactory) this.objectMappings.get(key); performSuperClassUpdate(gef); final PropertyDefinition[] propertyDefs = (PropertyDefinition[]) this.propertyDefinition.toArray(new PropertyDefinition[0]); final LookupDefinition[] lookupDefs = (LookupDefinition[]) this.lookupDefinitions.toArray(new LookupDefinition[0]); final AttributeDefinition[] attribDefs = (AttributeDefinition[]) this.attributeDefinition.toArray(new AttributeDefinition[0]); final ConstructorDefinition[] constructorDefs = (ConstructorDefinition[]) this.constructorDefinition.toArray(new ConstructorDefinition[0]); final String[] orderedNamesDefs = (String[]) this.orderedNames.toArray(new String[0]); final GenericObjectFactory objectFactory = new GenericObjectFactory (gef.getBaseClass(), gef.getRegisterName(), constructorDefs, propertyDefs, lookupDefs, attribDefs, orderedNamesDefs); newObjectDescriptions.put(key, objectFactory); this.propertyDefinition.clear(); this.attributeDefinition.clear(); this.constructorDefinition.clear(); this.lookupDefinitions.clear(); this.orderedNames.clear(); } this.objectMappings.clear(); this.objectMappings = newObjectDescriptions; this.propertyDefinition = null; this.attributeDefinition = null; this.constructorDefinition = null; this.lookupDefinitions = null; this.orderedNames = null; } private void performSuperClassUpdate(final GenericObjectFactory gef) { // first handle the super classes, ... final Class superClass = gef.getBaseClass().getSuperclass(); if (superClass != null && !superClass.equals(Object.class)) { final GenericObjectFactory superGef = (GenericObjectFactory) this.objectMappings.get( superClass ); if (superGef != null) { performSuperClassUpdate(superGef); } } // and finally append all local properties ... this.propertyDefinition.addAll(Arrays.asList(gef.getPropertyDefinitions())); this.attributeDefinition.addAll(Arrays.asList(gef.getAttributeDefinitions())); this.constructorDefinition.addAll(Arrays.asList(gef.getConstructorDefinitions())); this.lookupDefinitions.addAll(Arrays.asList(gef.getLookupDefinitions())); this.orderedNames.addAll(Arrays.asList(gef.getOrderedPropertyNames())); } /** * Starts a object definition. The object definition collects all properties of * an bean-class and defines, which constructor should be used when creating the * class. * * @param className the class name of the defined object * @param register the (optional) register name, to lookup and reference the object later. * @param ignore ignore? * * @return true, if the definition was accepted, false otherwise. * @throws ObjectDescriptionException if an unexpected error occured. */ protected boolean startObjectDefinition(final String className, final String register, final boolean ignore) throws ObjectDescriptionException { if (ignore) { return false; } this.target = loadClass(className); if (this.target == null) { Log.warn(new Log.SimpleMessage("Failed to load class ", className)); return false; } this.registerName = register; this.propertyDefinition = new ArrayList(); this.attributeDefinition = new ArrayList(); this.constructorDefinition = new ArrayList(); this.lookupDefinitions = new ArrayList(); this.orderedNames = new ArrayList(); return true; } /** * Handles an attribute definition. This method gets called after the object definition * was started. The method will be called for every defined attribute property. * * @param name the name of the property * @param attribName the xml-attribute name to use later. * @param handlerClass the attribute handler class. * @throws ObjectDescriptionException if an error occured. */ protected void handleAttributeDefinition(final String name, final String attribName, final String handlerClass) throws ObjectDescriptionException { final AttributeHandler handler = loadAttributeHandler(handlerClass); this.orderedNames.add(name); this.attributeDefinition.add(new AttributeDefinition(name, attribName, handler)); } /** * Handles an element definition. This method gets called after the object definition * was started. The method will be called for every defined element property. Element * properties are used to describe complex objects. * * @param name the name of the property * @param element the xml-tag name for the child element. * @throws ObjectDescriptionException if an error occurs. */ protected void handleElementDefinition(final String name, final String element) throws ObjectDescriptionException { this.orderedNames.add(name); this.propertyDefinition.add(new PropertyDefinition(name, element)); } /** * Handles an lookup definition. This method gets called after the object definition * was started. The method will be called for every defined lookup property. Lookup properties * reference previously created object using the object's registry name. * * @param name the property name of the base object * @param lookupKey the register key of the referenced object * @throws ObjectDescriptionException if an error occured. */ protected void handleLookupDefinition(final String name, final String lookupKey) throws ObjectDescriptionException { final LookupDefinition ldef = new LookupDefinition(name, lookupKey); this.orderedNames.add(name); this.lookupDefinitions.add(ldef); } /** * Finializes the object definition. * * @throws ObjectDescriptionException if an error occures. */ protected void endObjectDefinition() throws ObjectDescriptionException { final PropertyDefinition[] propertyDefs = (PropertyDefinition[]) this.propertyDefinition.toArray(new PropertyDefinition[0]); final LookupDefinition[] lookupDefs = (LookupDefinition[]) this.lookupDefinitions.toArray(new LookupDefinition[0]); final AttributeDefinition[] attribDefs = (AttributeDefinition[]) this.attributeDefinition.toArray(new AttributeDefinition[0]); final ConstructorDefinition[] constructorDefs = (ConstructorDefinition[]) this.constructorDefinition.toArray(new ConstructorDefinition[0]); final String[] orderedNamesDefs = (String[]) this.orderedNames.toArray(new String[0]); final GenericObjectFactory objectFactory = new GenericObjectFactory (this.target, this.registerName, constructorDefs, propertyDefs, lookupDefs, attribDefs, orderedNamesDefs); this.objectMappings.put(this.target, objectFactory); } /** * Handles a constructor definition. Only one constructor can be defined for * a certain object type. The constructor will be filled using the given properties. * * @param propertyName the property name of the referenced local property * @param parameterClass the parameter class for the parameter. */ protected void handleConstructorDefinition(final String propertyName, final String parameterClass) { final Class c = loadClass(parameterClass); this.orderedNames.add(propertyName); this.constructorDefinition.add(new ConstructorDefinition(propertyName, c)); } /** * Handles a manual mapping definition. The manual mapping maps specific * read and write handlers to a given base class. Manual mappings always * override any other definition. * * @param className the base class name * @param readHandler the class name of the read handler * @param writeHandler the class name of the write handler * @return true, if the mapping was accepted, false otherwise. * @throws ObjectDescriptionException if an unexpected error occured. */ protected boolean handleManualMapping(final String className, final String readHandler, final String writeHandler) throws ObjectDescriptionException { if (!this.manualMappings.containsKey(className)) { final Class loadedClass = loadClass(className); this.manualMappings.put(loadedClass, new ManualMappingDefinition (loadedClass, readHandler, writeHandler)); return true; } return false; } /** * Starts a multiplex mapping. Multiplex mappings are used to define polymorphic * argument handlers. The mapper will collect all derived classes of the given * base class and will select the corresponding mapping based on the given type * attribute. * * @param className the base class name * @param typeAttr the xml-attribute name containing the mapping key */ protected void startMultiplexMapping(final String className, final String typeAttr) { this.baseClass = className; this.attributeName = typeAttr; this.multiplexEntries = new ArrayList(); } /** * Defines an entry for the multiplex mapping. The new entry will be activated * when the base mappers type attribute contains this typename and * will resolve to the handler for the given classname. * * @param typeName the type value for this mapping. * @param className the class name to which this mapping resolves. * @throws ObjectDescriptionException if an error occurs. */ protected void handleMultiplexMapping(final String typeName, final String className) throws ObjectDescriptionException { this.multiplexEntries.add (new MultiplexMappingEntry(typeName, className)); } /** * Finializes the multiplexer mapping. * * @throws ObjectDescriptionException if an error occurs. */ protected void endMultiplexMapping() throws ObjectDescriptionException { final MultiplexMappingEntry[] mappings = (MultiplexMappingEntry[]) this.multiplexEntries.toArray(new MultiplexMappingEntry[0]); final Class c = loadClass(this.baseClass); this.multiplexMappings.put(c, new MultiplexMappingDefinition(c, this.attributeName, mappings)); this.multiplexEntries = null; } /** * Loads an instantiates the attribute handler specified by the given * class name. * * @param attribute the attribute handlers classname. * @return the created attribute handler instance * @throws ObjectDescriptionException if the handler could not be loaded. */ private AttributeHandler loadAttributeHandler(final String attribute) throws ObjectDescriptionException { final Class c = loadClass(attribute); try { return (AttributeHandler) c.newInstance(); } catch (Exception e) { throw new ObjectDescriptionException ("Invalid attribute handler specified: " + attribute); } } /** * Checks, whether the factory has a description for the given class. * * @param c the class to be handled by the factory. * @return true, if an description exists for the given class, false otherwise. */ public boolean isGenericHandler(final Class c) { return this.objectMappings.containsKey(c); } /** * Returns a factory instance for the given class. The factory is independent * from all previously generated instances. * * @param c the class * @return the object factory. */ public GenericObjectFactory getFactoryForClass(final Class c) { final GenericObjectFactory factory = (GenericObjectFactory) this.objectMappings.get(c); if (factory == null) { return null; } return factory.getInstance(); } /** * Returns the manual mapping definition for the given class, or null, if * not manual definition exists. * * @param c the class for which to check the existence of the definition * @return the manual mapping definition or null. */ public ManualMappingDefinition getManualMappingDefinition(final Class c) { return (ManualMappingDefinition) this.manualMappings.get(c); } /** * Returns the multiplex definition for the given class, or null, if no * such definition exists. * * @param c the class for which to check the existence of the multiplexer * @return the multiplexer for the class, or null if no multiplexer exists. */ public MultiplexMappingDefinition getMultiplexDefinition(final Class c) { final MultiplexMappingDefinition definition = (MultiplexMappingDefinition) this.multiplexMappings.get(c); return definition; } } jcommon-1.0.16/source/org/jfree/xml/util/PropertyDefinition.java0000644000175000017500000000476611172030703024645 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * PropertyDefinition.java * ----------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: PropertyDefinition.java,v 1.3 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 24.09.2003 : Initial version * */ package org.jfree.xml.util; /** * A property definition. */ public class PropertyDefinition { /** The property name. */ private String propertyName; /** The element name. */ private String elementName; /** * Creates a new property definition. * * @param propertyName the property name. * @param elementName the element name. */ public PropertyDefinition(final String propertyName, final String elementName) { this.elementName = elementName; this.propertyName = propertyName; } /** * Returns the property name. * * @return the property name. */ public String getPropertyName() { return this.propertyName; } /** * Returns the element name. * * @return the element name. */ public String getElementName() { return this.elementName; } } jcommon-1.0.16/source/org/jfree/xml/util/ConstructorDefinition.java0000644000175000017500000000525011172030703025333 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * ConstructorDefinition.java * -------------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ConstructorDefinition.java,v 1.3 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 24-Sep-2003 : Initial version * */ package org.jfree.xml.util; /** * A constructor definition. */ public class ConstructorDefinition { /** isNull flag. */ private boolean isNull; /** Property name. */ private String propertyName; /** The type. */ private Class type; /** * Creates a new constructor definition. * * @param propertyName the property name. * @param type the type. */ public ConstructorDefinition(final String propertyName, final Class type) { this.isNull = (propertyName == null); this.propertyName = propertyName; this.type = type; } /** * Returns the type. * * @return the type. */ public Class getType() { return this.type; } /** * Returns a flag. * * @return a boolean. */ public boolean isNull() { return this.isNull; } /** * Returns the property name. * * @return the property name. */ public String getPropertyName() { return this.propertyName; } } jcommon-1.0.16/source/org/jfree/xml/util/GenericObjectFactory.java0000644000175000017500000003774411172030703025045 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * GenericObjectFactory.java * ------------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: GenericObjectFactory.java,v 1.4 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 23-Sep-2003 : Initial version (TM); * */ package org.jfree.xml.util; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.HashMap; /** * The generic object factory contains all methods necessary to collect * the property values needed to produce a fully instantiated object. */ public final class GenericObjectFactory { /** Storage for the constructor definitions. */ private final ConstructorDefinition[] constructorDefinitions; /** Storage for the property definitions. */ private final PropertyDefinition[] propertyDefinitions; /** Storage for the lookup definitions. */ private final LookupDefinition[] lookupDefinitions; /** Storage for the attribute definitions. */ private final AttributeDefinition[] attributeDefinitions; /** The ordered property names. */ private final String[] orderedPropertyNames; /** Storage for property info. */ private final HashMap propertyInfos; /** Storage for property values. */ private final HashMap propertyValues; /** The base class. */ private final Class baseClass; /** The register name. */ private final String registerName; /** * Creates a new generic object factory. * * @param c the class. * @param registerName the (optional) name under which to register the class for * any later lookup. * @param constructors the constructor definitions. * @param propertyDefinitions the property definitions. * @param lookupDefinitions the lookup definitions. * @param attributeDefinitions the attribute definitions. * @param orderedPropertyNames the ordered property names. * * @throws ObjectDescriptionException if there is a problem. */ public GenericObjectFactory(final Class c, final String registerName, final ConstructorDefinition[] constructors, final PropertyDefinition[] propertyDefinitions, final LookupDefinition[] lookupDefinitions, final AttributeDefinition[] attributeDefinitions, final String[] orderedPropertyNames) throws ObjectDescriptionException { if (c == null) { throw new NullPointerException("BaseClass cannot be null."); } this.baseClass = c; this.registerName = registerName; this.propertyInfos = new HashMap(); this.propertyValues = new HashMap(); this.constructorDefinitions = constructors; this.propertyDefinitions = propertyDefinitions; this.lookupDefinitions = lookupDefinitions; this.attributeDefinitions = attributeDefinitions; this.orderedPropertyNames = orderedPropertyNames; try { final BeanInfo chartBeaninfo = Introspector.getBeanInfo(c, Object.class); final PropertyDescriptor[] pd = chartBeaninfo.getPropertyDescriptors(); for (int i = 0; i < pd.length; i++) { this.propertyInfos.put(pd[i].getName(), pd[i]); } } catch (IntrospectionException ioe) { throw new ObjectDescriptionException( "This is an ugly solution right now ... dirty hack attack" ); } } /** * A copy constructor. * * @param factory the factory to copy. */ private GenericObjectFactory (final GenericObjectFactory factory) { this.baseClass = factory.baseClass; this.propertyValues = new HashMap(); this.orderedPropertyNames = factory.orderedPropertyNames; this.constructorDefinitions = factory.constructorDefinitions; this.propertyDefinitions = factory.propertyDefinitions; this.attributeDefinitions = factory.attributeDefinitions; this.propertyInfos = factory.propertyInfos; this.registerName = factory.registerName; this.lookupDefinitions = factory.lookupDefinitions; } /** * Returns a copy of this instance. * * @return a copy of this instance. */ public GenericObjectFactory getInstance () { return new GenericObjectFactory(this); } /** * Returns the register name. * * @return the register name. */ public String getRegisterName() { return this.registerName; } /** * Returns a property descriptor. * * @param propertyName the property name. * * @return a property descriptor. */ private PropertyDescriptor getPropertyDescriptor(final String propertyName) { return (PropertyDescriptor) this.propertyInfos.get(propertyName); } /** * Returns the class for a tag name. * * @param tagName the tag name. * * @return the class. * * @throws ObjectDescriptionException if there is a problem. */ public Class getTypeForTagName(final String tagName) throws ObjectDescriptionException { final PropertyDefinition pdef = getPropertyDefinitionByTagName(tagName); final PropertyDescriptor pdescr = getPropertyDescriptor(pdef.getPropertyName()); if (pdescr == null) { throw new ObjectDescriptionException("Invalid Definition: " + pdef.getPropertyName()); } return pdescr.getPropertyType(); } /** * Returns true if there is a property definition for the specified property name. * * @param propertyName the property name. * * @return A boolean. */ public boolean isPropertyDefinition (final String propertyName) { for (int i = 0; i < this.propertyDefinitions.length; i++) { final PropertyDefinition pdef = this.propertyDefinitions[i]; if (pdef.getPropertyName().equals(propertyName)) { return true; } } return false; } /** * Returns the property definition for the specified property name. * * @param propertyName the property name. * * @return the property definition. * * @throws ObjectDescriptionException if there is no such property for this object. */ public PropertyDefinition getPropertyDefinitionByPropertyName(final String propertyName) throws ObjectDescriptionException { for (int i = 0; i < this.propertyDefinitions.length; i++) { final PropertyDefinition pdef = this.propertyDefinitions[i]; if (pdef.getPropertyName().equals(propertyName)) { return pdef; } } throw new ObjectDescriptionException( "This property is not defined for this kind of object. : " + propertyName ); } /** * Returns a property definition for the specified tag name. * * @param tagName the tag name. * * @return the property definition. * * @throws ObjectDescriptionException if there is no such tag defined for this object. */ public PropertyDefinition getPropertyDefinitionByTagName(final String tagName) throws ObjectDescriptionException { for (int i = 0; i < this.propertyDefinitions.length; i++) { final PropertyDefinition pdef = this.propertyDefinitions[i]; if (pdef.getElementName().equals(tagName)) { return pdef; } } throw new ObjectDescriptionException( "This tag is not defined for this kind of object. : " + tagName ); } /** * Returns the constructor definitions. * * @return the constructor definitions. */ public ConstructorDefinition[] getConstructorDefinitions() { return this.constructorDefinitions; } /** * Returns the attribute definitions. * * @return the attribute definitions. */ public AttributeDefinition[] getAttributeDefinitions() { return this.attributeDefinitions; } /** * Returns the property definitions. * * @return the property definitions. */ public PropertyDefinition[] getPropertyDefinitions() { return this.propertyDefinitions; } /** * Returns the property names. * * @return the property names. */ public String[] getOrderedPropertyNames() { return this.orderedPropertyNames; } /** * Returns the lookup definitions. * * @return the lookup definitions. */ public LookupDefinition[] getLookupDefinitions() { return this.lookupDefinitions; } /** * Returns the value of the specified property. * * @param name the property name. * * @return the property value. */ public Object getProperty(final String name) { return this.propertyValues.get(name); } /** * Creates an object according to the definition. * * @return the object. * * @throws ObjectDescriptionException if there is a problem with the object description. */ public Object createObject() throws ObjectDescriptionException { final Class[] cArgs = new Class[this.constructorDefinitions.length]; final Object[] oArgs = new Object[this.constructorDefinitions.length]; for (int i = 0; i < cArgs.length; i++) { final ConstructorDefinition cDef = this.constructorDefinitions[i]; cArgs[i] = cDef.getType(); if (cDef.isNull()) { oArgs[i] = null; } else { oArgs[i] = getProperty(cDef.getPropertyName()); } } try { final Constructor constr = this.baseClass.getConstructor(cArgs); final Object o = constr.newInstance(oArgs); return o; } catch (Exception e) { throw new ObjectDescriptionException("Ugh! Constructor made a buuuh!", e); } } /** * Sets a property value. * * @param propertyName the property name. * @param value the property value. * * @throws ObjectDescriptionException if there is a problem with the object description. */ public void setProperty(final String propertyName, final Object value) throws ObjectDescriptionException { final PropertyDescriptor pdesc = getPropertyDescriptor(propertyName); if (pdesc == null) { throw new ObjectDescriptionException("Unknown property " + propertyName); } if (!isAssignableOrPrimitive(pdesc.getPropertyType(), value.getClass())) { throw new ObjectDescriptionException( "Invalid value: " + pdesc.getPropertyType() + " vs. " + value.getClass() ); } this.propertyValues.put(propertyName, value); } /** * Returns true if the base type is a primitive or assignable from the value type. * * @param baseType the base class. * @param valueType the value class. * * @return A boolean. */ private boolean isAssignableOrPrimitive(final Class baseType, final Class valueType) { if (BasicTypeSupport.isBasicDataType(baseType)) { return true; } // verbose stuff below *should* no longer be needed return baseType.isAssignableFrom(valueType); } /** * Returns true if the specified property is... * * @param propertyName the property name. * * @return A boolean. */ private boolean isConstructorProperty(final String propertyName) { for (int i = 0; i < this.constructorDefinitions.length; i++) { final ConstructorDefinition cDef = this.constructorDefinitions[i]; if (propertyName.equals(cDef.getPropertyName())) { return true; } } return false; } /** * Writes the properties for the object. * * @param object the object. * * @throws ObjectDescriptionException if there is a problem. */ public void writeObjectProperties(final Object object) throws ObjectDescriptionException { // this assumes that the order of setting the attributes does not matter. for (int i = 0; i < this.orderedPropertyNames.length; i++) { try { final String name = this.orderedPropertyNames[i]; if (isConstructorProperty(name)) { continue; } final Object value = getProperty(name); if (value == null) { // do nothing if value is not defined ... continue; } final PropertyDescriptor pdescr = getPropertyDescriptor(name); final Method setter = pdescr.getWriteMethod(); setter.invoke(object, new Object[]{value}); } catch (Exception e) { throw new ObjectDescriptionException( "Failed to set properties." + getBaseClass(), e ); } } } /** * Reads the properties. * * @param object the object. * * @throws ObjectDescriptionException if there is a problem. */ public void readProperties(final Object object) throws ObjectDescriptionException { // this assumes that the order of setting the attributes does not matter. for (int i = 0; i < this.orderedPropertyNames.length; i++) { try { final String name = this.orderedPropertyNames[i]; final PropertyDescriptor pdescr = getPropertyDescriptor(name); if (pdescr == null) { throw new IllegalStateException("No property defined: " + name); } final Method setter = pdescr.getReadMethod(); final Object value = setter.invoke(object, new Object[0]); if (value == null) { // do nothing if value is not defined ... or null continue; } setProperty(name, value); } catch (Exception e) { throw new ObjectDescriptionException("Failed to set properties.", e); } } } /** * Returns the base class. * * @return the base class. */ public Class getBaseClass() { return this.baseClass; } } jcommon-1.0.16/source/org/jfree/xml/util/LookupDefinition.java0000644000175000017500000000474711172030703024271 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * LookupDefinition.java * --------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: LookupDefinition.java,v 1.3 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 24-Sep-2003 : Initial version * */ package org.jfree.xml.util; /** * A lookup definition. */ public class LookupDefinition { /** The property name. */ private String propertyName; /** The registry key. */ private String registryKey; /** * Creates a new lookup definition. * * @param propertyName the property name. * @param registryKey the registry key. */ public LookupDefinition(final String propertyName, final String registryKey) { this.propertyName = propertyName; this.registryKey = registryKey; } /** * Returns the property name. * * @return the property name. */ public String getPropertyName() { return this.propertyName; } /** * Returns the registry key. * * @return the registry key. */ public String getRegistryKey() { return this.registryKey; } } jcommon-1.0.16/source/org/jfree/xml/util/ClassModelTags.java0000644000175000017500000001064611172030703023647 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * ClassModelTags.java * ------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ClassModelTags.java,v 1.3 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 20-Nov-2003 : Initial version (TM); * 25-Nov-2003 : Header and Javadoc updates (DG); * */ package org.jfree.xml.util; /** * A collection of tags used in the object model description. */ public final class ClassModelTags { /** Objects tag text. */ public static final String OBJECTS_TAG = "objects"; /** Include tag text. */ public static final String INCLUDE_TAG = "include"; /** Source attribute text. */ public static final String SOURCE_ATTR = "src"; /** Object tag text. */ public static final String OBJECT_TAG = "object"; /** Ignore attribute text. */ public static final String IGNORE_ATTR = "ignore"; /** Class attribute text. */ public static final String CLASS_ATTR = "class"; /** Register name attribute text. */ public static final String REGISTER_NAMES_ATTR = "register-name"; /** Element property tag text. */ public static final String ELEMENT_PROPERTY_TAG = "element-property"; /** Attribute property tag text. */ public static final String ATTRIBUTE_PROPERTY_TAG = "attribute-property"; /** Lookup property tag text. */ public static final String LOOKUP_PROPERTY_TAG = "lookup"; /** Name attribute tag text. */ public static final String NAME_ATTR = "name"; /** Element attribute text. */ public static final String ELEMENT_ATTR = "element"; /** Attribute text. */ public static final String ATTRIBUTE_ATTR = "attribute"; /** Lookup attribute text. */ public static final String LOOKUP_ATTR = "lookup"; /** Constructor tag text. */ public static final String CONSTRUCTOR_TAG = "constructor"; /** Parameter tag text. */ public static final String PARAMETER_TAG = "parameter"; /** Property attribute text. */ public static final String PROPERTY_ATTR = "property"; /** Attribute handler text. */ public static final String ATTRIBUTE_HANDLER_ATTR = "handler"; /** Ignored property tag text. */ public static final String IGNORED_PROPERTY_TAG = "ignore"; /** Manual tag text. */ public static final String MANUAL_TAG = "manual"; /** Read handler attribute text. */ public static final String READ_HANDLER_ATTR = "read-handler"; /** Write handler attribute text. */ public static final String WRITE_HANDLER_ATTR = "write-handler"; /** Mapping tag text. */ public static final String MAPPING_TAG = "mapping"; /** Type attribute text. */ public static final String TYPE_ATTR = "type-attribute"; /** Base class attribute text. */ public static final String BASE_CLASS_ATTR = "base-class"; /** Type tag text. */ public static final String TYPE_TAG = "type"; /** * Private constructor prevents instantiation. */ private ClassModelTags() { super(); } } jcommon-1.0.16/source/org/jfree/xml/util/ManualMappingDefinition.java0000644000175000017500000000644011172030703025541 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------- * ManualMappingDefinition.java * ---------------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ManualMappingDefinition.java,v 1.3 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 22-Nov-2003 : Initial version * */ package org.jfree.xml.util; /** * Maps a class to a read handler and a write handler. */ public class ManualMappingDefinition { /** The class. */ private Class baseClass; /** The read handler. */ private String readHandler; /** The write handler. */ private String writeHandler; /** * Creates a mapping between the class and the read and write handlers. * * @param baseClass the class (null not permitted). * @param readHandler the name of the read handler. * @param writeHandler the name of the write handler. */ public ManualMappingDefinition(final Class baseClass, final String readHandler, final String writeHandler) { if (baseClass == null) { throw new NullPointerException("BaseClass must not be null"); } if (readHandler == null && writeHandler == null) { throw new NullPointerException ("At least one of readHandler or writeHandler must be defined."); } this.baseClass = baseClass; this.readHandler = readHandler; this.writeHandler = writeHandler; } /** * Returns the class. * * @return The class. */ public Class getBaseClass() { return this.baseClass; } /** * Returns the name of the read handler. * * @return The name of the read handler. */ public String getReadHandler() { return this.readHandler; } /** * Returns the name of the write handler. * * @return The name of the write handler. */ public String getWriteHandler() { return this.writeHandler; } } jcommon-1.0.16/source/org/jfree/xml/util/SimpleObjectFactory.java0000644000175000017500000001156511172030703024713 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * SimpleObjectFactory.java * ------------------------ * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: SimpleObjectFactory.java,v 1.3 2005/10/18 13:33:53 mungady Exp $ * * Changes * ------- * 02-Dec-2003 : Initial version * */ package org.jfree.xml.util; import java.util.HashMap; /** * A simple object factory. */ public class SimpleObjectFactory implements ObjectFactory { /** The object mappings. */ private HashMap objectMappings; /** The manual object mappings. */ private HashMap manualMappings; /** The multiplex mappings. */ private HashMap multiplexMappings; /** * Creates a new instance. */ public SimpleObjectFactory() { this.objectMappings = new HashMap(); this.manualMappings = new HashMap(); this.multiplexMappings = new HashMap(); } /** * Adds a manual mapping. * * @param mapping the mapping. */ public void addManualMapping(final ManualMappingDefinition mapping) { this.manualMappings.put(mapping.getBaseClass(), mapping); } /** * Adds a generic handler. * * @param handler the handler. */ public void addGenericHandler(final GenericObjectFactory handler) { this.objectMappings.put(handler.getBaseClass(), handler); } /** * Adds a multiplex mapping. * * @param mplex the multiplex mapping. */ public void addMultiplexMapping(final MultiplexMappingDefinition mplex) { this.multiplexMappings.put(mplex.getBaseClass(), mplex); } /** * Clears the mappings. */ public void clear() { this.objectMappings.clear(); this.manualMappings.clear(); this.multiplexMappings.clear(); } /** * Returns a factory instance for the given class. The factory is independent * from all previously generated instances. * * @param c the class * @return the object factory. */ public GenericObjectFactory getFactoryForClass(final Class c) { final GenericObjectFactory factory = (GenericObjectFactory) this.objectMappings.get(c); if (factory == null) { return null; } return factory.getInstance(); } /** * Returns the manual mapping definition for the given class, or null, if * not manual definition exists. * * @param c the class for which to check the existence of the definition * @return the manual mapping definition or null. */ public ManualMappingDefinition getManualMappingDefinition(final Class c) { return (ManualMappingDefinition) this.manualMappings.get(c); } /** * Returns the multiplex definition for the given class, or null, if no * such definition exists. * * @param c the class for which to check the existence of the multiplexer * @return the multiplexer for the class, or null if no multiplexer exists. */ public MultiplexMappingDefinition getMultiplexDefinition(final Class c) { final MultiplexMappingDefinition definition = (MultiplexMappingDefinition) this.multiplexMappings.get(c); return definition; } /** * Checks, whether a generic handler exists for the given class. This does * not check, whether an mapping exists. * * @param c the class for which to check * @return true, if an generic handler is defined, false otherwise. */ public boolean isGenericHandler(final Class c) { return this.objectMappings.containsKey(c); } } jcommon-1.0.16/source/org/jfree/xml/parser/0000755000175000017500000000000011351753320020455 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/xml/parser/coretypes/0000755000175000017500000000000011351753320022472 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/xml/parser/coretypes/InsetsReadHandler.java0000644000175000017500000000603511172030703026672 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * InsetsReadHandler.java * ---------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: InsetsReadHandler.java,v 1.2 2005/10/18 13:33:32 mungady Exp $ * * Changes * ------- * 03-Dec-2003 : Initial version * 11-Feb-2004 : Added missing Javadocs (DG); * */ package org.jfree.xml.parser.coretypes; import java.awt.Insets; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.jfree.xml.parser.XmlReaderException; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A reader that can parse the XML element for an {@link Insets} object. */ public class InsetsReadHandler extends AbstractXmlReadHandler { /** The insets under construction. */ private Insets insets; /** * Creates a new read handler. */ public InsetsReadHandler() { super(); } /** * Begins parsing. * * @param attrs the attributes. * * @throws SAXException if there is a parsing problem. */ protected void startParsing(final Attributes attrs) throws SAXException { final String top = attrs.getValue("top"); final String left = attrs.getValue("left"); final String bottom = attrs.getValue("bottom"); final String right = attrs.getValue("right"); this.insets = new Insets( Integer.parseInt(top), Integer.parseInt(left), Integer.parseInt(bottom), Integer.parseInt(right) ); } /** * Returns the object for this element. * * @return the object. * * @throws XmlReaderException never. */ public Object getObject() throws XmlReaderException { return this.insets; } } jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/RenderingHintValueReadHandler.java0000644000175000017500000001025011172030703031154 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------------- * RenderingHintValueReadHandler.java * ---------------------------------- * (C)opyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: RenderingHintValueReadHandler.java,v 1.3 2005/10/18 13:33:32 mungady Exp $ * * Changes * ------- * 03-Dec-2003 : Initial version * 11-Feb-2004 : Added missing Javadocs (DG); * */ package org.jfree.xml.parser.coretypes; import java.awt.RenderingHints; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import org.jfree.util.Log; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.jfree.xml.parser.XmlReaderException; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A read handler for a rendering hint value. */ public class RenderingHintValueReadHandler extends AbstractXmlReadHandler { /** The key under construction. */ private Object key; /** The value under construction. */ private Object value; /** * Creates a new read handler. */ public RenderingHintValueReadHandler() { super(); } /** * Starts parsing. * * @param attrs the attributes. * * @throws SAXException if there is a parsing error. */ protected void startParsing(final Attributes attrs) throws SAXException { final String keyText = attrs.getValue("key"); final String valueText = attrs.getValue("value"); this.key = stringToHintField(keyText); this.value = stringToHintField(valueText); } private Object stringToHintField (final String name) { final Field[] fields = RenderingHints.class.getFields(); for (int i = 0; i < fields.length; i++) { final Field f = fields[i]; if (Modifier.isFinal(f.getModifiers()) && Modifier.isPublic(f.getModifiers()) && Modifier.isStatic(f.getModifiers())) { try { final String fieldName = f.getName(); if (fieldName.equals(name)) { return f.get(null); } } catch (Exception e) { Log.info ("Unable to write RenderingHint", e); } } } throw new IllegalArgumentException("Invalid value given"); } /** * Returns the object for this element. * * @return the object. * * @throws XmlReaderException if there is a parsing error. */ public Object getObject() throws XmlReaderException { return new Object[] {this.key, this.value}; } /** * Returns the key. * * @return the key. */ public Object getKey() { return this.key; } /** * Returns the value. * * @return the value. */ public Object getValue() { return this.value; } } jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/Rectangle2DReadHandler.java0000644000175000017500000000630111172030703027513 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * Rectangle2DReadHandler * ---------------------- * (C) Copyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): -; * * $Id: Rectangle2DReadHandler.java,v 1.2 2005/10/18 13:33:32 mungady Exp $ * * Changes * ------- * */ package org.jfree.xml.parser.coretypes; import java.awt.geom.Rectangle2D; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A handler for reading a {@link Rectangle2D} object. */ public class Rectangle2DReadHandler extends AbstractXmlReadHandler { /** The rectangle being constructed. */ private Rectangle2D rectangle; /** * Default constructor. */ public Rectangle2DReadHandler() { super(); } /** * Begins parsing. * * @param attrs the attributes. * * @throws SAXException if there is a parsing error. */ protected void startParsing(final Attributes attrs) throws SAXException { final String type = attrs.getValue("type"); this.rectangle = createRect(type); final String x = attrs.getValue("x"); final String y = attrs.getValue("y"); final String w = attrs.getValue("width"); final String h = attrs.getValue("height"); this.rectangle.setRect( Double.parseDouble(x), Double.parseDouble(y), Double.parseDouble(w), Double.parseDouble(h) ); } /** * Creates a rectangle. * * @param type the type ('float' or 'double'). * * @return The rectangle. */ private Rectangle2D createRect(final String type) { if ("float".equals(type)) { return new Rectangle2D.Float(); } return new Rectangle2D.Double(); } /** * Returns the object under construction. * * @return The object. */ public Object getObject() { return this.rectangle; } } jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/StringReadHandler.java0000644000175000017500000000663411172030703026700 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * StringReadHandler.java * ---------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: StringReadHandler.java,v 1.6 2008/09/10 09:19:23 mungady Exp $ * * Changes * ------- * 03-Dec-2003 : Initial version * 11-Feb-2004 : Added missing Javadocs (DG); * */ package org.jfree.xml.parser.coretypes; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.jfree.xml.parser.XmlReaderException; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * Required for list contents ... */ public class StringReadHandler extends AbstractXmlReadHandler { /** * A string buffer. */ private StringBuffer buffer; /** * The string under construction. */ private String result; /** * Creates a new handler. */ public StringReadHandler () { super(); } /** * Starts parsing. * * @param attrs the attributes. * @throws SAXException if there is a parsing error. */ protected void startParsing (final Attributes attrs) throws SAXException { this.buffer = new StringBuffer(); } /** * This method is called to process the character data between element tags. * * @param ch the character buffer. * @param start the start index. * @param length the length. * @throws SAXException if there is a parsing error. */ public void characters (final char[] ch, final int start, final int length) throws SAXException { this.buffer.append(ch, start, length); } /** * Done parsing. * * @throws SAXException if there is a parsing error. * @throws XmlReaderException if there is a reader error. */ protected void doneParsing () throws SAXException, XmlReaderException { this.result = this.buffer.toString(); this.buffer = null; } /** * Returns the result. * * @return The result. */ public String getResult () { return this.result; } /** * Returns the object for this element. * * @return the object. */ public Object getObject () { return this.result; } } jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/NullReadHandler.java0000644000175000017500000000425311172030703026337 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * NullReadHandler.java * -------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: NullReadHandler.java,v 1.2 2005/10/18 13:33:32 mungady Exp $ * * Changes * ------- * 03-Dec-2003 : Initial version * */ package org.jfree.xml.parser.coretypes; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.jfree.xml.parser.XmlReaderException; /** * A null read handler. */ public class NullReadHandler extends AbstractXmlReadHandler { /** * Default constructor. */ public NullReadHandler() { super(); } /** * Returns the object for this element. * * @return the object. * * @throws XmlReaderException if there is a parsing error. */ public Object getObject() throws XmlReaderException { return null; } } jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/package.html0000644000175000017500000000021111172030703024737 0ustar twernertwerner XML writers for some core classes. jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/RenderingHintsReadHandler.java0000644000175000017500000001023511172030703030345 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------ * RenderingHintsReadHandler.java * ------------------------------ * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: RenderingHintsReadHandler.java,v 1.3 2005/10/18 13:33:32 mungady Exp $ * * Changes * ------- * 03-Dec-2003 : Initial version * 11-Feb-2004 : Added missing Javadocs (DG); * */ package org.jfree.xml.parser.coretypes; import java.awt.RenderingHints; import java.util.ArrayList; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.jfree.xml.parser.XmlReadHandler; import org.jfree.xml.parser.XmlReaderException; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A read handler that can parse the XML element for a {@link RenderingHints} collection. */ public class RenderingHintsReadHandler extends AbstractXmlReadHandler { /** The subhandlers. */ private ArrayList handlers; /** The rendering hints under construction. */ private RenderingHints renderingHints; /** * Creates a new read handler. */ public RenderingHintsReadHandler() { super(); } /** * Starts parsing. * * @param attrs the attributes. * * @throws SAXException never. */ protected void startParsing(final Attributes attrs) throws SAXException { this.handlers = new ArrayList(); } /** * Returns the handler for a child element. * * @param tagName the tag name. * @param atts the attributes. * * @return the handler. * * @throws SAXException if there is a parsing error. * @throws XmlReaderException if there is a reader error. */ protected XmlReadHandler getHandlerForChild(final String tagName, final Attributes atts) throws XmlReaderException, SAXException { if (!tagName.equals("entry")) { throw new SAXException("Expected 'entry' tag."); } final XmlReadHandler handler = new RenderingHintValueReadHandler(); this.handlers.add(handler); return handler; } /** * Done parsing. * * @throws SAXException if there is a parsing error. * @throws XmlReaderException if there is a reader error. */ protected void doneParsing() throws SAXException, XmlReaderException { this.renderingHints = new RenderingHints(null); for (int i = 0; i < this.handlers.size(); i++) { final RenderingHintValueReadHandler rh = (RenderingHintValueReadHandler) this.handlers.get(i); this.renderingHints.put(rh.getKey(), rh.getValue()); } } /** * Returns the object for this element. * * @return the object. * * @throws XmlReaderException if there is a parsing error. */ public Object getObject() throws XmlReaderException { return this.renderingHints; } } jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/ColorReadHandler.java0000644000175000017500000000600411172030703026477 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * ColorReadHandler * ---------------- * (C) Copyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ColorReadHandler.java,v 1.2 2005/10/18 13:33:32 mungady Exp $ * * Changes (from 25-Nov-2003) * -------------------------- * 25-Nov-2003 : Added standard header and Javadocs (DG); * */ package org.jfree.xml.parser.coretypes; import java.awt.Color; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A SAX handler for reading {@link Color} objects from an XML element. */ public class ColorReadHandler extends AbstractXmlReadHandler { /** The color under construction. */ private Color color; /** * Creates a new handler. */ public ColorReadHandler() { super(); } /** * Called at the start of parsing a {@link Color} element, this method reads the attributes and * constructs the {@link Color}. * * @param attrs the attributes. * * @throws SAXException to indicate a parsing error. */ protected void startParsing(final Attributes attrs) throws SAXException { final String encodedValue = attrs.getValue("value"); this.color = Color.decode(encodedValue); if (attrs.getValue("alpha") != null) { this.color = new Color(this.color.getRed(), this.color.getGreen(), this.color.getBlue(), Integer.parseInt(attrs.getValue("alpha"))); } } /** * Returns the color under construction. * * @return the color. */ public Object getObject() { return this.color; } } jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/GradientPaintReadHandler.java0000644000175000017500000001135411172030703030156 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * GradientPaintReadHandler * ------------------------ * (C) Copyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: GradientPaintReadHandler.java,v 1.2 2005/10/18 13:33:32 mungady Exp $ * * Changes (from 25-Nov-2003) * -------------------------- * 25-Nov-2003 : Added standard header and Javadocs (DG); * */ package org.jfree.xml.parser.coretypes; import java.awt.Color; import java.awt.GradientPaint; import java.awt.geom.Point2D; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.jfree.xml.parser.XmlReadHandler; import org.jfree.xml.parser.XmlReaderException; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A SAX handler for reading a {@link GradientPaint} from an XML element. */ public class GradientPaintReadHandler extends AbstractXmlReadHandler { /** The gradient paint under construction. */ private GradientPaint gradient; /** The handler for color 1. */ private XmlReadHandler color1Handler; /** The handler for color 2. */ private XmlReadHandler color2Handler; /** The handler for point 1. */ private XmlReadHandler point1Handler; /** The handler for point 2. */ private XmlReadHandler point2Handler; /** * Creates a new handler. */ public GradientPaintReadHandler() { super(); } /** * Returns the gradient paint under construction. * * @return the gradient paint. */ public Object getObject() { return this.gradient; } /** * Returns the handler for a child element. * * @param tagName the tag name. * @param atts the attributes. * * @return the handler. * @throws SAXException to indicate a parsing error. * @throws XmlReaderException if there is a reader error. */ protected XmlReadHandler getHandlerForChild(final String tagName, final Attributes atts) throws SAXException, XmlReaderException { if ("color1".equals(tagName)) { this.color1Handler = getRootHandler().createHandler(Color.class, tagName, atts); return this.color1Handler; } else if ("color2".equals(tagName)) { this.color2Handler = getRootHandler().createHandler(Color.class, tagName, atts); return this.color2Handler; } else if ("point1".equals(tagName)) { this.point1Handler = getRootHandler().createHandler(Point2D.class, tagName, atts); return this.point1Handler; } else if ("point2".equals(tagName)) { this.point2Handler = getRootHandler().createHandler(Point2D.class, tagName, atts); return this.point2Handler; } return null; } /** * At the end of parsing the element, the gradient paint is constructed. * * @throws XmlReaderException if there is a parsing error. */ protected void doneParsing() throws XmlReaderException { if (this.point1Handler == null || this.point2Handler == null || this.color1Handler == null || this.color2Handler == null) { throw new XmlReaderException("Not all required subelements are defined."); } this.gradient = new GradientPaint ((Point2D) this.point1Handler.getObject(), (Color) this.color1Handler.getObject(), (Point2D) this.point2Handler.getObject(), (Color) this.color2Handler.getObject()); } } jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/GenericReadHandler.java0000644000175000017500000002164411172030703027004 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * GenericReadHandler.java * ----------------------- * (C)opyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: GenericReadHandler.java,v 1.5 2005/10/18 13:33:32 mungady Exp $ * * Changes * ------- * 23-Sep-2003 : Initial version * */ package org.jfree.xml.parser.coretypes; import java.util.ArrayList; import java.util.HashMap; import org.jfree.util.Log; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.jfree.xml.parser.RootXmlReadHandler; import org.jfree.xml.parser.XmlReadHandler; import org.jfree.xml.parser.XmlReaderException; import org.jfree.xml.util.AttributeDefinition; import org.jfree.xml.util.ConstructorDefinition; import org.jfree.xml.util.GenericObjectFactory; import org.jfree.xml.util.LookupDefinition; import org.jfree.xml.util.ObjectDescriptionException; import org.jfree.xml.util.PropertyDefinition; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A SAX handler for reading a generic object from an XML element. */ public class GenericReadHandler extends AbstractXmlReadHandler { /** The object under construction. */ private Object object; /** The generic object factory. */ private GenericObjectFactory objectFactory; /** The object reference handlers. */ private ArrayList objectRefHandlers; /** The created handler. */ private HashMap createdHandler; /** * Creates a new handler. * * @param factory the generic object factory. */ public GenericReadHandler(final GenericObjectFactory factory) { this.createdHandler = new HashMap(); this.objectRefHandlers = new ArrayList(); this.objectFactory = factory; } /** * Called at the start of parsing. * * @param attrs the attributes. * * @throws SAXException if there is a parsing error. */ protected void startParsing(final Attributes attrs) throws SAXException { try { final AttributeDefinition[] attribs = this.objectFactory.getAttributeDefinitions(); for (int i = 0; i < attribs.length; i++) { final AttributeDefinition attrDef = attribs[i]; final String value = attrs.getValue(attrDef.getAttributeName()); if (value == null) { continue; } final Object o = attrDef.getHandler().toPropertyValue(value); this.objectFactory.setProperty(attrDef.getPropertyName(), o); } } catch (ObjectDescriptionException ode) { throw new SAXException(ode); } } /** * Returns the child handler. * * @param tagName the tag name. * @param atts the attributes. * * @return The handler. * * @throws SAXException if there is a parsing problem. */ protected XmlReadHandler getHandlerForChild(final String tagName, final Attributes atts) throws SAXException { try { if (tagName.equals("objectRef")) { // store them all and copy the properties later when the object is created final XmlReadHandler handler = new ObjectRefHandler(); this.objectRefHandlers.add(handler); return handler; } final XmlReadHandler handler = getRootHandler().createHandler (this.objectFactory.getTypeForTagName(tagName), tagName, atts); if (handler != null) { this.createdHandler.put(tagName, handler); } // will throw exception if handler is null... return handler; } catch (ObjectDescriptionException ode) { Log.debug ("Failed to get handler for child: ", ode); throw new SAXException(ode); } } /** * Returns the object. * * @return The object. * * @throws XmlReaderException ??? */ public Object getObject() throws XmlReaderException { if (this.object != null) { return this.object; } final RootXmlReadHandler rootHandler = getRootHandler(); try { for (int i = 0; i < this.objectRefHandlers.size(); i++) { final ObjectRefHandler handler = (ObjectRefHandler) this.objectRefHandlers.get(i); this.objectFactory.setProperty(handler.getPropertyName(), handler.getObject()); } final ArrayList lookups = new ArrayList(); final LookupDefinition[] lookupDefs = this.objectFactory.getLookupDefinitions(); for (int i = 0; i < lookupDefs.length; i++) { final LookupDefinition ldef = lookupDefs[i]; lookups.add(ldef.getPropertyName()); Log.debug ("lookup object: " + ldef.getPropertyName()); final Object value = rootHandler.getHelperObject(ldef.getRegistryKey()); if (value == null) { // todo may or may not be fatal -> define it in the xml? Log.warn ("Failed to lookup object: " + value); } else { this.objectFactory.setProperty(ldef.getPropertyName(), value); } } final ConstructorDefinition[] conDefs = this.objectFactory.getConstructorDefinitions(); for (int i = 0; i < conDefs.length; i++) { final ConstructorDefinition cDef = conDefs[i]; // if this is a lookup, then ignore if (lookups.contains(cDef.getPropertyName())) { continue; } if (this.objectFactory.isPropertyDefinition(cDef.getPropertyName())) { final PropertyDefinition pd = this.objectFactory.getPropertyDefinitionByPropertyName( cDef.getPropertyName() ); final XmlReadHandler handler = (XmlReadHandler) this.createdHandler.get( pd.getElementName() ); if (handler != null) { this.objectFactory.setProperty(pd.getPropertyName(), handler.getObject()); } } // hoping that the attribute is set .. } this.object = this.objectFactory.createObject(); Object oldValue = null; if (this.objectFactory.getRegisterName() != null) { oldValue = rootHandler.getHelperObject(this.objectFactory.getRegisterName()); rootHandler.setHelperObject(this.objectFactory.getRegisterName(), this.object); } final PropertyDefinition[] propertyDefs = this.objectFactory.getPropertyDefinitions(); for (int i = 0; i < propertyDefs.length; i++) { final PropertyDefinition pdef = propertyDefs[i]; final XmlReadHandler handler = (XmlReadHandler) this.createdHandler.get( pdef.getElementName() ); if (handler == null) { continue; } this.objectFactory.setProperty(pdef.getPropertyName(), handler.getObject()); } this.objectFactory.writeObjectProperties(this.object); if (this.objectFactory.getRegisterName() != null) { rootHandler.setHelperObject(this.objectFactory.getRegisterName(), oldValue); } } catch (ObjectDescriptionException ode) { Log.error ("Unable to create object.", ode); throw new XmlReaderException("Unable to create object.", ode); } return this.object; } } jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/Point2DReadHandler.java0000644000175000017500000000574711172030703026715 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * Point2DReadHandler * ------------------ * (C) Copyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Point2DReadHandler.java,v 1.2 2005/10/18 13:33:32 mungady Exp $ * * Changes (from 25-Nov-2003) * -------------------------- * 25-Nov-2003 : Added standard header and Javadocs (DG); * */ package org.jfree.xml.parser.coretypes; import java.awt.geom.Point2D; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A SAX handler for reading {@link Point2D} objects from an XML element. */ public class Point2DReadHandler extends AbstractXmlReadHandler { /** The point under construction. */ private Point2D point; /** * Creates a new handler. */ public Point2DReadHandler() { super(); } /** * At the start of parsing, the attributes are read and used to construct the point. * * @param attrs the attributes. * * @throws SAXException if there is a parsing error. */ protected void startParsing(final Attributes attrs) throws SAXException { final String x = attrs.getValue("x"); final String y = attrs.getValue("y"); this.point = new Point2D.Double(Double.parseDouble(x), Double.parseDouble(y)); } /** * Returns the point under construction. * * @return the point. */ public Point2D getPoint2D() { return this.point; } /** * Returns the point under construction. * * @return the point. */ public Object getObject() { return this.point; } } jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/ListReadHandler.java0000644000175000017500000001127011172030703026335 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * ListReadHandler.java * -------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ListReadHandler.java,v 1.3 2005/10/18 13:33:32 mungady Exp $ * * Changes * ------- * 12-Nov-2003 : Initial version (TM); * */ package org.jfree.xml.parser.coretypes; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Stack; import java.util.Vector; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.jfree.xml.parser.XmlReadHandler; import org.jfree.xml.parser.XmlReaderException; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A SAX handler for reading a list from an XML element. */ public class ListReadHandler extends AbstractXmlReadHandler { /** The list under construction. */ private List retval; /** The handlers. */ private ArrayList handlers; /** The type of list ('array-list', 'linked-list', 'stack', 'vector'). */ private String listType; /** * Default constructor. */ public ListReadHandler() { super(); } /** * Start parsing. * * @param attrs the attributes. * * @throws SAXException if there is a parsing error. */ protected void startParsing(final Attributes attrs) throws SAXException { this.listType = attrs.getValue("type"); if (this.listType == null) { this.listType = "array-list"; } this.handlers = new ArrayList(); } /** * Gets a handler for a child. * * @param tagName the tag name. * @param atts the attributes. * * @return A handler. * * @throws XmlReaderException if there is a problem with the reader. * @throws SAXException if there is a parsing error. */ protected XmlReadHandler getHandlerForChild(final String tagName, final Attributes atts) throws XmlReaderException, SAXException { final XmlReadHandler handler = getRootHandler().createHandler(Object.class, tagName, atts); this.handlers.add(handler); return handler; } /** * Parsing is finished. * * @throws SAXException if there is a parsing error. * @throws XmlReaderException if there is a problem with the reader. * */ protected void doneParsing() throws SAXException, XmlReaderException { final XmlReadHandler[] handler = (XmlReadHandler[]) this.handlers.toArray(new XmlReadHandler[this.handlers.size()]); this.retval = createList(handler.length); for (int i = 0; i < handler.length; i++) { this.retval.add(handler[i].getObject()); } this.handlers.clear(); } /** * Creates a list. * * @param initialSize the initial size. * * @return A new list. */ private List createList(final int initialSize) { if (this.listType.equals("stack")) { return new Stack(); } if (this.listType.equals("linked-list")) { return new LinkedList(); } if (this.listType.equals("vector")) { return new Vector(initialSize); } return new ArrayList(initialSize); } /** * Returns the object under construction. * * @return The list. */ public Object getObject() { return this.retval; } } jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/ObjectRefHandler.java0000644000175000017500000000646311172030703026501 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * ObjectRefHandler.java * --------------------- * (C)opyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ObjectRefHandler.java,v 1.3 2005/10/18 13:33:32 mungady Exp $ * * Changes * ------- * 29-Sep-2003 : Initial version (TM); * 25-Nov-2003 : Updated header and Javadocs (DG); * */ package org.jfree.xml.parser.coretypes; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A SAX handler for an object reference. */ public class ObjectRefHandler extends AbstractXmlReadHandler { /** The object. */ private Object object; /** The property name. */ private String propertyName; /** * Creates a new handler. */ public ObjectRefHandler() { super(); } /** * Starts parsing. * * @param attrs the attributes. * * @throws SAXException ???. */ protected void startParsing(final Attributes attrs) throws SAXException { final String tagName = getTagName(); if (tagName.equals("objectRef")) { final String sourceName = attrs.getValue("source"); if (sourceName == null) { throw new SAXException("Source name is not defined."); } this.propertyName = attrs.getValue("property"); if (this.propertyName == null) { throw new SAXException("Property name is not defined."); } this.object = getRootHandler().getHelperObject(sourceName); if (this.object == null) { throw new SAXException("Referenced object is undefined."); } } } /** * Returns the property name. * * @return the property name. */ public String getPropertyName() { return this.propertyName; } /** * Returns the value. * * @return the value. */ public Object getObject() { return this.object; } } jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/BasicStrokeReadHandler.java0000644000175000017500000001014111172030703027627 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * BasicStrokeReadHandler * ---------------------- * (C) Copyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: BasicStrokeReadHandler.java,v 1.2 2005/10/18 13:33:32 mungady Exp $ * * Changes (from 25-Nov-2003) * -------------------------- * 25-Nov-2003 : Added standard header and Javadocs (DG); * */ package org.jfree.xml.parser.coretypes; import java.awt.BasicStroke; import java.util.StringTokenizer; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A SAX handler for reading a {@link BasicStroke} object from XML. *

* To do: this should have a multiplexer in front like the PaintReadHandler */ public class BasicStrokeReadHandler extends AbstractXmlReadHandler { /** The stroke under construction. */ private BasicStroke stroke; /** * Creates a new handler. */ public BasicStrokeReadHandler() { super(); } /** * Called at the start of parsing a {@link BasicStroke} element, this method reads the * attributes and constructs the stroke. * * @param attrs the attributes. * * @throws SAXException to indicate a parsing error. */ protected void startParsing(final Attributes attrs) throws SAXException { final int endCap = Integer.parseInt(attrs.getValue("endCap")); final int lineJoin = Integer.parseInt(attrs.getValue("lineJoin")); final float lineWidth = Float.parseFloat(attrs.getValue("lineWidth")); final float miterLimit = Float.parseFloat(attrs.getValue("miterLimit")); final String dashArrayAttrib = attrs.getValue("dashArray"); if (dashArrayAttrib != null) { final float[] dashArray = parseDashArray(dashArrayAttrib); final float dashPhase = Float.parseFloat(attrs.getValue("dashPhase")); this.stroke = new BasicStroke( lineWidth, endCap, lineJoin, miterLimit, dashArray, dashPhase ); } else { this.stroke = new BasicStroke(lineWidth, endCap, lineJoin, miterLimit); } } /** * Parses the dash array. * * @param string the dash array string representation. * * @return a dash array. */ private float[] parseDashArray(final String string) { final StringTokenizer tokenizer = new StringTokenizer(string, ","); final float[] retVal = new float[tokenizer.countTokens()]; for (int i = 0; i < retVal.length; i++) { retVal[i] = Float.parseFloat(tokenizer.nextToken()); } return retVal; } /** * Returns the stroke under construction. * * @return the stroke. */ public Object getObject() { return this.stroke; } } jcommon-1.0.16/source/org/jfree/xml/parser/coretypes/FontReadHandler.java0000644000175000017500000000652211172030703026334 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * FontReadHandler * --------------- * (C) Copyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: FontReadHandler.java,v 1.2 2005/10/18 13:33:32 mungady Exp $ * * Changes (from 25-Nov-2003) * -------------------------- * 25-Nov-2003 : Added standard header and Javadocs (DG); * */ package org.jfree.xml.parser.coretypes; import java.awt.Font; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A SAX handler for reading a font definition. */ public class FontReadHandler extends AbstractXmlReadHandler { /** The font under construction. */ private Font font; /** * Creates a new SAX handler for reading a {@link Font} from XML. */ public FontReadHandler() { super(); } /** * Called at the start of parsing a font element, this method reads the attributes and * constructs the font. * * @param attrs the attributes. * * @throws SAXException to indicate a parsing error. */ protected void startParsing(final Attributes attrs) throws SAXException { final String family = attrs.getValue("family"); final int size = Integer.parseInt(attrs.getValue("size")); final int style = getFontStyle(attrs.getValue("style")); this.font = new Font(family, style, size); } /** * Converts a string to a font style constant. * * @param style the style as text. * * @return The font style. */ private int getFontStyle (final String style) { if ("bold-italic".equals(style)) { return Font.BOLD | Font.ITALIC; } if ("bold".equals(style)) { return Font.BOLD; } if ("italic".equals(style)) { return Font.ITALIC; } return Font.PLAIN; } /** * Returns the font under construction. * * @return the font. */ public Object getObject() { return this.font; } } jcommon-1.0.16/source/org/jfree/xml/parser/AbstractXmlReadHandler.java0000644000175000017500000001416211172030703025634 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------- * AbstractXmlReadHandler.java * --------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AbstractXmlReadHandler.java,v 1.5 2008/09/10 09:20:16 mungady Exp $ * * Changes (from 25-Nov-2003) * -------------------------- * 25-Nov-2003 : Added Javadocs (DG); * */ package org.jfree.xml.parser; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.jfree.util.Log; /** * A base class for implementing an {@link XmlReadHandler}. */ public abstract class AbstractXmlReadHandler implements XmlReadHandler { /** The root handler. */ private RootXmlReadHandler rootHandler; /** The tag name. */ private String tagName; /** A flag indicating the first call. */ private boolean firstCall = true; /** * Creates a new handler. */ public AbstractXmlReadHandler() { } /** * Initialises the handler. * * @param rootHandler the root handler. * @param tagName the tag name. */ public void init(final RootXmlReadHandler rootHandler, final String tagName) { if (rootHandler == null) { throw new NullPointerException("Root handler must not be null"); } if (tagName == null) { throw new NullPointerException("Tag name must not be null"); } this.rootHandler = rootHandler; this.tagName = tagName; } /** * This method is called at the start of an element. * * @param tagName the tag name. * @param attrs the attributes. * * @throws SAXException if there is a parsing error. * @throws XmlReaderException if there is a reader error. */ public final void startElement(final String tagName, final Attributes attrs) throws XmlReaderException, SAXException { if (this.firstCall) { if (!this.tagName.equals(tagName)) { throw new SAXException("Expected <" + this.tagName + ">, found <" + tagName + ">"); } this.firstCall = false; startParsing(attrs); } else { final XmlReadHandler childHandler = getHandlerForChild(tagName, attrs); if (childHandler == null) { Log.warn ("Unknown tag <" + tagName + ">"); return; } childHandler.init(getRootHandler(), tagName); this.rootHandler.recurse(childHandler, tagName, attrs); } } /** * This method is called to process the character data between element tags. * * @param ch the character buffer. * @param start the start index. * @param length the length. * * @throws SAXException if there is a parsing error. */ public void characters(final char[] ch, final int start, final int length) throws SAXException { // nothing required } /** * This method is called at the end of an element. * * @param tagName the tag name. * * @throws SAXException if there is a parsing error. */ public final void endElement(final String tagName) throws SAXException { if (this.tagName.equals(tagName)) { try { doneParsing(); this.rootHandler.unwind(tagName); } catch (XmlReaderException xre) { throw new SAXException(xre); } } } /** * Starts parsing. * * @param attrs the attributes. * * @throws SAXException if there is a parsing error. * @throws XmlReaderException ? */ protected void startParsing(final Attributes attrs) throws SAXException, XmlReaderException { // nothing required } /** * Done parsing. * * @throws SAXException if there is a parsing error. * @throws XmlReaderException if there is a reader error. */ protected void doneParsing() throws SAXException, XmlReaderException { // nothing required } /** * Returns the handler for a child element. * * @param tagName the tag name. * @param atts the attributes. * * @return the handler or null, if the tagname is invalid. * * @throws SAXException if there is a parsing error. * @throws XmlReaderException if there is a reader error. */ protected XmlReadHandler getHandlerForChild(final String tagName, final Attributes atts) throws XmlReaderException, SAXException { return null; } /** * Returns the tag name. * * @return the tag name. */ public String getTagName() { return this.tagName; } /** * Returns the root handler for the parsing. * * @return the root handler. */ public RootXmlReadHandler getRootHandler() { return this.rootHandler; } } jcommon-1.0.16/source/org/jfree/xml/parser/XmlReadHandler.java0000644000175000017500000000657611172030703024162 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * XmlReadHandler.java * ------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: XmlReadHandler.java,v 1.3 2005/10/18 13:32:52 mungady Exp $ * * Changes (from 25-Nov-2003) * -------------------------- * 25-Nov-2003 : Added Javadocs (DG); * */ package org.jfree.xml.parser; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A handler for reading an XML element. */ public interface XmlReadHandler { /** * This method is called at the start of an element. * * @param tagName the tag name. * @param attrs the attributes. * * @throws SAXException if there is a parsing error. * @throws XmlReaderException if there is a reader error. */ public void startElement(String tagName, Attributes attrs) throws SAXException, XmlReaderException; /** * This method is called to process the character data between element tags. * * @param ch the character buffer. * @param start the start index. * @param length the length. * * @throws SAXException if there is a parsing error. */ public void characters(char[] ch, int start, int length) throws SAXException; /** * This method is called at the end of an element. * * @param tagName the tag name. * * @throws SAXException if there is a parsing error. * @throws XmlReaderException if there is a reader error. */ public void endElement(String tagName) throws SAXException, XmlReaderException; /** * Returns the object for this element or null, if this element does * not create an object. * * @return the object. * * @throws XmlReaderException if there is a parsing error. */ public Object getObject() throws XmlReaderException; /** * Initialise. * * @param rootHandler the root handler. * @param tagName the tag name. */ public void init(RootXmlReadHandler rootHandler, String tagName); } jcommon-1.0.16/source/org/jfree/xml/parser/Base64ReadHandler.java0000644000175000017500000000645611172030703024443 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * Base64ReadHandler.java * ---------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Base64ReadHandler.java,v 1.4 2005/11/08 14:16:51 mungady Exp $ * * Changes * ------- * 11-Feb-2004 : Added standard header and Javadocs (DG); * */ package org.jfree.xml.parser; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import org.jfree.xml.util.Base64; import org.xml.sax.SAXException; /** * A read handler for Base64 encoded elements. * * @deprecated base64 encoded elements are no longer supported ... */ public class Base64ReadHandler extends AbstractXmlReadHandler { /** The encoded object. */ private String encodedObject; /** * Creates a new handler. */ public Base64ReadHandler() { super(); } /** * Process character data. * * @param ch the character buffer. * @param start the start index. * @param length the number of characters. * * @throws SAXException ???. */ public void characters(final char[] ch, final int start, final int length) throws SAXException { this.encodedObject = new String(ch, start, length); } /** * Returns the object under construction. * * @return the object * * @throws XmlReaderException ???. */ public Object getObject() throws XmlReaderException { try { final byte[] bytes = Base64.decode(this.encodedObject.toCharArray()); final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes)); return in.readObject(); } catch (IOException e) { throw new XmlReaderException("Can't read class for <" + getTagName() + ">", e); } catch (ClassNotFoundException e) { throw new XmlReaderException("Class not found for <" + getTagName() + ">", e); } } } jcommon-1.0.16/source/org/jfree/xml/parser/package.html0000644000175000017500000000016211172030703022727 0ustar twernertwerner XML parser. jcommon-1.0.16/source/org/jfree/xml/parser/XmlReaderException.java0000644000175000017500000000463411172030703025063 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * XmlReaderException.java * ----------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: XmlReaderException.java,v 1.2 2005/10/18 13:32:52 mungady Exp $ * * Changes * ------- * 22-Nov-2003 : Initial version * 11-Feb-2004 : Added missing Javadocs (DG); * */ package org.jfree.xml.parser; import org.jfree.xml.util.ObjectDescriptionException; /** * An XML reader exception. */ public class XmlReaderException extends ObjectDescriptionException { /** * Creates a StackableRuntimeException with no message and no parent. */ public XmlReaderException() { super(); } /** * Creates an exception. * * @param message the exception message. */ public XmlReaderException(final String message) { super(message); } /** * Creates an exception. * * @param message the exception message. * @param ex the parent exception. */ public XmlReaderException(final String message, final Exception ex) { super(message, ex); } } jcommon-1.0.16/source/org/jfree/xml/parser/RootXmlReadHandler.java0000644000175000017500000004731711172030703025024 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * RootXmlReadHandler.java * ----------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: RootXmlReadHandler.java,v 1.9 2008/09/10 09:20:16 mungady Exp $ * * Changes (from 25-Nov-2003) * -------------------------- * 25-Nov-2003 : Added Javadocs (DG); * 22-Feb-2005 : Fixed a bug when ending nested tags with the same tagname. */ package org.jfree.xml.parser; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Insets; import java.awt.Paint; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Stack; import java.util.Vector; import org.jfree.util.ObjectUtilities; import org.jfree.xml.FrontendDefaultHandler; import org.jfree.xml.ParseException; import org.jfree.xml.ElementDefinitionException; import org.jfree.xml.parser.coretypes.BasicStrokeReadHandler; import org.jfree.xml.parser.coretypes.ColorReadHandler; import org.jfree.xml.parser.coretypes.FontReadHandler; import org.jfree.xml.parser.coretypes.GenericReadHandler; import org.jfree.xml.parser.coretypes.GradientPaintReadHandler; import org.jfree.xml.parser.coretypes.InsetsReadHandler; import org.jfree.xml.parser.coretypes.ListReadHandler; import org.jfree.xml.parser.coretypes.Point2DReadHandler; import org.jfree.xml.parser.coretypes.Rectangle2DReadHandler; import org.jfree.xml.parser.coretypes.RenderingHintsReadHandler; import org.jfree.xml.parser.coretypes.StringReadHandler; import org.jfree.xml.util.ManualMappingDefinition; import org.jfree.xml.util.MultiplexMappingDefinition; import org.jfree.xml.util.MultiplexMappingEntry; import org.jfree.xml.util.ObjectFactory; import org.jfree.xml.util.SimpleObjectFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A base root SAX handler. */ public abstract class RootXmlReadHandler extends FrontendDefaultHandler { /** The current handlers. */ private Stack currentHandlers; /** ??. */ private Stack outerScopes; /** The root handler. */ private XmlReadHandler rootHandler; /** The object registry. */ private HashMap objectRegistry; /** Maps classes to handlers. */ private SimpleObjectFactory classToHandlerMapping; private boolean rootHandlerInitialized; /** * Creates a new root SAX handler. */ public RootXmlReadHandler() { this.objectRegistry = new HashMap(); this.classToHandlerMapping = new SimpleObjectFactory(); } /** * Adds the default mappings. */ protected void addDefaultMappings () { final MultiplexMappingEntry[] paintEntries = new MultiplexMappingEntry[2]; paintEntries[0] = new MultiplexMappingEntry("color", Color.class.getName()); paintEntries[1] = new MultiplexMappingEntry("gradientPaint", GradientPaint.class.getName()); addMultiplexMapping(Paint.class, "type", paintEntries); addManualMapping(Color.class, ColorReadHandler.class); addManualMapping(GradientPaint.class, GradientPaintReadHandler.class); final MultiplexMappingEntry[] point2DEntries = new MultiplexMappingEntry[2]; point2DEntries[0] = new MultiplexMappingEntry("float", Point2D.Float.class.getName()); point2DEntries[1] = new MultiplexMappingEntry("double", Point2D.Double.class.getName()); addMultiplexMapping(Point2D.class, "type", point2DEntries); addManualMapping(Point2D.Float.class, Point2DReadHandler.class); addManualMapping(Point2D.Double.class, Point2DReadHandler.class); final MultiplexMappingEntry[] rectangle2DEntries = new MultiplexMappingEntry[2]; rectangle2DEntries[0] = new MultiplexMappingEntry( "float", Rectangle2D.Float.class.getName() ); rectangle2DEntries[1] = new MultiplexMappingEntry( "double", Rectangle2D.Double.class.getName() ); addMultiplexMapping(Rectangle2D.class, "type", rectangle2DEntries); addManualMapping(Rectangle2D.Float.class, Rectangle2DReadHandler.class); addManualMapping(Rectangle2D.Double.class, Rectangle2DReadHandler.class); // Handle list types final MultiplexMappingEntry[] listEntries = new MultiplexMappingEntry[4]; listEntries[0] = new MultiplexMappingEntry("array-list", ArrayList.class.getName()); listEntries[1] = new MultiplexMappingEntry("linked-list", LinkedList.class.getName()); listEntries[2] = new MultiplexMappingEntry("vector", Vector.class.getName()); listEntries[3] = new MultiplexMappingEntry("stack", Stack.class.getName()); addMultiplexMapping(List.class, "type", listEntries); addManualMapping(LinkedList.class, ListReadHandler.class); addManualMapping(Vector.class, ListReadHandler.class); addManualMapping(ArrayList.class, ListReadHandler.class); addManualMapping(Stack.class, ListReadHandler.class); final MultiplexMappingEntry[] strokeEntries = new MultiplexMappingEntry[1]; strokeEntries[0] = new MultiplexMappingEntry("basic", BasicStroke.class.getName()); addMultiplexMapping(Stroke.class, "type", strokeEntries); addManualMapping(BasicStroke.class, BasicStrokeReadHandler.class); addManualMapping(Font.class, FontReadHandler.class); addManualMapping(Insets.class, InsetsReadHandler.class); addManualMapping(RenderingHints.class, RenderingHintsReadHandler.class); addManualMapping(String.class, StringReadHandler.class); } /** * Returns the object factory. * * @return The object factory. */ public abstract ObjectFactory getFactoryLoader(); /** * Adds a mapping between a class and the handler for the class. * * @param classToRead the class. * @param handler the handler class. */ protected void addManualMapping(final Class classToRead, final Class handler) { if (handler == null) { throw new NullPointerException("handler must not be null."); } if (classToRead == null) { throw new NullPointerException("classToRead must not be null."); } if (!XmlReadHandler.class.isAssignableFrom(handler)) { throw new IllegalArgumentException("The given handler is no XmlReadHandler."); } this.classToHandlerMapping.addManualMapping (new ManualMappingDefinition(classToRead, handler.getName(), null)); } /** * Adds a multiplex mapping. * * @param baseClass the base class. * @param typeAttr the type attribute. * @param mdef the mapping entry. */ protected void addMultiplexMapping(final Class baseClass, final String typeAttr, final MultiplexMappingEntry[] mdef) { this.classToHandlerMapping.addMultiplexMapping( new MultiplexMappingDefinition(baseClass, typeAttr, mdef) ); } /** * Adds an object to the registry. * * @param key the key. * @param value the object. */ public void setHelperObject(final String key, final Object value) { if (value == null) { this.objectRegistry.remove(key); } else { this.objectRegistry.put(key, value); } } /** * Returns an object from the registry. * * @param key the key. * * @return The object. */ public Object getHelperObject(final String key) { return this.objectRegistry.get(key); } /** * Creates a SAX handler for the specified class. * * @param classToRead the class. * @param tagName the tag name. * @param atts the attributes. * * @return a SAX handler. * * @throws XmlReaderException if there is a problem with the reader. */ public XmlReadHandler createHandler(final Class classToRead, final String tagName, final Attributes atts) throws XmlReaderException { final XmlReadHandler retval = findHandlerForClass(classToRead, atts, new ArrayList()); if (retval == null) { throw new NullPointerException("Unable to find handler for class: " + classToRead); } retval.init(this, tagName); return retval; } /** * Finds a handler for the specified class. * * @param classToRead the class to be read. * @param atts the attributes. * @param history the history. * * @return A handler for the specified class. * * @throws XmlReaderException if there is a problem with the reader. */ private XmlReadHandler findHandlerForClass(final Class classToRead, final Attributes atts, final ArrayList history) throws XmlReaderException { final ObjectFactory genericFactory = getFactoryLoader(); if (history.contains(classToRead)) { throw new IllegalStateException("Circular reference detected: " + history); } history.add(classToRead); // check the manual mappings ... ManualMappingDefinition manualDefinition = this.classToHandlerMapping.getManualMappingDefinition(classToRead); if (manualDefinition == null) { manualDefinition = genericFactory.getManualMappingDefinition(classToRead); } if (manualDefinition != null) { // Log.debug ("Locating handler for " + manualDefinition.getBaseClass()); return loadHandlerClass(manualDefinition.getReadHandler()); } // check whether a multiplexer is defined ... // find multiplexer for this class... MultiplexMappingDefinition mplex = getFactoryLoader().getMultiplexDefinition(classToRead); if (mplex == null) { mplex = this.classToHandlerMapping.getMultiplexDefinition(classToRead); } if (mplex != null) { final String attributeValue = atts.getValue(mplex.getAttributeName()); if (attributeValue == null) { throw new XmlReaderException( "Multiplexer type attribute is not defined: " + mplex.getAttributeName() + " for " + classToRead ); } final MultiplexMappingEntry entry = mplex.getEntryForType(attributeValue); if (entry == null) { throw new XmlReaderException( "Invalid type attribute value: " + mplex.getAttributeName() + " = " + attributeValue ); } final Class c = loadClass(entry.getTargetClass()); if (!c.equals(mplex.getBaseClass())) { return findHandlerForClass(c, atts, history); } } // check for generic classes ... // and finally try the generic handler matches ... if (this.classToHandlerMapping.isGenericHandler(classToRead)) { return new GenericReadHandler (this.classToHandlerMapping.getFactoryForClass(classToRead)); } if (getFactoryLoader().isGenericHandler(classToRead)) { return new GenericReadHandler (getFactoryLoader().getFactoryForClass(classToRead)); } return null; } /** * Sets the root SAX handler. * * @param handler the SAX handler. */ protected void setRootHandler(final XmlReadHandler handler) { this.rootHandler = handler; this.rootHandlerInitialized = false; } /** * Returns the root SAX handler. * * @return the root SAX handler. */ protected XmlReadHandler getRootHandler() { return this.rootHandler; } /** * Start a new handler stack and delegate to another handler. * * @param handler the handler. * @param tagName the tag name. * @param attrs the attributes. * * @throws XmlReaderException if there is a problem with the reader. * @throws SAXException if there is a problem with the parser. */ public void recurse(final XmlReadHandler handler, final String tagName, final Attributes attrs) throws XmlReaderException, SAXException { this.outerScopes.push(this.currentHandlers); this.currentHandlers = new Stack(); this.currentHandlers.push(handler); handler.startElement(tagName, attrs); } /** * Delegate to another handler. * * @param handler the new handler. * @param tagName the tag name. * @param attrs the attributes. * * @throws XmlReaderException if there is a problem with the reader. * @throws SAXException if there is a problem with the parser. */ public void delegate(final XmlReadHandler handler, final String tagName, final Attributes attrs) throws XmlReaderException, SAXException { this.currentHandlers.push(handler); handler.init(this, tagName); handler.startElement(tagName, attrs); } /** * Hand control back to the previous handler. * * @param tagName the tagname. * * @throws SAXException if there is a problem with the parser. * @throws XmlReaderException if there is a problem with the reader. */ public void unwind(final String tagName) throws SAXException, XmlReaderException { // remove current handler from stack .. this.currentHandlers.pop(); if (this.currentHandlers.isEmpty() && !this.outerScopes.isEmpty()) { // if empty, but "recurse" had been called, then restore the old handler stack .. // but do not end the recursed element .. this.currentHandlers = (Stack) this.outerScopes.pop(); } else if (!this.currentHandlers.isEmpty()) { // if there are some handlers open, close them too (these handlers must be delegates).. getCurrentHandler().endElement(tagName); } } /** * Returns the current handler. * * @return The current handler. */ protected XmlReadHandler getCurrentHandler() { return (XmlReadHandler) this.currentHandlers.peek(); } /** * Starts processing a document. * * @throws SAXException not in this implementation. */ public void startDocument() throws SAXException { this.outerScopes = new Stack(); this.currentHandlers = new Stack(); this.currentHandlers.push(this.rootHandler); } /** * Starts processing an element. * * @param uri the URI. * @param localName the local name. * @param qName the qName. * @param attributes the attributes. * * @throws SAXException if there is a parsing problem. */ public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { if (this.rootHandlerInitialized == false) { this.rootHandler.init(this, qName); this.rootHandlerInitialized = true; } try { getCurrentHandler().startElement(qName, attributes); } catch (XmlReaderException xre) { throw new ParseException(xre, getLocator()); } } /** * Process character data. * * @param ch the character buffer. * @param start the start index. * @param length the length of the character data. * * @throws SAXException if there is a parsing error. */ public void characters(final char[] ch, final int start, final int length) throws SAXException { try { getCurrentHandler().characters(ch, start, length); } catch (SAXException se) { throw se; } catch (Exception e) { throw new ParseException(e, getLocator()); } } /** * Finish processing an element. * * @param uri the URI. * @param localName the local name. * @param qName the qName. * * @throws SAXException if there is a parsing error. */ public void endElement(final String uri, final String localName, final String qName) throws SAXException { try { getCurrentHandler().endElement(qName); } catch (XmlReaderException xre) { throw new ParseException(xre, getLocator()); } } /** * Loads the given class, and ignores all exceptions which may occur * during the loading. If the class was invalid, null is returned instead. * * @param className the name of the class to be loaded. * @return the class or null. * @throws XmlReaderException if there is a reader error. */ protected XmlReadHandler loadHandlerClass(final String className) throws XmlReaderException { try { final Class c = loadClass(className); return (XmlReadHandler) c.newInstance(); } catch (Exception e) { // ignore buggy classes for now .. throw new XmlReaderException("LoadHanderClass: Unable to instantiate " + className, e); } } /** * Loads the given class, and ignores all exceptions which may occur * during the loading. If the class was invalid, null is returned instead. * * @param className the name of the class to be loaded. * @return the class or null. * @throws XmlReaderException if there is a reader error. */ protected Class loadClass(final String className) throws XmlReaderException { if (className == null) { throw new XmlReaderException("LoadHanderClass: Class name not defined"); } try { final Class c = ObjectUtilities.getClassLoader(getClass()).loadClass(className); return c; } catch (Exception e) { // ignore buggy classes for now .. throw new XmlReaderException("LoadHanderClass: Unable to load " + className, e); } } /** * Returns ???. * * @return ???. * * @throws SAXException ???. */ public Object getResult () throws SAXException { if (this.rootHandler != null) { try { return this.rootHandler.getObject(); } catch (XmlReaderException e) { throw new ElementDefinitionException(e); } } return null; } } jcommon-1.0.16/source/org/jfree/xml/ParseException.java0000644000175000017500000001366311172030703022760 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * ParseException.java * ------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ParseException.java,v 1.4 2005/10/18 13:25:44 mungady Exp $ * * Changes * ------------------------- * 10.06.2003 : Initial version * */ package org.jfree.xml; import java.io.PrintStream; import java.io.PrintWriter; import org.xml.sax.Locator; import org.xml.sax.SAXException; /** * A parse exception. * * @author Thomas Morgner */ public class ParseException extends SAXException { /** The line, where the error occured. */ private int line; /** The column, where the error occured. */ private int column; /** * Creates a new ParseException with the given message. * * @param message the message */ public ParseException(final String message) { super(message); fillLocation(null); } /** * Creates a new ParseException with the given root exception. * * @param e the exception */ public ParseException(final Exception e) { super(e); fillLocation(null); } /** * Creates a new ParseException with the given message and root exception. * * @param s the message * @param e the exception */ public ParseException(final String s, final Exception e) { super(s, e); fillLocation(null); } /** * Creates a new ParseException with the given message and the locator. * * @param message the message * @param locator the locator of the parser */ public ParseException(final String message, final Locator locator) { super(message); fillLocation(locator); } /** * Creates a new ParseException with the given root exception * and the locator. * * @param e the exception * @param locator the locator of the parser */ public ParseException(final Exception e, final Locator locator) { super(e); fillLocation(locator); } /** * Creates a new ParseException with the given message, root exception * and the locator. * * @param s the message * @param e the exception * @param locator the locator of the parser */ public ParseException(final String s, final Exception e, final Locator locator) { super(s, e); fillLocation(locator); } /** * Modifies the message to give more detailed location information. * * @return the modified exception message. */ public String getMessage() { final StringBuffer message = new StringBuffer(String.valueOf(super.getMessage())); message.append(" [Location: Line="); message.append(this.line); message.append(" Column="); message.append(this.column); message.append("] "); return message.toString(); } /** * Fills the location with the given locator. * * @param locator the locator or null. */ protected void fillLocation (final Locator locator) { if (locator == null) { this.line = -1; this.column = -1; } else { this.line = locator.getLineNumber(); this.column = locator.getColumnNumber(); } } /** * Returns the line of the parse position where the error occured. * * @return the line number or -1 if not known. */ public int getLine() { return this.line; } /** * Returns the column of the parse position where the error occured. * * @return the column number or -1 if not known. */ public int getColumn() { return this.column; } /** * Prints the stack trace to the specified stream. * * @param stream the output stream. */ public void printStackTrace(final PrintStream stream) { super.printStackTrace(stream); if (getException() != null) { stream.println("ParentException: "); getException().printStackTrace(stream); } } /** * Override toString to pick up any embedded exception. * * @return A string representation of this exception. */ public String toString() { return getClass().getName() + ": " + getMessage(); } /** * Prints the stack trace to the specified writer. * * @param writer the writer. */ public void printStackTrace(final PrintWriter writer) { super.printStackTrace(writer); if (getException() != null) { writer.println("ParentException: "); getException().printStackTrace(writer); } } } jcommon-1.0.16/source/org/jfree/xml/ParserUtil.java0000644000175000017500000002441311172030703022114 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * ParserUtil.java * --------------- * (C)opyright 2002-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner (taquera@sherito.org); * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ParserUtil.java,v 1.3 2005/10/18 13:25:44 mungady Exp $ * * Changes * ------- * 21-May-2002 : Contains utility functions to make parsing easier. * 10-Dec-2002 : Fixed issues reported by Checkstyle (DG); * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon; * 23-Sep-2003 : Minor Javadoc updates (DG); * */ package org.jfree.xml; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Stroke; import java.awt.geom.Rectangle2D; import java.lang.reflect.Field; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * Basic helper functions to ease up the process of parsing. * * @author Thomas Morgner */ public class ParserUtil { /** * Parses the string text into an int. If text is null or does not * contain a parsable value, the message given in message is used to * throw a SAXException. * * @param text the text to parse. * @param message the error message if parsing fails. * * @return the int value. * * @throws SAXException if there is a problem with the parsing. */ public static int parseInt(final String text, final String message) throws SAXException { if (text == null) { throw new SAXException(message); } try { return Integer.parseInt(text); } catch (NumberFormatException nfe) { throw new SAXException("NumberFormatError: " + message); } } /** * Parses an integer. * * @param text the text to parse. * @param defaultVal the default value. * * @return the integer. */ public static int parseInt(final String text, final int defaultVal) { if (text == null) { return defaultVal; } try { return Integer.parseInt(text); } catch (NumberFormatException nfe) { return defaultVal; } } /** * Parses the string text into an float. If text is null or does not * contain a parsable value, the message given in message is used to * throw a SAXException. * * @param text the text to parse. * @param message the error message if parsing fails. * * @return the float value. * * @throws SAXException if there is a problem with the parsing. */ public static float parseFloat(final String text, final String message) throws SAXException { if (text == null) { throw new SAXException(message); } try { return Float.parseFloat(text); } catch (NumberFormatException nfe) { throw new SAXException("NumberFormatError: " + message); } } /** * Parses the string text into an float. If text is null or does not * contain a parsable value, the message given in message is used to * throw a SAXException. * * @param text the text to parse. * @param defaultVal the defaultValue returned if parsing fails. * * @return the float value. */ public static float parseFloat(final String text, final float defaultVal) { if (text == null) { return defaultVal; } try { return Float.parseFloat(text); } catch (NumberFormatException nfe) { return defaultVal; } } /** * Parses a boolean. If the string text contains the value of "true", the * true value is returned, else false is returned. * * @param text the text to parse. * @param defaultVal the default value. * * @return a boolean. */ public static boolean parseBoolean(final String text, final boolean defaultVal) { if (text == null) { return defaultVal; } return text.equalsIgnoreCase("true"); } /** * Parses a string. If the text is null, defaultval is returned. * * @param text the text to parse. * @param defaultVal the default value. * * @return a string. */ public static String parseString(final String text, final String defaultVal) { if (text == null) { return defaultVal; } return text; } /** * Creates a basic stroke given the width contained as float in the given string. * If the string could not be parsed into a float, a basic stroke with the width of * 1 is returned. * * @param weight a string containing a number (the stroke weight). * * @return the stroke. */ public static Stroke parseStroke(final String weight) { try { if (weight != null) { final Float w = new Float(weight); return new BasicStroke(w.floatValue()); } } catch (NumberFormatException nfe) { //Log.warn("Invalid weight for stroke", nfe); } return new BasicStroke(1); } /** * Parses a color entry. If the entry is in hexadecimal or ocal notation, the color is * created using Color.decode(). If the string denotes a constant name of on of the color * constants defined in java.awt.Color, this constant is used. *

* As fallback the color black is returned if no color can be parsed. * * @param color the color (as a string). * * @return the paint. */ public static Color parseColor(final String color) { return parseColor(color, Color.black); } /** * Parses a color entry. If the entry is in hexadecimal or octal notation, the color is * created using Color.decode(). If the string denotes a constant name of one of the color * constants defined in java.awt.Color, this constant is used. *

* As fallback the supplied default value is returned if no color can be parsed. * * @param color the color (as a string). * @param defaultValue the default value (returned if no color can be parsed). * * @return the paint. */ public static Color parseColor(final String color, final Color defaultValue) { if (color == null) { return defaultValue; } try { // get color by hex or octal value return Color.decode(color); } catch (NumberFormatException nfe) { // if we can't decode lets try to get it by name try { // try to get a color by name using reflection // black is used for an instance and not for the color itselfs final Field f = Color.class.getField(color); return (Color) f.get(null); } catch (Exception ce) { //Log.warn("No such Color : " + color); // if we can't get any color return black return defaultValue; } } } /** * Parses a position of an element. If a relative postion is given, the returnvalue * is a negative number between 0 and -100. * * @param value the value. * @param exceptionMessage the exception message. * * @return the float value. * * @throws SAXException if there is a problem parsing the string. */ public static float parseRelativeFloat(final String value, final String exceptionMessage) throws SAXException { if (value == null) { throw new SAXException(exceptionMessage); } final String tvalue = value.trim(); if (tvalue.endsWith("%")) { final String number = tvalue.substring(0, tvalue.indexOf("%")); final float f = parseFloat(number, exceptionMessage) * -1.0f; return f; } else { return parseFloat(tvalue, exceptionMessage); } } /** * Parses an element position. The position is stored in the attributes "x", "y", "width" and * "height". The attributes are allowed to have relative notion. * * @param atts the attributes. * * @return the element position. * * @throws SAXException if there is a problem getting the element position. */ public static Rectangle2D getElementPosition(final Attributes atts) throws SAXException { final float x = ParserUtil.parseRelativeFloat(atts.getValue("x"), "Element x not specified"); final float y = ParserUtil.parseRelativeFloat(atts.getValue("y"), "Element y not specified"); final float w = ParserUtil.parseRelativeFloat(atts.getValue("width"), "Element width not specified"); final float h = ParserUtil.parseRelativeFloat(atts.getValue("height"), "Element height not specified"); final Rectangle2D.Float retval = new Rectangle2D.Float(x, y, w, h); return retval; } } jcommon-1.0.16/source/org/jfree/xml/CommentHandler.java0000644000175000017500000001416511172030703022725 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * CommentHandler.java * ------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: CommentHandler.java,v 1.3 2005/10/18 13:25:44 mungady Exp $ * * Changes * ------------------------- * 20-Jul-2003 : Initial version * */ package org.jfree.xml; import java.util.ArrayList; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; /** * The comment handler is used to collect all XML comments from the * SAX parser. The parser implementation must support comments to make * this feature work. * * @author Thomas Morgner */ public class CommentHandler implements LexicalHandler { /** A constant marking a comment on the opening tag. */ public static final String OPEN_TAG_COMMENT = "parser.comment.open"; /** A constant marking a comment on the closing tag. */ public static final String CLOSE_TAG_COMMENT = "parser.comment.close"; /** A list containing all collected comments. */ private final ArrayList comment; /** a flag marking whether the SAX parser is currently working in the DTD. */ private boolean inDTD; /** * DefaultConstructor. */ public CommentHandler() { this.comment = new ArrayList(); } /** * Report the start of DTD declarations, if any. * *

This method is empty.

* * @param name The document type name. * @param publicId The declared public identifier for the * external DTD subset, or null if none was declared. * @param systemId The declared system identifier for the * external DTD subset, or null if none was declared. * @exception org.xml.sax.SAXException The application may raise an * exception. * @see #endDTD() * @see #startEntity(String) */ public void startDTD(final String name, final String publicId, final String systemId) throws SAXException { this.inDTD = true; } /** * Report the end of DTD declarations. * *

This method is empty.

* * @exception org.xml.sax.SAXException The application may raise an exception. */ public void endDTD() throws SAXException { this.inDTD = false; } /** * Report the beginning of some internal and external XML entities. * *

This method is empty.

* * @param name The name of the entity. If it is a parameter * entity, the name will begin with '%', and if it is the * external DTD subset, it will be "[dtd]". * @exception org.xml.sax.SAXException The application may raise an exception. * @see #endEntity(String) * @see org.xml.sax.ext.DeclHandler#internalEntityDecl * @see org.xml.sax.ext.DeclHandler#externalEntityDecl */ public void startEntity(final String name) throws SAXException { // do nothing } /** * Report the end of an entity. * *

This method is empty.

* * @param name The name of the entity that is ending. * @exception org.xml.sax.SAXException The application may raise an exception. * @see #startEntity(String) */ public void endEntity(final String name) throws SAXException { // do nothing } /** * Report the start of a CDATA section. * *

This method is empty.

* * @exception org.xml.sax.SAXException The application may raise an exception. * @see #endCDATA() */ public void startCDATA() throws SAXException { // do nothing } /** * Report the end of a CDATA section. * *

This method is empty.

* * @exception org.xml.sax.SAXException The application may raise an exception. * @see #startCDATA() */ public void endCDATA() throws SAXException { // do nothing } /** * Report an XML comment anywhere in the document. * *

This callback will be used for comments inside or outside the * document element, including comments in the external DTD * subset (if read). Comments in the DTD must be properly * nested inside start/endDTD and start/endEntity events (if * used).

* * @param ch An array holding the characters in the comment. * @param start The starting position in the array. * @param length The number of characters to use from the array. * @exception org.xml.sax.SAXException The application may raise an exception. */ public void comment(final char[] ch, final int start, final int length) throws SAXException { if (!this.inDTD) { this.comment.add(new String(ch, start, length)); } } /** * Returns all collected comments as string array. * @return the array containing all comments. */ public String[] getComments() { if (this.comment.isEmpty()) { return null; } return (String[]) this.comment.toArray(new String[this.comment.size()]); } /** * Clears all comments. */ public void clearComments() { this.comment.clear(); } } jcommon-1.0.16/source/org/jfree/xml/JCommonXMLInfo.java0000644000175000017500000000576711172030703022574 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------ * JCommonXMLInfo.java * ------------ * (C) Copyright 2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: JCommonXMLInfo.java,v 1.5 2006/03/23 19:47:05 taqua Exp $ * * Changes * ------- * 22-Feb-2005 : Initial version. * 03-Mar-2005 : Updated copyright. * */ package org.jfree.xml; import java.util.Arrays; import org.jfree.JCommonInfo; import org.jfree.ui.about.Contributor; import org.jfree.ui.about.ProjectInfo; /** * The info implementation for the XML classes of JCommon. * * @author Thomas Morgner */ public class JCommonXMLInfo extends ProjectInfo { /** * The info singleton. */ private static JCommonXMLInfo singleton; /** * Returns the single instance of this class. * * @return The single instance of information about the JCommon library. */ public static synchronized JCommonXMLInfo getInstance() { if (singleton == null) { singleton = new JCommonXMLInfo(); } return singleton; } /** * Constructs an empty project info object. */ private JCommonXMLInfo() { final JCommonInfo info = JCommonInfo.getInstance(); setName("JCommon-XML"); setVersion(info.getVersion()); setInfo(info.getInfo()); setCopyright(info.getCopyright()); setLicenceName(info.getLicenceName()); setLicenceText(info.getLicenceText()); setContributors(Arrays.asList(new Contributor[]{ new Contributor("David Gilbert", "david.gilbert@object-refinery.com"), new Contributor("Thomas Morgner", "taqua@users.sourceforge.net"), new Contributor("Peter Becker", "-"), })); addLibrary(info); } } jcommon-1.0.16/source/org/jfree/xml/FrontendDefaultHandler.java0000644000175000017500000001607111172030703024405 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------ * FrontendDefaultHandler.java * ------------ * (C) Copyright 2002-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: FrontendDefaultHandler.java,v 1.9 2008/09/10 09:20:49 mungady Exp $ * * Changes * ------- * 02-Feb-2005 : Initial version. * */ package org.jfree.xml; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.Enumeration; import org.jfree.util.Configuration; import org.jfree.util.DefaultConfiguration; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * The frontenddefault handler connects the SAX-backend with the handler implementations. * It must be the base class for all parser implementations used by the ParserFrontEnd. * * @author Thomas Morgner */ public abstract class FrontendDefaultHandler extends DefaultHandler implements Configuration { /** * A key for the content base. */ public static final String CONTENTBASE_KEY = "content-base"; /** * Storage for the parser configuration. */ private DefaultConfiguration parserConfiguration; /** * The DocumentLocator can be used to resolve the current parse position. */ private Locator locator; /** * The current comment handler used to receive xml comments. */ private final CommentHandler commentHandler; /** * Default constructor. */ protected FrontendDefaultHandler() { this.parserConfiguration = new DefaultConfiguration(); this.commentHandler = new CommentHandler(); } /** * Returns the comment handler that is used to collect comments. * * @return the comment handler. */ public CommentHandler getCommentHandler() { return this.commentHandler; } /** * Receive an object for locating the origin of SAX document events. *

* The locator allows the application to determine the end position of * any document-related event, even if the parser is not reporting an * error. Typically, the application will use this information for * reporting its own errors (such as character content that does not * match an application's business rules). The information returned by * the locator is probably not sufficient for use with a search engine. * * @param locator the locator. */ public void setDocumentLocator(final Locator locator) { this.locator = locator; } /** * Returns the current locator. * * @return the locator. */ public Locator getLocator() { return this.locator; } /** * Returns the configuration property with the specified key. * * @param key the property key. * @return the property value. */ public String getConfigProperty(final String key) { return getConfigProperty(key, null); } /** * Returns the configuration property with the specified key (or the specified default value * if there is no such property). *

* If the property is not defined in this configuration, the code will lookup the property in * the parent configuration. * * @param key the property key. * @param defaultValue the default value. * @return the property value. */ public String getConfigProperty(final String key, final String defaultValue) { return this.parserConfiguration.getConfigProperty(key, defaultValue); } /** * Sets a parser configuration value. * * @param key the key. * @param value the value. */ public void setConfigProperty(final String key, final String value) { if (value == null) { this.parserConfiguration.remove(key); } else { this.parserConfiguration.setProperty(key, value); } } /** * Returns the configuration properties. * * @return An enumeration of the configuration properties. */ public Enumeration getConfigProperties() { return this.parserConfiguration.getConfigProperties(); } /** * Returns a new instance of the parser. * * @return a new instance of the parser. */ public abstract FrontendDefaultHandler newInstance(); /** * Returns all keys with the given prefix. * * @param prefix the prefix * @return the iterator containing all keys with that prefix */ public Iterator findPropertyKeys(final String prefix) { return this.parserConfiguration.findPropertyKeys(prefix); } /** * Returns the parse result. This method is called at the end of the * parsing process and expects the generated object. * * @return the object. * @throws SAXException if something went wrong. */ public abstract Object getResult() throws SAXException; /** * Gets the ContentBase used to resolve relative URLs. * * @return the current contentbase, or null if no contentBase is set. */ public URL getContentBase() { final String contentBase = getConfigProperty(Parser.CONTENTBASE_KEY); if (contentBase == null) { return null; } try { return new URL(contentBase); } catch (MalformedURLException mfe) { throw new IllegalStateException("Content Base is illegal." + contentBase); } } /** * Returns a clone of this instance. * * @return A clone. * * @throws CloneNotSupportedException if there is a problem cloning. */ public Object clone () throws CloneNotSupportedException { final FrontendDefaultHandler o = (FrontendDefaultHandler) super.clone(); o.parserConfiguration = (DefaultConfiguration) this.parserConfiguration.clone(); return o; } } jcommon-1.0.16/source/org/jfree/xml/attributehandlers/0000755000175000017500000000000011351753320022705 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/xml/attributehandlers/package.html0000644000175000017500000000023511172030703025160 0ustar twernertwerner Provides attribute handlers for standard object types. jcommon-1.0.16/source/org/jfree/xml/attributehandlers/IntegerAttributeHandler.java0000644000175000017500000000543411172030703030327 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------- * IntegerAttributeHandler.java * ---------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: IntegerAttributeHandler.java,v 1.2 2005/10/18 13:30:16 mungady Exp $ * * Changes * ------- * 24.09.2003 : Initial version * */ package org.jfree.xml.attributehandlers; import org.jfree.util.Log; /** * A class that handles the conversion of {@link Integer} attributes to and from an appropriate * {@link String} representation. */ public class IntegerAttributeHandler implements AttributeHandler { /** * Creates a new attribute handler. */ public IntegerAttributeHandler() { super(); } /** * Converts the attribute to a string. * * @param o the attribute ({@link Integer} expected). * * @return A string representing the integer value. */ public String toAttributeValue(final Object o) { try { final Integer in = (Integer) o; return in.toString(); } catch (ClassCastException cce) { if (o != null) { Log.debug("ClassCastException: Expected Integer, found " + o.getClass()); } throw cce; } } /** * Converts a string to a {@link Integer}. * * @param s the string. * * @return a {@link Integer}. */ public Object toPropertyValue(final String s) { return new Integer(s); } } jcommon-1.0.16/source/org/jfree/xml/attributehandlers/AttributeHandler.java0000644000175000017500000000424711172030703027012 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * AttributeHandler.java * --------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AttributeHandler.java,v 1.2 2005/10/18 13:30:16 mungady Exp $ * * Changes * ------- * 23.09.2003 : Initial version * */ package org.jfree.xml.attributehandlers; /** * An attribute handler is an object that can transform an object into a string or vice * versa. */ public interface AttributeHandler { /** * Converts an object to an attribute value. * * @param o the object. * * @return the attribute value. */ public String toAttributeValue (Object o); /** * Converts a string to a property value. * * @param s the string. * * @return a property value. */ public Object toPropertyValue (String s); } jcommon-1.0.16/source/org/jfree/xml/attributehandlers/FloatAttributeHandler.java0000644000175000017500000000501111172030703027766 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * FloatAttributeHandler.java * -------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: FloatAttributeHandler.java,v 1.2 2005/10/18 13:30:16 mungady Exp $ * * Changes * ------- * 24.09.2003 : Initial version * */ package org.jfree.xml.attributehandlers; /** * A class that handles the conversion of {@link Float} attributes to and from an appropriate * {@link String} representation. */ public class FloatAttributeHandler implements AttributeHandler { /** * Creates a new attribute handler. */ public FloatAttributeHandler() { super(); } /** * Converts the attribute to a string. * * @param o the attribute ({@link Float} expected). * * @return A string representing the {@link Float} value. */ public String toAttributeValue(final Object o) { final Float in = (Float) o; return in.toString(); } /** * Converts a string to a {@link Float}. * * @param s the string. * * @return a {@link Float}. */ public Object toPropertyValue(final String s) { return new Float(s); } } jcommon-1.0.16/source/org/jfree/xml/attributehandlers/CharacterAttributeHandler.java0000644000175000017500000000525411172030703030626 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------ * CharacterAttributeHandler.java * ------------------------------ * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: CharacterAttributeHandler.java,v 1.2 2005/10/18 13:30:16 mungady Exp $ * * Changes * ------- * 24.09.2003 : Initial version * */ package org.jfree.xml.attributehandlers; /** * A class that handles the conversion of {@link Character} attributes to and from an appropriate * {@link String} representation. */ public class CharacterAttributeHandler implements AttributeHandler { /** * Creates a new attribute handler. */ public CharacterAttributeHandler() { super(); } /** * Converts the attribute to a string. * * @param o the attribute ({@link Character} expected). * * @return A string representing the {@link Character} value. */ public String toAttributeValue(final Object o) { final Character in = (Character) o; return in.toString(); } /** * Converts a string to a {@link Character}. * * @param s the string. * * @return a {@link Character}. */ public Object toPropertyValue(final String s) { if (s.length() == 0) { throw new RuntimeException("Ugly, no char set!"); } return new Character(s.charAt(0)); } } jcommon-1.0.16/source/org/jfree/xml/attributehandlers/LongAttributeHandler.java0000644000175000017500000000477211172030703027635 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * LongAttributeHandler.java * ------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: LongAttributeHandler.java,v 1.2 2005/10/18 13:30:16 mungady Exp $ * * Changes * ------- * 24.09.2003 : Initial version * */ package org.jfree.xml.attributehandlers; /** * A class that handles the conversion of {@link Long} attributes to and from an appropriate * {@link String} representation. */ public class LongAttributeHandler implements AttributeHandler { /** * Creates a new attribute handler. */ public LongAttributeHandler() { super(); } /** * Converts the attribute to a string. * * @param o the attribute ({@link Long} expected). * * @return A string representing the {@link Long} value. */ public String toAttributeValue(final Object o) { final Long in = (Long) o; return in.toString(); } /** * Converts a string to a {@link Long}. * * @param s the string. * * @return a {@link Long}. */ public Object toPropertyValue(final String s) { return new Long(s); } } jcommon-1.0.16/source/org/jfree/xml/attributehandlers/StringAttributeHandler.java0000644000175000017500000000466511172030703030205 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------- * StringAttributeHandler.java * --------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: StringAttributeHandler.java,v 1.3 2005/11/03 09:30:38 mungady Exp $ * * Changes * ------- * 24.09.2003 : Initial version * */ package org.jfree.xml.attributehandlers; /** * A {@link String} attribute handler. */ public class StringAttributeHandler implements AttributeHandler { /** * Creates a new attribute handler. */ public StringAttributeHandler() { super(); } /** * Converts the attribute to a string. * * @param o the attribute ({@link String} expected). * * @return A string. */ public String toAttributeValue(final Object o) { final String in = (String) o; if (in != null) { return in; } return null; } /** * Converts a copy of the string. * * @param s the string. * * @return a {@link Short}. */ public Object toPropertyValue(final String s) { return s; } } jcommon-1.0.16/source/org/jfree/xml/attributehandlers/ShortAttributeHandler.java0000644000175000017500000000501011172030703030017 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------- * ShortAttributeHandler.java * -------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ShortAttributeHandler.java,v 1.2 2005/10/18 13:30:16 mungady Exp $ * * Changes * ------- * 24.09.2003 : Initial version * */ package org.jfree.xml.attributehandlers; /** * A class that handles the conversion of {@link Short} attributes to and from an appropriate * {@link String} representation. */ public class ShortAttributeHandler implements AttributeHandler { /** * Creates a new attribute handler. */ public ShortAttributeHandler() { super(); } /** * Converts the attribute to a string. * * @param o the attribute ({@link Short} expected). * * @return A string representing the {@link Short} value. */ public String toAttributeValue(final Object o) { final Short in = (Short) o; return in.toString(); } /** * Converts a string to a {@link Short}. * * @param s the string. * * @return a {@link Short}. */ public Object toPropertyValue(final String s) { return new Short(s); } } jcommon-1.0.16/source/org/jfree/xml/attributehandlers/DoubleAttributeHandler.java0000644000175000017500000000502611172030703030141 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------- * DoubleAttributeHandler.java * --------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DoubleAttributeHandler.java,v 1.2 2005/10/18 13:30:16 mungady Exp $ * * Changes * ------- * 24.09.2003 : Initial version * */ package org.jfree.xml.attributehandlers; /** * A class that handles the conversion of {@link Double} attributes to and from an appropriate * {@link String} representation. */ public class DoubleAttributeHandler implements AttributeHandler { /** * Creates a new attribute handler. */ public DoubleAttributeHandler() { super(); } /** * Converts the attribute to a string. * * @param o the attribute ({@link Double} expected). * * @return A string representing the {@link Double} value. */ public String toAttributeValue(final Object o) { final Double in = (Double) o; return in.toString(); } /** * Converts a string to a {@link Double}. * * @param s the string. * * @return a {@link Double}. */ public Object toPropertyValue(final String s) { return new Double(s); } } jcommon-1.0.16/source/org/jfree/xml/attributehandlers/ByteAttributeHandler.java0000644000175000017500000000477211172030703027641 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * ByteAttributeHandler.java * ------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ByteAttributeHandler.java,v 1.2 2005/10/18 13:30:16 mungady Exp $ * * Changes * ------- * 24.09.2003 : Initial version * */ package org.jfree.xml.attributehandlers; /** * A class that handles the conversion of {@link Byte} attributes to and from an appropriate * {@link String} representation. */ public class ByteAttributeHandler implements AttributeHandler { /** * Creates a new attribute handler. */ public ByteAttributeHandler() { super(); } /** * Converts the attribute to a string. * * @param o the attribute ({@link Byte} expected). * * @return A string representing the {@link Byte} value. */ public String toAttributeValue(final Object o) { final Byte in = (Byte) o; return in.toString(); } /** * Converts a string to a {@link Byte}. * * @param s the string. * * @return a {@link Byte}. */ public Object toPropertyValue(final String s) { return new Byte(s); } } jcommon-1.0.16/source/org/jfree/xml/attributehandlers/BooleanAttributeHandler.java0000644000175000017500000000513311172030703030305 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------------- * BooleanAttrbuteHandler.java * --------------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: BooleanAttributeHandler.java,v 1.2 2005/10/18 13:30:16 mungady Exp $ * * Changes * ------- * 23.09.2003 : Initial version * */ package org.jfree.xml.attributehandlers; /** * A class that handles the conversion of {@link Boolean} attributes to and from their * {@link String} representation. */ public class BooleanAttributeHandler implements AttributeHandler { /** * Creates a new attribute handler. */ public BooleanAttributeHandler() { super(); } /** * Converts the attribute to a string. * * @param o the attribute ({@link Boolean} expected). * * @return A string representing the {@link Boolean} value. */ public String toAttributeValue(final Object o) { if (o instanceof Boolean) { return o.toString(); } throw new ClassCastException("Give me a real type."); } /** * Converts a string to a {@link Boolean}. * * @param s the string. * * @return a {@link Boolean}. */ public Object toPropertyValue(final String s) { return new Boolean (s); } } jcommon-1.0.16/source/org/jfree/xml/Parser.java0000644000175000017500000002277211172030703021264 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------- * Parser.java * ----------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner (taquera@sherito.org); * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Parser.java,v 1.9 2008/09/10 09:20:49 mungady Exp $ * * Changes * ------- * 09-Jan-2003 : Initial version. * 29-Apr-2003 : Distilled from the JFreeReport project and moved into JCommon * 14-Jul-2003 : More help with the error location given by catching all exceptions. * */ package org.jfree.xml; import java.util.HashMap; import java.util.Stack; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * The Parser handles the SAXEvents and forwards the event call to the currently * active ElementDefinitionHandler. Contains methods to manage and * configure the parsing process. *

* An initial report definition handler must be set before the parser can be used. * * @author Thomas Morgner */ public abstract class Parser extends FrontendDefaultHandler { /** A key for the content base. */ public static final String CONTENTBASE_KEY = "content-base"; /** A stack for the active factories. */ private Stack activeFactories; /** The initial factory. */ private ElementDefinitionHandler initialFactory; /** Storage for temporary objects and factories used during the parsing process. */ private HashMap parserHelperObjects; /** * Creates a new parser. */ public Parser() { this.activeFactories = new Stack(); this.parserHelperObjects = new HashMap(); } /** * Returns the currently collected comments. * @return the comments. */ public String[] getComments() { return getCommentHandler().getComments(); } /** * Pushes a handler onto the stack. * * @param factory the handler. */ public void pushFactory(final ElementDefinitionHandler factory) { this.activeFactories.push(factory); } /** * Reads a handler off the stack without removing it. * * @return The handler. */ public ElementDefinitionHandler peekFactory() { return (ElementDefinitionHandler) this.activeFactories.peek(); } /** * Pops a handler from the stack. * * @return The handler. */ public ElementDefinitionHandler popFactory() { this.activeFactories.pop(); return peekFactory(); } /** * Receive notification of the end of the document. * *

By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the end * of a document (such as finalising a tree or closing an output * file).

* * @exception SAXException Any SAX exception, possibly wrapping another exception. * * @see org.xml.sax.ContentHandler#endDocument */ public void endDocument() throws SAXException { // ignored } /** * Receive notification of the beginning of the document. * *

By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the beginning * of a document (such as allocating the root node of a tree or * creating an output file).

* * @exception SAXException Any SAX exception, possibly wrapping another exception. * @see org.xml.sax.ContentHandler#startDocument */ public void startDocument() throws SAXException { this.activeFactories.clear(); pushFactory(getInitialFactory()); } /** * Receive notification of character data inside an element. * *

By default, do nothing. Application writers may override this * method to take specific actions for each chunk of character data * (such as adding the data to a node or buffer, or printing it to * a file).

* * @param ch the characters. * @param start the start position in the character array. * @param length the number of characters to use from the character array. * * @exception SAXException Any SAX exception, possibly wrapping another exception. * @see org.xml.sax.ContentHandler#characters */ public void characters(final char[] ch, final int start, final int length) throws SAXException { try { peekFactory().characters(ch, start, length); } catch (ParseException pe) { throw pe; } catch (Exception e) { throw new ParseException(e, getLocator()); } } /** * Receive notification of the end of an element. * *

By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the end of * each element (such as finalising a tree node or writing * output to a file).

* * @param uri the URI. * @param localName the element type name. * @param qName the name. * * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#endElement */ public void endElement(final String uri, final String localName, final String qName) throws SAXException { try { peekFactory().endElement(qName); } catch (ParseException pe) { throw pe; } catch (Exception e) { throw new ParseException(e, getLocator()); } finally { getCommentHandler().clearComments(); } } /** * Receive notification of the start of an element. * *

By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the start of * each element (such as allocating a new tree node or writing * output to a file).

* * @param uri the URI. * @param localName the element type name. * @param qName the name. * @param attributes the specified or defaulted attributes. * * @exception SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#startElement */ public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { try { peekFactory().startElement(qName, attributes); } catch (ParseException pe) { throw pe; } catch (Exception e) { throw new ParseException(e, getLocator()); } finally { getCommentHandler().clearComments(); } } /** * Sets the initial handler. * * @param factory the initial handler. */ public void setInitialFactory(final ElementDefinitionHandler factory) { this.initialFactory = factory; } /** * Returns the initial handler. * * @return The initial handler. */ public ElementDefinitionHandler getInitialFactory() { return this.initialFactory; } /** * Sets a helper object. * * @param key the key. * @param value the value. */ public void setHelperObject(final String key, final Object value) { if (value == null) { this.parserHelperObjects.remove(key); } else { this.parserHelperObjects.put(key, value); } } /** * Returns a helper object. * * @param key the key. * * @return The object. */ public Object getHelperObject(final String key) { return this.parserHelperObjects.get(key); } /** * Returns a new instance of the parser. * * @return a new instance of the parser. */ public abstract Parser getInstance(); /** * Returns a new instance of {@link FrontendDefaultHandler}. * * @return A new instance. */ public final FrontendDefaultHandler newInstance() { return getInstance(); } /** * Returns the parsed result object after the parsing is complete. Calling * this function during the parsing is undefined and may result in an * IllegalStateException. * * @return the parsed result. */ public abstract Object getResult(); } jcommon-1.0.16/source/org/jfree/base/0000755000175000017500000000000011351753320017273 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/base/ClassPathDebugger.java0000644000175000017500000000600111172030703023454 0ustar twernertwerner/** * ======================================== * JCommon : a free Java report library * ======================================== * * Project Info: http://www.jfree.org/jcommon/ * * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------ * $Id: ClassPathDebugger.java,v 1.2 2008/09/10 09:23:34 mungady Exp $ * ------------ * (C) Copyright 2002-2006, by Object Refinery Limited. */ package org.jfree.base; import java.util.Enumeration; import org.jfree.util.ObjectUtilities; /** * Creation-Date: 02.11.2007, 18:42:27 * * @author Thomas Morgner */ public class ClassPathDebugger { /** * Entry point. * * @param args command line arguments. */ public static void main(String[] args) { System.out.println ("Listing the various classloaders:"); System.out.println ("Defined classloader source: " + ObjectUtilities.getClassLoaderSource()); System.out.println ("User classloader: " + ObjectUtilities.getClassLoader()); System.out.println ("Classloader for ObjectUtilities.class: " + ObjectUtilities.getClassLoader(ObjectUtilities.class)); System.out.println ("Classloader for String.class: " + ObjectUtilities.getClassLoader(String.class)); System.out.println ("Thread-Context Classloader: " + Thread.currentThread().getContextClassLoader()); System.out.println ("Defined System classloader: " + ClassLoader.getSystemClassLoader()); System.out.println(); try { System.out.println ("Listing sources for '/jcommon.properties':"); Enumeration resources = ObjectUtilities.getClassLoader (ObjectUtilities.class).getResources("jcommon.properties"); while (resources.hasMoreElements()) { System.out.println (" " + resources.nextElement()); } System.out.println(); System.out.println ("Listing sources for 'org/jfree/JCommonInfo.class':"); resources = ObjectUtilities.getClassLoader (ObjectUtilities.class).getResources("org/jfree/JCommonInfo.class"); while (resources.hasMoreElements()) { System.out.println (" " + resources.nextElement()); } } catch (Exception e) { e.printStackTrace(); } } } jcommon-1.0.16/source/org/jfree/base/AbstractBoot.java0000644000175000017500000002702411172030703022524 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * AbstractBoot.java * ----------------- * (C)opyright 2004, 2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AbstractBoot.java,v 1.21 2008/09/10 09:22:57 mungady Exp $ * * Changes * ------- * 07-Jun-2004 : Added source headers (DG); * 18-Aug-2005 : Added casts to suppress compiler warnings, as suggested in * patch 1260622 (DG); * */ package org.jfree.base; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import org.jfree.base.config.HierarchicalConfiguration; import org.jfree.base.config.PropertyFileConfiguration; import org.jfree.base.config.SystemPropertyConfiguration; import org.jfree.base.modules.PackageManager; import org.jfree.base.modules.SubSystem; import org.jfree.util.Configuration; import org.jfree.util.ExtendedConfiguration; import org.jfree.util.ExtendedConfigurationWrapper; import org.jfree.util.Log; import org.jfree.util.ObjectUtilities; /** * The common base for all Boot classes. *

* This initializes the subsystem and all dependent subsystems. * Implementors of this class have to provide a public static * getInstance() method which returns a singleton instance of the * booter implementation. *

* Further creation of Boot object should be prevented using * protected or private constructors in that class, or proper * initialzation cannot be guaranteed. * * @author Thomas Morgner */ public abstract class AbstractBoot implements SubSystem { /** The configuration wrapper around the plain configuration. */ private ExtendedConfigurationWrapper extWrapper; /** A packageManager instance of the package manager. */ private PackageManager packageManager; /** Global configuration. */ private Configuration globalConfig; /** A flag indicating whether the booting is currenly in progress. */ private boolean bootInProgress; /** A flag indicating whether the booting is complete. */ private boolean bootDone; /** * Default constructor. */ protected AbstractBoot() { } /** * Returns the packageManager instance of the package manager. * * @return The package manager. */ public synchronized PackageManager getPackageManager() { if (this.packageManager == null) { this.packageManager = PackageManager.createInstance(this); } return this.packageManager; } /** * Returns the global configuration. * * @return The global configuration. */ public synchronized Configuration getGlobalConfig() { if (this.globalConfig == null) { this.globalConfig = loadConfiguration(); } return this.globalConfig; } /** * Checks, whether the booting is in progress. * * @return true, if the booting is in progress, false otherwise. */ public final synchronized boolean isBootInProgress() { return this.bootInProgress; } /** * Checks, whether the booting is complete. * * @return true, if the booting is complete, false otherwise. */ public final synchronized boolean isBootDone() { return this.bootDone; } /** * Loads the configuration. This will be called exactly once. * * @return The configuration. */ protected abstract Configuration loadConfiguration(); /** * Starts the boot process. */ public final void start() { synchronized (this) { if (isBootDone()) { return; } while (isBootInProgress()) { try { wait(); } catch (InterruptedException e) { // ignore .. } } if (isBootDone()) { return; } this.bootInProgress = true; } // boot dependent libraries ... final BootableProjectInfo info = getProjectInfo(); if (info != null) { final BootableProjectInfo[] childs = info.getDependencies(); for (int i = 0; i < childs.length; i++) { final AbstractBoot boot = loadBooter(childs[i].getBootClass()); if (boot != null) { // but we're waiting until the booting is complete ... synchronized(boot) { boot.start(); while (boot.isBootDone() == false) { try { boot.wait(); } catch (InterruptedException e) { // ignore it .. } } } } } } performBoot(); if (info != null) { Log.info (info.getName() + " " + info.getVersion() + " started."); } else { Log.info (getClass() + " started."); } synchronized (this) { this.bootInProgress = false; this.bootDone = true; notifyAll(); } } /** * Performs the boot. */ protected abstract void performBoot(); /** * Returns the project info. * * @return The project info. */ protected abstract BootableProjectInfo getProjectInfo(); /** * Loads the specified booter implementation. * * @param classname the class name. * * @return The boot class. */ protected AbstractBoot loadBooter(final String classname) { if (classname == null) { return null; } try { final Class c = ObjectUtilities.getClassLoader( getClass()).loadClass(classname); final Method m = c.getMethod("getInstance", (Class[]) null); return (AbstractBoot) m.invoke(null, (Object[]) null); } catch (Exception e) { Log.info ("Unable to boot dependent class: " + classname); return null; } } /** * Creates a default configuration setup, which loads its settings from * the static configuration (defaults provided by the developers of the * library) and the user configuration (settings provided by the deployer). * The deployer's settings override the developer's settings. * * If the parameter addSysProps is set to true, the system * properties will be added as third configuration layer. The system * properties configuration allows to override all other settings. * * @param staticConfig the resource name of the developers configuration * @param userConfig the resource name of the deployers configuration * @param addSysProps a flag defining whether to include the system * properties into the configuration. * @return the configured Configuration instance. */ protected Configuration createDefaultHierarchicalConfiguration (final String staticConfig, final String userConfig, final boolean addSysProps) { return createDefaultHierarchicalConfiguration (staticConfig, userConfig, addSysProps, PropertyFileConfiguration.class); } /** * Creates a default hierarchical configuration. * * @param staticConfig the static configuration. * @param userConfig the user configuration. * @param addSysProps additional system properties. * @param source the source. * * @return The configuration. */ protected Configuration createDefaultHierarchicalConfiguration (final String staticConfig, final String userConfig, final boolean addSysProps, final Class source) { final HierarchicalConfiguration globalConfig = new HierarchicalConfiguration(); if (staticConfig != null) { final PropertyFileConfiguration rootProperty = new PropertyFileConfiguration(); rootProperty.load(staticConfig, getClass()); globalConfig.insertConfiguration(rootProperty); globalConfig.insertConfiguration( getPackageManager().getPackageConfiguration()); } if (userConfig != null) { String userConfigStripped; if (userConfig.startsWith("/")) { userConfigStripped = userConfig.substring(1); } else { userConfigStripped = userConfig; } try { final Enumeration userConfigs = ObjectUtilities.getClassLoader (getClass()).getResources(userConfigStripped); final ArrayList configs = new ArrayList(); while (userConfigs.hasMoreElements()) { final URL url = (URL) userConfigs.nextElement(); try { final PropertyFileConfiguration baseProperty = new PropertyFileConfiguration(); final InputStream in = url.openStream(); baseProperty.load(in); in.close(); configs.add(baseProperty); } catch(IOException ioe) { Log.warn ("Failed to load the user configuration at " + url, ioe); } } for (int i = configs.size() - 1; i >= 0; i--) { final PropertyFileConfiguration baseProperty = (PropertyFileConfiguration) configs.get(i); globalConfig.insertConfiguration(baseProperty); } } catch (IOException e) { Log.warn ("Failed to lookup the user configurations.", e); } } if (addSysProps) { final SystemPropertyConfiguration systemConfig = new SystemPropertyConfiguration(); globalConfig.insertConfiguration(systemConfig); } return globalConfig; } /** * Returns the global configuration as extended configuration. * * @return the extended configuration. */ public synchronized ExtendedConfiguration getExtendedConfig () { if (this.extWrapper == null) { this.extWrapper = new ExtendedConfigurationWrapper(getGlobalConfig()); } return this.extWrapper; } } jcommon-1.0.16/source/org/jfree/base/config/0000755000175000017500000000000011351753320020540 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/base/config/ModifiableConfiguration.java0000644000175000017500000000477311172030703026173 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------------- * ModifiableConfiguration.java * ---------------------------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Thomas Morgner; * * $Id: ModifiableConfiguration.java,v 1.3 2005/10/18 13:14:12 mungady Exp $ * * Changes * ------- * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.base.config; import java.util.Enumeration; import java.util.Iterator; import org.jfree.util.Configuration; /** * A modifiable configuration. * * @author Thomas Morgner */ public interface ModifiableConfiguration extends Configuration { /** * Sets the value of a configuration property. * * @param key the property key. * @param value the property value. */ public void setConfigProperty(final String key, final String value); /** * Returns the configuration properties. * * @return The configuration properties. */ public Enumeration getConfigProperties(); /** * Returns an iterator for the keys beginning with the specified prefix. * * @param prefix the prefix. * * @return The iterator. */ public Iterator findPropertyKeys(final String prefix); } jcommon-1.0.16/source/org/jfree/base/config/HierarchicalConfiguration.java0000644000175000017500000002423611172030703026512 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------ * HierarchicalConfiguration.java * ------------------------------ * (C) Copyright 2004, by Object Refinery Limited. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: HierarchicalConfiguration.java,v 1.8 2008/09/10 09:17:28 mungady Exp $ * * Changes * ------- * 07-Jun-2004 : Added JCommon header (DG); * 29-Jul-2004 : Replaced 'enum' variable name (reserved word in JDK 1.5) (DG); * */ package org.jfree.base.config; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; import java.util.TreeSet; import org.jfree.util.Configuration; import org.jfree.util.PublicCloneable; /** * A hierarchical configuration. Such a configuration can have one or more * parent configurations providing usefull default values. * * @author Thomas Morgner */ public class HierarchicalConfiguration implements ModifiableConfiguration, PublicCloneable { /** * The instance configuration properties. */ private Properties configuration; /** * The parent configuration (null if this is the root configuration). */ private transient Configuration parentConfiguration; /** * Creates a new configuration. */ public HierarchicalConfiguration() { this.configuration = new Properties(); } /** * Creates a new configuration. * * @param parentConfiguration the parent configuration. */ public HierarchicalConfiguration(final Configuration parentConfiguration) { this(); this.parentConfiguration = parentConfiguration; } /** * Returns the configuration property with the specified key. * * @param key the property key. * @return the property value. */ public String getConfigProperty(final String key) { return getConfigProperty(key, null); } /** * Returns the configuration property with the specified key (or the * specified default value if there is no such property). *

* If the property is not defined in this configuration, the code will * lookup the property in the parent configuration. * * @param key the property key. * @param defaultValue the default value. * @return the property value. */ public String getConfigProperty(final String key, final String defaultValue) { String value = this.configuration.getProperty(key); if (value == null) { if (isRootConfig()) { value = defaultValue; } else { value = this.parentConfiguration.getConfigProperty(key, defaultValue); } } return value; } /** * Sets a configuration property. * * @param key the property key. * @param value the property value. */ public void setConfigProperty(final String key, final String value) { if (key == null) { throw new NullPointerException(); } if (value == null) { this.configuration.remove(key); } else { this.configuration.setProperty(key, value); } } /** * Returns true if this object has no parent. * * @return true, if this report is the root configuration, false otherwise. */ private boolean isRootConfig() { return this.parentConfiguration == null; } /** * Checks, whether the given key is localy defined in this instance or * whether the key's value is inherited. * * @param key the key that should be checked. * @return true, if the key is defined locally, false otherwise. */ public boolean isLocallyDefined(final String key) { return this.configuration.containsKey(key); } /** * Returns the collection of properties for the configuration. * * @return the properties. */ protected Properties getConfiguration() { return this.configuration; } /** * The new configuartion will be inserted into the list of report * configuration, so that this configuration has the given report * configuration instance as parent. * * @param config the new report configuration. */ public void insertConfiguration(final HierarchicalConfiguration config) { config.setParentConfig(getParentConfig()); setParentConfig(config); } /** * Set the parent configuration. The parent configuration is queried, if the * requested configuration values was not found in this report * configuration. * * @param config the parent configuration. */ protected void setParentConfig(final Configuration config) { if (this.parentConfiguration == this) { throw new IllegalArgumentException("Cannot add myself as parent configuration."); } this.parentConfiguration = config; } /** * Returns the parent configuration. The parent configuration is queried, if * the requested configuration values was not found in this report * configuration. * * @return the parent configuration. */ protected Configuration getParentConfig() { return this.parentConfiguration; } /** * Returns all defined configuration properties for the report. The * enumeration contains all keys of the changed properties, properties set * from files or the system properties are not included. * * @return all defined configuration properties for the report. */ public Enumeration getConfigProperties() { return this.configuration.keys(); } /** * Searches all property keys that start with a given prefix. * * @param prefix the prefix that all selected property keys should share * @return the properties as iterator. */ public Iterator findPropertyKeys(final String prefix) { final TreeSet keys = new TreeSet(); collectPropertyKeys(prefix, this, keys); return Collections.unmodifiableSet(keys).iterator(); } /** * Collects property keys from this and all parent report configurations, * which start with the given prefix. * * @param prefix the prefix, that selects the property keys. * @param config the currently processed report configuration. * @param collector the target list, that should receive all valid keys. */ private void collectPropertyKeys(final String prefix, final Configuration config, final TreeSet collector) { final Enumeration enum1 = config.getConfigProperties(); while (enum1.hasMoreElements()) { final String key = (String) enum1.nextElement(); if (key.startsWith(prefix)) { if (collector.contains(key) == false) { collector.add(key); } } } if (config instanceof HierarchicalConfiguration) { final HierarchicalConfiguration hconfig = (HierarchicalConfiguration) config; if (hconfig.parentConfiguration != null) { collectPropertyKeys(prefix, hconfig.parentConfiguration, collector); } } } /** * Checks, whether the parent configuration can be serialized. Usually the * global configuration is not serialized and should return false here. * * @return true, if the parent config can be serialized, false otherwise. */ protected boolean isParentSaved() { return true; } /** * A callback method to reconnect this configuration with the global * configuration after deserialization. */ protected void configurationLoaded() { } /** * Helper method for serialization. * * @param out the output stream where to write the object. * @throws java.io.IOException if errors occur while writing the stream. */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); if (isParentSaved() == false) { out.writeBoolean(false); } else { out.writeBoolean(true); out.writeObject(this.parentConfiguration); } } /** * Helper method for serialization. * * @param in the input stream from where to read the serialized object. * @throws IOException when reading the stream fails. * @throws ClassNotFoundException if a class definition for a serialized * object could not be found. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); final boolean readParent = in.readBoolean(); if (readParent) { this.parentConfiguration = (ModifiableConfiguration) in.readObject(); } else { this.parentConfiguration = null; } configurationLoaded(); } /** * Returns a clone of this instance. * * @return A clone. * * @throws CloneNotSupportedException if there is a problem cloning. */ public Object clone() throws CloneNotSupportedException { HierarchicalConfiguration config = (HierarchicalConfiguration) super.clone(); config.configuration = (Properties) this.configuration.clone(); return config; } } jcommon-1.0.16/source/org/jfree/base/config/PropertyFileConfiguration.java0000644000175000017500000000760611172030703026562 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------------ * PropertyFileReportConfiguration.java * ------------------------------------ * (C)opyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: PropertyFileConfiguration.java,v 1.10 2008/09/10 09:17:28 mungady Exp $ * * Changes * ------- * 14-Jan-2003 : Initial version */ package org.jfree.base.config; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.jfree.util.Log; import org.jfree.util.ObjectUtilities; /** * A report configuration that reads its values from an arbitary property file. * * @author Thomas Morgner */ public class PropertyFileConfiguration extends HierarchicalConfiguration { /** * Default constructor. */ public PropertyFileConfiguration() { // nothing required } /** * Load the properties in the given file. * * @param resourceName the file name. */ public void load(final String resourceName) { load(resourceName, PropertyFileConfiguration.class); } /** * Loads the properties stored in the given file. This method does nothing if * the file does not exist or is unreadable. Appends the contents of the loaded * properties to the already stored contents. * * @param resourceName the file name of the stored properties. * @param resourceSource ? */ public void load(final String resourceName, final Class resourceSource) { final InputStream in = ObjectUtilities.getResourceRelativeAsStream (resourceName, resourceSource); if (in != null) { try { load(in); } finally { try { in.close(); } catch (IOException e) { // ignore } } } else { Log.debug ("Configuration file not found in the classpath: " + resourceName); } } /** * Loads the properties stored in the given file. This method does nothing if * the file does not exist or is unreadable. Appends the contents of the loaded * properties to the already stored contents. * * @param in the input stream used to read the properties. */ public void load(final InputStream in) { if (in == null) { throw new NullPointerException(); } try { final BufferedInputStream bin = new BufferedInputStream(in); final Properties p = new Properties(); p.load(bin); this.getConfiguration().putAll(p); bin.close(); } catch (IOException ioe) { Log.warn("Unable to read configuration", ioe); } } } jcommon-1.0.16/source/org/jfree/base/config/SystemPropertyConfiguration.java0000644000175000017500000001102611172030703027156 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------------------- * SystemPropertyConfiguration.java * -------------------------------- * (C)opyright 2002-2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner * Contributor(s): Stefan Prange; * * $Id: SystemPropertyConfiguration.java,v 1.3 2005/10/18 13:14:12 mungady Exp $ * * Changes (from 8-Feb-2002) * ------------------------- * 14-Jan-2003 : Initial Version, moved from inner class of ReportConfiguration * 05-Feb-2003 : This implementation now handles SecurityExceptions. * */ package org.jfree.base.config; import java.util.Enumeration; import java.util.Vector; /** * A property configuration based on system properties. * * @author Thomas Morgner */ public class SystemPropertyConfiguration extends HierarchicalConfiguration { /** * Creates a report configuration that includes all the system properties (whether they are * related to reports or not). The parent configuration is a * PropertyFileConfiguration. */ public SystemPropertyConfiguration() { } /** * Sets a configuration property. * * @param key the property key. * @param value the property value. */ public void setConfigProperty(final String key, final String value) { throw new UnsupportedOperationException("The SystemPropertyConfiguration is readOnly"); } /** * Returns the configuration property with the specified key (or the specified default value * if there is no such property). *

* If the property is not defined in this configuration, the code will lookup the property in * the parent configuration. * * @param key the property key. * @param defaultValue the default value. * * @return the property value. */ public String getConfigProperty(final String key, final String defaultValue) { try { final String value = System.getProperty(key); if (value != null) { return value; } } catch (SecurityException se) { // ignore security exceptions, continue as if the property was not set.. } return super.getConfigProperty(key, defaultValue); } /** * Checks, whether the given key is locally defined in the system properties. * @see HierarchicalConfiguration#isLocallyDefined(java.lang.String) * * @param key the key that should be checked. * @return true, if the key is defined in the system properties, false otherwise. */ public boolean isLocallyDefined(final String key) { try { return System.getProperties().containsKey(key); } catch (SecurityException se) { return false; } } /** * Returns all defined configuration properties for the report. The enumeration * contains all keys of the changed properties, properties set from files or * the system properties are not included. * * @return all defined configuration properties for the report. */ public Enumeration getConfigProperties() { try { return System.getProperties().keys(); } catch (SecurityException se) { // should return an empty enumeration ... return new Vector().elements(); } } } jcommon-1.0.16/source/org/jfree/base/package.html0000644000175000017500000000017211172030703021546 0ustar twernertwerner Base level classes. jcommon-1.0.16/source/org/jfree/base/log/0000755000175000017500000000000011351753320020054 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/base/log/MemoryUsageMessage.java0000644000175000017500000000446511172030703024464 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * MemoryUsageMessage.java * ----------------------- * (C) Copyright 2004, by Object Refinery Limited. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: MemoryUsageMessage.java,v 1.3 2005/10/18 13:14:33 mungady Exp $ * * Changes * ------- * 15-Jul-2004 : Added JCommon header (DG); * */ package org.jfree.base.log; /** * A helper class to print memory usage message if needed. * * @author Thomas Morgner */ public class MemoryUsageMessage { /** The message. */ private final String message; /** * Creates a new message. * * @param message the message. */ public MemoryUsageMessage(final String message) { this.message = message; } /** * Returns a string representation of the message (useful for debugging). * * @return the string. */ public String toString() { return this.message + "Free: " + Runtime.getRuntime().freeMemory() + "; " + "Total: " + Runtime.getRuntime().totalMemory(); } } jcommon-1.0.16/source/org/jfree/base/log/DefaultLog.java0000644000175000017500000001112411172030703022736 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * DefaultLog.java * --------------- * (C) Copyright 2004, by Object Refinery Limited. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DefaultLog.java,v 1.9 2006/02/19 21:10:48 taqua Exp $ * * Changes * ------- * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.base.log; import org.jfree.util.Log; import org.jfree.util.LogTarget; import org.jfree.util.PrintStreamLogTarget; /** * A default log implementation. The Log class defines how to create Logger-contexts * and how to forward messages to the logtargets. * * @author Thomas Morgner */ public class DefaultLog extends Log { /** The default log target. */ private static final PrintStreamLogTarget DEFAULT_LOG_TARGET = new PrintStreamLogTarget(); /** The default log instance. */ private static final DefaultLog defaultLogInstance; /** * Creates a new log. */ protected DefaultLog () { // nothing required } static { defaultLogInstance = new DefaultLog(); defaultLogInstance.addTarget(DEFAULT_LOG_TARGET); try { // check the system property. This is the developers backdoor to activate // debug output as soon as possible. final String property = System.getProperty("org.jfree.DebugDefault", "false"); if (Boolean.valueOf(property).booleanValue()) { defaultLogInstance.setDebuglevel(LogTarget.DEBUG); } else { defaultLogInstance.setDebuglevel(LogTarget.WARN); } } catch (SecurityException se) { defaultLogInstance.setDebuglevel(LogTarget.WARN); } } /** * Initializes the log system after the log module was loaded and a log target * was defined. This is the second step of the log initialisation. */ public void init() { removeTarget(DEFAULT_LOG_TARGET); final String logLevel = LogConfiguration.getLogLevel(); if (logLevel.equalsIgnoreCase("error")) { setDebuglevel(LogTarget.ERROR); } else if (logLevel.equalsIgnoreCase("warn")) { setDebuglevel(LogTarget.WARN); } else if (logLevel.equalsIgnoreCase("info")) { setDebuglevel(LogTarget.INFO); } else if (logLevel.equalsIgnoreCase("debug")) { setDebuglevel(LogTarget.DEBUG); } } /** * Adds a log target to this facility. Log targets get informed, via the * LogTarget interface, whenever a message is logged with this class. * * @param target the target. */ public synchronized void addTarget(final LogTarget target) { super.addTarget(target); // as soon as there is a real log target added, we do no longer need // the default logging. This was only installed to be able to send messages // if the deepest basic logging failed. if (target != DEFAULT_LOG_TARGET) { removeTarget(DEFAULT_LOG_TARGET); } } /** * Returns the default log. * * @return The default log. */ public static DefaultLog getDefaultLog() { return defaultLogInstance; } /** * Makes this implementation the default instance. */ public static void installDefaultLog () { Log.defineLog(defaultLogInstance); } } jcommon-1.0.16/source/org/jfree/base/log/PadMessage.java0000644000175000017500000000527611172030703022734 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * PadMessage.java * --------------- * (C) Copyright 2004, by Object Refinery Limited. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: PadMessage.java,v 1.4 2005/10/18 13:14:33 mungady Exp $ * * Changes * ------- * 15-Jul-2004 : Added JCommon header (DG); * */ package org.jfree.base.log; import java.util.Arrays; /** * A message object that pads the output if the text is shorter than * the given length. This is usefull when concating multiple messages, * which should appear in a table like style. * * @author Thomas Morgner */ public class PadMessage { /** * The message. */ private final Object text; /** * The padding size. */ private final int length; /** * Creates a new message. * * @param message the message. * @param length the padding size. */ public PadMessage(final Object message, final int length) { this.text = message; this.length = length; } /** * Returns a string representation of the message. * * @return the string. */ public String toString() { final StringBuffer b = new StringBuffer(); b.append(this.text); if (b.length() < this.length) { final char[] pad = new char[this.length - b.length()]; Arrays.fill(pad, ' '); b.append(pad); } return b.toString(); } } jcommon-1.0.16/source/org/jfree/base/log/LogConfiguration.java0000644000175000017500000001210211172030703024156 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * LogConfiguration.java * --------------------- * (C) Copyright 2004, by Object Refinery Limited. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: LogConfiguration.java,v 1.6 2005/12/18 23:29:18 taqua Exp $ * * Changes * ------- * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.base.log; import org.jfree.base.BaseBoot; import org.jfree.util.PrintStreamLogTarget; /** * A log configuration class. This implementation is a simple frontend * to the global configuration. * * @author Thomas Morgner */ public class LogConfiguration { /** The default 'disable logging' property value. */ public static final String DISABLE_LOGGING_DEFAULT = "false"; /** The 'log level' property key. */ public static final String LOGLEVEL = "org.jfree.base.LogLevel"; /** The default 'log level' property value. */ public static final String LOGLEVEL_DEFAULT = "Info"; /** The 'log target' property key. */ public static final String LOGTARGET = "org.jfree.base.LogTarget"; /** The default 'log target' property value. */ public static final String LOGTARGET_DEFAULT = PrintStreamLogTarget.class.getName(); /** The 'disable logging' property key. */ public static final String DISABLE_LOGGING = "org.jfree.base.NoDefaultDebug"; /** * Default constructor. */ private LogConfiguration() { // nothing required. } /** * Returns the current log target. * * @return the log target. */ public static String getLogTarget() { return BaseBoot.getInstance().getGlobalConfig().getConfigProperty (LOGTARGET, LOGTARGET_DEFAULT); } /** * Sets the log target. * * @param logTarget the new log target. */ public static void setLogTarget(final String logTarget) { BaseBoot.getConfiguration().setConfigProperty (LOGTARGET, logTarget); } /** * Returns the log level. * * @return the log level. */ public static String getLogLevel() { return BaseBoot.getInstance().getGlobalConfig().getConfigProperty (LOGLEVEL, LOGLEVEL_DEFAULT); } /** * Sets the log level, which is read from the global report configuration at * the point that the classloader loads the {@link org.jfree.util.Log} class. *

* Valid log levels are: * *

    *
  • "Error" - error messages;
  • *
  • "Warn" - warning messages;
  • *
  • "Info" - information messages;
  • *
  • "Debug" - debug messages;
  • *
* * Notes: *
    *
  • the setting is not case sensitive.
  • *
  • changing the log level after the {@link org.jfree.util.Log} class has been * loaded will have no effect.
  • *
  • to turn of logging altogether, use the {@link #setDisableLogging} method.
  • *
* * @param level the new log level. */ public static void setLogLevel(final String level) { BaseBoot.getConfiguration().setConfigProperty(LOGLEVEL, level); } /** * Returns true if logging is disabled, and false otherwise. * * @return true, if logging is completly disabled, false otherwise. */ public static boolean isDisableLogging() { return BaseBoot.getInstance().getGlobalConfig().getConfigProperty (DISABLE_LOGGING, DISABLE_LOGGING_DEFAULT).equalsIgnoreCase("true"); } /** * Sets the flag that disables logging. *

* To switch off logging globally, you can use the following code: *

* ReportConfiguration.getGlobalConfig().setDisableLogging(true); * * @param disableLogging the flag. */ public static void setDisableLogging(final boolean disableLogging) { BaseBoot.getConfiguration().setConfigProperty (DISABLE_LOGGING, String.valueOf(disableLogging)); } } jcommon-1.0.16/source/org/jfree/base/log/DefaultLogModule.java0000644000175000017500000000666511172030703024122 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * DefaultLogModule.java * --------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DefaultLogModule.java,v 1.8 2005/12/18 23:29:18 taqua Exp $ * * Changes * ------- * 11-Jul-2003 : Initial version * 07-Jun-2004 : Added JCommon header (DG); * 25-Nov-2005 : The initialization was overly complicated. There is only * one logtarget here, and additional targets should create * an dependent module. */ package org.jfree.base.log; import org.jfree.base.modules.AbstractModule; import org.jfree.base.modules.ModuleInitializeException; import org.jfree.base.modules.SubSystem; import org.jfree.util.Log; import org.jfree.util.PrintStreamLogTarget; /** * The module definition for the System.out-Logging. This is the default log * implementation and is provided to insert the logging initialisation in the * module loading process. * * @author Thomas Morgner */ public class DefaultLogModule extends AbstractModule { /** * DefaultConstructor. Loads the module specification. * * @throws ModuleInitializeException if an error occured. */ public DefaultLogModule() throws ModuleInitializeException { loadModuleInfo(); } /** * Initalizes the module. This method initializes the logging system, if the * System.out logtarget is selected. * * @param subSystem the sub-system. * @throws ModuleInitializeException if an error occured. */ public void initialize(final SubSystem subSystem) throws ModuleInitializeException { if (LogConfiguration.isDisableLogging()) { return; } if (LogConfiguration.getLogTarget().equals (PrintStreamLogTarget.class.getName())) { DefaultLog.installDefaultLog(); Log.getInstance().addTarget(new PrintStreamLogTarget()); if ("true".equals(subSystem.getGlobalConfig().getConfigProperty ("org.jfree.base.LogAutoInit"))) { Log.getInstance().init(); } Log.info("Default log target started ... previous log messages " + "could have been ignored."); } } } jcommon-1.0.16/source/org/jfree/base/log/module.properties0000644000175000017500000000053511172030703023454 0ustar twernertwerner# # Support for logging. # module-info: name: base-logging-module producer: The JFreeChart project - www.jfree.org/jcommon description: Initialializer to configure the log system and to provide a facility for logging to the System.out stream. version.major: 1 version.minor: 0 version.patchlevel: 0 subsystem: logging jcommon-1.0.16/source/org/jfree/base/BootableProjectInfo.java0000644000175000017500000001234511172030703024027 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------ * BootableProjectInfo.java * ------------------------ * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: BootableProjectInfo.java,v 1.4 2006/03/23 19:47:05 taqua Exp $ * * Changes * ------- * 07-Jun-2004 : Added source headers (DG); * */ package org.jfree.base; import java.util.ArrayList; /** * Project info for a bootable project. A bootable project provides a controlled * way of initalizing all subsystems by providing a Boot loader implementation. * * @author Thomas Morgner */ public class BootableProjectInfo extends BasicProjectInfo { /** The boot class. */ private String bootClass; /** The auto-boot flag. */ private boolean autoBoot; /** * Creates a new instance. */ public BootableProjectInfo() { this.autoBoot = true; } /** * Creates a new library reference. * * @param name the name. * @param version the version. * @param licence the licence. * @param info the web address or other info. */ public BootableProjectInfo(final String name, final String version, final String licence, final String info) { this(); setName(name); setVersion(version); setLicenceName(licence); setInfo(info); } /** * Creates a new library reference. * * @param name the name. * @param version the version. * @param info the info (for example, the project URL). * @param copyright the copyright statement. * @param licenceName the license name. */ public BootableProjectInfo(final String name, final String version, final String info, final String copyright, final String licenceName) { this(); setName(name); setVersion(version); setLicenceName(licenceName); setInfo(info); setCopyright(copyright); } /** * Returns the dependencies. * * @return The dependencies. */ public BootableProjectInfo[] getDependencies() { final ArrayList dependencies = new ArrayList(); final Library[] libraries = getLibraries(); for (int i = 0; i < libraries.length; i++) { Library lib = libraries[i]; if (lib instanceof BootableProjectInfo) { dependencies.add(lib); } } final Library[] optionalLibraries = getOptionalLibraries(); for (int i = 0; i < optionalLibraries.length; i++) { Library lib = optionalLibraries[i]; if (lib instanceof BootableProjectInfo) { dependencies.add(lib); } } return (BootableProjectInfo[]) dependencies.toArray (new BootableProjectInfo[dependencies.size()]); } /** * Adds a dependency. * * @param projectInfo the project. * @deprecated use 'addLibrary' instead. */ public void addDependency(final BootableProjectInfo projectInfo) { if (projectInfo == null) { throw new NullPointerException(); } addLibrary(projectInfo); } /** * Returns the name of the boot class. * * @return The name of the boot class. */ public String getBootClass() { return this.bootClass; } /** * Sets the boot class name. * * @param bootClass the boot class name. */ public void setBootClass(final String bootClass) { this.bootClass = bootClass; } /** * Returns, whether the project should be booted automaticly. * * @return The auto-boot flag. */ public boolean isAutoBoot() { return this.autoBoot; } /** * Sets the auto boot flag. * * @param autoBoot true, if the project should be booted automaticly, false otherwise. */ public void setAutoBoot(final boolean autoBoot) { this.autoBoot = autoBoot; } } jcommon-1.0.16/source/org/jfree/base/jcommon.properties0000644000175000017500000000305611172030703023051 0ustar twernertwerner# # The minimum loglevel that is logged org.jfree.base.LogLevel=Debug # # Where to log. Give a classname of a valid LogTarget implementation. # If the name is invalid, no logging is done. org.jfree.base.LogTarget=*none* # # Do not initialize the logging. org.jfree.base.LogAutoInit=false # # Should the debugging system be disabled by default. This option will suppress all # output, no single line of debug information will be printed. If you want to remove # System.out-debugging on the server side, try to switch to a Log4J-LogTarget instead. org.jfree.base.NoDefaultDebug=false # # Which ClassLoader to use for loading external resources and classes. # One of "ThreadContext" or "CallerContext". org.jfree.ClassLoader=ThreadContext # # Applies a workaround to fix a JDK bug. When the value is set to auto, # This is enabled if the JDK is not version 1.4 or higher. org.jfree.text.UseDrawRotatedStringWorkaround=auto # # Applies a workaround to fix a JDK bug. When the value is set to auto, # This is disabled if the JDK is not version 1.4 or higher. org.jfree.text.UseFontMetricsGetStringBounds=auto # # Known extra modules. Do not edit and do not delete the following lines. # # That module loading mechanism is not really extensible. A better # implementation might solve that at a later time. org.jfree.jcommon.modules.logger.Log4J.Module=org.jfree.logger.java14.Java14LogModule org.jfree.jcommon.modules.logger.Java14Logging.Module=org.jfree.logger.log4j.Log4JLogModule org.jfree.jcommon.modules.logger.JakartaLogging.Module=org.jfree.logger.jcl.JakartaLogModule jcommon-1.0.16/source/org/jfree/base/BaseBoot.java0000644000175000017500000001035111172030703021626 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------- * BaseBoot.java * ------------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: BaseBoot.java,v 1.11 2007/11/02 17:50:34 taqua Exp $ * * Changes * ------- * 07-Jun-2004 : Added source headers (DG); * */ package org.jfree.base; import org.jfree.JCommon; import org.jfree.base.config.ModifiableConfiguration; import org.jfree.base.log.DefaultLogModule; import org.jfree.util.Configuration; import org.jfree.util.ObjectUtilities; /** * The base boot class. This initializes the services provided by * JCommon. * * @author Thomas Morgner */ public class BaseBoot extends AbstractBoot { /** * Singleton instance. */ private static BaseBoot singleton; /** * The project info. */ private BootableProjectInfo bootableProjectInfo; /** * Default constructor (private). */ private BaseBoot() { this.bootableProjectInfo = JCommon.INFO; } /** * Returns the global configuration as modifiable configuration reference. * * @return the global configuration */ public static ModifiableConfiguration getConfiguration() { return (ModifiableConfiguration) getInstance().getGlobalConfig(); } /** * Returns the global configuration for JFreeReport. *

* In the current implementation, the configuration has no properties defined, but * references a parent configuration that:

  • copies across all the * System properties to use as report configuration properties (obviously * the majority of them will not apply to reports);
  • itself references a parent * configuration that reads its properties from a file jfreereport.properties. *
* * @return the global configuration. */ protected synchronized Configuration loadConfiguration() { return createDefaultHierarchicalConfiguration ("/org/jfree/base/jcommon.properties", "/jcommon.properties", true, BaseBoot.class); } /** * Returns the boot instance. * * @return The boot instance. */ public static synchronized AbstractBoot getInstance() { if (singleton == null) { singleton = new BaseBoot(); } return singleton; } /** * Performs the boot process. */ protected void performBoot() { // configure the classloader from the properties-file. ObjectUtilities.setClassLoaderSource (getConfiguration().getConfigProperty("org.jfree.ClassLoader")); getPackageManager().addModule(DefaultLogModule.class.getName()); getPackageManager().load("org.jfree.jcommon.modules."); getPackageManager().initializeModules(); } /** * Returns the project info. * * @return The project info. */ protected BootableProjectInfo getProjectInfo() { return this.bootableProjectInfo; } } jcommon-1.0.16/source/org/jfree/base/BasicProjectInfo.java0000644000175000017500000002073711172030703023325 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------------- * BasicProjectInfo.java * --------------------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: BasicProjectInfo.java,v 1.10 2008/09/10 09:23:34 mungady Exp $ * * Changes * ------- * 07-Jun-2004 : Added source headers (DG); * */ package org.jfree.base; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.jfree.util.ObjectUtilities; /** * Basic project info. * * @author Thomas Morgner */ public class BasicProjectInfo extends Library { /** * A helper class, which simplifies the loading of optional library * implementations. */ private static class OptionalLibraryHolder { private String libraryClass; private transient Library library; public OptionalLibraryHolder(final String libraryClass) { if (libraryClass == null) { throw new NullPointerException("LibraryClass must not be null."); } this.libraryClass = libraryClass; } public OptionalLibraryHolder(final Library library) { if (library == null) { throw new NullPointerException("Library must not be null."); } this.library = library; this.libraryClass = library.getClass().getName(); } public String getLibraryClass() { return this.libraryClass; } public Library getLibrary() { if (this.library == null) { this.library = loadLibrary(this.libraryClass); } return this.library; } protected Library loadLibrary(final String classname) { if (classname == null) { return null; } try { final Class c = ObjectUtilities.getClassLoader( getClass()).loadClass(classname); try { final Method m = c.getMethod("getInstance", (Class[]) null); return (Library) m.invoke(null, (Object[]) null); } catch(Exception e) { // ok, fall back ... } return (Library) c.newInstance(); } catch (Exception e) { // ok, this library has no 'getInstance()' method. Check the // default constructor ... return null; } } } /** The project copyright statement. */ private String copyright; /** A list of libraries used by the project. */ private List libraries; private List optionalLibraries; /** * Default constructor. */ public BasicProjectInfo() { this.libraries = new ArrayList(); this.optionalLibraries = new ArrayList(); } /** * Creates a new library reference. * * @param name the name. * @param version the version. * @param licence the licence. * @param info the web address or other info. */ public BasicProjectInfo(final String name, final String version, final String licence, final String info) { this(); setName(name); setVersion(version); setLicenceName(licence); setInfo(info); } /** * Creates a new project info instance. * * @param name the project name. * @param version the project version. * @param info the project info (web site for example). * @param copyright the copyright statement. * @param licenceName the license name. */ public BasicProjectInfo(final String name, final String version, final String info, final String copyright, final String licenceName) { this(name, version, licenceName, info); setCopyright(copyright); } /** * Returns the copyright statement. * * @return The copyright statement. */ public String getCopyright() { return this.copyright; } /** * Sets the project copyright statement. * * @param copyright the project copyright statement. */ public void setCopyright(final String copyright) { this.copyright = copyright; } /** * Sets the project info string (for example, this could be the project URL). * * @param info the info string. */ public void setInfo(final String info) { super.setInfo(info); } /** * Sets the license name. * * @param licence the license name. */ public void setLicenceName(final String licence) { super.setLicenceName(licence); } /** * Sets the project name. * * @param name the project name. */ public void setName(final String name) { super.setName(name); } /** * Sets the project version number. * * @param version the version number. */ public void setVersion(final String version) { super.setVersion(version); } /** * Returns a list of libraries used by the project. * * @return the list of libraries. */ public Library[] getLibraries() { return (Library[]) this.libraries.toArray (new Library[this.libraries.size()]); } /** * Adds a library. * * @param library the library. */ public void addLibrary (final Library library) { if (library == null) { throw new NullPointerException(); } this.libraries.add(library); } /** * Returns a list of optional libraries used by the project. * * @return the list of libraries. */ public Library[] getOptionalLibraries() { final ArrayList libraries = new ArrayList(); for (int i = 0; i < this.optionalLibraries.size(); i++) { OptionalLibraryHolder holder = (OptionalLibraryHolder) this.optionalLibraries.get(i); Library l = holder.getLibrary(); if (l != null) { libraries.add(l); } } return (Library[]) libraries.toArray(new Library[libraries.size()]); } /** * Adds an optional library. These libraries will be booted, if they define * a boot class. A missing class is considered non-fatal and it is assumed * that the programm knows how to handle that. * * @param libraryClass the library. */ public void addOptionalLibrary (final String libraryClass) { if (libraryClass == null) { throw new NullPointerException("Library classname must be given."); } this.optionalLibraries.add (new OptionalLibraryHolder(libraryClass)); } /** * Adds an optional library. These libraries will be booted, if they define * a boot class. A missing class is considered non-fatal and it is assumed * that the programm knows how to handle that. * * @param library the library. */ public void addOptionalLibrary (final Library library) { if (library == null) { throw new NullPointerException("Library must be given."); } this.optionalLibraries.add(new OptionalLibraryHolder(library)); } } jcommon-1.0.16/source/org/jfree/base/Library.java0000644000175000017500000001134211172030703021535 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------ * Library.java * ------------ * (C) Copyright 2002-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: Library.java,v 1.7 2008/09/10 09:23:34 mungady Exp $ * * Changes * ------- * 21-Feb-2002 : Version 1 (DG); * 25-Mar-2002 : Added a new constructor (DG); * 02-Nov-2005 : Minor API doc updates (DG); * */ package org.jfree.base; import org.jfree.ui.about.AboutFrame; /** * A simple class representing a library in a software project. For use in * the {@link AboutFrame} class. * * @author David Gilbert */ public class Library { /** The name. */ private String name; /** The version. */ private String version; /** The licenceName. */ private String licenceName; /** The version. */ private String info; /** * Creates a new library reference. * * @param name the name. * @param version the version. * @param licence the licenceName. * @param info the web address or other info. */ public Library(final String name, final String version, final String licence, final String info) { this.name = name; this.version = version; this.licenceName = licence; this.info = info; } /** * Creates a new library reference. */ protected Library() { // nothing required } /** * Returns the library name. * * @return the library name. */ public String getName() { return this.name; } /** * Returns the library version. * * @return the library version. */ public String getVersion() { return this.version; } /** * Returns the licenceName text. * * @return the licenceName text. */ public String getLicenceName() { return this.licenceName; } /** * Returns the project info for the library. * * @return the project info. */ public String getInfo() { return this.info; } /** * Sets the project info. * * @param info the project info. */ protected void setInfo(final String info) { this.info = info; } /** * Sets the licence name. * * @param licenceName the licence name. */ protected void setLicenceName(final String licenceName) { this.licenceName = licenceName; } /** * Sets the project name. * * @param name the project name. */ protected void setName(final String name) { this.name = name; } /** * Sets the version identifier. * * @param version the version identifier. */ protected void setVersion(final String version) { this.version = version; } /** * Tests this object for equality with an arbitrary object. * * @param o the object. * * @return A boolean. */ public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Library library = (Library) o; if (this.name != null ? !this.name.equals(library.name) : library.name != null) { return false; } return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ public int hashCode() { return (this.name != null ? this.name.hashCode() : 0); } } jcommon-1.0.16/source/org/jfree/base/modules/0000755000175000017500000000000011351753320020743 5ustar twernertwernerjcommon-1.0.16/source/org/jfree/base/modules/PackageState.java0000644000175000017500000001674211172030703024146 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * PackageState.java * ----------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: PackageState.java,v 1.4 2006/04/14 13:00:56 taqua Exp $ * * Changes * ------- * 10-Jul-2003 : Initial version * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.base.modules; import org.jfree.util.Log; /** * The package state class is used by the package manager to keep track of * the activation level of the installed or errornous packages. * * @author Thomas Morgner */ public class PackageState { /** A constant defining that the package is new. */ public static final int STATE_NEW = 0; /** A constant defining that the package has been loaded and configured. */ public static final int STATE_CONFIGURED = 1; /** A constant defining that the package was initialized and is ready to use. */ public static final int STATE_INITIALIZED = 2; /** A constant defining that the package produced an error and is not available. */ public static final int STATE_ERROR = -2; /** The module class that contains the package information. */ private final Module module; /** The state of the module. */ private int state; /** * Creates a new package state for the given module. The module state will * be initialized to STATE_NEW. * * @param module the module. */ public PackageState(final Module module) { this (module, STATE_NEW); } /** * Creates a new package state for the given module. The module state will * be initialized to the given initial state. * * @param module the module. * @param state the initial state */ public PackageState(final Module module, final int state) { if (module == null) { throw new NullPointerException("Module must not be null."); } if (state != STATE_CONFIGURED && state != STATE_ERROR && state != STATE_INITIALIZED && state != STATE_NEW) { throw new IllegalArgumentException("State is not valid"); } this.module = module; this.state = state; } /** * Configures the module and raises the state to STATE_CONFIGURED if the * module is not yet configured. * * @param subSystem the sub-system. * * @return true, if the module was configured, false otherwise. */ public boolean configure(final SubSystem subSystem) { if (this.state == STATE_NEW) { try { this.module.configure(subSystem); this.state = STATE_CONFIGURED; return true; } catch (NoClassDefFoundError noClassDef) { Log.warn (new Log.SimpleMessage("Unable to load module classes for ", this.module.getName(), ":", noClassDef.getMessage())); this.state = STATE_ERROR; } catch (Exception e) { if (Log.isDebugEnabled()) { // its still worth a warning, but now we are more verbose ... Log.warn("Unable to configure the module " + this.module.getName(), e); } else if (Log.isWarningEnabled()) { Log.warn("Unable to configure the module " + this.module.getName()); } this.state = STATE_ERROR; } } return false; } /** * Returns the module managed by this state implementation. * * @return the module. */ public Module getModule() { return this.module; } /** * Returns the current state of the module. This method returns either * STATE_NEW, STATE_CONFIGURED, STATE_INITIALIZED or STATE_ERROR. * * @return the module state. */ public int getState() { return this.state; } /** * Initializes the contained module and raises the set of the module to * STATE_INITIALIZED, if the module was not yet initialized. In case of an * error, the module state will be set to STATE_ERROR and the module will * not be available. * * @param subSystem the sub-system. * * @return true, if the module was successfully initialized, false otherwise. */ public boolean initialize(final SubSystem subSystem) { if (this.state == STATE_CONFIGURED) { try { this.module.initialize(subSystem); this.state = STATE_INITIALIZED; return true; } catch (NoClassDefFoundError noClassDef) { Log.warn (new Log.SimpleMessage("Unable to load module classes for ", this.module.getName(), ":", noClassDef.getMessage())); this.state = STATE_ERROR; } catch (ModuleInitializeException me) { if (Log.isDebugEnabled()) { // its still worth a warning, but now we are more verbose ... Log.warn("Unable to initialize the module " + this.module.getName(), me); } else if (Log.isWarningEnabled()) { Log.warn("Unable to initialize the module " + this.module.getName()); } this.state = STATE_ERROR; } catch (Exception e) { if (Log.isDebugEnabled()) { // its still worth a warning, but now we are more verbose ... Log.warn("Unable to initialize the module " + this.module.getName(), e); } else if (Log.isWarningEnabled()) { Log.warn("Unable to initialize the module " + this.module.getName()); } this.state = STATE_ERROR; } } return false; } /** * Compares this object with the given other object for equality. * @see java.lang.Object#equals(java.lang.Object) * * @param o the other object to be compared * @return true, if the other object is also a PackageState containing * the same module, false otherwise. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof PackageState)) { return false; } final PackageState packageState = (PackageState) o; if (!this.module.getModuleClass().equals(packageState.module.getModuleClass())) { return false; } return true; } /** * Computes a hashcode for this package state. * @see java.lang.Object#hashCode() * * @return the hashcode. */ public int hashCode() { return this.module.hashCode(); } } jcommon-1.0.16/source/org/jfree/base/modules/PackageManager.java0000644000175000017500000005520111172030703024431 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * PackageManager.java * ------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: PackageManager.java,v 1.10 2006/11/02 13:10:35 taqua Exp $ * * Changes * ------- * 26-Jun-2003 : Initial version * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.base.modules; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import org.jfree.base.AbstractBoot; import org.jfree.base.config.HierarchicalConfiguration; import org.jfree.base.config.PropertyFileConfiguration; import org.jfree.base.log.PadMessage; import org.jfree.util.Configuration; import org.jfree.util.Log; import org.jfree.util.ObjectUtilities; /** * The PackageManager is used to load and configure the modules of JFreeReport. * Modules are used to extend the basic capabilities of JFreeReport by providing * a simple plugin-interface. *

* Modules provide a simple capability to remove unneeded functionality from the * JFreeReport system and to reduce the overall code size. The modularisation provides * a very strict way of removing unnecessary dependencies beween the various packages. *

* The package manager can be used to add new modules to the system or to check * the existence and state of installed modules. * * @author Thomas Morgner */ public final class PackageManager { /** * The PackageConfiguration handles the module level configuration. * * @author Thomas Morgner */ public static class PackageConfiguration extends PropertyFileConfiguration { /** * DefaultConstructor. Creates a new package configuration. */ public PackageConfiguration() { // nothing required } /** * The new configuartion will be inserted into the list of report configuration, * so that this configuration has the given report configuration instance as parent. * * @param config the new report configuration. */ public void insertConfiguration(final HierarchicalConfiguration config) { super.insertConfiguration(config); } } /** * An internal constant declaring that the specified module was already loaded. */ private static final int RETURN_MODULE_LOADED = 0; /** * An internal constant declaring that the specified module is not known. */ private static final int RETURN_MODULE_UNKNOWN = 1; /** * An internal constant declaring that the specified module produced an error while loading. */ private static final int RETURN_MODULE_ERROR = 2; /** * The module configuration instance that should be used to store module * properties. This separates the user defined properties from the implementation * defined properties. */ private final PackageConfiguration packageConfiguration; /** * A list of all defined modules. */ private final ArrayList modules; /** * A list of module name definitions. */ private final ArrayList initSections; /** The boot implementation for which the modules are managed. */ private AbstractBoot booter; /** The instances of all modules for all booters. */ private static HashMap instances; /** * Creates a package manager instance. * * @param booter the booter. * @return A package manager. */ public static PackageManager createInstance(final AbstractBoot booter) { PackageManager manager; if (instances == null) { instances = new HashMap(); manager = new PackageManager(booter); instances.put(booter, manager); return manager; } manager = (PackageManager) instances.get(booter); if (manager == null) { manager = new PackageManager(booter); instances.put(booter, manager); } return manager; } /** * Creates a new package manager. * * @param booter the booter (null not permitted). */ private PackageManager(final AbstractBoot booter) { if (booter == null) { throw new NullPointerException(); } this.booter = booter; this.packageConfiguration = new PackageConfiguration(); this.modules = new ArrayList(); this.initSections = new ArrayList(); } /** * Checks, whether a certain module is available. * * @param moduleDescription the module description of the desired module. * @return true, if the module is available and the version of the module * is compatible, false otherwise. */ public boolean isModuleAvailable(final ModuleInfo moduleDescription) { final PackageState[] packageStates = (PackageState[]) this.modules.toArray(new PackageState[this.modules.size()]); for (int i = 0; i < packageStates.length; i++) { final PackageState state = packageStates[i]; if (state.getModule().getModuleClass().equals(moduleDescription.getModuleClass())) { return (state.getState() == PackageState.STATE_INITIALIZED); } } return false; } /** * Loads all modules mentioned in the report configuration starting with * the given prefix. This method is used during the boot process of * JFreeReport. You should never need to call this method directly. * * @param modulePrefix the module prefix. */ public void load(final String modulePrefix) { if (this.initSections.contains(modulePrefix)) { return; } this.initSections.add(modulePrefix); final Configuration config = this.booter.getGlobalConfig(); final Iterator it = config.findPropertyKeys(modulePrefix); int count = 0; while (it.hasNext()) { final String key = (String) it.next(); if (key.endsWith(".Module")) { final String moduleClass = config.getConfigProperty(key); if (moduleClass != null && moduleClass.length() > 0) { addModule(moduleClass); count++; } } } Log.debug("Loaded a total of " + count + " modules under prefix: " + modulePrefix); } /** * Initializes all previously uninitialized modules. Once a module is initialized, * it is not re-initialized a second time. */ public synchronized void initializeModules() { // sort by subsystems and dependency PackageSorter.sort(this.modules); for (int i = 0; i < this.modules.size(); i++) { final PackageState mod = (PackageState) this.modules.get(i); if (mod.configure(this.booter)) { Log.debug(new Log.SimpleMessage("Conf: ", new PadMessage(mod.getModule().getModuleClass(), 70), " [", mod.getModule().getSubSystem(), "]")); } } for (int i = 0; i < this.modules.size(); i++) { final PackageState mod = (PackageState) this.modules.get(i); if (mod.initialize(this.booter)) { Log.debug(new Log.SimpleMessage("Init: ", new PadMessage(mod.getModule().getModuleClass(), 70), " [", mod.getModule().getSubSystem(), "]")); } } } /** * Adds a module to the package manager. * Once all modules are added, you have to call initializeModules() * to configure and initialize the new modules. * * @param modClass the module class */ public synchronized void addModule(final String modClass) { final ArrayList loadModules = new ArrayList(); final ModuleInfo modInfo = new DefaultModuleInfo (modClass, null, null, null); if (loadModule(modInfo, new ArrayList(), loadModules, false)) { for (int i = 0; i < loadModules.size(); i++) { final Module mod = (Module) loadModules.get(i); this.modules.add(new PackageState(mod)); } } } /** * Checks, whether the given module is already loaded in either the given * tempModules list or the global package registry. If tmpModules is null, * only the previously installed modules are checked. * * @param tempModules a list of previously loaded modules. * @param module the module specification that is checked. * @return true, if the module is already loaded, false otherwise. */ private int containsModule(final ArrayList tempModules, final ModuleInfo module) { if (tempModules != null) { final ModuleInfo[] mods = (ModuleInfo[]) tempModules.toArray(new ModuleInfo[tempModules.size()]); for (int i = 0; i < mods.length; i++) { if (mods[i].getModuleClass().equals(module.getModuleClass())) { return RETURN_MODULE_LOADED; } } } final PackageState[] packageStates = (PackageState[]) this.modules.toArray(new PackageState[this.modules.size()]); for (int i = 0; i < packageStates.length; i++) { if (packageStates[i].getModule().getModuleClass().equals(module.getModuleClass())) { if (packageStates[i].getState() == PackageState.STATE_ERROR) { return RETURN_MODULE_ERROR; } else { return RETURN_MODULE_LOADED; } } } return RETURN_MODULE_UNKNOWN; } /** * A utility method that collects all failed modules. Such an module caused * an error while being loaded, and is now cached in case it is referenced * elsewhere. * * @param state the failed module. */ private void dropFailedModule(final PackageState state) { if (this.modules.contains(state) == false) { this.modules.add(state); } } /** * Tries to load a given module and all dependent modules. If the dependency check * fails for that module (or for one of the dependent modules), the loaded modules * are discarded and no action is taken. * * @param moduleInfo the module info of the module that should be loaded. * @param incompleteModules a list of incompletly loaded modules. This are module * specifications which depend on the current module and wait for the module to * be completly loaded. * @param modules the list of previously loaded modules for this module. * @param fatal a flag that states, whether the failure of loading a module should * be considered an error. Root-modules load errors are never fatal, as we try * to load all known modules, regardless whether they are active or not. * @return true, if the module was loaded successfully, false otherwise. */ private boolean loadModule(final ModuleInfo moduleInfo, final ArrayList incompleteModules, final ArrayList modules, final boolean fatal) { try { final Class c = ObjectUtilities.getClassLoader(getClass()).loadClass(moduleInfo.getModuleClass()); final Module module = (Module) c.newInstance(); if (acceptVersion(moduleInfo, module) == false) { // module conflict! Log.warn("Module " + module.getName() + ": required version: " + moduleInfo + ", but found Version: \n" + module); final PackageState state = new PackageState(module, PackageState.STATE_ERROR); dropFailedModule(state); return false; } final int moduleContained = containsModule(modules, module); if (moduleContained == RETURN_MODULE_ERROR) { // the module caused harm before ... Log.debug("Indicated failure for module: " + module.getModuleClass()); final PackageState state = new PackageState(module, PackageState.STATE_ERROR); dropFailedModule(state); return false; } else if (moduleContained == RETURN_MODULE_UNKNOWN) { if (incompleteModules.contains(module)) { // we assume that loading will continue ... Log.error(new Log.SimpleMessage ("Circular module reference: This module definition is invalid: ", module.getClass())); final PackageState state = new PackageState(module, PackageState.STATE_ERROR); dropFailedModule(state); return false; } incompleteModules.add(module); final ModuleInfo[] required = module.getRequiredModules(); for (int i = 0; i < required.length; i++) { if (loadModule(required[i], incompleteModules, modules, true) == false) { Log.debug("Indicated failure for module: " + module.getModuleClass()); final PackageState state = new PackageState(module, PackageState.STATE_ERROR); dropFailedModule(state); return false; } } final ModuleInfo[] optional = module.getOptionalModules(); for (int i = 0; i < optional.length; i++) { if (loadModule(optional[i], incompleteModules, modules, true) == false) { Log.debug(new Log.SimpleMessage("Optional module: ", optional[i].getModuleClass(), " was not loaded.")); } } // maybe a dependent module defined the same base module ... if (containsModule(modules, module) == RETURN_MODULE_UNKNOWN) { modules.add(module); } incompleteModules.remove(module); } return true; } catch (ClassNotFoundException cnfe) { if (fatal) { Log.warn(new Log.SimpleMessage ("Unresolved dependency for package: ", moduleInfo.getModuleClass())); } Log.debug(new Log.SimpleMessage("ClassNotFound: ", cnfe.getMessage())); return false; } catch (Exception e) { Log.warn(new Log.SimpleMessage("Exception while loading module: ", moduleInfo), e); return false; } } /** * Checks, whether the given module meets the requirements defined in the module * information. * * @param moduleRequirement the required module specification. * @param module the module that should be checked against the specification. * @return true, if the module meets the given specifications, false otherwise. */ private boolean acceptVersion(final ModuleInfo moduleRequirement, final Module module) { if (moduleRequirement.getMajorVersion() == null) { return true; } if (module.getMajorVersion() == null) { Log.warn("Module " + module.getName() + " does not define a major version."); } else { final int compare = acceptVersion(moduleRequirement.getMajorVersion(), module.getMajorVersion()); if (compare > 0) { return false; } else if (compare < 0) { return true; } } if (moduleRequirement.getMinorVersion() == null) { return true; } if (module.getMinorVersion() == null) { Log.warn("Module " + module.getName() + " does not define a minor version."); } else { final int compare = acceptVersion(moduleRequirement.getMinorVersion(), module.getMinorVersion()); if (compare > 0) { return false; } else if (compare < 0) { return true; } } if (moduleRequirement.getPatchLevel() == null) { return true; } if (module.getPatchLevel() == null) { Log.debug("Module " + module.getName() + " does not define a patch level."); } else { if (acceptVersion(moduleRequirement.getPatchLevel(), module.getPatchLevel()) > 0) { Log.debug("Did not accept patchlevel: " + moduleRequirement.getPatchLevel() + " - " + module.getPatchLevel()); return false; } } return true; } /** * Compare the version strings. If the strings have a different length, * the shorter string is padded with spaces to make them compareable. * * @param modVer the version string of the module * @param depModVer the version string of the dependent or optional module * @return 0, if the dependent module version is equal tothe module's required * version, a negative number if the dependent module is newer or a positive * number if the dependent module is older and does not fit. */ private int acceptVersion(final String modVer, final String depModVer) { final int mLength = Math.max(modVer.length(), depModVer.length()); final char[] modVerArray; final char[] depVerArray; if (modVer.length() > depModVer.length()) { modVerArray = modVer.toCharArray(); depVerArray = new char[mLength]; final int delta = modVer.length() - depModVer.length(); Arrays.fill(depVerArray, 0, delta, ' '); System.arraycopy(depVerArray, delta, depModVer.toCharArray(), 0, depModVer.length()); } else if (modVer.length() < depModVer.length()) { depVerArray = depModVer.toCharArray(); modVerArray = new char[mLength]; final char[] b1 = new char[mLength]; final int delta = depModVer.length() - modVer.length(); Arrays.fill(b1, 0, delta, ' '); System.arraycopy(b1, delta, modVer.toCharArray(), 0, modVer.length()); } else { depVerArray = depModVer.toCharArray(); modVerArray = modVer.toCharArray(); } return new String(modVerArray).compareTo(new String(depVerArray)); } /** * Returns the default package configuration. Private report configuration * instances may be inserted here. These inserted configuration can never override * the settings from this package configuration. * * @return the package configuration. */ public PackageConfiguration getPackageConfiguration() { return this.packageConfiguration; } /** * Returns an array of the currently active modules. The module definition * returned contain all known modules, including buggy and unconfigured * instances. * * @return the modules. */ public Module[] getAllModules() { final Module[] mods = new Module[this.modules.size()]; for (int i = 0; i < this.modules.size(); i++) { final PackageState state = (PackageState) this.modules.get(i); mods[i] = state.getModule(); } return mods; } /** * Returns all active modules. This array does only contain modules * which were successfully configured and initialized. * * @return the list of all active modules. */ public Module[] getActiveModules() { final ArrayList mods = new ArrayList(); for (int i = 0; i < this.modules.size(); i++) { final PackageState state = (PackageState) this.modules.get(i); if (state.getState() == PackageState.STATE_INITIALIZED) { mods.add(state.getModule()); } } return (Module[]) mods.toArray(new Module[mods.size()]); } /** * Prints the modules that are used. * * @param p the print stream. */ public void printUsedModules(final PrintStream p) { final Module[] allMods = getAllModules(); final ArrayList activeModules = new ArrayList(); final ArrayList failedModules = new ArrayList(); for (int i = 0; i < allMods.length; i++) { if (isModuleAvailable(allMods[i])) { activeModules.add(allMods[i]); } else { failedModules.add(allMods[i]); } } p.print("Active modules: "); p.println(activeModules.size()); p.println("----------------------------------------------------------"); for (int i = 0; i < activeModules.size(); i++) { final Module mod = (Module) activeModules.get(i); p.print(new PadMessage(mod.getModuleClass(), 70)); p.print(" ["); p.print(mod.getSubSystem()); p.println("]"); p.print(" Version: "); p.print(mod.getMajorVersion()); p.print("-"); p.print(mod.getMinorVersion()); p.print("-"); p.print(mod.getPatchLevel()); p.print(" Producer: "); p.println(mod.getProducer()); p.print(" Description: "); p.println(mod.getDescription()); } } } jcommon-1.0.16/source/org/jfree/base/modules/package.html0000644000175000017500000000102211172030703023211 0ustar twernertwerner Module definitions:

By default the JFreeReport base package and JCommon are included. Additionally the J2SDK package exists in the system by default. A module that requires a specific java version should create a dependency to the module "J2SDK" and set the required version numbers.

Known modules: org.jfree.report.modules.output.csv.CSVModule org.jfree.report.modules.output.xml.XMLModule org.jfree.report.modules.output.base.OutputBaseModule org.jfree.report.modules.output.csv.CSVModule jcommon-1.0.16/source/org/jfree/base/modules/Module.java0000644000175000017500000000745011172030703023033 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------- * Module.java * ----------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: Module.java,v 1.3 2005/10/18 13:14:50 mungady Exp $ * * Changes * ------- * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.base.modules; /** * A module encapsulates optional functionality within a project. Modules can * be used as an easy way to make projects more configurable. *

* The module system provides a controled way to check dependencies and to initialize * the modules in a controlled way. * * @author Thomas Morgner */ public interface Module extends ModuleInfo { /** * Returns an array of all required modules. If one of these modules is missing * or cannot be initialized, the module itself will be not available. * * @return an array of the required modules. */ public ModuleInfo[] getRequiredModules(); /** * Returns an array of optional modules. Missing or invalid modules are non fatal * and will not harm the module itself. * * @return an array of optional module specifications. */ public ModuleInfo[] getOptionalModules(); /** * Initializes the module. Use this method to perform all initial setup operations. * This method is called only once in a modules lifetime. If the initializing cannot * be completed, throw a ModuleInitializeException to indicate the error,. The module * will not be available to the system. * * @param subSystem the subSystem. * * @throws ModuleInitializeException if an error ocurred while initializing the module. */ public void initialize(SubSystem subSystem) throws ModuleInitializeException; /** * Configures the module. This should load the default settings of the module. * * @param subSystem the subSystem. */ public void configure(SubSystem subSystem); /** * Returns a short description of the modules functionality. * * @return a module description. */ public String getDescription(); /** * Returns the name of the module producer. * * @return the producer name */ public String getProducer(); /** * Returns the module name. This name should be a short descriptive handle of the * module. * * @return the module name */ public String getName(); /** * Returns the modules subsystem. If this module is not part of an subsystem * then return the modules name, but never null. * * @return the name of the subsystem. */ public String getSubSystem (); } jcommon-1.0.16/source/org/jfree/base/modules/ModuleInitializeException.java0000644000175000017500000000526411172030703026735 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------ * ModuleInitializeException.java * ------------------------------ * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ModuleInitializeException.java,v 1.2 2005/10/18 13:14:50 mungady Exp $ * * Changes * ------- * 05-Jul-2003 : Initial version * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.base.modules; import org.jfree.util.StackableException; /** * This exception is thrown when the module initialization encountered an * unrecoverable error which prevents the module from being used. * * @author Thomas Morgner */ public class ModuleInitializeException extends StackableException { /** * Creates a ModuleInitializeException with no message and no base * exception. */ public ModuleInitializeException() { // nothing required } /** * Creates a ModuleInitializeException with the given message and base * exception. * * @param s the message * @param e the root exception */ public ModuleInitializeException(final String s, final Exception e) { super(s, e); } /** * Creates a ModuleInitializeException with the given message and no base * exception. * * @param s the exception message */ public ModuleInitializeException(final String s) { super(s); } } jcommon-1.0.16/source/org/jfree/base/modules/ModuleInitializer.java0000644000175000017500000000455011172030703025235 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * ModuleInitializer.java * ---------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ModuleInitializer.java,v 1.2 2005/10/18 13:14:50 mungady Exp $ * * Changes * ------- * 14-Jul-2003 : Initial version * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.base.modules; /** * The module initializer is used to separate the initialization process from * the module definition. An invalid classpath setup or an missing base module * may throw an ClassCastException if the module class references this missing * resource. Separating them is the best way to make sure that the classloader * does not interrupt the module loading process. * * @author Thomas Morgner */ public interface ModuleInitializer { /** * Performs the initalization of the module. * * @throws ModuleInitializeException if an error occurs which prevents the module * from being usable. */ public void performInit() throws ModuleInitializeException; } jcommon-1.0.16/source/org/jfree/base/modules/DefaultModuleInfo.java0000644000175000017500000001577511172030703025165 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * DefaultModuleInfo.java * ---------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: DefaultModuleInfo.java,v 1.2 2005/10/18 13:14:50 mungady Exp $ * * Changes * ------- * 05-Jul-2003 : Initial version * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.base.modules; /** * Provides a default implementation of the module info interface. * * @author Thomas Morgner */ public class DefaultModuleInfo implements ModuleInfo { /** The name of the module class. */ private String moduleClass; /** The major version of the described module. */ private String majorVersion; /** The minor version of the described module. */ private String minorVersion; /** The patchlevel version of the described module. */ private String patchLevel; /** * DefaultConstructor. */ public DefaultModuleInfo() { // nothing required } /** * Creates a new module info an initalizes it with the given values. * * @param moduleClass the class name of the module implementation holding the module * description. * @param majorVersion the modules major version. * @param minorVersion the modules minor version. * @param patchLevel the modules patchlevel. * @throws NullPointerException if the moduleClass is null. */ public DefaultModuleInfo(final String moduleClass, final String majorVersion, final String minorVersion, final String patchLevel) { if (moduleClass == null) { throw new NullPointerException("Module class must not be null."); } this.moduleClass = moduleClass; this.majorVersion = majorVersion; this.minorVersion = minorVersion; this.patchLevel = patchLevel; } /** * Returns the class name of the module described implementation. * * @see ModuleInfo#getModuleClass() * * @return the module class name. */ public String getModuleClass() { return this.moduleClass; } /** * Defines the module class name. * * @param moduleClass the class name of the module implementation. */ public void setModuleClass(final String moduleClass) { if (moduleClass == null) { throw new NullPointerException(); } this.moduleClass = moduleClass; } /** * Returns the major version of the module. This property may be * null to indicate that the module version is not specified. * @see ModuleInfo#getMajorVersion() * * @return the major version. */ public String getMajorVersion() { return this.majorVersion; } /** * Defines the major version of the module. This property may be * null to indicate that the module version is not specified. * @see ModuleInfo#getMajorVersion() * * @param majorVersion the major version. */ public void setMajorVersion(final String majorVersion) { this.majorVersion = majorVersion; } /** * Returns the minor version of the module. This property may be * null to indicate that the module version is not specified. * @see ModuleInfo#getMajorVersion() * * @return the minor version. */ public String getMinorVersion() { return this.minorVersion; } /** * Defines the minor version of the module. This property may be * null to indicate that the module version is not specified. * @see ModuleInfo#getMajorVersion() * * @param minorVersion the minor version. */ public void setMinorVersion(final String minorVersion) { this.minorVersion = minorVersion; } /** * Returns the patch level version of the module. This property may be * null to indicate that the module version is not specified. * @see ModuleInfo#getMajorVersion() * * @return the patch level version. */ public String getPatchLevel() { return this.patchLevel; } /** * Defines the patch level version of the module. This property may be * null to indicate that the module version is not specified. * @see ModuleInfo#getMajorVersion() * * @param patchLevel the patch level version. */ public void setPatchLevel(final String patchLevel) { this.patchLevel = patchLevel; } /** * Two moduleinfos are equal,if they have the same module class. * * @param o the other object to compare. * @return true, if the module points to the same module, false otherwise. */ public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof DefaultModuleInfo)) { return false; } final ModuleInfo defaultModuleInfo = (ModuleInfo) o; if (!this.moduleClass.equals(defaultModuleInfo.getModuleClass())) { return false; } return true; } /** * Computes an hashcode for this module information. * @see java.lang.Object#hashCode() * * @return the hashcode. */ public int hashCode() { final int result; result = this.moduleClass.hashCode(); return result; } /** * Returns a string representation of this module information. * * @see java.lang.Object#toString() * * @return a string describing this class. */ public String toString() { final StringBuffer buffer = new StringBuffer(); buffer.append(getClass().getName()); buffer.append("={ModuleClass="); buffer.append(getModuleClass()); if (getMajorVersion() != null) { buffer.append("; Version="); buffer.append(getMajorVersion()); if (getMinorVersion() != null) { buffer.append("-"); buffer.append(getMinorVersion()); if (getPatchLevel() != null) { buffer.append("_"); buffer.append(getPatchLevel()); } } } buffer.append("}"); return buffer.toString(); } } jcommon-1.0.16/source/org/jfree/base/modules/PackageSorter.java0000644000175000017500000003306111172030703024335 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------ * PackageSorter.java * ------------------ * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: PackageSorter.java,v 1.3 2007/05/15 12:32:15 taqua Exp $ * * Changes * ------- * 02-Sep-2003 : Initial version * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.base.modules; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import org.jfree.util.Log; /** * Compares two modules for order. A module is considered less than an other * module if the module is a required module of the compared module. Modules * are considered equal if they have no relation. *

* When sorting, we match this modules position against all dependent * modules until all positions are stable. Circular references are evil * and are filtered during the module loading process in the package manager. * * @author Thomas Morgner */ public final class PackageSorter { /** * An Internal wrapper class which collects additional information * on the given module. Every module has a position, which is heigher * than the position of all dependent modules. * * @author Thomas Morgner */ private static class SortModule implements Comparable { /** stores the relative position of the module in the global list. */ private int position; /** The package state of the to be matched module. */ private final PackageState state; /** A list of all directly dependent subsystems. */ private ArrayList dependSubsystems; // direct dependencies, indirect ones are handled by the // dependent classes ... /** * Creates a new SortModule for the given package state. * * @param state the package state object, that should be wrapped up * by this class. */ public SortModule(final PackageState state) { this.position = -1; this.state = state; } /** * Returns the list of all dependent subsystems. The list gets defined * when the sorting is started. * * @return the list of all dependent subsystems. */ public ArrayList getDependSubsystems() { return this.dependSubsystems; } /** * Defines a list of dependent subsystems for this module. The list contains * the names of the dependent subsystems as strings. * * @param dependSubsystems a list of all dependent subsystems. */ public void setDependSubsystems(final ArrayList dependSubsystems) { this.dependSubsystems = dependSubsystems; } /** * Returns the current position of this module in the global list. * The position is computed by comparing all positions of all dependent * subsystem modules. * * @return the current module position. */ public int getPosition() { return this.position; } /** * Defines the position of this module in the global list of all * known modules. * * @param position the position. */ public void setPosition(final int position) { this.position = position; } /** * Returns the package state contained in this SortModule. * * @return the package state of this module. */ public PackageState getState() { return this.state; } /** * Returns a basic string representation of this SortModule. This * should be used for debugging purposes only. * @see java.lang.Object#toString() * * @return a string representation of this module. */ public String toString () { final StringBuffer buffer = new StringBuffer(); buffer.append("SortModule: "); buffer.append(this.position); buffer.append(" "); buffer.append(this.state.getModule().getName()); buffer.append(" "); buffer.append(this.state.getModule().getModuleClass()); return buffer.toString(); } /** * Compares this module against an other sort module. * * @see java.lang.Comparable#compareTo(java.lang.Object) * * @param o the other sort module instance. * @return -1 if the other's module position is less than * this modules position, +1 if this module is less than the * other module or 0 if both modules have an equal position in * the list. */ public int compareTo(final Object o) { final SortModule otherModule = (SortModule) o; if (this.position > otherModule.position) { return +1; } if (this.position < otherModule.position) { return -1; } return 0; } } /** * DefaultConstructor. */ private PackageSorter() { // nothing required. } /** * Sorts the given list of package states. The packages * are sorted by their dependencies in a way so that all * dependent packages are placed on lower positions than * the packages which declared the dependency. * * @param modules the list of modules. */ public static void sort (final List modules) { final HashMap moduleMap = new HashMap(); final ArrayList errorModules = new ArrayList(); final ArrayList weightModules = new ArrayList(); for (int i = 0; i < modules.size(); i++) { final PackageState state = (PackageState) modules.get(i); if (state.getState() == PackageState.STATE_ERROR) { errorModules.add (state); } else { final SortModule mod = new SortModule(state); weightModules.add (mod); moduleMap.put(state.getModule().getModuleClass(), mod); } } final SortModule[] weigths = (SortModule[]) weightModules.toArray(new SortModule[weightModules.size()]); for (int i = 0; i < weigths.length; i++) { final SortModule sortMod = weigths[i]; sortMod.setDependSubsystems (collectSubsystemModules(sortMod.getState().getModule(), moduleMap)); } // repeat the computation until all modules have a matching // position. This is not the best algorithm, but it works // and is relativly simple. It will need some optimizations // in the future, but as this is only executed once, we don't // have to care much about it. boolean doneWork = true; while (doneWork) { doneWork = false; for (int i = 0; i < weigths.length; i++) { final SortModule mod = weigths[i]; final int position = searchModulePosition(mod, moduleMap); if (position != mod.getPosition()) { mod.setPosition(position); doneWork = true; } } } Arrays.sort(weigths); modules.clear(); for (int i = 0; i < weigths.length; i++) { modules.add (weigths[i].getState()); } for (int i = 0; i < errorModules.size(); i++) { modules.add (errorModules.get(i)); } } /** * Computes the new module position. This position is computed * according to the dependent modules and subsystems. The returned * position will be higher than the highest dependent module position. * * @param smodule the sort module for that we compute the new positon. * @param moduleMap the map with all modules. * @return the new positon. */ private static int searchModulePosition (final SortModule smodule, final HashMap moduleMap) { final Module module = smodule.getState().getModule(); int position = 0; // check the required modules. Increase our level to at least // one point over the highest dependent module // ignore missing modules. ModuleInfo[] modInfo = module.getOptionalModules(); for (int modPos = 0; modPos < modInfo.length; modPos++) { final String moduleName = modInfo[modPos].getModuleClass(); final SortModule reqMod = (SortModule) moduleMap.get(moduleName); if (reqMod == null) { continue; } if (reqMod.getPosition() >= position) { position = reqMod.getPosition() + 1; } } // check the required modules. Increase our level to at least // one point over the highest dependent module // there are no missing modules here (or the package manager // is invalid) modInfo = module.getRequiredModules(); for (int modPos = 0; modPos < modInfo.length; modPos++) { final String moduleName = modInfo[modPos].getModuleClass(); final SortModule reqMod = (SortModule) moduleMap.get(moduleName); if (reqMod == null) { Log.warn ("Invalid state: Required dependency of '" + moduleName + "' had an error."); continue; } if (reqMod.getPosition() >= position) { position = reqMod.getPosition() + 1; } } // check the subsystem dependencies. This way we make sure // that subsystems are fully initialized before we try to use // them. final String subSystem = module.getSubSystem(); final Iterator it = moduleMap.values().iterator(); while (it.hasNext()) { final SortModule mod = (SortModule) it.next(); // it is evil to compute values on ourself... if (mod.getState().getModule() == module) { // same module ... continue; } final Module subSysMod = mod.getState().getModule(); // if the module we check is part of the same subsystem as // we are, then we dont do anything. Within the same subsystem // the dependencies are computed solely by the direct references. if (subSystem.equals(subSysMod.getSubSystem())) { // same subsystem ... ignore continue; } // does the module from the global list depend on the // subsystem we are part of? // // if yes, we have a relation and may need to adjust the level... if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem())) { // check whether the module is a base module of the given // subsystem. We will not adjust our position in that case, // as this would lead to an infinite loop if (isBaseModule(subSysMod, module) == false) { if (mod.getPosition() >= position) { position = mod.getPosition() + 1; } } } } return position; } /** * Checks, whether a module is a base module of an given module. * * @param mod the module which to check * @param mi the module info of the suspected base module. * @return true, if the given module info describes a base module of the * given module, false otherwise. */ private static boolean isBaseModule(final Module mod, final ModuleInfo mi) { ModuleInfo[] info = mod.getRequiredModules(); for (int i = 0; i < info.length; i++) { if (info[i].getModuleClass().equals(mi.getModuleClass())) { return true; } } info = mod.getOptionalModules(); for (int i = 0; i < info.length; i++) { if (info[i].getModuleClass().equals(mi.getModuleClass())) { return true; } } return false; } /** * Collects all directly dependent subsystems. * * @param childMod the module which to check * @param moduleMap the map of all other modules, keyed by module class. * @return the list of all dependent subsystems. */ private static ArrayList collectSubsystemModules (final Module childMod, final HashMap moduleMap) { final ArrayList collector = new ArrayList(); ModuleInfo[] info = childMod.getRequiredModules(); for (int i = 0; i < info.length; i++) { final SortModule dependentModule = (SortModule) moduleMap.get(info[i].getModuleClass()); if (dependentModule == null) { Log.warn (new Log.SimpleMessage ("A dependent module was not found in the list of known modules.", info[i].getModuleClass())); continue; } collector.add (dependentModule.getState().getModule().getSubSystem()); } info = childMod.getOptionalModules(); for (int i = 0; i < info.length; i++) { final Module dependentModule = (Module) moduleMap.get(info[i].getModuleClass()); if (dependentModule == null) { Log.warn ("A dependent module was not found in the list of known modules."); continue; } collector.add (dependentModule.getSubSystem()); } return collector; } } jcommon-1.0.16/source/org/jfree/base/modules/ModuleInfo.java0000644000175000017500000000573211172030703023650 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * --------------- * ModuleInfo.java * --------------- * (C)opyright 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ModuleInfo.java,v 1.3 2005/10/18 13:14:50 mungady Exp $ * * Changes * ------- * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.base.modules; /** * The Module info class encapsulates metadata about a given module. It holds the * list of dependencies and the module version and description. * * @author Thomas Morgner */ public interface ModuleInfo { /** * Returns the module class of the desired base module. * * @return The module class. */ public String getModuleClass(); /** * Returns the major version of the base module. The string should * contain a compareable character sequence so that higher versions * of the module are considered greater than lower versions. * * @return The major version of the module. */ public String getMajorVersion(); /** * Returns the minor version of the base module. The string should * contain a compareable character sequence so that higher versions * of the module are considered greater than lower versions. * * @return The minor version of the module. */ public String getMinorVersion(); /** * Returns the patchlevel version of the base module. The patch level * should be used to mark bugfixes. The string should * contain a compareable character sequence so that higher versions * of the module are considered greater than lower versions. * * @return The patch level version of the module. */ public String getPatchLevel(); } jcommon-1.0.16/source/org/jfree/base/modules/SubSystem.java0000644000175000017500000000514611172030703023544 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------- * SubSystem.java * -------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: SubSystem.java,v 1.5 2005/10/18 13:14:50 mungady Exp $ * * Changes * ------- * 10-Jul-2003 : Initial version * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.base.modules; import org.jfree.util.Configuration; import org.jfree.util.ExtendedConfiguration; /** * A sub-system holds a separate collection of modules. *

* On a simple level, subsystems can be just libraries. * Libraries offering services need a controlled way to * initialize these services before dependent code starts * using the library. This can be achived by embedding the * library services into an own subsystem. * * @author Thomas Morgner */ public interface SubSystem { /** * Returns the global configuration. * * @return The global configuration. */ public Configuration getGlobalConfig(); /** * Returns the global configuration as ExtendedConfiguration instance. * * @return the extended configuration. */ public ExtendedConfiguration getExtendedConfig (); /** * Returns the package manager. * * @return The package manager. */ public PackageManager getPackageManager(); } jcommon-1.0.16/source/org/jfree/base/modules/AbstractModule.java0000644000175000017500000005304211172030703024515 0ustar twernertwerner/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * AbstractModule.java * ------------------- * (C)opyright 2003, 2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: AbstractModule.java,v 1.7 2008/09/10 09:16:54 mungady Exp $ * * Changes * ------- * 05-Jul-2003 : Initial version * 07-Jun-2004 : Added JCommon header (DG); * */ package org.jfree.base.modules; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.jfree.util.ObjectUtilities; /** * The abstract module provides a default implementation of the module interface. *

* The module can be specified in an external property file. The file name of this * specification defaults to "module.properties". This file is no real property file, * it follows a more complex rule set. *

* Lines starting with '#' are considered comments. * Section headers start at the beginning of the line, section properties * are indented with at least one whitespace. *

* The first section is always the module info and contains the basic module * properties like name, version and a short description. *

*

 * module-info:
 *   name: xls-export-gui
 *   producer: The JFreeReport project - www.jfree.org/jfreereport
 *   description: A dialog component for the Excel table export.
 *   version.major: 0
 *   version.minor: 84
 *   version.patchlevel: 0
 * 
* The properties name, producer and description are simple strings. They may * span multiple lines, but may not contain a colon (':'). * The version properties are integer values. *

* This section may be followed by one or more "depends" sections. These * sections describe the base modules that are required to be active to make this * module work. The package manager will enforce this policy and will deactivate this * module if one of the base modules is missing. *

*

 * depends:
 *   module: org.jfree.report.modules.output.table.xls.XLSTableModule
 *   version.major: 0
 *   version.minor: 84
 * 
*

* The property module references to the module implementation of the module package. * * @author Thomas Morgner */ public abstract class AbstractModule extends DefaultModuleInfo implements Module { /** * The reader helper provides a pushback interface for the reader to read and * buffer complete lines. * @author Thomas Morgner */ private static class ReaderHelper { /** The line buffer containing the last line read. */ private String buffer; /** The reader from which to read the text. */ private final BufferedReader reader; /** * Creates a new reader helper for the given buffered reader. * * @param reader the buffered reader that is the source of the text. */ protected ReaderHelper(final BufferedReader reader) { this.reader = reader; } /** * Checks, whether the reader contains a next line. Returns false if the end * of the stream has been reached. * * @return true, if there is a next line to read, false otherwise. * @throws IOException if an error occures. */ public boolean hasNext() throws IOException { if (this.buffer == null) { this.buffer = readLine(); } return this.buffer != null; } /** * Returns the next line. * * @return the next line. */ public String next() { final String line = this.buffer; this.buffer = null; return line; } /** * Pushes the given line back into the buffer. Only one line can be contained in * the buffer at one time. * * @param line the line that should be pushed back into the buffer. */ public void pushBack(final String line) { this.buffer = line; } /** * Reads the next line skipping all comment lines. * * @return the next line, or null if no line can be read. * @throws IOException if an IO error occures. */ protected String readLine() throws IOException { String line = this.reader.readLine(); while (line != null && (line.length() == 0 || line.startsWith("#"))) { // empty line or comment is ignored line = this.reader.readLine(); } return line; } /** * Closes the reader. * * @throws IOException if an IOError occurs. */ public void close() throws IOException { this.reader.close(); } } /** The list of required modules. */ private ModuleInfo[] requiredModules; /** The list of optional modules. */ private ModuleInfo[] optionalModules; /** The name of the module. */ private String name; /** A short description of the module. */ private String description; /** The name of the module producer. */ private String producer; /** The modules subsystem. */ private String subsystem; /** * Default Constructor. */ public AbstractModule() { setModuleClass(this.getClass().getName()); } /** * Loads the default module description from the file "module.properties". This file * must be in the same package as the implementing class. * * @throws ModuleInitializeException if an error occurs. */ protected void loadModuleInfo() throws ModuleInitializeException { final InputStream in = ObjectUtilities.getResourceRelativeAsStream ("module.properties", getClass()); if (in == null) { throw new ModuleInitializeException ("File 'module.properties' not found in module package."); } loadModuleInfo(in); } /** * Loads the module descriptiong from the given input stream. The module description * must conform to the rules define in the class description. The file must be encoded * with "ISO-8859-1" (like property files). * * @param in the input stream from where to read the file * @throws ModuleInitializeException if an error occurs. */ protected void loadModuleInfo(final InputStream in) throws ModuleInitializeException { if (in == null) { throw new NullPointerException ("Given InputStream is null."); } try { final ArrayList optionalModules = new ArrayList(); final ArrayList dependendModules = new ArrayList(); final ReaderHelper rh = new ReaderHelper(new BufferedReader (new InputStreamReader(in, "ISO-8859-1"))); try { while (rh.hasNext()) { final String lastLineRead = rh.next(); if (lastLineRead.startsWith("module-info:")) { readModuleInfo(rh); } else if (lastLineRead.startsWith("depends:")) { dependendModules.add(readExternalModule(rh)); } else if (lastLineRead.startsWith("optional:")) { optionalModules.add(readExternalModule(rh)); } else { // we dont understand the current line, so we skip it ... // should we throw a parse exception instead? } } } finally { rh.close(); } this.optionalModules = (ModuleInfo[]) optionalModules.toArray(new ModuleInfo[optionalModules.size()]); this.requiredModules = (ModuleInfo[]) dependendModules.toArray(new ModuleInfo[dependendModules.size()]); } catch (IOException ioe) { throw new ModuleInitializeException("Failed to load properties", ioe); } } /** * Reads a multiline value the stream. This will read the stream until * a new key is found or the end of the file is reached. * * @param reader the reader from where to read. * @param firstLine the first line (which was read elsewhere). * @return the complete value, never null * @throws IOException if an IO error occurs. */ private String readValue(final ReaderHelper reader, String firstLine) throws IOException { final StringBuffer b = new StringBuffer(firstLine.trim()); boolean newLine = true; while (isNextLineValueLine(reader)) { firstLine = reader.next(); final String trimedLine = firstLine.trim(); if (trimedLine.length() == 0 && (newLine == false)) { b.append ("\n"); newLine = true; } else { if (newLine == false) { b.append(" "); } b.append(parseValue(trimedLine)); newLine = false; } } return b.toString(); } /** * Checks, whether the next line in the reader is a value line. * * @param reader from where to read the lines. * @return true, if the next line is a value line, false otherwise. * @throws IOException if an IO error occurs. */ private boolean isNextLineValueLine (final ReaderHelper reader) throws IOException { if (reader.hasNext() == false) { return false; } final String firstLine = reader.next(); if (firstLine == null) { return false; } if (parseKey(firstLine) != null) { reader.pushBack(firstLine); return false; } reader.pushBack(firstLine); return true; } /** * Reads the module definition header. This header contains information about * the module itself. * * @param reader the reader from where to read the content. * @throws IOException if an error occures */ private void readModuleInfo(final ReaderHelper reader) throws IOException { while (reader.hasNext()) { final String lastLineRead = reader.next(); if (Character.isWhitespace(lastLineRead.charAt(0)) == false) { // break if the current character is no whitespace ... reader.pushBack(lastLineRead); return; } final String line = lastLineRead.trim(); final String key = parseKey(line); if (key != null) { // parse error: Non data line does not contain a colon final String b = readValue(reader, parseValue(line.trim())); if ("name".equals(key)) { setName(b); } else if ("producer".equals(key)) { setProducer(b); } else if ("description".equals(key)) { setDescription(b); } else if ("subsystem".equals(key)) { setSubSystem(b); } else if ("version.major".equals(key)) { setMajorVersion(b); } else if ("version.minor".equals(key)) { setMinorVersion(b); } else if ("version.patchlevel".equals(key)) { setPatchLevel(b); } } } } /** * Parses an string to find the key section of the line. This section ends with * an colon. * * @param line the line which to parse * @return the key or null if no key is found. */ private String parseKey(final String line) { final int idx = line.indexOf(':'); if (idx == -1) { return null; } return line.substring(0, idx); } /** * Parses the value section of the given line. * * @param line the line that should be parsed * @return the value, never null */ private String parseValue(final String line) { final int idx = line.indexOf(':'); if (idx == -1) { return line; } if ((idx + 1) == line.length()) { return ""; } return line.substring(idx + 1); } /** * Reads an external module description. This describes either an optional or * a required module. * * @param reader the reader from where to read the module * @return the read module, never null * @throws IOException if an error occures. */ private DefaultModuleInfo readExternalModule(final ReaderHelper reader) throws IOException { final DefaultModuleInfo mi = new DefaultModuleInfo(); while (reader.hasNext()) { final String lastLineRead = reader.next(); if (Character.isWhitespace(lastLineRead.charAt(0)) == false) { // break if the current character is no whitespace ... reader.pushBack(lastLineRead); return mi; } final String line = lastLineRead.trim(); final String key = parseKey(line); if (key != null) { final String b = readValue(reader, parseValue(line)); if ("module".equals(key)) { mi.setModuleClass(b); } else if ("version.major".equals(key)) { mi.setMajorVersion(b); } else if ("version.minor".equals(key)) { mi.setMinorVersion(b); } else if ("version.patchlevel".equals(key)) { mi.setPatchLevel(b); } } } return mi; } /** * Returns the name of this module. * * @see Module#getName() * * @return the module name */ public String getName() { return this.name; } /** * Defines the name of the module. * * @param name the module name. */ protected void setName(final String name) { this.name = name; } /** * Returns the module description. * @see Module#getDescription() * * @return the description of the module. */ public String getDescription() { return this.description; } /** * Defines the description of the module. * * @param description the module's desciption. */ protected void setDescription(final String description) { this.description = description; } /** * Returns the producer of the module. * * @see Module#getProducer() * * @return the producer. */ public String getProducer() { return this.producer; } /** * Defines the producer of the module. * * @param producer the producer. */ protected void setProducer(final String producer) { this.producer = producer; } /** * Returns a copy of the required modules array. This array contains all * description of the modules that need to be present to make this module work. * @see Module#getRequiredModules() * * @return an array of all required modules. */ public ModuleInfo[] getRequiredModules() { final ModuleInfo[] retval = new ModuleInfo[this.requiredModules.length]; System.arraycopy(this.requiredModules, 0, retval, 0, this.requiredModules.length); return retval; } /** * Returns a copy of the required modules array. This array contains all * description of the optional modules that may improve the modules functonality. * @see Module#getRequiredModules() * * @return an array of all required modules. */ public ModuleInfo[] getOptionalModules() { final ModuleInfo[] retval = new ModuleInfo[this.optionalModules.length]; System.arraycopy(this.optionalModules, 0, retval, 0, this.optionalModules.length); return retval; } /** * Defines the required module descriptions for this module. * * @param requiredModules the required modules. */ protected void setRequiredModules(final ModuleInfo[] requiredModules) { this.requiredModules = new ModuleInfo[requiredModules.length]; System.arraycopy(requiredModules, 0, this.requiredModules, 0, requiredModules.length); } /** * Defines the optional module descriptions for this module. * * @param optionalModules the optional modules. */ public void setOptionalModules(final ModuleInfo[] optionalModules) { this.optionalModules = new ModuleInfo[optionalModules.length]; System.arraycopy(optionalModules, 0, this.optionalModules, 0, optionalModules.length); } /** * Returns a string representation of this module. * @see java.lang.Object#toString() * * @return the string representation of this module for debugging purposes. */ public String toString() { final StringBuffer buffer = new StringBuffer(); buffer.append("Module : "); buffer.append(getName()); buffer.append("\n"); buffer.append("ModuleClass : "); buffer.append(getModuleClass()); buffer.append("\n"); buffer.append("Version: "); buffer.append(getMajorVersion()); buffer.append("."); buffer.append(getMinorVersion()); buffer.append("."); buffer.append(getPatchLevel()); buffer.append("\n"); buffer.append("Producer: "); buffer.append(getProducer()); buffer.append("\n"); buffer.append("Description: "); buffer.append(getDescription()); buffer.append("\n"); return buffer.toString(); } /** * Tries to load a class to indirectly check for the existence * of a certain library. * * @param name the name of the library class. * @return true, if the class could be loaded, false otherwise. * @deprecated use the method that passes in a context-class. */ protected static boolean isClassLoadable(final String name) { try { final ClassLoader loader = ObjectUtilities.getClassLoader(AbstractModule.class); if (loader == null) { // this should not happen .. If it happens, it measn we dont even have a system-classloader. return false; } loader.loadClass(name); return true; } catch (Exception e) { return false; } } /** * Tries to load a class to indirectly check for the existence * of a certain library. * * @param name the name of the library class. * @param context the context class to get a classloader from. * @return true, if the class could be loaded, false otherwise. */ protected static boolean isClassLoadable(final String name, final Class context) { try { ObjectUtilities.getClassLoader(context).loadClass(name); return true; } catch (Exception e) { return false; } } /** * Configures the module by loading the configuration properties and * adding them to the package configuration. * * @param subSystem the subsystem. */ public void configure(final SubSystem subSystem) { final InputStream in = ObjectUtilities.getResourceRelativeAsStream ("configuration.properties", getClass()); if (in == null) { return; } try { subSystem.getPackageManager().getPackageConfiguration().load(in); } finally { try { in.close(); } catch (IOException e) { // can be ignored ... } } } /** * Tries to load an module initializer and uses this initializer to initialize * the module. * * @param classname the class name of the initializer. * @throws ModuleInitializeException if an error occures * @deprecated Use the method that provides a class-context instead. */ protected void performExternalInitialize(final String classname) throws ModuleInitializeException { try { final ModuleInitializer mi = (ModuleInitializer) ObjectUtilities.loadAndInstantiate(classname, AbstractModule.class, ModuleInitializer.class); if (mi == null) { throw new ModuleInitializeException("Failed to load specified initializer class."); } mi.performInit(); } catch (ModuleInitializeException mie) { throw mie; } catch (Exception e) { throw new ModuleInitializeException("Failed to load specified initializer class.", e); } } /** * ???. * * @param classname ? * @param context ? * @throws ModuleInitializeException */ protected void performExternalInitialize(final String classname, final Class context) throws ModuleInitializeException { try { final ModuleInitializer mi = (ModuleInitializer) ObjectUtilities.loadAndInstantiate(classname, context, ModuleInitializer.class); if (mi == null) { throw new ModuleInitializeException("Failed to load specified initializer class."); } mi.performInit(); } catch (ModuleInitializeException mie) { throw mie; } catch (Exception e) { throw new ModuleInitializeException("Failed to load specified initializer class.", e); } } /** * Returns the modules subsystem. If this module is not part of an subsystem * then return the modules name, but never null. * * @return the name of the subsystem. */ public String getSubSystem() { if (this.subsystem == null) { return getName(); } return this.subsystem; } /** * Defines the subsystem name for this module. * * @param name the new name of the subsystem. */ protected void setSubSystem (final String name) { this.subsystem = name; } } jcommon-1.0.16/source/com/0000755000175000017500000000000011172030703015247 5ustar twernertwernerjcommon-1.0.16/source/com/keypoint/0000755000175000017500000000000011351753320017117 5ustar twernertwernerjcommon-1.0.16/source/com/keypoint/package.html0000644000175000017500000000025111172030703021370 0ustar twernertwerner A package containing the PNG encoder written by J David Eisenberg. jcommon-1.0.16/source/com/keypoint/PngEncoder.java0000644000175000017500000005700611172030703022010 0ustar twernertwernerpackage com.keypoint; import java.awt.Image; import java.awt.image.ImageObserver; import java.awt.image.PixelGrabber; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.CRC32; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; /** * PngEncoder takes a Java Image object and creates a byte string which can be * saved as a PNG file. The Image is presumed to use the DirectColorModel. * *

Thanks to Jay Denny at KeyPoint Software * http://www.keypoint.com/ * who let me develop this code on company time.

* *

You may contact me with (probably very-much-needed) improvements, * comments, and bug fixes at:

* *

david@catcode.com

* *

This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version.

* *

This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details.

* *

You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. A copy of the GNU LGPL may be found at * http://www.gnu.org/copyleft/lesser.html

* * @author J. David Eisenberg * @version 1.5, 19 Oct 2003 * * CHANGES: * -------- * 19-Nov-2002 : CODING STYLE CHANGES ONLY (by David Gilbert for Object * Refinery Limited); * 19-Sep-2003 : Fix for platforms using EBCDIC (contributed by Paulo Soares); * 19-Oct-2003 : Change private fields to protected fields so that * PngEncoderB can inherit them (JDE) * Fixed bug with calculation of nRows * 15-Aug-2008 : Added scrunch.end() in writeImageData() method - see * JFreeChart bug report 2037930 (David Gilbert); */ public class PngEncoder { /** Constant specifying that alpha channel should be encoded. */ public static final boolean ENCODE_ALPHA = true; /** Constant specifying that alpha channel should not be encoded. */ public static final boolean NO_ALPHA = false; /** Constants for filter (NONE). */ public static final int FILTER_NONE = 0; /** Constants for filter (SUB). */ public static final int FILTER_SUB = 1; /** Constants for filter (UP). */ public static final int FILTER_UP = 2; /** Constants for filter (LAST). */ public static final int FILTER_LAST = 2; /** IHDR tag. */ protected static final byte[] IHDR = {73, 72, 68, 82}; /** IDAT tag. */ protected static final byte[] IDAT = {73, 68, 65, 84}; /** IEND tag. */ protected static final byte[] IEND = {73, 69, 78, 68}; /** PHYS tag. */ protected static final byte[] PHYS = {(byte)'p', (byte)'H', (byte)'Y', (byte)'s'}; /** The png bytes. */ protected byte[] pngBytes; /** The prior row. */ protected byte[] priorRow; /** The left bytes. */ protected byte[] leftBytes; /** The image. */ protected Image image; /** The width. */ protected int width; /** The height. */ protected int height; /** The byte position. */ protected int bytePos; /** The maximum position. */ protected int maxPos; /** CRC. */ protected CRC32 crc = new CRC32(); /** The CRC value. */ protected long crcValue; /** Encode alpha? */ protected boolean encodeAlpha; /** The filter type. */ protected int filter; /** The bytes-per-pixel. */ protected int bytesPerPixel; /** The physical pixel dimension : number of pixels per inch on the X axis. */ private int xDpi = 0; /** The physical pixel dimension : number of pixels per inch on the Y axis. */ private int yDpi = 0; /** Used for conversion of DPI to Pixels per Meter. */ static private float INCH_IN_METER_UNIT = 0.0254f; /** * The compression level (1 = best speed, 9 = best compression, * 0 = no compression). */ protected int compressionLevel; /** * Class constructor. */ public PngEncoder() { this(null, false, FILTER_NONE, 0); } /** * Class constructor specifying Image to encode, with no alpha channel * encoding. * * @param image A Java Image object which uses the DirectColorModel * @see java.awt.Image */ public PngEncoder(Image image) { this(image, false, FILTER_NONE, 0); } /** * Class constructor specifying Image to encode, and whether to encode * alpha. * * @param image A Java Image object which uses the DirectColorModel * @param encodeAlpha Encode the alpha channel? false=no; true=yes * @see java.awt.Image */ public PngEncoder(Image image, boolean encodeAlpha) { this(image, encodeAlpha, FILTER_NONE, 0); } /** * Class constructor specifying Image to encode, whether to encode alpha, * and filter to use. * * @param image A Java Image object which uses the DirectColorModel * @param encodeAlpha Encode the alpha channel? false=no; true=yes * @param whichFilter 0=none, 1=sub, 2=up * @see java.awt.Image */ public PngEncoder(Image image, boolean encodeAlpha, int whichFilter) { this(image, encodeAlpha, whichFilter, 0); } /** * Class constructor specifying Image source to encode, whether to encode * alpha, filter to use, and compression level. * * @param image A Java Image object * @param encodeAlpha Encode the alpha channel? false=no; true=yes * @param whichFilter 0=none, 1=sub, 2=up * @param compLevel 0..9 (1 = best speed, 9 = best compression, 0 = no * compression) * @see java.awt.Image */ public PngEncoder(Image image, boolean encodeAlpha, int whichFilter, int compLevel) { this.image = image; this.encodeAlpha = encodeAlpha; setFilter(whichFilter); if (compLevel >= 0 && compLevel <= 9) { this.compressionLevel = compLevel; } } /** * Set the image to be encoded. * * @param image A Java Image object which uses the DirectColorModel * @see java.awt.Image * @see java.awt.image.DirectColorModel */ public void setImage(Image image) { this.image = image; this.pngBytes = null; } /** * Returns the image to be encoded. * * @return The image. */ public Image getImage() { return this.image; } /** * Creates an array of bytes that is the PNG equivalent of the current * image, specifying whether to encode alpha or not. * * @param encodeAlpha boolean false=no alpha, true=encode alpha * @return an array of bytes, or null if there was a problem */ public byte[] pngEncode(boolean encodeAlpha) { byte[] pngIdBytes = {-119, 80, 78, 71, 13, 10, 26, 10}; if (this.image == null) { return null; } this.width = this.image.getWidth(null); this.height = this.image.getHeight(null); /* * start with an array that is big enough to hold all the pixels * (plus filter bytes), and an extra 200 bytes for header info */ this.pngBytes = new byte[((this.width + 1) * this.height * 3) + 200]; /* * keep track of largest byte written to the array */ this.maxPos = 0; this.bytePos = writeBytes(pngIdBytes, 0); //hdrPos = bytePos; writeHeader(); writeResolution(); //dataPos = bytePos; if (writeImageData()) { writeEnd(); this.pngBytes = resizeByteArray(this.pngBytes, this.maxPos); } else { this.pngBytes = null; } return this.pngBytes; } /** * Creates an array of bytes that is the PNG equivalent of the current * image. Alpha encoding is determined by its setting in the constructor. * * @return an array of bytes, or null if there was a problem */ public byte[] pngEncode() { return pngEncode(this.encodeAlpha); } /** * Set the alpha encoding on or off. * * @param encodeAlpha false=no, true=yes */ public void setEncodeAlpha(boolean encodeAlpha) { this.encodeAlpha = encodeAlpha; } /** * Retrieve alpha encoding status. * * @return boolean false=no, true=yes */ public boolean getEncodeAlpha() { return this.encodeAlpha; } /** * Set the filter to use. * * @param whichFilter from constant list */ public void setFilter(int whichFilter) { this.filter = FILTER_NONE; if (whichFilter <= FILTER_LAST) { this.filter = whichFilter; } } /** * Retrieve filtering scheme. * * @return int (see constant list) */ public int getFilter() { return this.filter; } /** * Set the compression level to use. * * @param level the compression level (1 = best speed, 9 = best compression, * 0 = no compression) */ public void setCompressionLevel(int level) { if (level >= 0 && level <= 9) { this.compressionLevel = level; } } /** * Retrieve compression level. * * @return int (1 = best speed, 9 = best compression, 0 = no compression) */ public int getCompressionLevel() { return this.compressionLevel; } /** * Increase or decrease the length of a byte array. * * @param array The original array. * @param newLength The length you wish the new array to have. * @return Array of newly desired length. If shorter than the * original, the trailing elements are truncated. */ protected byte[] resizeByteArray(byte[] array, int newLength) { byte[] newArray = new byte[newLength]; int oldLength = array.length; System.arraycopy(array, 0, newArray, 0, Math.min(oldLength, newLength)); return newArray; } /** * Write an array of bytes into the pngBytes array. * Note: This routine has the side effect of updating * maxPos, the largest element written in the array. * The array is resized by 1000 bytes or the length * of the data to be written, whichever is larger. * * @param data The data to be written into pngBytes. * @param offset The starting point to write to. * @return The next place to be written to in the pngBytes array. */ protected int writeBytes(byte[] data, int offset) { this.maxPos = Math.max(this.maxPos, offset + data.length); if (data.length + offset > this.pngBytes.length) { this.pngBytes = resizeByteArray(this.pngBytes, this.pngBytes.length + Math.max(1000, data.length)); } System.arraycopy(data, 0, this.pngBytes, offset, data.length); return offset + data.length; } /** * Write an array of bytes into the pngBytes array, specifying number of * bytes to write. Note: This routine has the side effect of updating * maxPos, the largest element written in the array. * The array is resized by 1000 bytes or the length * of the data to be written, whichever is larger. * * @param data The data to be written into pngBytes. * @param nBytes The number of bytes to be written. * @param offset The starting point to write to. * @return The next place to be written to in the pngBytes array. */ protected int writeBytes(byte[] data, int nBytes, int offset) { this.maxPos = Math.max(this.maxPos, offset + nBytes); if (nBytes + offset > this.pngBytes.length) { this.pngBytes = resizeByteArray(this.pngBytes, this.pngBytes.length + Math.max(1000, nBytes)); } System.arraycopy(data, 0, this.pngBytes, offset, nBytes); return offset + nBytes; } /** * Write a two-byte integer into the pngBytes array at a given position. * * @param n The integer to be written into pngBytes. * @param offset The starting point to write to. * @return The next place to be written to in the pngBytes array. */ protected int writeInt2(int n, int offset) { byte[] temp = {(byte) ((n >> 8) & 0xff), (byte) (n & 0xff)}; return writeBytes(temp, offset); } /** * Write a four-byte integer into the pngBytes array at a given position. * * @param n The integer to be written into pngBytes. * @param offset The starting point to write to. * @return The next place to be written to in the pngBytes array. */ protected int writeInt4(int n, int offset) { byte[] temp = {(byte) ((n >> 24) & 0xff), (byte) ((n >> 16) & 0xff), (byte) ((n >> 8) & 0xff), (byte) (n & 0xff)}; return writeBytes(temp, offset); } /** * Write a single byte into the pngBytes array at a given position. * * @param b The integer to be written into pngBytes. * @param offset The starting point to write to. * @return The next place to be written to in the pngBytes array. */ protected int writeByte(int b, int offset) { byte[] temp = {(byte) b}; return writeBytes(temp, offset); } /** * Write a PNG "IHDR" chunk into the pngBytes array. */ protected void writeHeader() { int startPos = this.bytePos = writeInt4(13, this.bytePos); this.bytePos = writeBytes(IHDR, this.bytePos); this.width = this.image.getWidth(null); this.height = this.image.getHeight(null); this.bytePos = writeInt4(this.width, this.bytePos); this.bytePos = writeInt4(this.height, this.bytePos); this.bytePos = writeByte(8, this.bytePos); // bit depth this.bytePos = writeByte((this.encodeAlpha) ? 6 : 2, this.bytePos); // direct model this.bytePos = writeByte(0, this.bytePos); // compression method this.bytePos = writeByte(0, this.bytePos); // filter method this.bytePos = writeByte(0, this.bytePos); // no interlace this.crc.reset(); this.crc.update(this.pngBytes, startPos, this.bytePos - startPos); this.crcValue = this.crc.getValue(); this.bytePos = writeInt4((int) this.crcValue, this.bytePos); } /** * Perform "sub" filtering on the given row. * Uses temporary array leftBytes to store the original values * of the previous pixels. The array is 16 bytes long, which * will easily hold two-byte samples plus two-byte alpha. * * @param pixels The array holding the scan lines being built * @param startPos Starting position within pixels of bytes to be filtered. * @param width Width of a scanline in pixels. */ protected void filterSub(byte[] pixels, int startPos, int width) { int offset = this.bytesPerPixel; int actualStart = startPos + offset; int nBytes = width * this.bytesPerPixel; int leftInsert = offset; int leftExtract = 0; for (int i = actualStart; i < startPos + nBytes; i++) { this.leftBytes[leftInsert] = pixels[i]; pixels[i] = (byte) ((pixels[i] - this.leftBytes[leftExtract]) % 256); leftInsert = (leftInsert + 1) % 0x0f; leftExtract = (leftExtract + 1) % 0x0f; } } /** * Perform "up" filtering on the given row. * Side effect: refills the prior row with current row * * @param pixels The array holding the scan lines being built * @param startPos Starting position within pixels of bytes to be filtered. * @param width Width of a scanline in pixels. */ protected void filterUp(byte[] pixels, int startPos, int width) { final int nBytes = width * this.bytesPerPixel; for (int i = 0; i < nBytes; i++) { final byte currentByte = pixels[startPos + i]; pixels[startPos + i] = (byte) ((pixels[startPos + i] - this.priorRow[i]) % 256); this.priorRow[i] = currentByte; } } /** * Write the image data into the pngBytes array. * This will write one or more PNG "IDAT" chunks. In order * to conserve memory, this method grabs as many rows as will * fit into 32K bytes, or the whole image; whichever is less. * * * @return true if no errors; false if error grabbing pixels */ protected boolean writeImageData() { int rowsLeft = this.height; // number of rows remaining to write int startRow = 0; // starting row to process this time through int nRows; // how many rows to grab at a time byte[] scanLines; // the scan lines to be compressed int scanPos; // where we are in the scan lines int startPos; // where this line's actual pixels start (used // for filtering) byte[] compressedLines; // the resultant compressed lines int nCompressed; // how big is the compressed area? //int depth; // color depth ( handle only 8 or 32 ) PixelGrabber pg; this.bytesPerPixel = (this.encodeAlpha) ? 4 : 3; Deflater scrunch = new Deflater(this.compressionLevel); ByteArrayOutputStream outBytes = new ByteArrayOutputStream(1024); DeflaterOutputStream compBytes = new DeflaterOutputStream(outBytes, scrunch); try { while (rowsLeft > 0) { nRows = Math.min(32767 / (this.width * (this.bytesPerPixel + 1)), rowsLeft); nRows = Math.max(nRows, 1); int[] pixels = new int[this.width * nRows]; pg = new PixelGrabber(this.image, 0, startRow, this.width, nRows, pixels, 0, this.width); try { pg.grabPixels(); } catch (Exception e) { System.err.println("interrupted waiting for pixels!"); return false; } if ((pg.getStatus() & ImageObserver.ABORT) != 0) { System.err.println("image fetch aborted or errored"); return false; } /* * Create a data chunk. scanLines adds "nRows" for * the filter bytes. */ scanLines = new byte[this.width * nRows * this.bytesPerPixel + nRows]; if (this.filter == FILTER_SUB) { this.leftBytes = new byte[16]; } if (this.filter == FILTER_UP) { this.priorRow = new byte[this.width * this.bytesPerPixel]; } scanPos = 0; startPos = 1; for (int i = 0; i < this.width * nRows; i++) { if (i % this.width == 0) { scanLines[scanPos++] = (byte) this.filter; startPos = scanPos; } scanLines[scanPos++] = (byte) ((pixels[i] >> 16) & 0xff); scanLines[scanPos++] = (byte) ((pixels[i] >> 8) & 0xff); scanLines[scanPos++] = (byte) ((pixels[i]) & 0xff); if (this.encodeAlpha) { scanLines[scanPos++] = (byte) ((pixels[i] >> 24) & 0xff); } if ((i % this.width == this.width - 1) && (this.filter != FILTER_NONE)) { if (this.filter == FILTER_SUB) { filterSub(scanLines, startPos, this.width); } if (this.filter == FILTER_UP) { filterUp(scanLines, startPos, this.width); } } } /* * Write these lines to the output area */ compBytes.write(scanLines, 0, scanPos); startRow += nRows; rowsLeft -= nRows; } compBytes.close(); /* * Write the compressed bytes */ compressedLines = outBytes.toByteArray(); nCompressed = compressedLines.length; this.crc.reset(); this.bytePos = writeInt4(nCompressed, this.bytePos); this.bytePos = writeBytes(IDAT, this.bytePos); this.crc.update(IDAT); this.bytePos = writeBytes(compressedLines, nCompressed, this.bytePos); this.crc.update(compressedLines, 0, nCompressed); this.crcValue = this.crc.getValue(); this.bytePos = writeInt4((int) this.crcValue, this.bytePos); scrunch.finish(); scrunch.end(); return true; } catch (IOException e) { System.err.println(e.toString()); return false; } } /** * Write a PNG "IEND" chunk into the pngBytes array. */ protected void writeEnd() { this.bytePos = writeInt4(0, this.bytePos); this.bytePos = writeBytes(IEND, this.bytePos); this.crc.reset(); this.crc.update(IEND); this.crcValue = this.crc.getValue(); this.bytePos = writeInt4((int) this.crcValue, this.bytePos); } /** * Set the DPI for the X axis. * * @param xDpi The number of dots per inch */ public void setXDpi(int xDpi) { this.xDpi = Math.round(xDpi / INCH_IN_METER_UNIT); } /** * Get the DPI for the X axis. * * @return The number of dots per inch */ public int getXDpi() { return Math.round(this.xDpi * INCH_IN_METER_UNIT); } /** * Set the DPI for the Y axis. * * @param yDpi The number of dots per inch */ public void setYDpi(int yDpi) { this.yDpi = Math.round(yDpi / INCH_IN_METER_UNIT); } /** * Get the DPI for the Y axis. * * @return The number of dots per inch */ public int getYDpi() { return Math.round(this.yDpi * INCH_IN_METER_UNIT); } /** * Set the DPI resolution. * * @param xDpi The number of dots per inch for the X axis. * @param yDpi The number of dots per inch for the Y axis. */ public void setDpi(int xDpi, int yDpi) { this.xDpi = Math.round(xDpi / INCH_IN_METER_UNIT); this.yDpi = Math.round(yDpi / INCH_IN_METER_UNIT); } /** * Write a PNG "pHYs" chunk into the pngBytes array. */ protected void writeResolution() { if (this.xDpi > 0 && this.yDpi > 0) { final int startPos = this.bytePos = writeInt4(9, this.bytePos); this.bytePos = writeBytes(PHYS, this.bytePos); this.bytePos = writeInt4(this.xDpi, this.bytePos); this.bytePos = writeInt4(this.yDpi, this.bytePos); this.bytePos = writeByte(1, this.bytePos); // unit is the meter. this.crc.reset(); this.crc.update(this.pngBytes, startPos, this.bytePos - startPos); this.crcValue = this.crc.getValue(); this.bytePos = writeInt4((int) this.crcValue, this.bytePos); } } } jcommon-1.0.16/README.txt0000644000175000017500000002134211172030703014671 0ustar twernertwerner********************************************* * THE JCOMMON CLASS LIBRARY: Version 1.0.16 * ********************************************* 17 April 2009. (C)opyright, 2000-2009, by Object Refinery Limited and Contributors. ----------------- 1. INTRODUCTION ----------------- JCommon is a free general purpose Java class library that is used in several projects including JFreeChart and Pentaho Reporting. ***** SPECIAL NOTICE: BOTH JFREECHART AND PENTAHO REPORTING ARE MOVING TOWARDS ELIMINATING THEIR DEPENDENCY ON JCOMMON. AFTER THIS HAPPENS, JCOMMON WILL MOST LIKELY BE "RETIRED". ***** JCommon is licensed, free of charge, under the terms of the GNU Lesser General Public Licence. A copy of the licence is included in the download. The latest version of this class library can be obtained from: http://www.jfree.org/jcommon/ If you have any comments, suggestions or bugs to report, please post a message in the JCommon forum. ----------------- 2. CONTRIBUTORS ----------------- Thanks to the following developers who have contributed code to this class library: Anthony Boulestreau, Jeremy Bowman, J. David Eisenberg, Paul English, Hans-Jurgen Greiner, Bill Kelemen, Arik Levin, Achilleus Mantzios, Thomas Meier, Thomas Morgner, Krzysztof Paz, Andrzej Porebski, Nabuo Tamemasa, Mark Watson and Hari. --------------- 3. TEST CASES --------------- Some test cases have been developed using the JUnit testing framework. These are included with the source code, in the following packages: org.jfree.junit org.jfree.date.junit org.jfree.io.junit org.jfree.text.junit org.jfree.ui.junit org.jfree.util.junit If you want to recompile these packages, you will need the junit.jar file that is included in the 'lib' subdirectory. To find out more about JUnit, please visit: http://www.junit.org/ The current JCommon tests have been written using JUnit 3.8. --------------- 4. WHAT'S NEW --------------- Changes in each version are listed here: 1.0.16: (17-Apr-2009) Fix for bug 2612649, NullPointerException in StrokeChooserPanel. 1.0.15: (19-Dec-2008) New ResourceBundleWrapper class to enable applets to bypass codeBase lookup. Updated Maven specs. 1.0.14: (10-Sep-2008) Workaround added to PngEncoder, bug fix in ShapeList. 1.0.13: (05-Jun-2008) Bug fixes for TextBox and ShapeUtilities. 1.0.12: (02-Nov-2007) Made the resource-loading and classloader selection more robust in cases where the jars were distributed over several classloaders. 1.0.11: (19-Oct-2007) BugFix in the KeyedComboBoxModel causing NullPointerExceptions on MacOS-X; Make sure that all resource-streams that get opened also get safely closed in case of errors. 1.0.10: (21-May-2007) BugFix in the PackageSorter, Window positioning is now multi-screen aware. 1.0.9 : (23-Mar-2007) Serialization fix in TextFragment. 1.0.8 : (11-Dec-2006) Minor bugfixes in the synchronization of the Booting code and the FastStack. 1.0.7 : (03-Dec-2006) Cosmetic fixes for the logging of the PackageManager, ObjectTable implementation allows faster cloning of its contents, minor improvements to the GUI classes. 1.0.6 : (26-Sep-2006) BugFixes in the TextLayoutUtilities, SpreadSheetDate and ResourceBundleSupport classes. 1.0.5 : (29-Jun-2006) BugFixes in the boot code (synchronization added) and WaitingImageObserver (possible deadlock fixed). ObjectUtilities did not handle all cases where a ClassLoader could be null. 1.0.4 : (30-Apr-2006) Date- and NumberCellRenderer did not handle null-values properly. 1.0.3 : (17-Apr-2006) More improvements in the boot process for dependent library hierarchies. 1.0.1 : (10-Feb-2006) This release adds new boot capabilities and fixes some bugs in the XML classes. This version is required for JFreeReport and it is fully backward compatible with the 1.0.x branch. 1.0.0 : (14-Nov-2005) This is the official 1.0.0 release. All future releases in the 1.0.x series will maintain backward compatibility with the 1.0.0 API. 1.0.0-rc1 : (01-Jun-2005) : Update to coincide with JFreeReport 0.8.5-5. JavaDoc update and classloader handling changed. 1.0.0-pre3 : (15-Apr-2005) : Some minor changes in the ResourceBundleSupport to allow the explicit definition of a locale. 1.0.0-pre2 : (04-Mar-2005) : Update to coincide with JFreeReport 0.8.5. Separated the xml-support packages into an own jar file. JFreeChart does not use these classes (except in experimental non-release code). Therefore, JFreeChart needs both libs to build, but only the jcommon.jar library to run. The a more detailed list of changed please have a look at the CHANGELOG.txt file. 1.0.0-pre1 : (29-Nov-2004) : Update to coincide with JFreeChart 1.0.0-pre1. 0.9.7 : (13-Oct-2004) Update to join JFreeReport with latest JFreeChart. 0.9.6 : (10-Sep-2004) Update to coincide with JFreeChart 0.9.21. 0.9.5 : (7-Jun-2004) Update to coincide with JFreeChart 0.9.20. 0.9.4 : (28-May-2004) Update to coincide with JFreeChart 0.9.19. 0.9.3 : (15-Apr-2004) Update to coincide with JFreeChart 0.9.18. 0.9.2 : (26-Mar-2004) Update to coincide with JFreeChart 0.9.17. 0.9.1 : (9-Jan-2004) Update to coincide with JFreeChart 0.9.16. 0.9.0 : (28-Nov-2003) Update to coincide with JFreeChart 0.9.15. 0.8.9 : (17-Nov-2003) Update to coincide with JFreeChart 0.9.14. 0.8.8 : (26-Sep-2003) Update to coincide with JFreeChart 0.9.13. 0.8.7 : (11-Sep-2003) Update to coincide with JFreeChart 0.9.12. 0.8.6 : (8-Aug-2003) Update to coincide with JFreeChart 0.9.11. 0.8.5 : (25-Jul-2003) Transferred some support classes from JFreeChart. 0.8.3 : (16-Jun-2003) XML Parser: error locations are printed in the parse exceptions to make debugging xml files easier. 0.8.2a: (04-Jun-2003) xml parser: configuration interface modified. + Bugfixes ... 0.8.2 : (26-May-2003) xml parser class factory bug fix 0.8.1 : (09-May-2003) Added support for the xml parser and imported some base classes from the JFreeReport project. 0.8.0 : (24-Apr-2003) Renamed all packages from com.jrefinery.* to org.jfree.*. 0.7.3 : (11-Apr-2003) Added serialization for SerialDate and SpreadsheetDate classes. Added a SerialUtilities class. Removed palette classes (now in JFreeChart). Added an attribute to control whether or not a workaround is used for drawing rotated text. 0.7.2 : (6-Feb-2003) Bug fixes and Javadoc updates, incorporated an Ant script to recompile the source files and generate the Javadocs. 0.7.1 : (18-Oct-2002) Bug fixes and Javadoc updates. 0.7.0 : (4-Sep-2002) Moved package (com.jrefinery.data) to JFreeChart project. Bug fixes and Javadoc updates. 0.6.4 : (27-Jun-2002) Added logo to about box. Minor bug fixes (plus JUnit tests) and code tidy up. 0.6.3 : (14-Jun-2002) Bug fixes and Javadoc updates. 0.6.2 : (7-Jun-2002) Added GanttSeriesCollection and supporting classes. Added Polish resource bundle. Minor bug fixes. 0.6.1 : (5-Apr-2002) Added MeterDataset interface and DefaultMeterDataset class. Resource bundles for French, German and Spanish languages. Reinstated the Week class. Minor bugfixes. 0.6.0 : (22-Mar-2002) Changes to the API for the TimePeriod classes, to improve methods that convert to java.util.Date. New DefaultHighLowDataset class. New ResourceBundles for items that require localisation. 0.5.6 : (6-Mar-2002) Bug fix for combined datasets. Additional methods in the TimePeriod class to handle different timezones. Updated About box classes moved to new package com.jrefinery.ui.about. Renamed Files.java --> FileUtilities.java and SerialDates.java --> SerialDateUtilities.java. Added new domain name (http://www.object-refinery.com) in the source headers. 0.5.5 : (15-Feb-2002) Fixed bugs in the constructors for the TimePeriod subclasses. Reversed the order of the parameters in the Month(int, int) constructor. Added methods to Datasets.java to handle stacked data ranges. Fixed bug in CombinedDataset. 0.5.4 : (8-Feb-2002) New WindDataset interface and DefaultWindDataset class. Bug fix for DefaultCategoryDataset. 0.5.3 : (25-Jan-2002) Bug fixes, some minor API changes. 0.5.2 : (10-Dec-2001) Added new combination datasets by Bill Kelemen. Added contributors table to the AboutFrame class. 0.5.1 : (27-Nov-2001) AboutPanel and AboutFrame classes added. 0.5.0 : (21-Nov-2001) PieDataset and DefaultPieDataset classes added. 0.4.2 : (16-Nov-2001) New classes in the com.jrefinery.data.* package, plus some new JUnit test cases. jcommon-1.0.16/licence-LGPL.txt0000644000175000017500000006347611172030703016110 0ustar twernertwerner GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! jcommon-1.0.16/maven-jcommon-project.xml0000644000175000017500000000417611172030703020135 0ustar twernertwerner 3 jcommon JCommon jfree @VERSION@ JFree.org http://www.jfree.org/ 2001 JCommon is a free general purpose Java class library that is used in several projects at www.jfree.org, including JFreeChart and JFreeReport. A free general purpose Java class library. http://www.jfree.org/jcommon/ http://sourceforge.net/tracker/?group_id=15494 scm:cvs:pserver:anonymous@cvs.sourceforge.net:/cvsroot/jfreechart:jcommon http://cvs.sourceforge.net/viewcvs.py/jfreechart/jcommon JFreeChart Developer List jfreechart-dev-request@lists.sourceforge.net?subject=subscribe jfreechart-dev-request@lists.sourceforge.net?subject=unsubscribe http://sourceforge.net/mailarchive/forum.php?forum=jfreechart-dev GNU Lesser General Public Licence http://www.gnu.org/licenses/lgpl.txt repo junit junit 3.7 http://www.junit.org/