KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > axis > components > net > DefaultSocketFactory


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2001-2003 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "Axis" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation. For more
52  * information on the Apache Software Foundation, please see
53  * <http://www.apache.org/>.
54  */

55 package org.jboss.axis.components.net;
56
57 import java.net.Socket JavaDoc;
58 import java.util.HashMap JavaDoc;
59 import java.util.StringTokenizer JavaDoc;
60
61 import org.jboss.axis.encoding.Base64;
62 import org.jboss.axis.transport.http.HTTPConstants;
63 import org.jboss.axis.utils.Messages;
64 import org.jboss.logging.Logger;
65
66 /**
67  * Default socket factory.
68  *
69  * @author Davanum Srinivas (dims@yahoo.com)
70  */

71 public class DefaultSocketFactory implements SocketFactory
72 {
73
74    /**
75     * Field log
76     */

77    private static Logger log = Logger.getLogger(DefaultSocketFactory.class.getName());
78
79    /**
80     * options
81     */

82    protected HashMap JavaDoc options = null;
83
84    /**
85     * Constructor is used only by subclasses.
86     *
87     * @param attributes
88     */

89    public DefaultSocketFactory(HashMap JavaDoc options)
90    {
91       this.options = options;
92    }
93
94    /**
95     * Creates a socket.
96     *
97     * @param host
98     * @param port
99     * @param otherHeaders
100     * @param useFullURL
101     * @return Socket
102     * @throws Exception
103     */

104    public Socket JavaDoc create(String JavaDoc host, int port, StringBuffer JavaDoc otherHeaders, BooleanHolder useFullURL)
105            throws Exception JavaDoc
106    {
107
108       TransportClientProperties tcp = TransportClientPropertiesFactory.create("http");
109
110       Socket JavaDoc sock = null;
111       boolean hostInNonProxyList = isHostInNonProxyList(host, tcp.getNonProxyHosts());
112
113       if (tcp.getProxyUser().length() != 0)
114       {
115          StringBuffer JavaDoc tmpBuf = new StringBuffer JavaDoc();
116
117          tmpBuf.append(tcp.getProxyUser())
118                  .append(":")
119                  .append(tcp.getProxyPassword());
120          otherHeaders.append(HTTPConstants.HEADER_PROXY_AUTHORIZATION)
121                  .append(": Basic ")
122                  .append(Base64.encode(tmpBuf.toString().getBytes()))
123                  .append("\r\n");
124       }
125       if (port == -1)
126       {
127          port = 80;
128       }
129       if ((tcp.getProxyHost().length() == 0) ||
130               (tcp.getProxyPort().length() == 0) ||
131               hostInNonProxyList)
132       {
133          sock = new Socket JavaDoc(host, port);
134          if (log.isDebugEnabled())
135          {
136             log.debug(Messages.getMessage("createdHTTP00"));
137          }
138       }
139       else
140       {
141          sock = new Socket JavaDoc(tcp.getProxyHost(),
142                  new Integer JavaDoc(tcp.getProxyPort()).intValue());
143          if (log.isDebugEnabled())
144          {
145             log.debug(Messages.getMessage("createdHTTP01", tcp.getProxyHost(),
146                     tcp.getProxyPort()));
147          }
148          useFullURL.value = true;
149       }
150       return sock;
151    }
152
153    /**
154     * Check if the specified host is in the list of non proxy hosts.
155     *
156     * @param host host name
157     * @param nonProxyHosts string containing the list of non proxy hosts
158     * @return true/false
159     */

160    protected boolean isHostInNonProxyList(String JavaDoc host, String JavaDoc nonProxyHosts)
161    {
162
163       if ((nonProxyHosts == null) || (host == null))
164       {
165          return false;
166       }
167
168       /*
169        * The http.nonProxyHosts system property is a list enclosed in
170        * double quotes with items separated by a vertical bar.
171        */

172       StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(nonProxyHosts, "|\"");
173
174       while (tokenizer.hasMoreTokens())
175       {
176          String JavaDoc pattern = tokenizer.nextToken();
177
178          if (log.isDebugEnabled())
179          {
180             log.debug(Messages.getMessage("match00",
181                     new String JavaDoc[]{"HTTPSender",
182                                  host,
183                                  pattern}));
184          }
185          if (match(pattern, host, false))
186          {
187             return true;
188          }
189       }
190       return false;
191    }
192
193    /**
194     * Matches a string against a pattern. The pattern contains two special
195     * characters:
196     * '*' which means zero or more characters,
197     *
198     * @param pattern the (non-null) pattern to match against
199     * @param str the (non-null) string that must be matched against the
200     * pattern
201     * @param isCaseSensitive
202     * @return <code>true</code> when the string matches against the pattern,
203     * <code>false</code> otherwise.
204     */

205    protected static boolean match(String JavaDoc pattern, String JavaDoc str,
206                                   boolean isCaseSensitive)
207    {
208
209       char[] patArr = pattern.toCharArray();
210       char[] strArr = str.toCharArray();
211       int patIdxStart = 0;
212       int patIdxEnd = patArr.length - 1;
213       int strIdxStart = 0;
214       int strIdxEnd = strArr.length - 1;
215       char ch;
216       boolean containsStar = false;
217
218       for (int i = 0; i < patArr.length; i++)
219       {
220          if (patArr[i] == '*')
221          {
222             containsStar = true;
223             break;
224          }
225       }
226       if (!containsStar)
227       {
228
229          // No '*'s, so we make a shortcut
230
if (patIdxEnd != strIdxEnd)
231          {
232             return false; // Pattern and string do not have the same size
233
}
234          for (int i = 0; i <= patIdxEnd; i++)
235          {
236             ch = patArr[i];
237             if (isCaseSensitive && (ch != strArr[i]))
238             {
239                return false; // Character mismatch
240
}
241             if (!isCaseSensitive
242                     && (Character.toUpperCase(ch)
243                     != Character.toUpperCase(strArr[i])))
244             {
245                return false; // Character mismatch
246
}
247          }
248          return true; // String matches against pattern
249
}
250       if (patIdxEnd == 0)
251       {
252          return true; // Pattern contains only '*', which matches anything
253
}
254
255       // Process characters before first star
256
while ((ch = patArr[patIdxStart]) != '*'
257               && (strIdxStart <= strIdxEnd))
258       {
259          if (isCaseSensitive && (ch != strArr[strIdxStart]))
260          {
261             return false; // Character mismatch
262
}
263          if (!isCaseSensitive
264                  && (Character.toUpperCase(ch)
265                  != Character.toUpperCase(strArr[strIdxStart])))
266          {
267             return false; // Character mismatch
268
}
269          patIdxStart++;
270          strIdxStart++;
271       }
272       if (strIdxStart > strIdxEnd)
273       {
274
275          // All characters in the string are used. Check if only '*'s are
276
// left in the pattern. If so, we succeeded. Otherwise failure.
277
for (int i = patIdxStart; i <= patIdxEnd; i++)
278          {
279             if (patArr[i] != '*')
280             {
281                return false;
282             }
283          }
284          return true;
285       }
286
287       // Process characters after last star
288
while ((ch = patArr[patIdxEnd]) != '*' && (strIdxStart <= strIdxEnd))
289       {
290          if (isCaseSensitive && (ch != strArr[strIdxEnd]))
291          {
292             return false; // Character mismatch
293
}
294          if (!isCaseSensitive
295                  && (Character.toUpperCase(ch)
296                  != Character.toUpperCase(strArr[strIdxEnd])))
297          {
298             return false; // Character mismatch
299
}
300          patIdxEnd--;
301          strIdxEnd--;
302       }
303       if (strIdxStart > strIdxEnd)
304       {
305
306          // All characters in the string are used. Check if only '*'s are
307
// left in the pattern. If so, we succeeded. Otherwise failure.
308
for (int i = patIdxStart; i <= patIdxEnd; i++)
309          {
310             if (patArr[i] != '*')
311             {
312                return false;
313             }
314          }
315          return true;
316       }
317
318       // process pattern between stars. padIdxStart and patIdxEnd point
319
// always to a '*'.
320
while ((patIdxStart != patIdxEnd) && (strIdxStart <= strIdxEnd))
321       {
322          int patIdxTmp = -1;
323
324          for (int i = patIdxStart + 1; i <= patIdxEnd; i++)
325          {
326             if (patArr[i] == '*')
327             {
328                patIdxTmp = i;
329                break;
330             }
331          }
332          if (patIdxTmp == patIdxStart + 1)
333          {
334
335             // Two stars next to each other, skip the first one.
336
patIdxStart++;
337             continue;
338          }
339
340          // Find the pattern between padIdxStart & padIdxTmp in str between
341
// strIdxStart & strIdxEnd
342
int patLength = (patIdxTmp - patIdxStart - 1);
343          int strLength = (strIdxEnd - strIdxStart + 1);
344          int foundIdx = -1;
345
346          strLoop:
347          for (int i = 0; i <= strLength - patLength; i++)
348          {
349             for (int j = 0; j < patLength; j++)
350             {
351                ch = patArr[patIdxStart + j + 1];
352                if (isCaseSensitive
353                        && (ch != strArr[strIdxStart + i + j]))
354                {
355                   continue strLoop;
356                }
357                if (!isCaseSensitive && (Character
358                        .toUpperCase(ch) != Character
359                        .toUpperCase(strArr[strIdxStart + i + j])))
360                {
361                   continue strLoop;
362                }
363             }
364             foundIdx = strIdxStart + i;
365             break;
366          }
367          if (foundIdx == -1)
368          {
369             return false;
370          }
371          patIdxStart = patIdxTmp;
372          strIdxStart = foundIdx + patLength;
373       }
374
375       // All characters in the string are used. Check if only '*'s are left
376
// in the pattern. If so, we succeeded. Otherwise failure.
377
for (int i = patIdxStart; i <= patIdxEnd; i++)
378       {
379          if (patArr[i] != '*')
380          {
381             return false;
382          }
383       }
384       return true;
385    }
386 }
387
Popular Tags