OSDN Git Service

overhaul
[android-x86/packages-apps-Eleven.git] / src / com / andrew / apollo / utils / StringUtilities.java
1 /*\r
2  * Copyright (c) 2012, the Last.fm Java Project and Committers\r
3  * All rights reserved.\r
4  *\r
5  * Redistribution and use of this software in source and binary forms, with or without modification, are\r
6  * permitted provided that the following conditions are met:\r
7  *\r
8  * - Redistributions of source code must retain the above\r
9  *   copyright notice, this list of conditions and the\r
10  *   following disclaimer.\r
11  *\r
12  * - Redistributions in binary form must reproduce the above\r
13  *   copyright notice, this list of conditions and the\r
14  *   following disclaimer in the documentation and/or other\r
15  *   materials provided with the distribution.\r
16  *\r
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED\r
18  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\r
19  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\r
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
21  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r
22  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\r
23  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\r
24  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
25  */\r
26 package com.andrew.apollo.utils;\r
27 \r
28 import java.io.UnsupportedEncodingException;\r
29 import java.net.URLDecoder;\r
30 import java.net.URLEncoder;\r
31 import java.security.MessageDigest;\r
32 import java.security.NoSuchAlgorithmException;\r
33 import java.util.HashMap;\r
34 import java.util.Map;\r
35 import java.util.regex.Pattern;\r
36 \r
37 /**\r
38  * Utilitiy class with methods to calculate an md5 hash and to encode URLs.\r
39  *\r
40  * @author Janni Kovacs\r
41  */\r
42 public final class StringUtilities {\r
43 \r
44         private static MessageDigest digest;\r
45         private static Pattern MBID_PATTERN = Pattern\r
46                         .compile("^[0-9a-f]{8}\\-[0-9a-f]{4}\\-[0-9a-f]{4}\\-[0-9a-f]{4}\\-[0-9a-f]{12}$",\r
47                                         Pattern.CASE_INSENSITIVE);\r
48         private static final Pattern MD5_PATTERN = Pattern.compile("[a-fA-F0-9]{32}");\r
49 \r
50         static {\r
51                 try {\r
52                         digest = MessageDigest.getInstance("MD5");\r
53                 } catch (NoSuchAlgorithmException e) {\r
54                         // better never happens\r
55                 }\r
56         }\r
57 \r
58         /**\r
59          * Returns a 32 chararacter hexadecimal representation of an MD5 hash of the given String.\r
60          * \r
61          * @param s the String to hash\r
62          * @return the md5 hash\r
63          */\r
64         public static String md5(String s) {\r
65                 try {\r
66                         byte[] bytes = digest.digest(s.getBytes("UTF-8"));\r
67                         StringBuilder b = new StringBuilder(32);\r
68                         for (byte aByte : bytes) {\r
69                                 String hex = Integer.toHexString((int) aByte & 0xFF);\r
70                                 if (hex.length() == 1)\r
71                                         b.append('0');\r
72                                 b.append(hex);\r
73                         }\r
74                         return b.toString();\r
75                 } catch (UnsupportedEncodingException e) {\r
76                         // utf-8 always available\r
77                 }\r
78                 return null;\r
79         }\r
80 \r
81         /**\r
82          * URL Encodes the given String <code>s</code> using the UTF-8 character encoding.\r
83          *\r
84          * @param s a String\r
85          * @return url encoded string\r
86          */\r
87         public static String encode(String s) {\r
88                 if(s == null)\r
89                         return null;\r
90                 try {\r
91                         return URLEncoder.encode(s, "UTF-8");\r
92                 } catch (UnsupportedEncodingException e) {\r
93                         // utf-8 always available\r
94                 }\r
95                 return null;\r
96         }\r
97 \r
98         /**\r
99          * Decodes an URL encoded String <code>s</code> using the UTF-8 character encoding.\r
100          *\r
101          * @param s an encoded String\r
102          * @return the decoded String\r
103          */\r
104         public static String decode(String s) {\r
105                 if(s == null)\r
106                         return null;\r
107                 try {\r
108                         return URLDecoder.decode(s, "UTF-8");\r
109                 } catch (UnsupportedEncodingException e) {\r
110                         // utf-8 always available\r
111                 }\r
112                 return null;\r
113         }\r
114 \r
115         /**\r
116          * Checks if the supplied String <i>may</i> be a Musicbrainz ID. This method returns <code>true</code> for Strings that are\r
117          * exactly 36 characters long and match the MBID pattern <code>[0-9a-f]{8}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{12}</code>.\r
118          *\r
119          * @param nameOrMbid a possible MBID\r
120          * @return <code>true</code> if this String <i>may</i> be a MBID\r
121          */\r
122         public static boolean isMbid(String nameOrMbid) {\r
123                 // example: bfcc6d75-a6a5-4bc6-8282-47aec8531818\r
124                 return nameOrMbid != null && nameOrMbid.length() == 36 && MBID_PATTERN.matcher(nameOrMbid).matches();\r
125         }\r
126 \r
127         /**\r
128          * Creates a Map out of an array with Strings.\r
129          *\r
130          * @param strings input strings, key-value alternating\r
131          * @return a parameter map\r
132          */\r
133         public static Map<String, String> map(String... strings) {\r
134                 if (strings.length % 2 != 0)\r
135                         throw new IllegalArgumentException("strings.length % 2 != 0");\r
136                 Map<String, String> mp = new HashMap<String, String>();\r
137                 for (int i = 0; i < strings.length; i += 2) {\r
138                         mp.put(strings[i], strings[i + 1]);\r
139                 }\r
140                 return mp;\r
141         }\r
142 \r
143         /**\r
144          * Strips all characters from a String, that might be invalid to be used in file names.\r
145          * By default <tt>: / \ < > | ? " *</tt> are all replaced by <tt>-</tt>.\r
146          * Note that this is no guarantee that the returned name will be definately valid.\r
147          *\r
148          * @param s the String to clean up\r
149          * @return the cleaned up String\r
150          */\r
151         public static String cleanUp(String s) {\r
152                 return s.replaceAll("[*:/\\\\?|<>\"]", "-");\r
153         }\r
154 \r
155         /**\r
156          * Tests if the given string <i>might</i> already be a 32-char md5 string.\r
157          *\r
158          * @param s String to test\r
159          * @return <code>true</code> if the given String might be a md5 string\r
160          */\r
161         public static boolean isMD5(String s) {\r
162                 return s.length() == 32 && MD5_PATTERN.matcher(s).matches();\r
163         }\r
164 \r
165         /**\r
166          * Converts a Last.fm boolean result string to a boolean.\r
167          *\r
168          * @param resultString A Last.fm boolean result string.\r
169          * @return <code>true</code> if the given String represents a true, <code>false</code> otherwise.\r
170          */\r
171         public static boolean convertToBoolean(String resultString) {\r
172                 return "1".equals(resultString);\r
173         }\r
174 \r
175         /**\r
176          * Converts from a boolean to a Last.fm boolean result string.\r
177          * \r
178          * @param value A boolean value.\r
179          * @return A string representing a Last.fm boolean.\r
180          */\r
181         public static String convertFromBoolean(boolean value) {\r
182                 if (value) {\r
183                         return "1";\r
184                 } else {\r
185                         return "0";\r
186                 }\r
187         }\r
188 \r
189 }\r