cleanup
[cdm-vaadin.git] / src / main / java / eu / etaxonomy / cdm / vaadin / util / converter / GeoLocationConverterValidator.java
1 /**
2 * Copyright (C) 2018 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 java.text.ParseException;
12 import java.util.Locale;
13
14 import org.apache.logging.log4j.LogManager;
15 import org.apache.logging.log4j.Logger;
16
17 import com.vaadin.data.Validator;
18 import com.vaadin.data.util.converter.Converter;
19
20 import eu.etaxonomy.cdm.model.location.Point;
21 import eu.etaxonomy.cdm.model.location.Point.Sexagesimal;
22
23 /**
24 * Converts longitute and latitute string representations into
25 * double values. At the same time this class can be used as Validator.
26 *
27 * @author a.kohlbecker
28 * @since Nov 20, 2018
29 */
30 public class GeoLocationConverterValidator implements Converter<String, Double>, Validator {
31
32 private static final Logger logger = LogManager.getLogger();
33
34 public enum Axis {
35 LONGITUDE, LATITUDE;
36 }
37
38 private static final long serialVersionUID = -1780028474672132160L;
39
40 private Axis axis;
41
42 public GeoLocationConverterValidator(Axis axis){
43 this.axis = axis;
44 }
45
46 @Override
47 public Double convertToModel(String value, Class<? extends Double> targetType, Locale locale)
48 throws com.vaadin.data.util.converter.Converter.ConversionException {
49
50 if(value == null){
51 return null;
52 }
53 try {
54 if(axis == Axis.LONGITUDE){
55 return Point.parseLongitude(value);
56 } else {
57 return Point.parseLatitude(value);
58 }
59 } catch (ParseException e) {
60 logger.error(e);
61 throw new ConversionException(e);
62 }
63 }
64
65 @Override
66 public String convertToPresentation(Double value, Class<? extends String> targetType, Locale locale)
67 throws com.vaadin.data.util.converter.Converter.ConversionException {
68
69 if(value == null){
70 return null;
71 }
72 if(axis == Axis.LONGITUDE){
73 return Sexagesimal.valueOf(value, false).toString();
74 } else {
75 return Sexagesimal.valueOf(value, true).toString();
76 }
77 }
78
79 @Override
80 public Class<Double> getModelType() {
81 return Double.class;
82 }
83
84 @Override
85 public Class<String> getPresentationType() {
86 return String.class;
87 }
88
89 @Override
90 public void validate(Object value) throws InvalidValueException {
91 if(value != null && value instanceof String && !((String)value).isEmpty()){
92 try {
93 convertToModel((String)value, Double.class, null);
94 } catch (com.vaadin.data.util.converter.Converter.ConversionException e) {
95 throw new InvalidValueException("Invalid " + axis.name().toLowerCase());
96 }
97 }
98 }
99 }