Standardize and update all copyright statements to name "ZXing authors" as suggested...
[zxing.git] / core / src / com / google / zxing / client / result / URIParsedResult.java
1 /*
2  * Copyright 2007 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  * @author srowen@google.com (Sean Owen)
23  */
24 public final class URIParsedResult extends ParsedReaderResult {
25
26   private final String uri;
27
28   private URIParsedResult(String uri) {
29     super(ParsedReaderResultType.URI);
30     this.uri = uri;
31   }
32
33   public static URIParsedResult parse(Result result) {
34     String rawText = result.getText();
35     if (!isBasicallyValidURI(rawText)) {
36       return null;
37     }
38     String uri = massagePossibleURI(rawText);
39     return new URIParsedResult(uri);
40   }
41
42   public String getURI() {
43     return uri;
44   }
45
46   public String getDisplayResult() {
47     return uri;
48   }
49
50   /**
51    * Transforms a string that possibly represents a URI into something more proper, by adding or canonicalizing
52    * the protocol.
53    */
54   private static String massagePossibleURI(String uri) {
55     // Take off leading "URL:" if present
56     if (uri.startsWith("URL:")) {
57       uri = uri.substring(4);
58     }
59     int protocolEnd = uri.indexOf(':');
60     if (protocolEnd < 0) {
61       // No protocol, assume http
62       uri = "http://" + uri;
63     } else {
64       // Lowercase protocol to avoid problems
65       uri = uri.substring(0, protocolEnd).toLowerCase() + uri.substring(protocolEnd);
66       // TODO this logic isn't quite right for URIs like "example.org:443/foo"
67     }
68     return uri;
69   }
70
71   /**
72    * Determines whether a string is not obviously not a URI. This implements crude checks; this class does not
73    * intend to strictly check URIs as its only function is to represent what is in a barcode, but, it does
74    * need to know when a string is obviously not a URI.
75    */
76   static boolean isBasicallyValidURI(String uri) {
77     return uri != null && uri.indexOf(' ') < 0 && (uri.indexOf(':') >= 0 || uri.indexOf('.') >= 0);
78   }
79
80 }