Preserve query in geo URI
[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 query;
42     String geoURIWithoutQuery;
43     if (queryStart < 0) {
44       query = null;
45       geoURIWithoutQuery = rawText.substring(4);
46     } else {
47       query = rawText.substring(queryStart + 1);
48       geoURIWithoutQuery = rawText.substring(4, queryStart);
49     }
50     int latitudeEnd = geoURIWithoutQuery.indexOf(',');
51     if (latitudeEnd < 0) {
52       return null;
53     }
54     int longitudeEnd = geoURIWithoutQuery.indexOf(',', latitudeEnd + 1);    
55     double latitude, longitude, altitude;
56     try {
57       latitude = Double.parseDouble(geoURIWithoutQuery.substring(0, latitudeEnd));
58       if (latitude > 90.0 || latitude < -90.0) {
59         return null;
60       }
61       if (longitudeEnd < 0) {
62         longitude = Double.parseDouble(geoURIWithoutQuery.substring(latitudeEnd + 1));
63         altitude = 0.0;
64       } else {
65         longitude = Double.parseDouble(geoURIWithoutQuery.substring(latitudeEnd + 1, longitudeEnd));
66         altitude = Double.parseDouble(geoURIWithoutQuery.substring(longitudeEnd + 1));
67       }
68       if (longitude > 180.0 || longitude < -180.0 || altitude < 0) {
69         return null;
70       }
71     } catch (NumberFormatException nfe) {
72       return null;
73     }
74     return new GeoParsedResult(latitude, longitude, altitude, query);
75   }
76
77 }