Search in sources :

Example 31 with Format

use of java.text.Format in project SimpleFlatMapper by arnaudroger.

the class FieldMapperToAppendableFactory method newFieldMapper.

@Override
@SuppressWarnings("unchecked")
public <S, P> FieldMapper<S, Appendable> newFieldMapper(PropertyMapping<S, P, CsvColumnKey, FieldMapperColumnDefinition<CsvColumnKey>> pm, MappingContextFactoryBuilder builder, MapperBuilderErrorHandler mappingErrorHandler) {
    if (pm == null)
        throw new NullPointerException("pm is null");
    Getter<? super S, ? extends P> getter;
    Getter<?, ?> customGetter = pm.getColumnDefinition().getCustomGetterFrom(pm.getPropertyMeta().getOwnerType());
    if (customGetter != null) {
        getter = (Getter<S, P>) customGetter;
    } else {
        getter = pm.getPropertyMeta().getGetter();
    }
    ColumnDefinition<CsvColumnKey, ?> columnDefinition = pm.getColumnDefinition();
    Type type = pm.getPropertyMeta().getPropertyType();
    if (TypeHelper.isPrimitive(type) && !columnDefinition.has(FormatProperty.class)) {
        if (getter instanceof BooleanGetter) {
            return new BooleanFieldMapper<S, Appendable>((BooleanGetter) getter, new BooleanAppendableSetter(cellWriter));
        } else if (getter instanceof ByteGetter) {
            return new ByteFieldMapper<S, Appendable>((ByteGetter) getter, new ByteAppendableSetter(cellWriter));
        } else if (getter instanceof CharacterGetter) {
            return new CharacterFieldMapper<S, Appendable>((CharacterGetter) getter, new CharacterAppendableSetter(cellWriter));
        } else if (getter instanceof ShortGetter) {
            return new ShortFieldMapper<S, Appendable>((ShortGetter) getter, new ShortAppendableSetter(cellWriter));
        } else if (getter instanceof IntGetter) {
            return new IntFieldMapper<S, Appendable>((IntGetter) getter, new IntegerAppendableSetter(cellWriter));
        } else if (getter instanceof LongGetter) {
            return new LongFieldMapper<S, Appendable>((LongGetter) getter, new LongAppendableSetter(cellWriter));
        } else if (getter instanceof FloatGetter) {
            return new FloatFieldMapper<S, Appendable>((FloatGetter) getter, new FloatAppendableSetter(cellWriter));
        } else if (getter instanceof DoubleGetter) {
            return new DoubleFieldMapper<S, Appendable>((DoubleGetter) getter, new DoubleAppendableSetter(cellWriter));
        }
    }
    Setter<Appendable, ? super P> setter = null;
    if (TypeHelper.isEnum(type) && columnDefinition.has(EnumOrdinalFormatProperty.class)) {
        setter = (Setter) new EnumOrdinalAppendableSetter(cellWriter);
    }
    Format format = null;
    if (columnDefinition.has(FormatProperty.class)) {
        format = columnDefinition.lookFor(FormatProperty.class).format();
    } else if (TypeHelper.areEquals(type, Date.class)) {
        String df = DEFAULT_DATE_FORMAT;
        DateFormatProperty dfp = columnDefinition.lookFor(DateFormatProperty.class);
        if (dfp != null) {
            df = dfp.get();
        }
        format = new SimpleDateFormat(df);
    }
    if (format != null) {
        final Format f = format;
        builder.addSupplier(pm.getColumnKey().getIndex(), new CloneFormatSupplier(f));
        return new FormatingAppender<S>(getter, new MappingContextFormatGetter<S>(pm.getColumnKey().getIndex()), cellWriter);
    }
    if (setter == null) {
        setter = getSetter(pm, cellWriter);
    }
    if (setter == null) {
        Converter<? super P, ? extends CharSequence> converter = converterService.findConverter(pm.getPropertyMeta().getPropertyType(), CharSequence.class, columnDefinition != null ? columnDefinition.properties() : new Object[0]);
        if (converter != null) {
            return new ConvertingAppender<S, P>(getter, converter, cellWriter);
        }
    }
    return new FieldMapperImpl<S, Appendable, P>(getter, setter);
}
Also used : ByteGetter(org.simpleflatmapper.reflect.primitive.ByteGetter) DoubleGetter(org.simpleflatmapper.reflect.primitive.DoubleGetter) LongGetter(org.simpleflatmapper.reflect.primitive.LongGetter) FieldMapperImpl(org.simpleflatmapper.map.fieldmapper.FieldMapperImpl) BooleanGetter(org.simpleflatmapper.reflect.primitive.BooleanGetter) Format(java.text.Format) SimpleDateFormat(java.text.SimpleDateFormat) CharacterGetter(org.simpleflatmapper.reflect.primitive.CharacterGetter) IntFieldMapper(org.simpleflatmapper.map.fieldmapper.IntFieldMapper) CharacterFieldMapper(org.simpleflatmapper.map.fieldmapper.CharacterFieldMapper) FloatGetter(org.simpleflatmapper.reflect.primitive.FloatGetter) BooleanFieldMapper(org.simpleflatmapper.map.fieldmapper.BooleanFieldMapper) ShortGetter(org.simpleflatmapper.reflect.primitive.ShortGetter) EnumOrdinalFormatProperty(org.simpleflatmapper.map.property.EnumOrdinalFormatProperty) Date(java.util.Date) DateFormatProperty(org.simpleflatmapper.map.property.DateFormatProperty) Type(java.lang.reflect.Type) FloatFieldMapper(org.simpleflatmapper.map.fieldmapper.FloatFieldMapper) CsvColumnKey(org.simpleflatmapper.csv.CsvColumnKey) SimpleDateFormat(java.text.SimpleDateFormat) IntGetter(org.simpleflatmapper.reflect.primitive.IntGetter)

Example 32 with Format

use of java.text.Format in project spf4j by zolyfarkas.

the class MessageFormat method subformat.

/**
 * Internal routine used by format. If <code>characterIterators</code> is non-null, AttributedCharacterIterator will
 * be created from the sub-formats as necessary. If <code>characterIterators</code> is null and <code>fp</code> is
 * non-null and identifies <code>Field.MESSAGE_ARGUMENT</code>, the location of the first replaced argument will be
 * set in it.
 *
 * @exception IllegalArgumentException if an argument in the <code>arguments</code> array is not of the type expected
 * by the format element(s) that use it.
 */
// Unfortunately I have no other way to write this
@SuppressFBWarnings({ "PDP_POORLY_DEFINED_PARAMETER", "PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS" })
private <// without code duplication to work for StringBuilder and StringBuffer....
T extends Appendable & CharSequence> T subformat(@Nullable Object[] arguments, @Nonnull T result, @Nullable FieldPosition fp, @Nullable List<AttributedCharacterIterator> characterIterators) throws IOException {
    int lastOffset = 0;
    int last = result.length();
    for (int i = 0; i <= maxOffset; ++i) {
        FormatInfo finfo = formats[i];
        int offset = finfo.getOffset();
        result.append(pattern, lastOffset, offset);
        lastOffset = offset;
        int argumentNumber = finfo.getArgumentNumber();
        if (arguments == null || argumentNumber >= arguments.length) {
            result.append('{').append(Integer.toString(argumentNumber)).append('}');
            continue;
        }
        Object obj = arguments[argumentNumber];
        String arg = null;
        Format subFormatter = null;
        Format fmt = finfo.getFormat();
        if (obj == null) {
            arg = "null";
        } else if (fmt != null) {
            subFormatter = fmt;
            if (subFormatter instanceof ChoiceFormat) {
                arg = subFormatter.format(obj);
                if (arg.indexOf('{') >= 0) {
                    subFormatter = new MessageFormat(arg, locale);
                    obj = arguments;
                    arg = null;
                }
            }
        } else if (obj instanceof Number) {
            // format number if can
            subFormatter = NumberFormat.getInstance(locale);
        } else if (obj instanceof Date) {
            // format a Date if can
            subFormatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, // fix
            locale);
        } else if (obj instanceof String) {
            arg = (String) obj;
        } else {
            arg = obj.toString();
        }
        // or arg is non-null and we should use it as the value.
        if (characterIterators != null) {
            // If characterIterators is non-null, it indicates we need
            // to get the CharacterIterator from the child formatter.
            int cl = result.length();
            if (last != cl) {
                characterIterators.add(createAttributedCharacterIterator(result.subSequence(last, cl).toString()));
                last = cl;
            }
            if (subFormatter != null) {
                AttributedCharacterIterator subIterator = subFormatter.formatToCharacterIterator(obj);
                append(result, subIterator);
                int cl2 = result.length();
                if (last != cl2) {
                    characterIterators.add(createAttributedCharacterIterator(subIterator, java.text.MessageFormat.Field.ARGUMENT, Integer.valueOf(argumentNumber)));
                    last = cl2;
                }
                arg = null;
            }
            if (arg != null && arg.length() > 0) {
                result.append(arg);
                characterIterators.add(createAttributedCharacterIterator(arg, java.text.MessageFormat.Field.ARGUMENT, Integer.valueOf(argumentNumber)));
                last = result.length();
            }
        } else {
            if (subFormatter != null) {
                arg = subFormatter.format(obj);
            }
            last = result.length();
            result.append(arg);
            if (i == 0 && fp != null && java.text.MessageFormat.Field.ARGUMENT.equals(fp.getFieldAttribute())) {
                fp.setBeginIndex(last);
                fp.setEndIndex(result.length());
            }
            last = result.length();
        }
    }
    result.append(pattern, lastOffset, pattern.length());
    if (characterIterators != null && last != result.length()) {
        characterIterators.add(createAttributedCharacterIterator(result.subSequence(last, result.length()).toString()));
    }
    return result;
}
Also used : Format(java.text.Format) SimpleDateFormat(java.text.SimpleDateFormat) NumberFormat(java.text.NumberFormat) DateFormat(java.text.DateFormat) DecimalFormat(java.text.DecimalFormat) ChoiceFormat(java.text.ChoiceFormat) ChoiceFormat(java.text.ChoiceFormat) Date(java.util.Date) AttributedCharacterIterator(java.text.AttributedCharacterIterator) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 33 with Format

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

the class FormComponent method newValidationError.

/**
 * This method is called, when the validation triggered by {@link FormComponent#convertInput()}
 * failed with a {@link ConversionException}, to construct a {@link ValidationError} based on
 * the exception.
 * <p>
 * Override this method to modify the ValidationError object, e.g. add a custom variable for
 * message substitution:
 * <p>
 *
 * <pre>
 * new FormComponent&lt;T&gt;(id)
 * {
 * 	protected ValidationError newValidationError(ConversionException cause)
 * 	{
 * 		return super.newValidationError(cause).setVariable(&quot;foo&quot;, foovalue);
 * 	}
 * };
 * </pre>
 *
 * @param cause
 *            the original cause
 * @return {@link ValidationError}
 */
protected ValidationError newValidationError(ConversionException cause) {
    ValidationError error = new ValidationError(cause.getMessage());
    if (cause.getResourceKey() != null) {
        error.addKey(cause.getResourceKey());
    }
    if (typeName == null) {
        if (cause.getTargetType() != null) {
            error.addKey("ConversionError." + Classes.simpleName(cause.getTargetType()));
        }
        error.addKey("ConversionError");
    } else {
        String simpleName = Classes.simpleName(getType());
        error.addKey("IConverter." + simpleName);
        error.addKey("IConverter");
        error.setVariable("type", simpleName);
    }
    final Locale locale = cause.getLocale();
    if (locale != null) {
        error.setVariable("locale", locale);
    }
    error.setVariable("exception", cause);
    Format format = cause.getFormat();
    if (format instanceof SimpleDateFormat) {
        error.setVariable("format", ((SimpleDateFormat) format).toLocalizedPattern());
    }
    Map<String, Object> variables = cause.getVariables();
    if (variables != null) {
        error.getVariables().putAll(variables);
    }
    return error;
}
Also used : Locale(java.util.Locale) Format(java.text.Format) SimpleDateFormat(java.text.SimpleDateFormat) ValidationError(org.apache.wicket.validation.ValidationError) IValidationError(org.apache.wicket.validation.IValidationError) SimpleDateFormat(java.text.SimpleDateFormat)

Example 34 with Format

use of java.text.Format in project Spark by igniterealtime.

the class BroadcastHistoryFrame method initComponents.

private void initComponents() {
    SearchButton = new javax.swing.JToggleButton();
    DateField = new javax.swing.JFormattedTextField();
    SearchDate = new javax.swing.JLabel();
    Date date = new Date();
    Format formatter = new SimpleDateFormat("yyy-MM");
    String myDate = formatter.format(date);
    DateField.setValue(myDate);
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    JScrollPane panelPane = new JScrollPane(BroadcastHistoryArea);
    SearchDate.setText(Res.getString("label.broadcast.history.search.date"));
    setTitle(Res.getString("title.broadcast.history"));
    try {
        readFromFile(myDate);
    } catch (IOException ex) {
        Log.error("Couldn't read from file" + ex.getMessage() + ex.getStackTrace());
    }
    SearchButton.setText((Res.getString("button.search")));
    SearchButton.addMouseListener(new java.awt.event.MouseAdapter() {

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            SearchButtonMouseClicked(evt);
        }
    });
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(panelPane, javax.swing.GroupLayout.DEFAULT_SIZE, 533, javax.swing.GroupLayout.DEFAULT_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(SearchDate).addComponent(SearchButton).addComponent(DateField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(22, 22, 22)));
    layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(15, 15, 15).addComponent(panelPane, javax.swing.GroupLayout.DEFAULT_SIZE, 350, javax.swing.GroupLayout.DEFAULT_SIZE)).addGroup(layout.createSequentialGroup().addGap(15, 15, 15).addComponent(SearchDate).addGap(10, 10, 10).addComponent(DateField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(10, 10, 10).addComponent(SearchButton))).addContainerGap(15, Short.MAX_VALUE)));
    pack();
    final Rectangle bounds = LayoutSettingsManager.getLayoutSettings().getBroadcastHistoryBounds();
    if (bounds == null || bounds.width <= 0 || bounds.height <= 0) {
        // Use default settings.
        setLocationRelativeTo(null);
    } else {
        setBounds(bounds);
    }
    addComponentListener(new ComponentAdapter() {

        @Override
        public void componentResized(ComponentEvent e) {
            LayoutSettingsManager.getLayoutSettings().setBroadcastHistoryBounds(getBounds());
        }

        @Override
        public void componentMoved(ComponentEvent e) {
            LayoutSettingsManager.getLayoutSettings().setBroadcastHistoryBounds(getBounds());
        }
    });
}
Also used : JScrollPane(javax.swing.JScrollPane) IOException(java.io.IOException) Date(java.util.Date) Format(java.text.Format) SimpleDateFormat(java.text.SimpleDateFormat) ComponentEvent(java.awt.event.ComponentEvent) SimpleDateFormat(java.text.SimpleDateFormat) ComponentAdapter(java.awt.event.ComponentAdapter)

Example 35 with Format

use of java.text.Format in project GenericKnimeNodes by genericworkflownodes.

the class Helper method readFileSummary.

/**
 * Reads the first lines of the file into a string. At maximum maxLines will
 * be read.
 *
 * @param file
 *            The file to read.
 * @param maxLines
 *            The number of maximal lines to read.
 * @return The string containing the first maxLines lines.
 * @throws IOException
 *             if the file does not exist or cannot be opened or read.
 */
public static String readFileSummary(final File file, int maxLines) throws IOException {
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    StringBuffer sb = new StringBuffer();
    try {
        String line = "";
        int cnt = 0;
        sb.append("File path: ").append(file.getAbsolutePath()).append(System.getProperty("line.separator"));
        sb.append("File size: ").append(file.length()).append(" bytes").append(System.getProperty("line.separator"));
        Date date = new Date(file.lastModified());
        Format formatter = new SimpleDateFormat("yyyy.MM.dd HH.mm.ss");
        String s = formatter.format(date);
        sb.append("File time: ").append(s).append(System.getProperty("line.separator"));
        sb.append(String.format("File content (first %d lines):", maxLines)).append(System.getProperty("line.separator"));
        while ((line = br.readLine()) != null) {
            sb.append(line + System.getProperty("line.separator"));
            cnt++;
            if (cnt > maxLines) {
                sb.append("######### OUTPUT TRUNCATED #########").append(System.getProperty("line.separator"));
                break;
            }
        }
    } catch (IOException ex) {
        // close readers
        br.close();
        fr.close();
        // rethrow
        throw ex;
    }
    // close readers
    br.close();
    fr.close();
    return sb.toString();
}
Also used : Format(java.text.Format) SimpleDateFormat(java.text.SimpleDateFormat) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) IOException(java.io.IOException) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

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