summaryrefslogtreecommitdiffstats
path: root/src/com/cyngn/eleven/lastfm/StringUtilities.java
blob: 982ea5f822bc4b14c4c95505d2047d7034482d89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/*
 * Copyright (c) 2012, the Last.fm Java Project and Committers All rights
 * reserved. Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the following
 * conditions are met: - Redistributions of source code must retain the above
 * copyright notice, this list of conditions and the following disclaimer. -
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution. THIS SOFTWARE IS
 * PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.cyngn.eleven.lastfm;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Utilitiy class with methods to calculate an md5 hash and to encode URLs.
 * 
 * @author Janni Kovacs
 */
public final class StringUtilities {

    private static MessageDigest mDigest;

    private final static Pattern MD5_PATTERN = Pattern.compile("[a-fA-F0-9]{32}");

    static {
        try {
            mDigest = MessageDigest.getInstance("MD5");
        } catch (final NoSuchAlgorithmException ignored) {
        }
    }

    /**
     * Returns a 32 chararacter hexadecimal representation of an MD5 hash of the
     * given String.
     * 
     * @param s the String to hash
     * @return the md5 hash
     */
    public final static String md5(final String s) {
        try {
            final byte[] mBytes = mDigest.digest(s.getBytes("UTF-8"));
            final StringBuilder mBuilder = new StringBuilder(32);
            for (final byte aByte : mBytes) {
                final String mHex = Integer.toHexString(aByte & 0xFF);
                if (mHex.length() == 1) {
                    mBuilder.append('0');
                }
                mBuilder.append(mHex);
            }
            return mBuilder.toString();
        } catch (final UnsupportedEncodingException ignored) {
        }
        return null;
    }

    /**
     * URL Encodes the given String <code>s</code> using the UTF-8 character
     * encoding.
     * 
     * @param s a String
     * @return url encoded string
     */
    public static String encode(final String s) {
        if (s == null) {
            return null;
        }
        try {
            return URLEncoder.encode(s, "UTF-8");
        } catch (final UnsupportedEncodingException ignored) {
        }
        return null;
    }

    /**
     * Decodes an URL encoded String <code>s</code> using the UTF-8 character
     * encoding.
     * 
     * @param s an encoded String
     * @return the decoded String
     */
    public static String decode(final String s) {
        if (s == null) {
            return null;
        }
        try {
            return URLDecoder.decode(s, "UTF-8");
        } catch (final UnsupportedEncodingException ignored) {
        }
        return null;
    }

    /**
     * Creates a Map out of an array with Strings.
     * 
     * @param strings input strings, key-value alternating
     * @return a parameter map
     */
    public static Map<String, String> map(final String... strings) {
        if (strings.length % 2 != 0) {
            throw new IllegalArgumentException("strings.length % 2 != 0");
        }
        final Map<String, String> sMap = new HashMap<String, String>();
        for (int i = 0; i < strings.length; i += 2) {
            sMap.put(strings[i], strings[i + 1]);
        }
        return sMap;
    }

    /**
     * Strips all characters from a String, that might be invalid to be used in
     * file names. By default <tt>: / \ < > | ? " *</tt> are all replaced by
     * <tt>-</tt>. Note that this is no guarantee that the returned name will be
     * definately valid.
     * 
     * @param s the String to clean up
     * @return the cleaned up String
     */
    public static String cleanUp(final String s) {
        return s.replaceAll("[*:/\\\\?|<>\"]", "-");
    }

    /**
     * Tests if the given string <i>might</i> already be a 32-char md5 string.
     * 
     * @param s String to test
     * @return <code>true</code> if the given String might be a md5 string
     */
    public static boolean isMD5(final String s) {
        return s.length() == 32 && MD5_PATTERN.matcher(s).matches();
    }

    /**
     * Converts a Last.fm boolean result string to a boolean.
     * 
     * @param resultString A Last.fm boolean result string.
     * @return <code>true</code> if the given String represents a true,
     *         <code>false</code> otherwise.
     */
    public static boolean convertToBoolean(final String resultString) {
        return "1".equals(resultString);
    }

    /**
     * Converts from a boolean to a Last.fm boolean result string.
     * 
     * @param value A boolean value.
     * @return A string representing a Last.fm boolean.
     */
    public static String convertFromBoolean(final boolean value) {
        if (value) {
            return "1";
        } else {
            return "0";
        }
    }

}