uricomponent.java

来自「resetful样式的ws样例,一种面向资源的webservices服务」· Java 代码 · 共 482 行 · 第 1/2 页

JAVA
482
字号
/* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. *  * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. *  * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License").  You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://jersey.dev.java.net/CDDL+GPL.html * or jersey/legal/LICENSE.txt.  See the License for the specific * language governing permissions and limitations under the License. *  * When distributing the software, include this License Header Notice in each * file and include the License file at jersey/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code.  If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" *  * Contributor(s): *  * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license."  If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above.  However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */package com.sun.jersey.api.uri;import com.sun.jersey.impl.MultivaluedMapImpl;import java.io.UnsupportedEncodingException;import java.net.URI;import java.net.URLDecoder;import java.nio.ByteBuffer;import java.nio.CharBuffer;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import javax.ws.rs.core.MultivaluedMap;/** * Utility class for validating, encoding and decoding components * of a URI. * * TODO rewrite to use masks and not lookup tables * * @author Paul.Sandoz@Sun.Com */public final class UriComponent {    public enum Type {        SCHEME, USER_INFO, HOST, PORT, PATH, PATH_SEGMENT, QUERY, FRAGMENT,    }        private UriComponent() {    }    /**     * Validates the legal characters of a percent-encoded string that      * represents a URI component type.     *     * @param s the encoded string.     * @param t the URI compontent type identifying the legal characters.     * @throws IllegalArgumentException if the encoded string contains illegal     *         characters.     */    public static void validate(String s, Type t) {        validate(s, t, false);    }        /**     * Validates the legal characters of a percent-encoded string that      * represents a URI component type.     *     * @param s the encoded string.     * @param t the URI compontent type identifying the legal characters.     * @param template true if the encoded string contains URI template variables     * @throws IllegalArgumentException if the encoded string contains illegal     *         characters.     */    public static void validate(String s, Type t, boolean template) {        int i = _valid(s, t, template);        if (i > -1)            // TODO localize            throw new IllegalArgumentException("The string '" + s +                     "' for the URI component " + t +                     " contains an invalid character, '" + s.charAt(i) + "', at index " + i);    }    /**     * Validates the legal characters of a percent-encoded string that      * represents a URI component type.     *     * @param s the encoded string.     * @param t the URI compontent type identifying the legal characters.     * @return true if the encoded string is valid, otherwise false.     */    public static boolean valid(String s, Type t) {        return valid(s, t, false);    }        /**     * Validates the legal characters of a percent-encoded string that      * represents a URI component type.     *     * @param s the encoded string.     * @param t the URI compontent type identifying the legal characters.     * @param template true if the encoded string contains URI template variables     * @return true if the encoded string is valid, otherwise false.     */    public static boolean valid(String s, Type t, boolean template) {        return _valid(s, t, template) == -1;    }        private static int _valid(String s, Type t, boolean template) {        boolean[] table = ENCODING_TABLES[t.ordinal()];                for (int i = 0; i < s.length(); i++) {            final char c = s.charAt(i);            if ((c < 0x80 && c != '%' && !table[c]) || c >= 0x80)                if (!template || (c != '{' && c != '}'))                    return i;        }        return -1;    }        /**     * Encodes the characters of string that are either non-ASCII characters      * or are ASCII characters that must be percent-encoded using the      * UTF-8 encoding.     *     * @param s the string to be encoded.     * @param t the URI compontent type identifying the ASCII characters that      *          must be percent-encoded.     * @return the encoded string.     */    public static String encode(String s, Type t) {        return encode(s, t, false);    }        /**     * Encodes the characters of string that are either non-ASCII characters      * or are ASCII characters that must be percent-encoded using the      * UTF-8 encoding.     *     * @param s the string to be encoded.     * @param t the URI compontent type identifying the ASCII characters that      *          must be percent-encoded.     * @param template true if the encoded string contains URI template variables     * @return the encoded string.     */    public static String encode(String s, Type t, boolean template) {        boolean[] table = ENCODING_TABLES[t.ordinal()];        StringBuilder sb = null;        for (int i = 0; i < s.length(); i++) {            final char c = s.charAt(i);            if (c < 0x80 && table[c]) {                if (sb != null) sb.append(c);            } else {                if (template && (c == '{' || c == '}')) {                    if (sb != null) sb.append(c);                    continue;                }                if (sb == null) {                     sb = new StringBuilder();                    sb.append(s.substring(0, i));                }                if (c < 0x80)                    appendPercentEncodedOctet(sb, c);                else                     appendUTF8EncodedCharacter(sb, c);            }                    }                return (sb == null) ? s : sb.toString();    }    private final static char[] HEX_DIGITS = {	'0', '1', '2', '3', '4', '5', '6', '7',	'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'    };    private static void appendPercentEncodedOctet(StringBuilder sb, int b) {	sb.append('%');	sb.append(HEX_DIGITS[b >> 4]);	sb.append(HEX_DIGITS[b & 0x0F]);    }        private static void appendUTF8EncodedCharacter(StringBuilder sb, char c) {        final ByteBuffer bb = UTF_8_CHARSET.encode("" + c);        	while (bb.hasRemaining()) {            appendPercentEncodedOctet(sb, bb.get() & 0xFF);	}    }        private static final String[] SCHEME = {"0-9", "A-Z", "a-z", "+", "-", "."};        private static final String[] UNRESERVED = {"0-9", "A-Z", "a-z", "-", ".", "_", "~"};        private static final String[] SUB_DELIMS = {"!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="};        private static final boolean[][] ENCODING_TABLES = creatingEncodingTables();        private static boolean[][] creatingEncodingTables() {        boolean[][] tables = new boolean[Type.values().length][];        List<String> l = new ArrayList<String>();        l.addAll(Arrays.asList(SCHEME));        tables[Type.SCHEME.ordinal()] = creatingEncodingTable(l);        l.clear();        l.addAll(Arrays.asList(UNRESERVED));        l.addAll(Arrays.asList(SUB_DELIMS));        tables[Type.HOST.ordinal()] = creatingEncodingTable(l);                tables[Type.PORT.ordinal()] = creatingEncodingTable(Arrays.asList("0-9"));                l.add(":");        tables[Type.USER_INFO.ordinal()] = creatingEncodingTable(l);        l.add("@");        tables[Type.PATH_SEGMENT.ordinal()] = creatingEncodingTable(l);                l.add("/");

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?