Project

General

Profile

Revision 6cc0be7e

ID6cc0be7e64296574192e6e197067bc4f62d77d24
Parent 2921c66d
Child 5367d5aa

Added by Andreas Kohlbecker over 2 years ago

ref #6169 JodaTimePartialConverter support for multiple formats

View differences:

src/main/java/eu/etaxonomy/cdm/vaadin/component/PartialDateField.java
25 25
 */
26 26
public class PartialDateField extends TextField {
27 27

  
28
    JodaTimePartialConverter.DateFormat format = JodaTimePartialConverter.DateFormat.DAY_MONTH_YEAR_DOT;
29

  
28 30
    /**
29 31
     *
30 32
     */
31 33
    public PartialDateField() {
32 34
        super();
33
        setConverter(new JodaTimePartialConverter());
35
        setConverter(new JodaTimePartialConverter(format));
34 36
    }
35 37

  
36 38
    /**
......
38 40
     */
39 41
    public PartialDateField(Property dataSource) {
40 42
        super(dataSource);
41
        setConverter(new JodaTimePartialConverter());
43
        setConverter(new JodaTimePartialConverter(format));
42 44
    }
43 45

  
44 46
    /**
......
47 49
     */
48 50
    public PartialDateField(String caption, Property dataSource) {
49 51
        super(caption, dataSource);
50
        setConverter(new JodaTimePartialConverter());
52
        setConverter(new JodaTimePartialConverter(format));
51 53
    }
52 54

  
53 55
    /**
......
56 58
     */
57 59
    public PartialDateField(String caption, String value) {
58 60
        super(caption, value);
59
        setConverter(new JodaTimePartialConverter());
61
        setConverter(new JodaTimePartialConverter(format));
60 62
    }
61 63

  
62 64
    /**
......
64 66
     */
65 67
    public PartialDateField(String caption) {
66 68
        super(caption);
67
        setConverter(new JodaTimePartialConverter());
69
        setConverter(new JodaTimePartialConverter(format));
68 70
    }
69 71

  
70 72

  
src/main/java/eu/etaxonomy/cdm/vaadin/component/TimePeriodField.java
73 73
        parseField.addTextChangeListener(e -> parseInput(e));
74 74

  
75 75
        PartialDateField startDate = new PartialDateField("Start");
76
        startDate.setInputPrompt("dd.mm.yyy");
76 77
        PartialDateField endDate = new PartialDateField("End");
78
        endDate.setInputPrompt("dd.mm.yyy");
77 79
        freeText = new TextField("FreeText");
78 80
        freeText.setWidth(100, Unit.PERCENTAGE);
79 81

  
src/main/java/eu/etaxonomy/cdm/vaadin/util/converter/JodaTimePartialConverter.java
8 8
*/
9 9
package eu.etaxonomy.cdm.vaadin.util.converter;
10 10

  
11
import java.util.Arrays;
12
import java.util.List;
11 13
import java.util.Locale;
12 14
import java.util.regex.Matcher;
13 15
import java.util.regex.Pattern;
......
20 22

  
21 23

  
22 24
/**
25
 *
23 26
 * @author a.kohlbecker
24 27
 * @since Apr 7, 2017
25 28
 *
26 29
 */
27 30
public class JodaTimePartialConverter implements Converter<String, Partial> {
28 31

  
32
    /**
33
     * iso8601: YYY-MM-DD
34
     * yyyymmddDot: dd.mm.yyyy
35
     *
36
     * @author a.kohlbecker
37
     * @since Apr 10, 2017
38
     *
39
     */
40
    public enum DateFormat {
41
        ISO8601,
42
        DAY_MONTH_YEAR_DOT
43
    }
44

  
29 45
    private static final long serialVersionUID = 976413549472527584L;
30 46

  
31
    static final String GLUE = "-";
47
    DateFormat format;
48

  
49
    Pattern partialPatternIso8601 = Pattern.compile("^(?<year>(?:[1,2][7,8,9,0,1])?[0-9]{2})(?:-(?<month>[0-1]?[0-9])(?:-(?<day>[0-3]?[0-9]))?)?$");
50

  
51
    Pattern partialPatternDayMonthYearDot = Pattern.compile("^(?:(?:(?<day>[0-3]?[0-9])\\.)?(?<month>[0-1]?[0-9])\\.)?(?<year>(?:[1,2][7,8,9,0,1])?[0-9]{2})$");
52

  
53
    List<Pattern> patterns = Arrays.asList(new Pattern[]{partialPatternIso8601, partialPatternDayMonthYearDot});
54

  
32 55

  
33
    Pattern partialPattern = Pattern.compile("^(?<year>(?:[1,2][7,8,9,0,1])?[0-9]{2})(?:-(?<month>[0-1]?[0-9])(?:-(?<day>[0-3]?[0-9]))?)?$");
34 56

  
35 57
    /**
36
     *
58
     * @param format The format of the string representation
37 59
     */
38
    public JodaTimePartialConverter() {
60
    public JodaTimePartialConverter(DateFormat format) {
39 61
        super();
62
        this.format = format;
40 63
    }
41 64

  
42 65
    /**
......
48 71
        Partial partial = null;
49 72
        if(value != null){
50 73
            partial = new Partial();
51
            Matcher m = partialPattern.matcher(value);
52
            if(m.matches()){
74
            for(Pattern pattern : patterns){
75
            Matcher m = pattern.matcher(value);
76
                if(m.matches()){
77
                    partial = makePartial(m);
78
                    break;
79
                }
80
            }
81
        }
82
        return partial;
83
    }
84

  
85
    /**
86
     * @param partial
87
     * @param m
88
     */
89
    private Partial makePartial(Matcher m) {
90

  
91
        Partial partial = new Partial();
92
        try {
93
            try {
94
                String year = m.group("year");
95
                partial = partial.with(DateTimeFieldType.year(), Integer.parseInt(year));
96
            } catch (IllegalArgumentException e) {
97
                // a valid year should be present here
98
                throw new ConversionException(e);
99
            }
100
            try {
101
                String month = m.group("month");
102
                partial = partial.with(DateTimeFieldType.monthOfYear(), Integer.parseInt(month));
53 103
                try {
54
                    try {
55
                        partial.with(DateTimeFieldType.year(), Integer.parseInt(m.group("year")));
56
                    } catch (IllegalArgumentException e) {
57
                        // a valid year should be present here
58
                        throw new ConversionException(e);
59
                    }
60
                    try {
61
                        partial.with(DateTimeFieldType.monthOfYear(), Integer.parseInt(m.group("month")));
62
                        try {
63
                            partial.with(DateTimeFieldType.dayOfMonth(), Integer.parseInt(m.group("day")));
64
                        } catch (IllegalArgumentException e) {
65
                            /* IGNORE days are not required */
66
                        }
67
                    } catch (IllegalArgumentException e) {
68
                        /* IGNORE months are not required */
69
                    }
70
                } catch (NumberFormatException ne) {
71
                    // all numbers should be parsable, this is guaranteed by the partialPattern
72
                    throw new ConversionException(ne);
104
                    String day = m.group("day");
105
                    partial = partial.with(DateTimeFieldType.dayOfMonth(), Integer.parseInt(day));
106
                } catch (IllegalArgumentException e) {
107
                    /* IGNORE days are not required */
73 108
                }
109
            } catch (IllegalArgumentException e) {
110
                /* IGNORE months are not required */
74 111
            }
112
        } catch (NumberFormatException ne) {
113
            // all numbers should be parsable, this is guaranteed by the partialPattern
114
            throw new ConversionException(ne);
75 115
        }
76 116
        return partial;
77 117
    }
......
82 122
    @Override
83 123
    public String convertToPresentation(Partial value, Class<? extends String> targetType, Locale locale)
84 124
            throws com.vaadin.data.util.converter.Converter.ConversionException {
85
        StringBuffer sb = new StringBuffer();
86 125
        if(value != null){
126
            switch(format) {
127
            case ISO8601:
128
                return formatIso8601(value);
129
            case DAY_MONTH_YEAR_DOT:
130
                return formatYyyymmddDot(value);
131
            default:
132
                return "JodaTimePartialConverter Error: unsupported format";
133
           }
134
        }
135
        return "";
136
    }
137

  
138
    /**
139
     * @param value
140
     * @param sb
141
     */
142
    private String formatIso8601(Partial value) {
143
        StringBuffer sb = new StringBuffer();
144
        String glue = "-";
145
        try {
146
            sb.append(value.get(DateTimeFieldType.year()));
87 147
            try {
88
                sb.append(value.get(DateTimeFieldType.year()));
148
                String month = StringUtils.leftPad(Integer.toString((value.get(DateTimeFieldType.monthOfYear()))), 2, "0");
149
                sb.append(glue).append(month);
89 150
                try {
90
                    String month = StringUtils.leftPad(Integer.toString((value.get(DateTimeFieldType.monthOfYear()))), 2, "0");
91
                    sb.append(GLUE).append(month);
92
                    try {
93
                        String day = StringUtils.leftPad(Integer.toString((value.get(DateTimeFieldType.dayOfMonth()))), 2, "0");
94
                        sb.append(GLUE).append(day);
95
                    } catch (IllegalArgumentException e){
96
                        /* IGNORE */
97
                    }
151
                    String day = StringUtils.leftPad(Integer.toString((value.get(DateTimeFieldType.dayOfMonth()))), 2, "0");
152
                    sb.append(glue).append(day);
98 153
                } catch (IllegalArgumentException e){
99 154
                    /* IGNORE */
100 155
                }
101 156
            } catch (IllegalArgumentException e){
102 157
                /* IGNORE */
103 158
            }
159
        } catch (IllegalArgumentException e){
160
            /* IGNORE */
104 161
        }
105 162
        return sb.toString();
106 163
    }
107 164

  
108 165
    /**
166
     * @param value
167
     * @param sb
168
     */
169
    private String formatYyyymmddDot(Partial value) {
170
        StringBuffer sb = new StringBuffer();
171
        String glue = ".";
172
        try {
173
            sb.append(StringUtils.reverse(Integer.toString(value.get(DateTimeFieldType.year()))));
174
            try {
175
                String month = StringUtils.leftPad(Integer.toString((value.get(DateTimeFieldType.monthOfYear()))), 2, "0");
176
                sb.append(glue).append(StringUtils.reverse(month));
177
                try {
178
                    String day = StringUtils.leftPad(Integer.toString((value.get(DateTimeFieldType.dayOfMonth()))), 2, "0");
179
                    sb.append(glue).append(StringUtils.reverse(day));
180
                } catch (IllegalArgumentException e){
181
                    /* IGNORE */
182
                }
183
            } catch (IllegalArgumentException e){
184
                /* IGNORE */
185
            }
186
        } catch (IllegalArgumentException e){
187
            /* IGNORE */
188
        }
189
        return StringUtils.reverse(sb.toString());
190
    }
191

  
192
    /**
109 193
     * {@inheritDoc}
110 194
     */
111 195
    @Override
src/test/java/eu/etaxonomy/cdm/vaadin/util/JodaTimePartialConverterTest.java
1
/**
2
* Copyright (C) 2017 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.vaadin.util;
10

  
11
import org.joda.time.DateTimeFieldType;
12
import org.joda.time.Partial;
13
import org.junit.Assert;
14
import org.junit.Test;
15

  
16
import eu.etaxonomy.cdm.vaadin.util.converter.JodaTimePartialConverter;
17

  
18
/**
19
 * @author a.kohlbecker
20
 * @since Apr 10, 2017
21
 *
22
 */
23
public class JodaTimePartialConverterTest extends Assert {
24

  
25
    Partial y = new Partial(
26
            new DateTimeFieldType[]{
27
                    DateTimeFieldType.year()
28
                    },
29
            new int[]{
30
                    2012
31
                    }
32
            );
33
    Partial ym = new Partial(
34
            new DateTimeFieldType[]{
35
                    DateTimeFieldType.year(),
36
                    DateTimeFieldType.monthOfYear()
37
                    },
38
            new int[]{
39
                    2013,
40
                    04
41
                    }
42
            );
43
    Partial ymd = new Partial(
44
            new DateTimeFieldType[]{
45
                    DateTimeFieldType.year(),
46
                    DateTimeFieldType.monthOfYear(),
47
                    DateTimeFieldType.dayOfMonth()
48
                    },
49
            new int[]{
50
                    2014,
51
                    04,
52
                    12
53
                    }
54
            );
55

  
56

  
57
    @Test
58
    public void toISO8601() {
59
        JodaTimePartialConverter conv = new JodaTimePartialConverter(JodaTimePartialConverter.DateFormat.ISO8601);
60
        assertEquals("2012", conv.convertToPresentation(y, String.class, null));
61
        assertEquals("2013-04", conv.convertToPresentation(ym, String.class, null));
62
        assertEquals("2014-04-12", conv.convertToPresentation(ymd, String.class, null));
63
    }
64

  
65

  
66
    @Test
67
    public void toDAY_MONTH_YEAR_DOT() {
68
        JodaTimePartialConverter conv = new JodaTimePartialConverter(JodaTimePartialConverter.DateFormat.DAY_MONTH_YEAR_DOT);
69
        assertEquals("2012", conv.convertToPresentation(y, String.class, null));
70
        assertEquals("04.2013", conv.convertToPresentation(ym, String.class, null));
71
        assertEquals("12.04.2014", conv.convertToPresentation(ymd, String.class, null));
72
    }
73

  
74
    @Test
75
    public void fromDAY_MONTH_YEAR_DOT() {
76
        // using null as format since the conversion should work for all formats
77
        JodaTimePartialConverter conv = new JodaTimePartialConverter(null);
78
        assertEquals(y, conv.convertToModel("2012", Partial.class, null));
79
        assertEquals(ym, conv.convertToModel("2013-04", Partial.class, null));
80
        assertEquals(ym, conv.convertToModel("04.2013", Partial.class, null));
81
        assertEquals(ymd, conv.convertToModel("2014-04-12", Partial.class, null));
82
        assertEquals(ymd, conv.convertToModel("12.04.2014", Partial.class, null));
83
        assertEquals(ymd, conv.convertToModel("12.4.2014", Partial.class, null));
84
    }
85

  
86
}
src/test/java/eu/etaxonomy/cdm/vaadin/util/TypeDesignationConverterTest.java
1
/**
2
* Copyright (C) 2017 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.vaadin.util;
10

  
11
import static org.junit.Assert.assertNotNull;
12

  
13
import java.util.ArrayList;
14
import java.util.List;
15

  
16
import org.apache.log4j.Logger;
17
import org.junit.Test;
18

  
19
import eu.etaxonomy.cdm.model.name.NameTypeDesignation;
20
import eu.etaxonomy.cdm.model.name.Rank;
21
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
22
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignationStatus;
23
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
24
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
25
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
26
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
27
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationType;
28
import eu.etaxonomy.cdm.model.reference.Reference;
29
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
30
import eu.etaxonomy.cdm.vaadin.CdmVaadinBaseTest;
31

  
32
/**
33
 * @author a.kohlbecker
34
 * @since Mar 10, 2017
35
 *
36
 */
37
public class TypeDesignationConverterTest extends CdmVaadinBaseTest{
38

  
39

  
40
    @Test
41
    public void test1(){
42

  
43
        NameTypeDesignation ntd = NameTypeDesignation.NewInstance();
44
        TaxonNameBase typeName = TaxonNameFactory.NewBacterialInstance(Rank.SPECIES());
45
        typeName.setTitleCache("Prionus coriatius L.", true);
46
        ntd.setTypeName(typeName);
47
        Reference citation = ReferenceFactory.newGeneric();
48
        citation.setTitleCache("Species Platarum", true);
49
        ntd.setCitation(citation);
50

  
51
        SpecimenTypeDesignation std = SpecimenTypeDesignation.NewInstance();
52
        DerivedUnit specimen = DerivedUnit.NewInstance(SpecimenOrObservationType.PreservedSpecimen);
53
        specimen.setTitleCache("OHA", true);
54
        std.setTypeSpecimen(specimen);
55
        std.setTypeStatus(SpecimenTypeDesignationStatus.HOLOTYPE());
56

  
57
        List<TypeDesignationBase> tds = new ArrayList<>();
58
        tds.add(ntd);
59
        tds.add(std);
60

  
61
        String result = new TypeDesignationConverter(tds, null).buildString().print();
62
        Logger.getLogger(this.getClass()).debug(result);
63
        assertNotNull(result);
64
    }
65

  
66
}
src/test/java/eu/etaxonomy/cdm/vaadin/util/converter/TypeDesignationConverterTest.java
1
/**
2
* Copyright (C) 2017 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.vaadin.util.converter;
10

  
11
import static org.junit.Assert.assertNotNull;
12

  
13
import java.util.ArrayList;
14
import java.util.List;
15

  
16
import org.apache.log4j.Logger;
17
import org.junit.Test;
18

  
19
import eu.etaxonomy.cdm.model.name.NameTypeDesignation;
20
import eu.etaxonomy.cdm.model.name.Rank;
21
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignation;
22
import eu.etaxonomy.cdm.model.name.SpecimenTypeDesignationStatus;
23
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
24
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
25
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
26
import eu.etaxonomy.cdm.model.occurrence.DerivedUnit;
27
import eu.etaxonomy.cdm.model.occurrence.SpecimenOrObservationType;
28
import eu.etaxonomy.cdm.model.reference.Reference;
29
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
30
import eu.etaxonomy.cdm.vaadin.CdmVaadinBaseTest;
31
import eu.etaxonomy.cdm.vaadin.util.TypeDesignationConverter;
32

  
33
/**
34
 * @author a.kohlbecker
35
 * @since Mar 10, 2017
36
 *
37
 */
38
public class TypeDesignationConverterTest extends CdmVaadinBaseTest{
39

  
40

  
41
    @Test
42
    public void test1(){
43

  
44
        NameTypeDesignation ntd = NameTypeDesignation.NewInstance();
45
        TaxonNameBase typeName = TaxonNameFactory.NewBacterialInstance(Rank.SPECIES());
46
        typeName.setTitleCache("Prionus coriatius L.", true);
47
        ntd.setTypeName(typeName);
48
        Reference citation = ReferenceFactory.newGeneric();
49
        citation.setTitleCache("Species Platarum", true);
50
        ntd.setCitation(citation);
51

  
52
        SpecimenTypeDesignation std = SpecimenTypeDesignation.NewInstance();
53
        DerivedUnit specimen = DerivedUnit.NewInstance(SpecimenOrObservationType.PreservedSpecimen);
54
        specimen.setTitleCache("OHA", true);
55
        std.setTypeSpecimen(specimen);
56
        std.setTypeStatus(SpecimenTypeDesignationStatus.HOLOTYPE());
57

  
58
        List<TypeDesignationBase> tds = new ArrayList<>();
59
        tds.add(ntd);
60
        tds.add(std);
61

  
62
        String result = new TypeDesignationConverter(tds, null).buildString().print();
63
        Logger.getLogger(this.getClass()).debug(result);
64
        assertNotNull(result);
65
    }
66

  
67
}

Also available in: Unified diff

Add picture from clipboard (Maximum size: 40 MB)