KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > activemq > util > URISupport


1 /**
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one or more
4  * contributor license agreements. See the NOTICE file distributed with
5  * this work for additional information regarding copyright ownership.
6  * The ASF licenses this file to You under the Apache License, Version 2.0
7  * (the "License"); you may not use this file except in compliance with
8  * the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18 package org.apache.activemq.util;
19
20 import java.io.UnsupportedEncodingException JavaDoc;
21 import java.net.URI JavaDoc;
22 import java.net.URISyntaxException JavaDoc;
23 import java.net.URLDecoder JavaDoc;
24 import java.net.URLEncoder JavaDoc;
25 import java.util.ArrayList JavaDoc;
26 import java.util.Collections JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.Map JavaDoc;
30
31 /**
32  * @version $Revision$
33  */

34 public class URISupport {
35     
36     public static class CompositeData {
37         String JavaDoc scheme;
38         String JavaDoc path;
39         URI JavaDoc components[];
40         Map JavaDoc parameters;
41         String JavaDoc fragment;
42         public String JavaDoc host;
43         
44         public URI JavaDoc[] getComponents() {
45             return components;
46         }
47         public String JavaDoc getFragment() {
48             return fragment;
49         }
50         public Map JavaDoc getParameters() {
51             return parameters;
52         }
53         public String JavaDoc getScheme() {
54             return scheme;
55         }
56         public String JavaDoc getPath() {
57             return path;
58         }
59         public String JavaDoc getHost() {
60             return host;
61         }
62         
63         public URI JavaDoc toURI() throws URISyntaxException JavaDoc {
64             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
65             if( scheme!=null ) {
66                 sb.append(scheme);
67                 sb.append(':');
68             }
69             
70             if( host!=null && host.length()!=0 ) {
71                 sb.append(host);
72             } else {
73                 sb.append('(');
74                 for (int i = 0; i < components.length; i++) {
75                     if( i!=0 )
76                         sb.append(',');
77                     sb.append(components[i].toString());
78                 }
79                 sb.append(')');
80             }
81             
82             if( path !=null ) {
83                 sb.append('/');
84                 sb.append(path);
85             }
86             if(!parameters.isEmpty()) {
87                 sb.append("?");
88                 sb.append(createQueryString(parameters));
89             }
90             if( fragment!=null ) {
91                 sb.append("#");
92                 sb.append(fragment);
93             }
94             return new URI JavaDoc(sb.toString());
95         }
96     }
97
98     public static Map JavaDoc parseQuery(String JavaDoc uri) throws URISyntaxException JavaDoc{
99         try{
100             Map JavaDoc rc=new HashMap JavaDoc();
101             if(uri!=null){
102                 String JavaDoc[] parameters=uri.split("&");
103                 for(int i=0;i<parameters.length;i++){
104                     int p=parameters[i].indexOf("=");
105                     if(p>=0){
106                         String JavaDoc name=URLDecoder.decode(parameters[i].substring(0,p),"UTF-8");
107                         String JavaDoc value=URLDecoder.decode(parameters[i].substring(p+1),"UTF-8");
108                         rc.put(name,value);
109                     }else{
110                         rc.put(parameters[i],null);
111                     }
112                 }
113             }
114             return rc;
115         }catch(UnsupportedEncodingException JavaDoc e){
116             throw (URISyntaxException JavaDoc) new URISyntaxException JavaDoc(e.toString(),"Invalid encoding").initCause(e);
117         }
118     }
119     
120     public static Map JavaDoc parseParamters(URI JavaDoc uri) throws URISyntaxException JavaDoc {
121         return uri.getQuery()==null ? Collections.EMPTY_MAP : parseQuery(stripPrefix(uri.getQuery(), "?"));
122     }
123
124     /**
125      * Removes any URI query from the given uri
126      */

127     public static URI JavaDoc removeQuery(URI JavaDoc uri) throws URISyntaxException JavaDoc {
128         return createURIWithQuery(uri, null);
129     }
130
131     /**
132      * Creates a URI with the given query
133      */

134     public static URI JavaDoc createURIWithQuery(URI JavaDoc uri, String JavaDoc query) throws URISyntaxException JavaDoc {
135         return new URI JavaDoc(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), query, uri.getFragment());
136     }
137     
138     public static CompositeData parseComposite(URI JavaDoc uri) throws URISyntaxException JavaDoc {
139         
140         CompositeData rc = new CompositeData();
141         rc.scheme = uri.getScheme();
142         String JavaDoc ssp = stripPrefix(uri.getSchemeSpecificPart().trim(), "//").trim();
143
144         parseComposite(uri, rc, ssp);
145         
146         rc.fragment = uri.getFragment();
147         return rc;
148     }
149
150     /**
151      * @param uri
152      * @param rc
153      * @param ssp
154      * @param p
155      * @throws URISyntaxException
156      */

157     private static void parseComposite(URI JavaDoc uri, CompositeData rc, String JavaDoc ssp) throws URISyntaxException JavaDoc {
158         String JavaDoc componentString;
159         String JavaDoc params;
160         
161         if(!checkParenthesis(ssp)){
162             throw new URISyntaxException JavaDoc(uri.toString(), "Not a matching number of '(' and ')' parenthesis");
163         }
164         
165         int p;
166         int intialParen = ssp.indexOf("(");
167         if( intialParen==0 ) {
168             rc.host = ssp.substring(0, intialParen);
169             p = rc.host.indexOf("/");
170             if( p >= 0 ) {
171                 rc.path = rc.host.substring(p);
172                 rc.host = rc.host.substring(0,p);
173             }
174             p = ssp.lastIndexOf(")");
175             componentString = ssp.substring(intialParen+1,p);
176             params = ssp.substring(p+1).trim();
177             
178         } else {
179             componentString = ssp;
180             params="";
181         }
182
183         String JavaDoc components[] = splitComponents(componentString);
184         rc.components=new URI JavaDoc[components.length];
185         for (int i = 0; i < components.length; i++) {
186             rc.components[i] = new URI JavaDoc(components[i].trim());
187         }
188         
189         p = params.indexOf("?");
190         if( p >= 0 ) {
191             if( p > 0) {
192                 rc.path = stripPrefix(params.substring(0, p), "/");
193             }
194             rc.parameters = parseQuery(params.substring(p+1));
195         } else {
196             if( params.length() > 0 )
197                 rc.path = stripPrefix(params, "/");
198             rc.parameters = Collections.EMPTY_MAP;
199         }
200     }
201
202     /**
203      * @param componentString
204      * @return
205      */

206     private static String JavaDoc[] splitComponents(String JavaDoc str) {
207         ArrayList JavaDoc l = new ArrayList JavaDoc();
208         
209         int last=0;
210         int depth = 0;
211         char chars[] = str.toCharArray();
212         for( int i=0; i < chars.length; i ++ ) {
213             switch( chars[i] ) {
214             case '(':
215                 depth++;
216                 break;
217             case ')':
218                 depth--;
219                 break;
220             case ',':
221                 if( depth == 0 ) {
222                     String JavaDoc s = str.substring(last, i);
223                     l.add(s);
224                     last=i+1;
225                 }
226             }
227         }
228         
229         String JavaDoc s = str.substring(last);
230         if( s.length() !=0 )
231             l.add(s);
232         
233         String JavaDoc rc[] = new String JavaDoc[l.size()];
234         l.toArray(rc);
235         return rc;
236     }
237     
238     public static String JavaDoc stripPrefix(String JavaDoc value, String JavaDoc prefix) {
239         if( value.startsWith(prefix) )
240             return value.substring(prefix.length());
241         return value;
242     }
243     
244     public static URI JavaDoc stripScheme(URI JavaDoc uri) throws URISyntaxException JavaDoc {
245         return new URI JavaDoc(stripPrefix(uri.getSchemeSpecificPart().trim(), "//"));
246     }
247
248     public static String JavaDoc createQueryString(Map JavaDoc options) throws URISyntaxException JavaDoc {
249         try {
250             if(options.size()>0) {
251                 StringBuffer JavaDoc rc = new StringBuffer JavaDoc();
252                 boolean first=true;
253                 for (Iterator JavaDoc iter = options.keySet().iterator(); iter.hasNext();) {
254                     if( first )
255                         first=false;
256                     else
257                         rc.append("&");
258                                     
259                     String JavaDoc key = (String JavaDoc) iter.next();
260                     String JavaDoc value = (String JavaDoc)options.get(key);
261                     rc.append(URLEncoder.encode(key, "UTF-8"));
262                     rc.append("=");
263                     rc.append(URLEncoder.encode(value, "UTF-8"));
264                 }
265                 return rc.toString();
266             } else {
267                 return "";
268             }
269         } catch (UnsupportedEncodingException JavaDoc e) {
270             throw (URISyntaxException JavaDoc)new URISyntaxException JavaDoc(e.toString(), "Invalid encoding").initCause(e);
271         }
272     }
273
274     /**
275      * Creates a URI from the original URI and the remaining paramaters
276      * @throws URISyntaxException
277      */

278     public static URI JavaDoc createRemainingURI(URI JavaDoc originalURI, Map JavaDoc params) throws URISyntaxException JavaDoc {
279         String JavaDoc s = createQueryString(params);
280         if( s.length()==0 )
281             s = null;
282         return createURIWithQuery(originalURI, s);
283     }
284
285     static public URI JavaDoc changeScheme(URI JavaDoc bindAddr, String JavaDoc scheme) throws URISyntaxException JavaDoc {
286         return new URI JavaDoc(scheme, bindAddr.getUserInfo(), bindAddr.getHost(), bindAddr.getPort(), bindAddr.getPath(), bindAddr.getQuery(), bindAddr.getFragment());
287     }
288     
289     public static boolean checkParenthesis(String JavaDoc str){
290         boolean result=true;
291         if(str!=null){
292             int open=0;
293             int closed=0;
294             
295             int i=0;
296             while((i=str.indexOf('(',i)) >=0 ){
297                 i++;
298                 open++;
299             }
300             i=0;
301             while((i=str.indexOf(')',i)) >=0 ){
302                 i++;
303                 closed++;
304             }
305             result = open == closed;
306         }
307         return result;
308     }
309     
310     public int indexOfParenthesisMatch(String JavaDoc str){
311         int result = -1;
312         
313         return result;
314     }
315
316 }
317
Popular Tags