sis-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From desruisse...@apache.org
Subject svn commit: r1402735 - in /sis/branches/JDK7/sis-utility/src: main/java/org/apache/sis/io/ test/java/org/apache/sis/io/
Date Sat, 27 Oct 2012 03:29:29 GMT
Author: desruisseaux
Date: Sat Oct 27 03:29:29 2012
New Revision: 1402735

URL: http://svn.apache.org/viewvc?rev=1402735&view=rev
Log:
Make possible to use TableFormatter without dealing with IOException when the output is known
to be a StringBuilder.

Modified:
    sis/branches/JDK7/sis-utility/src/main/java/org/apache/sis/io/FilteredAppendable.java
    sis/branches/JDK7/sis-utility/src/main/java/org/apache/sis/io/TableFormatter.java
    sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/io/FormatterTestCase.java
    sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/io/TableFormatterTest.java

Modified: sis/branches/JDK7/sis-utility/src/main/java/org/apache/sis/io/FilteredAppendable.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK7/sis-utility/src/main/java/org/apache/sis/io/FilteredAppendable.java?rev=1402735&r1=1402734&r2=1402735&view=diff
==============================================================================
--- sis/branches/JDK7/sis-utility/src/main/java/org/apache/sis/io/FilteredAppendable.java
(original)
+++ sis/branches/JDK7/sis-utility/src/main/java/org/apache/sis/io/FilteredAppendable.java
Sat Oct 27 03:29:29 2012
@@ -125,15 +125,15 @@ public abstract class FilteredAppendable
      * given to the previous call of this method. This works only if this method is consistently
      * invoked for every characters.
      */
-    final int toCodePoint(final char c) throws IOException {
+    final int toCodePoint(final char c) {
         final char h = highSurrogate;
         if (h != 0) {
             highSurrogate = 0;
             if (Character.isLowSurrogate(c)) {
                 return Character.toCodePoint(h, c);
-            } else {
-                throw new CharConversionException();
             }
+            // Unpaired surrogate.  This is usually an error, but this not the fault of
+            // this class since we are processing data supplied by the user. Be lenient.
         }
         if (Character.isHighSurrogate(c)) {
             highSurrogate = c;
@@ -203,8 +203,7 @@ public abstract class FilteredAppendable
         if (sequence == null) {
             sequence = "null";
         }
-        append(sequence, 0, sequence.length());
-        return this;
+        return append(sequence, 0, sequence.length());
     }
 
     /**

Modified: sis/branches/JDK7/sis-utility/src/main/java/org/apache/sis/io/TableFormatter.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK7/sis-utility/src/main/java/org/apache/sis/io/TableFormatter.java?rev=1402735&r1=1402734&r2=1402735&view=diff
==============================================================================
--- sis/branches/JDK7/sis-utility/src/main/java/org/apache/sis/io/TableFormatter.java (original)
+++ sis/branches/JDK7/sis-utility/src/main/java/org/apache/sis/io/TableFormatter.java Sat
Oct 27 03:29:29 2012
@@ -23,7 +23,6 @@ import java.util.StringTokenizer;
 import java.io.Flushable;
 import java.io.IOException;
 import org.apache.sis.util.Decorator;
-import org.apache.sis.util.CharSequences;
 import org.apache.sis.util.ArgumentChecks;
 import org.apache.sis.util.resources.Errors;
 
@@ -203,35 +202,47 @@ public class TableFormatter extends Filt
     private boolean skipLF;
 
     /**
-     * Creates a new table formatter with a default column separator. The default is a double
-     * vertical line for the left and right table borders, and a single horizontal line
-     * between the columns.
+     * Sets to {@code true} at construction time if {@link #out} has been created by the
+     * constructor rather than supplied by the user.
+     */
+    private boolean ownOut;
+
+    /**
+     * Creates a new table formatter writing in an internal buffer with a default column
separator.
+     * The default is a vertical double line for the left and right table borders, and a
single
+     * line between the columns.
+     */
+    public TableFormatter() {
+        this(new StringBuilder(256));
+        ownOut = true;
+    }
+
+    /**
+     * Creates a new table formatter writing in an internal buffer with the specified column
separator.
      *
-     * @param out The underlying stream or buffer to write to.
+     * @param separator String to write between columns.
      */
-    public TableFormatter(final Appendable out) {
-        super(out);
-        leftBorder      =  "║ ";
-        rightBorder     = " ║" ;
-        columnSeparator = " │ ";
+    public TableFormatter(final String separator) {
+        this(new StringBuilder(256), separator);
+        ownOut = true;
     }
 
     /**
-     * Creates a new table formatter with the specified amount of spaces as column separator.
+     * Creates a new table formatter writing in the given output with a default column separator.
+     * The default is a vertical double line for the left and right table borders, and a
single
+     * line between the columns.
      *
-     * @param out    The underlying stream or buffer to write to.
-     * @param spaces Amount of white spaces to use as column separator.
+     * @param out The underlying stream or buffer to write to.
      */
-    public TableFormatter(final Appendable out, final int spaces) {
+    public TableFormatter(final Appendable out) {
         super(out);
-        ArgumentChecks.ensurePositive("spaces", spaces);
-        leftBorder      = "";
-        rightBorder     = "";
-        columnSeparator = CharSequences.spaces(spaces);
+        leftBorder      =  "║ ";
+        rightBorder     = " ║" ;
+        columnSeparator = " │ ";
     }
 
     /**
-     * Creates a new table writer with the specified column separator.
+     * Creates a new table formatter writing in the given output with the specified column
separator.
      *
      * @param out The underlying stream or buffer to write to.
      * @param separator String to write between columns.
@@ -434,10 +445,9 @@ public class TableFormatter extends Filt
      * </ul>
      *
      * @param  c Character to write.
-     * @throws IOException If an I/O error occurs.
      */
     @Override
-    public Appendable append(final char c) throws IOException {
+    public TableFormatter append(final char c) {
         final int cp = toCodePoint(c);
         if (!multiLinesCells) {
             if (cp == '\t') {
@@ -464,22 +474,41 @@ public class TableFormatter extends Filt
     }
 
     /**
+     * Appends the specified character sequence.
+     *
+     * @param  sequence The character sequence to append, or {@code null}.
+     * @return A reference to this {@code Appendable}.
+     */
+    @Override
+    public TableFormatter append(CharSequence sequence) {
+        if (sequence == null) {
+            sequence = "null";
+        }
+        return append(sequence, 0, sequence.length());
+    }
+
+    /**
      * Writes a portion of a character sequence. Tabulations and line separators are
      * interpreted as by {@link #append(c)}.
      *
      * @param  sequence The character sequence to be written.
      * @param  start    Index from which to start reading characters.
      * @param  end      Index of the character following the last character to read.
-     * @throws IOException If an I/O error occurs.
      */
     @Override
     @SuppressWarnings("fallthrough")
-    public Appendable append(final CharSequence sequence, int start, int end) throws IOException
{
+    public TableFormatter append(final CharSequence sequence, int start, int end) {
         ArgumentChecks.ensureValidIndexRange(sequence.length(), start, end);
         if (lineSeparator == null) {
             lineSeparator = lineSeparator(sequence, start, end);
         }
-        start = appendSurrogate(sequence, start, end);
+        try {
+            start = appendSurrogate(sequence, start, end);
+        } catch (IOException e) {
+            // Should never happen, because appendSurrogate(…) delegates to append(char)
+            // which is overriden without 'throws IOException' clause in this class.
+            throw new AssertionError(e);
+        }
         if (start != end) {
             if (skipLF && sequence.charAt(start) == '\n') {
                 start++;
@@ -607,7 +636,9 @@ public class TableFormatter extends Filt
             nextLine();
             assert buffer.length() == 0;
         }
-        writeTable();
+        if (!ownOut) {
+            writeTable();
+        }
         cells.clear();
         currentRow    = 0;
         currentColumn = 0;
@@ -621,6 +652,33 @@ public class TableFormatter extends Filt
     }
 
     /**
+     * Returns the content of this {@code TableFormatter} as a string if possible.
+     *
+     * <ul>
+     *   <li>If this {@code TableFormatter} has been created without explicit {@link
Appendable},
+     *       then this method always returns the current table content formatted as a string.</li>
+     *   <li>Otherwise, if {@link #out} implements {@link CharSequence} or is directly
or
+     *       indirectly a wrapper around a {@code CharSequence}, returns its {@code toString()}
+     *       representation. The string will contain this table content only if {@link #flush()}
+     *       has been invoked prior this {@code toString()} method.</li>
+     *   <li>Otherwise returns the localized "<cite>Unavailable content</cite>"
string.</li>
+     * </ul>
+     */
+    @Override
+    public String toString() {
+        if (ownOut) {
+            ((StringBuilder) out).setLength(0);
+            try {
+                writeTable();
+            } catch (IOException e) {
+                // Should never happen because we are writing in a StringBuilder.
+                throw new AssertionError(e);
+            }
+        }
+        return super.toString();
+    }
+
+    /**
      * Writes the table without clearing the {@code TableFormatter} content.
      * Invoking this method many time would result in the same table being
      * repeated.
@@ -741,10 +799,10 @@ public class TableFormatter extends Filt
                             break;
                         }
                         case ALIGN_CENTER: {
-                            final int rightMargin = (cellWidth-textLength)/2;
+                            final int rightMargin = (cellWidth - textLength) / 2;
                             repeat(tabExpander, cell.fill, rightMargin);
                             tabExpander.append(cellText);
-                            repeat(tabExpander, cell.fill, (cellWidth-rightMargin)-textLength);
+                            repeat(tabExpander, cell.fill, (cellWidth - rightMargin) - textLength);
                             break;
                         }
                     }

Modified: sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/io/FormatterTestCase.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/io/FormatterTestCase.java?rev=1402735&r1=1402734&r2=1402735&view=diff
==============================================================================
--- sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/io/FormatterTestCase.java (original)
+++ sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/io/FormatterTestCase.java Sat
Oct 27 03:29:29 2012
@@ -51,7 +51,7 @@ public abstract class FormatterTestCase 
      * Creates a new test case.
      */
     FormatterTestCase() {
-        buffer = new StringBuilder(40);
+        buffer = new StringBuilder(128);
         formatter = buffer;
     }
 

Modified: sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/io/TableFormatterTest.java
URL: http://svn.apache.org/viewvc/sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/io/TableFormatterTest.java?rev=1402735&r1=1402734&r2=1402735&view=diff
==============================================================================
--- sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/io/TableFormatterTest.java
(original)
+++ sis/branches/JDK7/sis-utility/src/test/java/org/apache/sis/io/TableFormatterTest.java
Sat Oct 27 03:29:29 2012
@@ -19,6 +19,7 @@ package org.apache.sis.io;
 import java.io.IOException;
 import org.apache.sis.test.DependsOn;
 import org.apache.sis.util.CharSequencesTest;
+import org.junit.Test;
 
 import static org.junit.Assert.*;
 
@@ -97,4 +98,46 @@ public final strictfp class TableFormatt
                 + "║ Neptune │ Neptune │ 3.883  ║" + lineSeparator
                 + "╚═════════╧═════════╧════════╝"
+ lineSeparator);
     }
+
+    /**
+     * Tests the {@link TableFormatter#toString()} method.
+     * The intend of this test is also to ensure that we can use the API
+     * more easily, without having to deal with {@link IOException}.
+     */
+    @Test
+    public void testToString() { // NO throws IOException
+        /*
+         * First, ensure that TableFormatter.toString() does not
+         * mess with the content of user-supplied Appendable.
+         */
+        testToString(table, "");
+        /*
+         * When TableFormatter is created with its own internal buffer,
+         * then TableFormatter.toString() is allowed to format the table.
+         */
+        testToString(new TableFormatter(),
+                "╔═════════╤═════════╤════════╗\n"
+              + "║ English │ French  │ r.e.d. ║\n"
+              + "╟─────────┼─────────┼────────╢\n"
+              + "║ Mercury │ Mercure │ 0.382  ║\n"
+              + "║ Venus   │ Vénus   │ 0.949  ║\n"
+              + "║ Earth   │ Terre   │ 1.00   ║\n"
+              + "╚═════════╧═════════╧════════╝\n");
+    }
+
+    /**
+     * Helper method for {@link #testToString()}.
+     *
+     * @param table    Where to format the table.
+     * @param expected The expected string representation of the formatted table.
+     */
+    private static void testToString(final TableFormatter table, final String expected) {
+        table.nextLine('═');
+        table.append("English\tFrench\tr.e.d.\n").writeHorizontalSeparator();
+        table.append("Mercury\tMercure\t0.382\n")
+             .append("Venus\tVénus\t0.949\n")
+             .append("Earth\tTerre\t1.00\n")
+             .nextLine('═');
+        assertEquals(expected, table.toString());
+    }
 }



Mime
View raw message