package sharin.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class StringUtils {

    public static String decodeUrl(String s, String enc) {

        try {
            return URLDecoder.decode(s, enc);

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static String encodeUrl(String s, String enc) {

        try {
            return URLEncoder.encode(s, enc);

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static String escapeXml(String s) {
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);

            switch (ch) {
            case '"':
                builder.append("&quot;");
                break;

            case '&':
                builder.append("&amp;");
                break;

            case '<':
                builder.append("&lt;");
                break;

            case '>':
                builder.append("&gt;");
                break;

            case '\'':
                builder.append("&apos;");
                break;

            default:
                builder.append(ch);
                break;
            }
        }

        return builder.toString();
    }
}
