Search in sources :

Example 41 with Format

use of java.text.Format in project sis by apache.

the class CompoundFormat method getFormat.

/**
 * Returns the format to use for parsing and formatting values of the given type.
 * This method applies the following algorithm:
 *
 * <ol>
 *   <li>If a format is cached for the given type, return that format.</li>
 *   <li>Otherwise if a format can be {@linkplain #createFormat(Class) created}
 *       for the given type, cache the newly created format and return it.</li>
 *   <li>Otherwise do again the same checks for the {@linkplain Class#getSuperclass() super class}.</li>
 *   <li>If no format can be created, returns {@code null}.</li>
 * </ol>
 *
 * See {@link #createFormat(Class)} for the list of value types recognized by the default
 * {@code CompoundFormat} implementation.
 *
 * @param  valueType  the base type of values to parse or format, or {@code null} if unknown.
 * @return the format to use for parsing and formatting values of the given type or any parent type,
 *         or {@code null} if none.
 */
protected Format getFormat(final Class<?> valueType) {
    Format format = null;
    Map<Class<?>, Format> formats = this.formats;
    for (Class<?> type = valueType; type != null; type = type.getSuperclass()) {
        if (formats != null) {
            format = formats.get(type);
            if (format != null) {
                if (type != valueType) {
                    formats.put(valueType, format);
                }
                break;
            }
        }
        format = createFormat(type);
        if (format != null) {
            if (formats == null) {
                this.formats = formats = new IdentityHashMap<>(4);
            }
            formats.put(type, format);
            break;
        }
    }
    return format;
}
Also used : Format(java.text.Format) UnitFormat(org.apache.sis.measure.UnitFormat) SimpleDateFormat(java.text.SimpleDateFormat) NumberFormat(java.text.NumberFormat) RangeFormat(org.apache.sis.measure.RangeFormat) DateFormat(java.text.DateFormat) AngleFormat(org.apache.sis.measure.AngleFormat) IdentityHashMap(java.util.IdentityHashMap)

Example 42 with Format

use of java.text.Format in project sis by apache.

the class TreeTableFormat method parse.

/**
 * Creates a tree from the given character sequence,
 * or returns {@code null} if the given text does not look like a tree for this method.
 * This method can parse the trees created by the {@code format(…)} methods
 * defined in this class.
 *
 * <div class="section">Parsing rules</div>
 * <ul>
 *   <li>Each node shall be represented by a single line made of two parts, in that order:
 *     <ol>
 *       <li>white spaces and tree drawing characters ({@code '│'}, {@code '├'}, {@code '└'} or {@code '─'});</li>
 *       <li>string representations of node values, separated by the
 *           {@linkplain #getColumnSeparatorPattern() colunm separator}.</li>
 *     </ol>
 *   </li>
 *   <li>The number of spaces and drawing characters before the node values determines the node
 *       indentation. This indentation does not need to be a factor of the {@link #getIndentation()}
 *       value, but must be consistent across all the parsed tree.</li>
 *   <li>The indentation determines the parent of each node.</li>
 *   <li>Parsing stops at first empty line (ignoring whitespaces), or at the end of the given text.</li>
 * </ul>
 *
 * <div class="section">Error index</div>
 * If the given text does not seem to be a tree table, then this method returns {@code null}.
 * Otherwise if parsing started but failed, then:
 *
 * <ul>
 *   <li>{@link ParsePosition#getErrorIndex()} will give the index at the beginning
 *       of line or beginning of cell where the error occurred, and</li>
 *   <li>{@link ParseException#getErrorOffset()} will give either the same value,
 *       or a slightly more accurate value inside the cell.</li>
 * </ul>
 *
 * @param  text  the character sequence for the tree to parse.
 * @param  pos   the position where to start the parsing.
 * @return the parsed tree, or {@code null} if the given character sequence can not be parsed.
 * @throws ParseException if an error occurred while parsing a node value.
 */
@Override
@SuppressWarnings("null")
public TreeTable parse(final CharSequence text, final ParsePosition pos) throws ParseException {
    final Matcher matcher = getColumnSeparatorMatcher(text);
    final int length = text.length();
    int indexOfLineStart = pos.getIndex();
    // Current index in the 'indentations' array.
    int indentationLevel = 0;
    // Number of spaces (ignoring drawing characters) for each level.
    int[] indentations = new int[16];
    // Last parsed node, having 'indentation[level]' characters before its content.
    TreeTable.Node lastNode = null;
    // First node found while parsing.
    TreeTable.Node root = null;
    final DefaultTreeTable table = new DefaultTreeTable(columnIndices != null ? columnIndices : TableColumn.NAME_MAP);
    final TableColumn<?>[] columns = DefaultTreeTable.getColumns(table.columnIndices);
    final Format[] formats = getFormats(columns, true);
    do {
        final int startNextLine = CharSequences.indexOfLineStart(text, 1, indexOfLineStart);
        int endOfLine = startNextLine;
        while (endOfLine > indexOfLineStart) {
            final int c = text.charAt(endOfLine - 1);
            if (c != '\r' && c != '\n')
                break;
            // Skip trailing '\r' and '\n'.
            endOfLine--;
        }
        /*
             * Skip leading spaces using Character.isSpaceChar(…) instead than isWhitespace(…)
             * because we need to skip non-breaking spaces as well as ordinary space. We don't
             * need to consider line feeds since they were handled by the lines just above.
             */
        boolean hasChar = false;
        // The indentation of current line.
        int i;
        for (i = indexOfLineStart; i < endOfLine; ) {
            final int c = Character.codePointAt(text, i);
            if (!Character.isSpaceChar(c)) {
                hasChar = true;
                if ("─│└├".indexOf(c) < 0) {
                    break;
                }
            }
            i += Character.charCount(c);
        }
        if (!hasChar) {
            // The line contains only whitespaces.
            break;
        }
        /*
             * Go back to the fist non-space character (should be '─'). We do that in case the
             * user puts some spaces in the text of the node label, since we don't want those
             * user-spaces to interfer with the calculation of indentation.
             */
        int indexOfValue = i;
        i = CharSequences.skipTrailingWhitespaces(text, indexOfLineStart, i) - indexOfLineStart;
        /*
             * Found the first character which is not part of the indentation. Create a new root
             * (without parent for now) and parse the values for each column. Columns with empty
             * text are not parsed (the value is left to null).
             */
        final TreeTable.Node node = new DefaultTreeTable.Node(table);
        matcher.region(indexOfValue, endOfLine);
        for (int ci = 0; ci < columns.length; ci++) {
            final boolean found = matcher.find();
            int endOfColumn = found ? matcher.start() : endOfLine;
            indexOfValue = CharSequences.skipLeadingWhitespaces(text, indexOfValue, endOfColumn);
            int endOfValue = CharSequences.skipTrailingWhitespaces(text, indexOfValue, endOfColumn);
            if (endOfValue > indexOfValue) {
                final String valueText = text.subSequence(indexOfValue, endOfValue).toString();
                try {
                    parseValue(node, columns[ci], formats[ci], valueText);
                } catch (ParseException | ClassCastException e) {
                    // See method javadoc.
                    pos.setErrorIndex(indexOfValue);
                    if (e instanceof ParseException) {
                        indexOfValue += ((ParseException) e).getErrorOffset();
                    }
                    throw new LocalizedParseException(getDisplayLocale(), Errors.Keys.UnparsableStringForClass_2, new Object[] { columns[ci].getElementType(), valueText }, indexOfValue).initCause(e);
                }
            }
            if (!found)
                break;
            /*
                 * The end of this column will be the beginning of the next column,
                 * after skipping the last character of the column separator.
                 */
            indexOfValue = matcher.end();
        }
        /*
             * If this is the first node created so far, it will be the root.
             */
        if (root == null) {
            indentations[0] = i;
            root = node;
        } else {
            int p;
            while (i < (p = indentations[indentationLevel])) {
                /*
                     * Lower indentation level: go up in the tree until we find the new parent.
                     * Note that lastNode.getParent() should never return null, since only the
                     * node at 'indentationLevel == 0' has a null parent and we check that case.
                     */
                if (--indentationLevel < 0) {
                    pos.setErrorIndex(indexOfLineStart);
                    throw new LocalizedParseException(getDisplayLocale(), Errors.Keys.NodeHasNoParent_1, new Object[] { node }, indexOfLineStart);
                }
                lastNode = lastNode.getParent();
            }
            if (i == p) {
                /*
                     * The node we just created is a sibling of the previous node. This is
                     * illegal if level==0, in which case we have no parent. Otherwise add
                     * the sibling to the common parent and let the indentation level unchanged.
                     */
                final TreeTable.Node parent = lastNode.getParent();
                if (parent == null) {
                    pos.setErrorIndex(indexOfLineStart);
                    throw new LocalizedParseException(getDisplayLocale(), Errors.Keys.NodeHasNoParent_1, new Object[] { node }, indexOfLineStart);
                }
                parent.getChildren().add(node);
            } else if (i > p) {
                /*
                     * The node we just created is a child of the previous node.
                     * Add a new indentation level.
                     */
                lastNode.getChildren().add(node);
                if (++indentationLevel == indentations.length) {
                    indentations = Arrays.copyOf(indentations, indentationLevel * 2);
                }
                indentations[indentationLevel] = i;
            }
        }
        lastNode = node;
        indexOfLineStart = startNextLine;
    } while (indexOfLineStart != length);
    if (root == null) {
        return null;
    }
    pos.setIndex(indexOfLineStart);
    table.setRoot(root);
    return table;
}
Also used : Matcher(java.util.regex.Matcher) InternationalString(org.opengis.util.InternationalString) Format(java.text.Format) CompoundFormat(org.apache.sis.io.CompoundFormat) TabularFormat(org.apache.sis.io.TabularFormat) LocalizedParseException(org.apache.sis.internal.util.LocalizedParseException) ParseException(java.text.ParseException) LocalizedParseException(org.apache.sis.internal.util.LocalizedParseException)

Example 43 with Format

use of java.text.Format in project Eidolons by IDemiurge.

the class TimeMaster method getMonthName.

// String[] monthName = { "January", "February", "March", "April", "May",
// "June", "July",
// "August", "September", "October", "November", "December" };
// 
// Calendar cal = Calendar.getInstance();
// String month = monthName[cal.get(Calendar.MONTH)];
public static String getMonthName() {
    Format formatter = new SimpleDateFormat("MMMM");
    String s = formatter.format(new Date());
    return s;
// switch(getMonth()+1){
// case 1:
// return "January";
// }
// return null;
}
Also used : Format(java.text.Format) SimpleDateFormat(java.text.SimpleDateFormat) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 44 with Format

use of java.text.Format in project directory-ldap-api by apache.

the class FilterEncoder method format.

/**
 * Formats a filter and handles encoding of special characters in the value arguments using the
 * &lt;valueencoding&gt; rule as described in <a href="http://www.ietf.org/rfc/rfc4515.txt">RFC 4515</a>.
 * <p>
 * Example of filter template format: <code>(&amp;(cn={0})(uid={1}))</code>
 *
 * @param filterTemplate the filter with placeholders
 * @param values the values to encode and substitute
 * @return the formatted filter with escaped values
 * @throws IllegalArgumentException if the number of values does not match the number of placeholders in the template
 */
public static String format(String filterTemplate, String... values) {
    if (values == null) {
        values = Strings.EMPTY_STRING_ARRAY;
    }
    MessageFormat mf = new MessageFormat(filterTemplate, Locale.ROOT);
    // check element count and argument count
    Format[] formats = mf.getFormatsByArgumentIndex();
    if (formats.length != values.length) {
        throw new IllegalArgumentException(I18n.err(I18n.ERR_13300_BAD_PLACE_HOLDERS_NUMBER, filterTemplate, formats.length, values.length));
    }
    // encode arguments
    for (int i = 0; i < values.length; i++) {
        values[i] = encodeFilterValue(values[i]);
    }
    // format the filter
    return mf.format(values);
}
Also used : Format(java.text.Format) MessageFormat(java.text.MessageFormat) MessageFormat(java.text.MessageFormat)

Example 45 with Format

use of java.text.Format in project portfolio by buchen.

the class ISINFieldTest method testPartialMatch.

@Test
public void testPartialMatch() throws ParseException {
    ISINField field = new ISINField(Messages.CSVColumn_ISIN);
    Format format = field.createFormat(Arrays.asList(new Security("SAP", "DE0007164600", "SAP.DE", QuoteFeed.MANUAL)));
    assertThat(format.parseObject("Zins/Dividende ISIN DE0007164600 SAP SE O."), is("DE0007164600"));
    assertThat(format.parseObject("ISIN DE0007164600"), is("DE0007164600"));
}
Also used : Format(java.text.Format) ISINField(name.abuchen.portfolio.datatransfer.csv.CSVImporter.ISINField) Security(name.abuchen.portfolio.model.Security) Test(org.junit.Test)

Aggregations

Format (java.text.Format)146 SimpleDateFormat (java.text.SimpleDateFormat)60 DecimalFormat (java.text.DecimalFormat)39 Test (org.junit.Test)38 DateFormat (java.text.DateFormat)34 NumberFormat (java.text.NumberFormat)29 DateTimeFormatter (java.time.format.DateTimeFormatter)27 Date (java.util.Date)26 ChoiceFormat (java.text.ChoiceFormat)24 ParsePosition (java.text.ParsePosition)22 MessageFormat (java.text.MessageFormat)20 FieldPosition (java.text.FieldPosition)16 Test (org.testng.annotations.Test)16 IOException (java.io.IOException)14 ParseException (java.text.ParseException)11 Locale (java.util.Locale)10 AttributedString (java.text.AttributedString)9 ArrayList (java.util.ArrayList)9 TemporalAccessor (java.time.temporal.TemporalAccessor)7 Calendar (java.util.Calendar)7