File: TextUtils.java

package info (click to toggle)
subethasmtp 4.0~rc6-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 964 kB
  • sloc: java: 6,330; xml: 322; sh: 12; makefile: 2
file content (71 lines) | stat: -rw-r--r-- 2,047 bytes parent folder | download
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
package org.subethamail.smtp.internal.util;

import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Iterator;

import com.google.common.annotations.VisibleForTesting;

/**
 * @author Jeff Schnitzer
 */
public final class TextUtils {

    private TextUtils() {
        // prevent instantiation
    }

    /**
     * @return a delimited string containing the specified items
     */
    public static String joinTogether(Collection<String> items, String delim) {
        StringBuffer ret = new StringBuffer();

        for (Iterator<String> it = items.iterator(); it.hasNext();) {
            ret.append(it.next());
            if (it.hasNext()) {
                ret.append(delim);
            }
        }

        return ret.toString();
    }

    /**
     * @return the value of str.getBytes() without the idiotic checked exception
     */
    public static byte[] getBytes(String str, String charset) {
        try {
            return str.getBytes(charset);
        } catch (UnsupportedEncodingException ex) {
            throw new IllegalArgumentException(charset, ex);
        }
    }

    /** @return the string as US-ASCII bytes */
    public static byte[] getAsciiBytes(String str) {
        return getBytes(str, "US-ASCII");
    }

    /**
     * Converts the specified byte array to a string using the specified
     * encoding but without throwing a checked exception. This is useful if the
     * specified encoding is required to be available by the JRE specification,
     * so the exception would be guaranteed to be not thrown anyway.
     */
    @VisibleForTesting
    static String getString(byte[] bytes, String charset) {
        try {
            return new String(bytes, charset);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * Converts the specified bytes to String using UTF-8 encoding.
     */
    public static String getStringUtf8(byte[] bytes) {
        return getString(bytes, "UTF-8");
    }
}