3d21bf3659fcaaa636780b1b835fb74821acb364
[zxing.git] / core / src / com / google / zxing / client / result / GeoResultParser.java
1 /*
2  * Copyright 2008 ZXing 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  *      http://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
17 package com.google.zxing.client.result;
18
19 import com.google.zxing.Result;
20
21 /**
22  * Parses a "geo:" URI result, which specifies a location on the surface of
23  * the Earth as well as an optional altitude above the surface. See
24  * <a href="http://tools.ietf.org/html/draft-mayrhofer-geo-uri-00">
25  * http://tools.ietf.org/html/draft-mayrhofer-geo-uri-00</a>.
26  *
27  * @author Sean Owen
28  */
29 final class GeoResultParser extends ResultParser {
30
31   private GeoResultParser() {
32   }
33
34   public static GeoParsedResult parse(Result result) {
35     String rawText = result.getText();
36     if (rawText == null || (!rawText.startsWith("geo:") && !rawText.startsWith("GEO:"))) {
37       return null;
38     }
39     // Drop geo, query portion
40     int queryStart = rawText.indexOf('?', 4);
41     String geoURIWithoutQuery = queryStart < 0 ? rawText.substring(4) : rawText.substring(4, queryStart);
42     int latitudeEnd = geoURIWithoutQuery.indexOf(',');
43     if (latitudeEnd < 0) {
44       return null;
45     }
46     int longitudeEnd = geoURIWithoutQuery.indexOf(',', latitudeEnd + 1);    
47     double latitude, longitude, altitude;
48     try {
49       latitude = Double.parseDouble(geoURIWithoutQuery.substring(0, latitudeEnd));
50       if (latitude > 90.0 || latitude < -90.0) {
51         return null;
52       }
53       if (longitudeEnd < 0) {
54         longitude = Double.parseDouble(geoURIWithoutQuery.substring(latitudeEnd + 1));
55         altitude = 0.0;
56       } else {
57         longitude = Double.parseDouble(geoURIWithoutQuery.substring(latitudeEnd + 1, longitudeEnd));
58         altitude = Double.parseDouble(geoURIWithoutQuery.substring(longitudeEnd + 1));
59       }
60       if (longitude > 180.0 || longitude < -180.0 || altitude < 0) {
61         return null;
62       }
63     } catch (NumberFormatException nfe) {
64       return null;
65     }
66     return new GeoParsedResult(latitude, longitude, altitude);
67   }
68
69 }