1 /*
2  * Copyright 2014-2020 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      https://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.springframework.data.geo.format;
17
18 import java.text.ParseException;
19 import java.util.Locale;
20
21 import javax.annotation.Nonnull;
22
23 import org.springframework.core.convert.converter.Converter;
24 import org.springframework.core.convert.converter.GenericConverter.ConvertiblePair;
25 import org.springframework.data.geo.Point;
26 import org.springframework.format.Formatter;
27
28 /**
29  * Converter to parse two comma-separated doubles into a {@link Point}.
30  *
31  * @author Oliver Gierke
32  */

33 public enum PointFormatter implements Converter<String, Point>, Formatter<Point> {
34
35     INSTANCE;
36
37     public static final ConvertiblePair CONVERTIBLE = new ConvertiblePair(String.class, Point.class);
38
39     private static final String INVALID_FORMAT = "Expected two doubles separated by a comma but got '%s'!";
40
41     /*
42      * (non-Javadoc)
43      * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object)
44      */

45     @Nonnull
46     @Override
47     public Point convert(String source) {
48
49         String[] parts = source.split(",");
50
51         if (parts.length != 2) {
52             throw new IllegalArgumentException(String.format(INVALID_FORMAT, source));
53         }
54
55         try {
56
57             double latitude = Double.parseDouble(parts[0]);
58             double longitude = Double.parseDouble(parts[1]);
59
60             return new Point(longitude, latitude);
61
62         } catch (NumberFormatException o_O) {
63             throw new IllegalArgumentException(String.format(INVALID_FORMAT, source), o_O);
64         }
65     }
66
67     /*
68      * (non-Javadoc)
69      * @see org.springframework.format.Printer#print(java.lang.Object, java.util.Locale)
70      */

71     @Override
72     public String print(Point point, Locale locale) {
73         return point == null ? null : String.format("%s,%s", point.getY(), point.getX());
74     }
75
76     /*
77      * (non-Javadoc)
78      * @see org.springframework.format.Parser#parse(java.lang.String, java.util.Locale)
79      */

80     @Override
81     public Point parse(String text, Locale locale) throws ParseException {
82         return convert(text);
83     }
84 }
85