KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > nutch > protocol > ProtocolFactory


1 /* Copyright (c) 2003 The Nutch Organization. All rights reserved. */
2 /* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
3
4 package net.nutch.protocol;
5
6 import java.util.Hashtable JavaDoc;
7 import java.net.URL JavaDoc;
8 import java.net.MalformedURLException JavaDoc;
9
10 import net.nutch.plugin.*;
11
12 import java.util.logging.Logger JavaDoc;
13 import net.nutch.util.LogFormatter;
14
15 /** Creates and caches {@link Protocol} plugins. Protocol plugins should
16  * define the attribute "protocolName" with the name of the protocol that they
17  * implement. */

18 public class ProtocolFactory {
19
20   public static final Logger JavaDoc LOG = LogFormatter
21     .getLogger(ProtocolFactory.class.getName());
22
23   private final static ExtensionPoint X_POINT = PluginRepository.getInstance()
24       .getExtensionPoint(Protocol.X_POINT_ID);
25
26   static {
27     if (X_POINT == null) {
28       throw new RuntimeException JavaDoc("x-point "+Protocol.X_POINT_ID+" not found.");
29     }
30   }
31
32   private static final Hashtable JavaDoc CACHE = new Hashtable JavaDoc();
33
34   private ProtocolFactory() {} // no public ctor
35

36   /** Returns the appropriate {@link Protocol} implementation for a url. */
37   public static Protocol getProtocol(String JavaDoc urlString)
38     throws ProtocolNotFound {
39     try {
40       URL JavaDoc url = new URL JavaDoc(urlString);
41       String JavaDoc protocolName = url.getProtocol();
42       if (protocolName == null)
43         throw new ProtocolNotFound(urlString);
44       Extension extension = getExtension(protocolName);
45       if (extension == null)
46         throw new ProtocolNotFound(protocolName);
47
48       return (Protocol)extension.getExtensionInstance();
49
50     } catch (MalformedURLException JavaDoc e) {
51       throw new ProtocolNotFound(urlString, e.toString());
52     } catch (PluginRuntimeException e) {
53       throw new ProtocolNotFound(urlString, e.toString());
54     }
55   }
56
57   private static Extension getExtension(String JavaDoc name)
58     throws PluginRuntimeException {
59
60     if (CACHE.containsKey(name))
61       return (Extension)CACHE.get(name);
62     
63     Extension extension = findExtension(name);
64     
65     CACHE.put(name, extension);
66     
67     return extension;
68   }
69
70   private static Extension findExtension(String JavaDoc name)
71     throws PluginRuntimeException {
72
73     Extension[] extensions = X_POINT.getExtentens();
74
75     for (int i = 0; i < extensions.length; i++) {
76       Extension extension = extensions[i];
77
78       if (name.equals(extension.getAttribute("protocolName")))
79         return extension;
80     }
81     return null;
82   }
83 }
84
Popular Tags