All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cucumber.runtime.xstream.TimeConverter Maven / Gradle / Ivy

There is a newer version: 1.2.6
Show newest version
package cucumber.runtime.xstream;

import cucumber.runtime.ParameterInfo;

import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static java.util.Arrays.asList;

abstract class TimeConverter extends ConverterWithFormat {
    private final List formats = new ArrayList();
    private SimpleDateFormat onlyFormat;

    TimeConverter(Locale locale, Class[] convertibleTypes) {
        super(convertibleTypes);

        // TODO - these are expensive to create. Cache by format+string, or use the XStream DF cache util thingy
        addFormat(DateFormat.SHORT, locale);
        addFormat(DateFormat.MEDIUM, locale);
        addFormat(DateFormat.LONG, locale);
        addFormat(DateFormat.FULL, locale);
    }

    void addFormat(int style, Locale locale) {
        add(DateFormat.getDateInstance(style, locale));
    }

    void add(DateFormat dateFormat) {
        dateFormat.setLenient(false);
        formats.add(dateFormat);
    }

    public List getFormats() {
        return onlyFormat == null ? formats : asList(onlyFormat);
    }

    @Override
    public String toString(Object obj) {
        if (obj instanceof Calendar) {
            obj = ((Calendar) obj).getTime();
        }
        return super.toString(obj);
    }

    @Override
    public void setParameterInfoAndLocale(ParameterInfo parameterInfo, Locale locale) {
        super.setParameterInfoAndLocale(parameterInfo, locale);
        if(parameterInfo.getFormat() != null) {
            onlyFormat = new SimpleDateFormat(parameterInfo.getFormat(), locale);
            onlyFormat.setLenient(false);
        }
    }

    public void removeOnlyFormat() {
        onlyFormat = null;
    }

    public static List getTimeClasses() {
        List classes = new ArrayList();
        classes.add(Date.class);
        classes.add(Calendar.class);
        return classes;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy