1/*
2 * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package com.sun.jmx.mbeanserver;
27
28import java.util.ArrayList;
29import java.util.Arrays;
30import java.util.Collection;
31import java.util.Collections;
32import java.util.Comparator;
33import java.util.HashMap;
34import java.util.HashSet;
35import java.util.IdentityHashMap;
36import java.util.LinkedHashMap;
37import java.util.List;
38import java.util.Map;
39import java.util.Set;
40import java.util.SortedMap;
41import java.util.TreeMap;
42import javax.management.MalformedObjectNameException;
43import javax.management.ObjectName;
44
45public class Util {
46    public static ObjectName newObjectName(String string) {
47        try {
48            return new ObjectName(string);
49        } catch (MalformedObjectNameException e) {
50            throw new IllegalArgumentException(e);
51        }
52    }
53
54    static <K, V> Map<K, V> newMap() {
55        return new HashMap<K, V>();
56    }
57
58    static <K, V> Map<K, V> newSynchronizedMap() {
59        return Collections.synchronizedMap(Util.<K, V>newMap());
60    }
61
62    static <K, V> IdentityHashMap<K, V> newIdentityHashMap() {
63        return new IdentityHashMap<K, V>();
64    }
65
66    static <K, V> Map<K, V> newSynchronizedIdentityHashMap() {
67        Map<K, V> map = newIdentityHashMap();
68        return Collections.synchronizedMap(map);
69    }
70
71    static <K, V> SortedMap<K, V> newSortedMap() {
72        return new TreeMap<K, V>();
73    }
74
75    static <K, V> SortedMap<K, V> newSortedMap(Comparator<? super K> comp) {
76        return new TreeMap<K, V>(comp);
77    }
78
79    static <K, V> Map<K, V> newInsertionOrderMap() {
80        return new LinkedHashMap<K, V>();
81    }
82
83    static <E> Set<E> newSet() {
84        return new HashSet<E>();
85    }
86
87    static <E> Set<E> newSet(Collection<E> c) {
88        return new HashSet<E>(c);
89    }
90
91    static <E> List<E> newList() {
92        return new ArrayList<E>();
93    }
94
95    static <E> List<E> newList(Collection<E> c) {
96        return new ArrayList<E>(c);
97    }
98
99    /* This method can be used by code that is deliberately violating the
100     * allowed checked casts.  Rather than marking the whole method containing
101     * the code with @SuppressWarnings, you can use a call to this method for
102     * the exact place where you need to escape the constraints.  Typically
103     * you will "import static" this method and then write either
104     *    X x = cast(y);
105     * or, if that doesn't work (e.g. X is a type variable)
106     *    Util.<X>cast(y);
107     */
108    @SuppressWarnings("unchecked")
109    public static <T> T cast(Object x) {
110        return (T) x;
111    }
112
113    /**
114     * Computes a descriptor hashcode from its names and values.
115     * @param names  the sorted array of descriptor names.
116     * @param values the array of descriptor values.
117     * @return a hash code value, as described in {@link #hashCode(Descriptor)}
118     */
119    public static int hashCode(String[] names, Object[] values) {
120        int hash = 0;
121        for (int i = 0; i < names.length; i++) {
122            Object v = values[i];
123            int h;
124            if (v == null) {
125                h = 0;
126            } else if (v instanceof Object[]) {
127                h = Arrays.deepHashCode((Object[]) v);
128            } else if (v.getClass().isArray()) {
129                h = Arrays.deepHashCode(new Object[]{v}) - 31;
130            // hashcode of a list containing just v is
131            // v.hashCode() + 31, see List.hashCode()
132            } else {
133                h = v.hashCode();
134            }
135            hash += names[i].toLowerCase().hashCode() ^ h;
136        }
137        return hash;
138    }
139
140    /** Match a part of a string against a shell-style pattern.
141        The only pattern characters recognized are <code>?</code>,
142        standing for any one character,
143        and <code>*</code>, standing for any string of
144        characters, including the empty string. For instance,
145        {@code wildmatch("sandwich","sa?d*ch",1,4,1,4)} will match
146        {@code "and"} against {@code "a?d"}.
147
148        @param str  the string containing the sequence to match.
149        @param pat  a string containing a pattern to match the sub string
150                    against.
151        @param stri   the index in the string at which matching should begin.
152        @param strend the index in the string at which the matching should
153                      end.
154        @param pati   the index in the pattern at which matching should begin.
155        @param patend the index in the pattern at which the matching should
156                      end.
157
158        @return true if and only if the string matches the pattern.
159    */
160    /* The algorithm is a classical one.  We advance pointers in
161       parallel through str and pat.  If we encounter a star in pat,
162       we remember its position and continue advancing.  If at any
163       stage we get a mismatch between str and pat, we look to see if
164       there is a remembered star.  If not, we fail.  If so, we
165       retreat pat to just past that star and str to the position
166       after the last one we tried, and we let the match advance
167       again.
168
169       Even though there is only one remembered star position, the
170       algorithm works when there are several stars in the pattern.
171       When we encounter the second star, we forget the first one.
172       This is OK, because if we get to the second star in A*B*C
173       (where A etc are arbitrary strings), we have already seen AXB.
174       We're therefore setting up a match of *C against the remainder
175       of the string, which will match if that remainder looks like
176       YC, so the whole string looks like AXBYC.
177    */
178    private static boolean wildmatch(final String str, final String pat,
179            int stri, final int strend, int pati, final int patend) {
180
181        // System.out.println("matching "+pat.substring(pati,patend)+
182        //        " against "+str.substring(stri, strend));
183        int starstri; // index for backtrack if "*" attempt fails
184        int starpati; // index for backtrack if "*" attempt fails, +1
185
186        starstri = starpati = -1;
187
188        /* On each pass through this loop, we either advance pati,
189           or we backtrack pati and advance starstri.  Since starstri
190           is only ever assigned from pati, the loop must terminate.  */
191        while (true) {
192            if (pati < patend) {
193                final char patc = pat.charAt(pati);
194                switch (patc) {
195                case '?':
196                    if (stri == strend)
197                        break;
198                    stri++;
199                    pati++;
200                    continue;
201                case '*':
202                    pati++;
203                    starpati = pati;
204                    starstri = stri;
205                    continue;
206                default:
207                    if (stri < strend && str.charAt(stri) == patc) {
208                        stri++;
209                        pati++;
210                        continue;
211                    }
212                    break;
213                }
214            } else if (stri == strend)
215                return true;
216
217            // Mismatched, can we backtrack to a "*"?
218            if (starpati < 0 || starstri == strend)
219                return false;
220
221            // Retry the match one position later in str
222            pati = starpati;
223            starstri++;
224            stri = starstri;
225        }
226    }
227
228    /** Match a string against a shell-style pattern.  The only pattern
229        characters recognized are <code>?</code>, standing for any one
230        character, and <code>*</code>, standing for any string of
231        characters, including the empty string.
232
233        @param str the string to match.
234        @param pat the pattern to match the string against.
235
236        @return true if and only if the string matches the pattern.
237    */
238    public static boolean wildmatch(String str, String pat) {
239        return wildmatch(str,pat,0,str.length(),0,pat.length());
240    }
241}
242