001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2017, by Object Refinery Limited and Contributors.
006 *
007 * Project Info:  http://www.jfree.org/jfreechart/index.html
008 *
009 * This library is free software; you can redistribute it and/or modify it
010 * under the terms of the GNU Lesser General Public License as published by
011 * the Free Software Foundation; either version 2.1 of the License, or
012 * (at your option) any later version.
013 *
014 * This library is distributed in the hope that it will be useful, but
015 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017 * License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this library; if not, write to the Free Software
021 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
022 * USA.
023 *
024 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
025 * Other names may be trademarks of their respective owners.]
026 *
027 */
028
029package org.jfree.chart.util;
030
031import java.awt.AlphaComposite;
032import java.awt.BasicStroke;
033import java.awt.Color;
034import java.awt.Composite;
035import java.awt.GradientPaint;
036import java.awt.Paint;
037import java.awt.Shape;
038import java.awt.Stroke;
039import java.awt.geom.Arc2D;
040import java.awt.geom.Ellipse2D;
041import java.awt.geom.GeneralPath;
042import java.awt.geom.Line2D;
043import java.awt.geom.PathIterator;
044import java.awt.geom.Point2D;
045import java.awt.geom.Rectangle2D;
046import java.io.IOException;
047import java.io.ObjectInputStream;
048import java.io.ObjectOutputStream;
049import java.io.Serializable;
050import java.text.AttributedCharacterIterator;
051import java.text.AttributedString;
052import java.text.CharacterIterator;
053import java.util.HashMap;
054import java.util.Map;
055
056/**
057 * A class containing useful utility methods relating to serialization.
058 */
059public class SerialUtils {
060
061    /**
062     * Private constructor prevents object creation.
063     */
064    private SerialUtils() {
065    }
066
067    /**
068     * Returns {@code true} if a class implements {@code Serializable}
069     * and {@code false} otherwise.
070     *
071     * @param c  the class.
072     *
073     * @return A boolean.
074     */
075    public static boolean isSerializable(Class c) {
076        return (Serializable.class.isAssignableFrom(c));
077    }
078
079    /**
080     * Reads a {@code Paint} object that has been serialised by the
081     * {@link #writePaint(Paint, ObjectOutputStream)} method.
082     *
083     * @param stream  the input stream ({@code null} not permitted).
084     *
085     * @return The paint object (possibly {@code null}).
086     *
087     * @throws IOException  if there is an I/O problem.
088     * @throws ClassNotFoundException  if there is a problem loading a class.
089     */
090    public static Paint readPaint(ObjectInputStream stream)
091        throws IOException, ClassNotFoundException {
092
093        if (stream == null) {
094            throw new IllegalArgumentException("Null 'stream' argument.");
095        }
096        Paint result = null;
097        boolean isNull = stream.readBoolean();
098        if (!isNull) {
099            final Class c = (Class) stream.readObject();
100            if (isSerializable(c)) {
101                result = (Paint) stream.readObject();
102            }
103            else if (c.equals(GradientPaint.class)) {
104                float x1 = stream.readFloat();
105                float y1 = stream.readFloat();
106                Color c1 = (Color) stream.readObject();
107                float x2 = stream.readFloat();
108                float y2 = stream.readFloat();
109                Color c2 = (Color) stream.readObject();
110                boolean isCyclic = stream.readBoolean();
111                result = new GradientPaint(x1, y1, c1, x2, y2, c2, isCyclic);
112            }
113        }
114        return result;
115
116    }
117
118    /**
119     * Serialises a {@code Paint} object.
120     *
121     * @param paint  the paint object ({@code null} permitted).
122     * @param stream  the output stream ({@code null} not permitted).
123     *
124     * @throws IOException if there is an I/O error.
125     */
126    public static void writePaint(Paint paint, ObjectOutputStream stream)
127        throws IOException {
128
129        if (stream == null) {
130            throw new IllegalArgumentException("Null 'stream' argument.");
131        }
132        if (paint != null) {
133            stream.writeBoolean(false);
134            stream.writeObject(paint.getClass());
135            if (paint instanceof Serializable) {
136                stream.writeObject(paint);
137            }
138            else if (paint instanceof GradientPaint) {
139                final GradientPaint gp = (GradientPaint) paint;
140                stream.writeFloat((float) gp.getPoint1().getX());
141                stream.writeFloat((float) gp.getPoint1().getY());
142                stream.writeObject(gp.getColor1());
143                stream.writeFloat((float) gp.getPoint2().getX());
144                stream.writeFloat((float) gp.getPoint2().getY());
145                stream.writeObject(gp.getColor2());
146                stream.writeBoolean(gp.isCyclic());
147            }
148        }
149        else {
150            stream.writeBoolean(true);
151        }
152
153    }
154
155    /**
156     * Reads a {@code Stroke} object that has been serialised by the
157     * {@link #writeStroke(Stroke, ObjectOutputStream)} method.
158     *
159     * @param stream  the input stream ({@code null} not permitted).
160     *
161     * @return The stroke object (possibly {@code null}).
162     *
163     * @throws IOException  if there is an I/O problem.
164     * @throws ClassNotFoundException  if there is a problem loading a class.
165     */
166    public static Stroke readStroke(ObjectInputStream stream)
167        throws IOException, ClassNotFoundException {
168
169        if (stream == null) {
170            throw new IllegalArgumentException("Null 'stream' argument.");
171        }
172        Stroke result = null;
173        boolean isNull = stream.readBoolean();
174        if (!isNull) {
175            Class c = (Class) stream.readObject();
176            if (c.equals(BasicStroke.class)) {
177                float width = stream.readFloat();
178                int cap = stream.readInt();
179                int join = stream.readInt();
180                float miterLimit = stream.readFloat();
181                float[] dash = (float[]) stream.readObject();
182                float dashPhase = stream.readFloat();
183                result = new BasicStroke(width, cap, join, miterLimit, dash, 
184                        dashPhase);
185            }
186            else {
187                result = (Stroke) stream.readObject();
188            }
189        }
190        return result;
191
192    }
193
194    /**
195     * Serialises a {@code Stroke} object.  This code handles the
196     * {@code BasicStroke} class which is the only {@code Stroke}
197     * implementation provided by the JDK (and isn't directly
198     * {@code Serializable}).
199     *
200     * @param stroke  the stroke object ({@code null} permitted).
201     * @param stream  the output stream ({@code null} not permitted).
202     *
203     * @throws IOException if there is an I/O error.
204     */
205    public static void writeStroke(Stroke stroke, ObjectOutputStream stream)
206            throws IOException {
207
208        if (stream == null) {
209            throw new IllegalArgumentException("Null 'stream' argument.");
210        }
211        if (stroke != null) {
212            stream.writeBoolean(false);
213            if (stroke instanceof BasicStroke) {
214                BasicStroke s = (BasicStroke) stroke;
215                stream.writeObject(BasicStroke.class);
216                stream.writeFloat(s.getLineWidth());
217                stream.writeInt(s.getEndCap());
218                stream.writeInt(s.getLineJoin());
219                stream.writeFloat(s.getMiterLimit());
220                stream.writeObject(s.getDashArray());
221                stream.writeFloat(s.getDashPhase());
222            } else {
223                stream.writeObject(stroke.getClass());
224                stream.writeObject(stroke);
225            }
226        } else {
227            stream.writeBoolean(true);
228        }
229    }
230
231    /**
232     * Reads a {@code Composite} object that has been serialised by the
233     * {@link #writeComposite(Composite, ObjectOutputStream)}
234     * method.
235     *
236     * @param stream  the input stream ({@code null} not permitted).
237     *
238     * @return The composite object (possibly {@code null}).
239     *
240     * @throws IOException  if there is an I/O problem.
241     * @throws ClassNotFoundException  if there is a problem loading a class.
242     * 
243     * @since 1.0.17
244     */
245    public static Composite readComposite(ObjectInputStream stream)
246            throws IOException, ClassNotFoundException {
247
248        if (stream == null) {
249            throw new IllegalArgumentException("Null 'stream' argument.");
250        }
251        Composite result = null;
252        boolean isNull = stream.readBoolean();
253        if (!isNull) {
254            Class c = (Class) stream.readObject();
255            if (isSerializable(c)) {
256                result = (Composite) stream.readObject();
257            }
258            else if (c.equals(AlphaComposite.class)) {
259                int rule = stream.readInt();
260                float alpha = stream.readFloat();
261                result = AlphaComposite.getInstance(rule, alpha);
262            }
263        }
264        return result;
265
266    }
267
268    /**
269     * Serialises a {@code Composite} object.
270     *
271     * @param composite  the composite object ({@code null} permitted).
272     * @param stream  the output stream ({@code null} not permitted).
273     *
274     * @throws IOException if there is an I/O error.
275     * 
276     * @since 1.0.17
277     */
278    public static void writeComposite(Composite composite, 
279            ObjectOutputStream stream) throws IOException {
280
281        if (stream == null) {
282            throw new IllegalArgumentException("Null 'stream' argument.");
283        }
284        if (composite != null) {
285            stream.writeBoolean(false);
286            stream.writeObject(composite.getClass());
287            if (composite instanceof Serializable) {
288                stream.writeObject(composite);
289            }
290            else if (composite instanceof AlphaComposite) {
291                AlphaComposite ac = (AlphaComposite) composite;
292                stream.writeInt(ac.getRule());
293                stream.writeFloat(ac.getAlpha());
294            }
295        } else {
296            stream.writeBoolean(true);
297        }
298    }
299
300    /**
301     * Reads a {@code Shape} object that has been serialised by the
302     * {@link #writeShape(Shape, ObjectOutputStream)} method.
303     *
304     * @param stream  the input stream ({@code null} not permitted).
305     *
306     * @return The shape object (possibly {@code null}).
307     *
308     * @throws IOException  if there is an I/O problem.
309     * @throws ClassNotFoundException  if there is a problem loading a class.
310     */
311    public static Shape readShape(ObjectInputStream stream)
312        throws IOException, ClassNotFoundException {
313
314        if (stream == null) {
315            throw new IllegalArgumentException("Null 'stream' argument.");
316        }
317        Shape result = null;
318        boolean isNull = stream.readBoolean();
319        if (!isNull) {
320            Class c = (Class) stream.readObject();
321            if (c.equals(Line2D.class)) {
322                double x1 = stream.readDouble();
323                double y1 = stream.readDouble();
324                double x2 = stream.readDouble();
325                double y2 = stream.readDouble();
326                result = new Line2D.Double(x1, y1, x2, y2);
327            }
328            else if (c.equals(Rectangle2D.class)) {
329                double x = stream.readDouble();
330                double y = stream.readDouble();
331                double w = stream.readDouble();
332                double h = stream.readDouble();
333                result = new Rectangle2D.Double(x, y, w, h);
334            }
335            else if (c.equals(Ellipse2D.class)) {
336                double x = stream.readDouble();
337                double y = stream.readDouble();
338                double w = stream.readDouble();
339                double h = stream.readDouble();
340                result = new Ellipse2D.Double(x, y, w, h);
341            }
342            else if (c.equals(Arc2D.class)) {
343                double x = stream.readDouble();
344                double y = stream.readDouble();
345                double w = stream.readDouble();
346                double h = stream.readDouble();
347                double as = stream.readDouble(); // Angle Start
348                double ae = stream.readDouble(); // Angle Extent
349                int at = stream.readInt();       // Arc type
350                result = new Arc2D.Double(x, y, w, h, as, ae, at);
351            }
352            else if (c.equals(GeneralPath.class)) {
353                GeneralPath gp = new GeneralPath();
354                float[] args = new float[6];
355                boolean hasNext = stream.readBoolean();
356                while (!hasNext) {
357                    int type = stream.readInt();
358                    for (int i = 0; i < 6; i++) {
359                        args[i] = stream.readFloat();
360                    }
361                    switch (type) {
362                        case PathIterator.SEG_MOVETO :
363                            gp.moveTo(args[0], args[1]);
364                            break;
365                        case PathIterator.SEG_LINETO :
366                            gp.lineTo(args[0], args[1]);
367                            break;
368                        case PathIterator.SEG_CUBICTO :
369                            gp.curveTo(args[0], args[1], args[2],
370                                    args[3], args[4], args[5]);
371                            break;
372                        case PathIterator.SEG_QUADTO :
373                            gp.quadTo(args[0], args[1], args[2], args[3]);
374                            break;
375                        case PathIterator.SEG_CLOSE :
376                            gp.closePath();
377                            break;
378                        default :
379                            throw new RuntimeException(
380                                    "JFreeChart - No path exists");
381                    }
382                    gp.setWindingRule(stream.readInt());
383                    hasNext = stream.readBoolean();
384                }
385                result = gp;
386            }
387            else {
388                result = (Shape) stream.readObject();
389            }
390        }
391        return result;
392
393    }
394
395    /**
396     * Serialises a {@code Shape} object.
397     *
398     * @param shape  the shape object ({@code null} permitted).
399     * @param stream  the output stream ({@code null} not permitted).
400     *
401     * @throws IOException if there is an I/O error.
402     */
403    public static void writeShape(Shape shape, ObjectOutputStream stream)
404            throws IOException {
405
406        if (stream == null) {
407            throw new IllegalArgumentException("Null 'stream' argument.");
408        }
409        if (shape != null) {
410            stream.writeBoolean(false);
411            if (shape instanceof Line2D) {
412                final Line2D line = (Line2D) shape;
413                stream.writeObject(Line2D.class);
414                stream.writeDouble(line.getX1());
415                stream.writeDouble(line.getY1());
416                stream.writeDouble(line.getX2());
417                stream.writeDouble(line.getY2());
418            }
419            else if (shape instanceof Rectangle2D) {
420                final Rectangle2D rectangle = (Rectangle2D) shape;
421                stream.writeObject(Rectangle2D.class);
422                stream.writeDouble(rectangle.getX());
423                stream.writeDouble(rectangle.getY());
424                stream.writeDouble(rectangle.getWidth());
425                stream.writeDouble(rectangle.getHeight());
426            }
427            else if (shape instanceof Ellipse2D) {
428                final Ellipse2D ellipse = (Ellipse2D) shape;
429                stream.writeObject(Ellipse2D.class);
430                stream.writeDouble(ellipse.getX());
431                stream.writeDouble(ellipse.getY());
432                stream.writeDouble(ellipse.getWidth());
433                stream.writeDouble(ellipse.getHeight());
434            }
435            else if (shape instanceof Arc2D) {
436                final Arc2D arc = (Arc2D) shape;
437                stream.writeObject(Arc2D.class);
438                stream.writeDouble(arc.getX());
439                stream.writeDouble(arc.getY());
440                stream.writeDouble(arc.getWidth());
441                stream.writeDouble(arc.getHeight());
442                stream.writeDouble(arc.getAngleStart());
443                stream.writeDouble(arc.getAngleExtent());
444                stream.writeInt(arc.getArcType());
445            }
446            else if (shape instanceof GeneralPath) {
447                stream.writeObject(GeneralPath.class);
448                final PathIterator pi = shape.getPathIterator(null);
449                final float[] args = new float[6];
450                stream.writeBoolean(pi.isDone());
451                while (!pi.isDone()) {
452                    final int type = pi.currentSegment(args);
453                    stream.writeInt(type);
454                    // TODO: could write this to only stream the values
455                    // required for the segment type
456                    for (int i = 0; i < 6; i++) {
457                        stream.writeFloat(args[i]);
458                    }
459                    stream.writeInt(pi.getWindingRule());
460                    pi.next();
461                    stream.writeBoolean(pi.isDone());
462                }
463            }
464            else {
465                stream.writeObject(shape.getClass());
466                stream.writeObject(shape);
467            }
468        }
469        else {
470            stream.writeBoolean(true);
471        }
472    }
473
474    /**
475     * Reads a {@code Point2D} object that has been serialised by the
476     * {@link #writePoint2D(Point2D, ObjectOutputStream)} method.
477     *
478     * @param stream  the input stream ({@code null} not permitted).
479     *
480     * @return The point object (possibly {@code null}).
481     *
482     * @throws IOException  if there is an I/O problem.
483     */
484    public static Point2D readPoint2D(ObjectInputStream stream)
485            throws IOException {
486
487        if (stream == null) {
488            throw new IllegalArgumentException("Null 'stream' argument.");
489        }
490        Point2D result = null;
491        boolean isNull = stream.readBoolean();
492        if (!isNull) {
493            double x = stream.readDouble();
494            double y = stream.readDouble();
495            result = new Point2D.Double(x, y);
496        }
497        return result;
498
499    }
500
501    /**
502     * Serialises a {@code Point2D} object.
503     *
504     * @param p  the point object ({@code null} permitted).
505     * @param stream  the output stream ({@code null} not permitted).
506     *
507     * @throws IOException if there is an I/O error.
508     */
509    public static void writePoint2D(Point2D p, ObjectOutputStream stream)
510            throws IOException {
511
512        if (stream == null) {
513            throw new IllegalArgumentException("Null 'stream' argument.");
514        }
515        if (p != null) {
516            stream.writeBoolean(false);
517            stream.writeDouble(p.getX());
518            stream.writeDouble(p.getY());
519        }
520        else {
521            stream.writeBoolean(true);
522        }
523    }
524
525    /**
526     * Reads a {@code AttributedString} object that has been serialised by
527     * the {@link #writeAttributedString(AttributedString,
528     * ObjectOutputStream)} method.
529     *
530     * @param stream  the input stream ({@code null} not permitted).
531     *
532     * @return The attributed string object (possibly {@code null}).
533     *
534     * @throws IOException  if there is an I/O problem.
535     * @throws ClassNotFoundException  if there is a problem loading a class.
536     */
537    public static AttributedString readAttributedString(
538            ObjectInputStream stream)
539            throws IOException, ClassNotFoundException {
540
541        if (stream == null) {
542            throw new IllegalArgumentException("Null 'stream' argument.");
543        }
544        AttributedString result = null;
545        final boolean isNull = stream.readBoolean();
546        if (!isNull) {
547            // read string and attributes then create result
548            String plainStr = (String) stream.readObject();
549            result = new AttributedString(plainStr);
550            char c = stream.readChar();
551            int start = 0;
552            while (c != CharacterIterator.DONE) {
553                int limit = stream.readInt();
554                Map atts = (Map) stream.readObject();
555                result.addAttributes(atts, start, limit);
556                start = limit;
557                c = stream.readChar();
558            }
559        }
560        return result;
561    }
562
563    /**
564     * Serialises an {@code AttributedString} object.
565     *
566     * @param as  the attributed string object ({@code null} permitted).
567     * @param stream  the output stream ({@code null} not permitted).
568     *
569     * @throws IOException if there is an I/O error.
570     */
571    public static void writeAttributedString(AttributedString as,
572            ObjectOutputStream stream) throws IOException {
573
574        if (stream == null) {
575            throw new IllegalArgumentException("Null 'stream' argument.");
576        }
577        if (as != null) {
578            stream.writeBoolean(false);
579            AttributedCharacterIterator aci = as.getIterator();
580            // build a plain string from aci
581            // then write the string
582            StringBuffer plainStr = new StringBuffer();
583            char current = aci.first();
584            while (current != CharacterIterator.DONE) {
585                plainStr = plainStr.append(current);
586                current = aci.next();
587            }
588            stream.writeObject(plainStr.toString());
589
590            // then write the attributes and limits for each run
591            current = aci.first();
592            int begin = aci.getBeginIndex();
593            while (current != CharacterIterator.DONE) {
594                // write the current character - when the reader sees that this
595                // is not CharacterIterator.DONE, it will know to read the
596                // run limits and attributes
597                stream.writeChar(current);
598
599                // now write the limit, adjusted as if beginIndex is zero
600                int limit = aci.getRunLimit();
601                stream.writeInt(limit - begin);
602
603                // now write the attribute set
604                Map atts = new HashMap(aci.getAttributes());
605                stream.writeObject(atts);
606                current = aci.setIndex(limit);
607            }
608            // write a character that signals to the reader that all runs
609            // are done...
610            stream.writeChar(CharacterIterator.DONE);
611        }
612        else {
613            // write a flag that indicates a null
614            stream.writeBoolean(true);
615        }
616
617    }
618
619}