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