KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > resource > ResourceHandlerChain


1 package org.sapia.resource;
2
3 import java.io.IOException JavaDoc;
4 import java.util.ArrayList JavaDoc;
5 import java.util.List JavaDoc;
6
7 /**
8  * This class implements a chain of responsibility: an instance of this class
9  * holds a list of <code>ResourceHandler</code> instances. The instances are
10  * traversed when client application request a specific handler, given a URI.
11  *
12  * @author Yanick Duchesne
13  */

14 public class ResourceHandlerChain implements ResourceCapable{
15
16   private List JavaDoc _handlers = new ArrayList JavaDoc();
17  
18   /**
19    * Adds a resource handler to the beginning of the list that this instance
20    * holds.
21    *
22    * @param handler
23    * a <code>ResourceHandler</code>.
24    */

25   public synchronized void prepend(ResourceHandler handler) {
26     _handlers.add(0, handler);
27   }
28
29   /**
30    * Adds a resource handler to the end of the list that this instance holds.
31    *
32    * @param handler
33    * a <code>ResourceHandler</code>.
34    */

35   public synchronized void append(ResourceHandler handler) {
36     _handlers.add(handler);
37   }
38   
39   public synchronized Resource resolveResource(String JavaDoc uri)
40     throws ResourceNotFoundException, IOException JavaDoc{
41     ResourceHandler handler = doSelect(uri);
42     if(handler == null){
43       throw new ResourceNotFoundException("Could not find resource handler for: " + uri);
44     }
45     return handler.getResourceObject(uri);
46   }
47
48   /**
49    * Selects a <code>ResourceHandler</code> from this instance and returns it.
50    * The handler is chose based on the given URI. <p/>This instance traverses
51    * its handlers, calling the <code>accepts()</code> method on them (the
52    * method takes the given URI as a parameter). The first handler that
53    * "accepts" the URI (by returning <code>true</code>) is returned to the
54    * caller. If no handler as accepted the URI, <code>null</code> is returned.
55    *
56    * @param uri
57    * a URI.
58    * @return a <b>ResourceHandler </b>, or <code>null</code> if no handler
59    * could be found for the given URI.
60    */

61   public synchronized ResourceHandler select(String JavaDoc uri) {
62     
63     return doSelect(uri);
64   }
65   
66   protected ResourceHandler doSelect(String JavaDoc uri){
67     ResourceHandler handler = null;
68     for(int i = 0; i < _handlers.size(); i++) {
69       handler = (ResourceHandler) _handlers.get(i);
70       if(handler.accepts(uri)) {
71         break;
72       }
73       else{
74         handler = null;
75       }
76     }
77     return handler;
78   }
79   
80 }
81
Popular Tags