Android activity to add a network, and all associated code for dealing
[zxing.git] / android / src / com / google / zxing / client / android / wifi / NetworkUtil.java
1 /*
2  * Copyright (C) 2010 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.android.wifi;
18
19 import android.text.TextUtils;
20
21 /**
22  * Try with:
23  * http://chart.apis.google.com/chart?cht=qr&chs=240x240&chl=WIFI:S:linksys;P:mypass;T:WPA;;
24  * @author Vikram Aggarwal
25  *
26  * TODO(vikrama): Test with binary ssid or password.
27  */
28 public final class NetworkUtil {
29   /**
30    * Encloses the incoming string inside double quotes, if it isn't already quoted.
31    * @param string: the input string
32    * @return a quoted string, of the form "input".  If the input string is null, it returns null as well.
33    */
34   public static String convertToQuotedString(String string) {
35     if (string == null){
36       return null;
37     }
38     if (TextUtils.isEmpty(string)) {
39       return "";
40     }
41     final int lastPos = string.length() - 1;
42     if (lastPos < 0 || (string.charAt(0) == '"' && string.charAt(lastPos) == '"')) {
43       return string;
44     }        
45     return "\"" + string + "\"";
46   }
47
48   private static boolean isHex(String key) {
49     if (key == null){
50       return false;
51     }
52     for (int i = key.length() - 1; i >= 0; i--) {
53       final char c = key.charAt(i);
54       if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) {
55         return false;
56       }
57     }        
58     return true;
59   }
60
61   /**
62    * Check if wepKey is a valid hexadecimal string.
63    * @param wepKey the input to be checked
64    * @return true if the input string is indeed hex or empty.  False if the input string is non-hex or null.
65    */
66   public static boolean isHexWepKey(String wepKey) {
67     if (wepKey == null)
68       return false;
69     final int len = wepKey.length();
70     // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
71     if (len != 10 && len != 26 && len != 58) {
72       return false;
73     }
74     return isHex(wepKey);
75   }     
76 }