Search in sources :

Example 36 with Format

use of java.text.Format in project commons-text by apache.

the class ExtendedMessageFormat method applyPattern.

/**
 * Apply the specified pattern.
 *
 * @param pattern String
 */
@Override
public final void applyPattern(final String pattern) {
    if (registry == null) {
        super.applyPattern(pattern);
        toPattern = super.toPattern();
        return;
    }
    final ArrayList<Format> foundFormats = new ArrayList<>();
    final ArrayList<String> foundDescriptions = new ArrayList<>();
    final StringBuilder stripCustom = new StringBuilder(pattern.length());
    final ParsePosition pos = new ParsePosition(0);
    final char[] c = pattern.toCharArray();
    int fmtCount = 0;
    while (pos.getIndex() < pattern.length()) {
        switch(c[pos.getIndex()]) {
            case QUOTE:
                appendQuotedString(pattern, pos, stripCustom);
                break;
            case START_FE:
                fmtCount++;
                seekNonWs(pattern, pos);
                final int start = pos.getIndex();
                final int index = readArgumentIndex(pattern, next(pos));
                stripCustom.append(START_FE).append(index);
                seekNonWs(pattern, pos);
                Format format = null;
                String formatDescription = null;
                if (c[pos.getIndex()] == START_FMT) {
                    formatDescription = parseFormatDescription(pattern, next(pos));
                    format = getFormat(formatDescription);
                    if (format == null) {
                        stripCustom.append(START_FMT).append(formatDescription);
                    }
                }
                foundFormats.add(format);
                foundDescriptions.add(format == null ? null : formatDescription);
                if (foundFormats.size() != fmtCount) {
                    throw new IllegalArgumentException("The validated expression is false");
                }
                if (foundDescriptions.size() != fmtCount) {
                    throw new IllegalArgumentException("The validated expression is false");
                }
                if (c[pos.getIndex()] != END_FE) {
                    throw new IllegalArgumentException("Unreadable format element at position " + start);
                }
            // $FALL-THROUGH$
            default:
                stripCustom.append(c[pos.getIndex()]);
                next(pos);
        }
    }
    super.applyPattern(stripCustom.toString());
    toPattern = insertFormats(super.toPattern(), foundDescriptions);
    if (containsElements(foundFormats)) {
        final Format[] origFormats = getFormats();
        // only loop over what we know we have, as MessageFormat on Java 1.3
        // seems to provide an extra format element:
        int i = 0;
        for (final Iterator<Format> it = foundFormats.iterator(); it.hasNext(); i++) {
            final Format f = it.next();
            if (f != null) {
                origFormats[i] = f;
            }
        }
        super.setFormats(origFormats);
    }
}
Also used : Format(java.text.Format) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) ParsePosition(java.text.ParsePosition)

Example 37 with Format

use of java.text.Format in project commons-text by apache.

the class CompositeFormatTest method testCompositeFormat.

/**
 * Ensures that the parse/format separation is correctly maintained.
 */
@Test
public void testCompositeFormat() {
    final Format parser = new Format() {

        private static final long serialVersionUID = 1L;

        @Override
        public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
            throw new UnsupportedOperationException("Not implemented");
        }

        @Override
        public Object parseObject(final String source, final ParsePosition pos) {
            // do nothing
            return null;
        }
    };
    final Format formatter = new Format() {

        private static final long serialVersionUID = 1L;

        @Override
        public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
            // do nothing
            return null;
        }

        @Override
        public Object parseObject(final String source, final ParsePosition pos) {
            throw new UnsupportedOperationException("Not implemented");
        }
    };
    final CompositeFormat composite = new CompositeFormat(parser, formatter);
    composite.parseObject("", null);
    composite.format(new Object(), new StringBuffer(), null);
    assertEquals("Parser get method incorrectly implemented", parser, composite.getParser());
    assertEquals("Formatter get method incorrectly implemented", formatter, composite.getFormatter());
}
Also used : Format(java.text.Format) SimpleDateFormat(java.text.SimpleDateFormat) FieldPosition(java.text.FieldPosition) ParsePosition(java.text.ParsePosition) Test(org.junit.Test)

Example 38 with Format

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

the class CoordinateFormat method format.

/**
 * Formats the given coordinate and appends the resulting text to the given stream or buffer.
 *
 * @param  position    the coordinate to format.
 * @param  toAppendTo  where the text is to be appended.
 * @throws IOException if an error occurred while writing to the given appendable.
 */
@Override
@SuppressWarnings("UnnecessaryBoxing")
public void format(final DirectPosition position, final Appendable toAppendTo) throws IOException {
    ArgumentChecks.ensureNonNull("position", position);
    ArgumentChecks.ensureNonNull("toAppendTo", toAppendTo);
    CoordinateReferenceSystem crs = position.getCoordinateReferenceSystem();
    if (crs == null) {
        // May still be null.
        crs = defaultCRS;
    }
    if (crs != lastCRS) {
        initialize(crs);
    }
    /*
         * Standard java.text.Format API can only write into a StringBuffer. If the given Appendable is not a
         * StringBuffer, then we will need to format in a temporary buffer before to copy to the Appendable.
         */
    final StringBuffer destination;
    if (toAppendTo instanceof StringBuffer) {
        destination = (StringBuffer) toAppendTo;
    } else {
        if (buffer == null) {
            buffer = new StringBuffer();
        }
        destination = buffer;
        destination.setLength(0);
    }
    if (dummy == null) {
        dummy = new FieldPosition(0);
    }
    /*
         * The format to use for each ordinate has been computed by 'initialize'.  The format array length
         * should match the number of dimensions in the given position if the DirectPosition is consistent
         * with its CRS, but we will nevertheless verify has a paranoiac check.  If there is no CRS, or if
         * the DirectPosition dimension is (illegally) greater than the CRS dimension, then we will format
         * the ordinate as a number.
         */
    final int dimension = position.getDimension();
    for (int i = 0; i < dimension; i++) {
        double value = position.getOrdinate(i);
        final Object object;
        final Format f;
        if (formats != null && i < formats.length) {
            f = formats[i];
            if (isNegative(i)) {
                value = -value;
            }
            if (toFormatUnit != null) {
                final UnitConverter c = toFormatUnit[i];
                if (c != null) {
                    value = c.convert(value);
                }
            }
            switch(types[i]) {
                default:
                    object = Double.valueOf(value);
                    break;
                case LONGITUDE:
                    object = new Longitude(value);
                    break;
                case LATITUDE:
                    object = new Latitude(value);
                    break;
                case ANGLE:
                    object = new Angle(value);
                    break;
                case DATE:
                    object = new Date(Math.round(value) + epochs[i]);
                    break;
            }
        } else {
            object = value;
            f = getFormat(Number.class);
        }
        /*
             * At this point we got the value to format together with the Format instance to use.
             */
        if (i != 0) {
            toAppendTo.append(separator);
        }
        if (f.format(object, destination, dummy) != toAppendTo) {
            toAppendTo.append(destination);
            destination.setLength(0);
        }
        if (unitSymbols != null && i < unitSymbols.length) {
            final String symbol = unitSymbols[i];
            if (symbol != null) {
                toAppendTo.append(Characters.NO_BREAK_SPACE).append(symbol);
            }
        }
    }
}
Also used : Latitude(org.apache.sis.measure.Latitude) FieldPosition(java.text.FieldPosition) Longitude(org.apache.sis.measure.Longitude) Date(java.util.Date) Format(java.text.Format) SimpleDateFormat(java.text.SimpleDateFormat) NumberFormat(java.text.NumberFormat) DateFormat(java.text.DateFormat) AngleFormat(org.apache.sis.measure.AngleFormat) CompoundFormat(org.apache.sis.io.CompoundFormat) DecimalFormat(java.text.DecimalFormat) Angle(org.apache.sis.measure.Angle) UnitConverter(javax.measure.UnitConverter) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem)

Example 39 with Format

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

the class CoordinateFormat method applyPattern.

/**
 * Sets the pattern for number, angle or date fields.
 * The pattern syntax depends on the {@code valueType} argument:
 *
 * <ul>
 *   <li>If {@code valueType} is {@code Number.class}, then the pattern syntax shall be as described in the
 *     {@link DecimalFormat} class. This pattern may be used for any ordinate to be formatted as plain number,
 *     for example in {@linkplain org.apache.sis.referencing.cs.DefaultCartesianCS Cartesian coordinate system}.</li>
 *   <li>If {@code valueType} is {@code Angle.class}, then the pattern syntax shall be as described in the
 *     {@link AngleFormat} class. This pattern may be used for any ordinate to be formatted as latitude or longitude,
 *     for example in {@linkplain org.apache.sis.referencing.cs.DefaultEllipsoidalCS ellipsoidal coordinate system}.</li>
 *   <li>If {@code valueType} is {@code Date.class}, then the pattern syntax shall be as described in the
 *     {@link SimpleDateFormat} class. This pattern may be used for any ordinate to be formatted as date and time,
 *     for example in {@linkplain org.apache.sis.referencing.cs.DefaultTimeCS time coordinate system}.</li>
 * </ul>
 *
 * @param  valueType  the base type of ordinate values to parse and format:
 *                    {@code Number.class}, {@code Angle.class} or {@code Date.class}.
 * @param  pattern    the pattern as specified in {@link DecimalFormat}, {@link AngleFormat}
 *                    or {@link SimpleDateFormat} javadoc.
 * @return {@code true} if the pattern has been applied, or {@code false} if {@code valueType} does not
 *         specify a known type or if the format associated to that type does not support patterns.
 * @throws IllegalArgumentException if the given pattern is invalid.
 */
public boolean applyPattern(final Class<?> valueType, final String pattern) {
    ArgumentChecks.ensureNonNull("pattern", pattern);
    final Format format = getFormat(valueType);
    if (format instanceof DecimalFormat) {
        ((DecimalFormat) format).applyPattern(pattern);
    } else if (format instanceof SimpleDateFormat) {
        ((SimpleDateFormat) format).applyPattern(pattern);
    } else if (format instanceof AngleFormat) {
        ((AngleFormat) format).applyPattern(pattern);
    } else {
        return false;
    }
    return true;
}
Also used : Format(java.text.Format) SimpleDateFormat(java.text.SimpleDateFormat) NumberFormat(java.text.NumberFormat) DateFormat(java.text.DateFormat) AngleFormat(org.apache.sis.measure.AngleFormat) CompoundFormat(org.apache.sis.io.CompoundFormat) DecimalFormat(java.text.DecimalFormat) DecimalFormat(java.text.DecimalFormat) AngleFormat(org.apache.sis.measure.AngleFormat) SimpleDateFormat(java.text.SimpleDateFormat)

Example 40 with Format

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

the class LocationFormat method createFormat.

/**
 * Creates the format to use for formatting a latitude, longitude or projected coordinate.
 * This method is invoked by {@code format(Location, Appendable)} when first needed.
 *
 * @param  valueType  {@code Angle.class}. {@code Number.class} or {@code Unit.class}.
 * @return a new {@link AngleFormat}, {@link NumberFormat} or {@link UnitFormat} instance
 *         depending on the argument value.
 */
@Override
protected Format createFormat(final Class<?> valueType) {
    final Format f = super.createFormat(valueType);
    if (f instanceof NumberFormat) {
        final NumberFormat nf = (NumberFormat) f;
        nf.setMinimumFractionDigits(0);
        // 1 metre accuracy, assuming lengths in metres.
        nf.setMaximumFractionDigits(0);
    } else if (f instanceof AngleFormat) {
        // 30 metres accuracy.
        ((AngleFormat) f).applyPattern("D°MM′SS″");
    }
    return f;
}
Also used : Format(java.text.Format) UnitFormat(org.apache.sis.measure.UnitFormat) NumberFormat(java.text.NumberFormat) AngleFormat(org.apache.sis.measure.AngleFormat) TabularFormat(org.apache.sis.io.TabularFormat) AngleFormat(org.apache.sis.measure.AngleFormat) NumberFormat(java.text.NumberFormat)

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