Annotation of java/classes/org/w3c/www/protocol/http/HttpManager.java, revision 1.2
1.1 abaird 1: // HttpManager.java
1.2 ! abaird 2: // $Id: HttpManager.java,v 1.1 1996/07/08 18:56:14 abaird Exp $
1.1 abaird 3: // (c) COPYRIGHT MIT and INRIA, 1996.
4: // Please first read the full copyright statement in file COPYRIGHT.html
5:
6: package w3c.www.protocol.http ;
7:
8: import java.util.*;
9: import java.net.*;
10: import java.io.*; // FIXME - DEBUG
11:
12: import w3c.www.mime.*;
13:
14: class ReplyFactory implements MimeParserFactory {
15:
16: public MimeHeaderHolder createHeaderHolder(MimeParser parser) {
17: return new Reply(parser);
18: }
19:
20: }
21:
22:
23: /**
24: * The client side HTTP request manager.
25: * This class is the user interface (along with the other public classes of
26: * this package) for the W3C client side library implementing HTTP.
27: * A typicall request is launched though the following sequence:
28: * <pre>
29: * HttpManager manager = HttpManager.getManager() ;
30: * Request request = manager.makeRequest() ;
31: * request.setMethod(HTTP.GET) ;
32: * request.setURL(new URL("http://www.w3.org/pub/WWW/"));
33: * Reply reply = manager.runRequest(request) ;
34: * // Get the reply input stream that contains the actual data:
35: * InputStream in = reply.getInputStream() ;
36: * ...
37: * </pre>
38: */
39:
40: public class HttpManager {
1.2 ! abaird 41: /**
! 42: * The name of the property containing the ProprequestFilter to launch.
! 43: */
! 44: private static final String FILTERS_PROP = "w3c.www.protocol.http.filters";
! 45:
1.1 abaird 46: private static HttpManager manager = null;
47:
48: /**
49: * The server this manager knows about, indexed by FQDN of target servers.
50: */
51: protected Hashtable servers = null;
52: /**
53: * The template request (the request we will clone to create new requests)
54: */
55: Request template = null ;
56: /**
57: * The filter engine attached to this manager.
58: */
59: FilterEngine filteng = null;
60:
61:
62: /**
63: * Get an instance of the HTTP manager.
64: * This method returns an actual instance of the HTTP manager. It may
65: * return different managers, if it decides to distribute the load on
66: * different managers (avoid the HttpManager being a bottleneck).
67: * @return An application wide instance of the HTTP manager.
68: */
69:
70: public static synchronized HttpManager getManager() {
71: if ( manager == null ) {
72: manager = new HttpManager() ;
1.2 ! abaird 73: // Initialize this new manager:
! 74: String filters = System.getProperty(FILTERS_PROP);
! 75: if ( filters == null )
! 76: return manager;
! 77: StringTokenizer st = new StringTokenizer(filters, "|");
! 78: while (st.hasMoreTokens() ) {
! 79: String cls = (String) st.nextElement();
! 80: try {
! 81: Class c = Class.forName(cls);
! 82: PropRequestFilter f = (PropRequestFilter) c.newInstance();
! 83: f.initialize(manager);
! 84: } catch (Exception ex) {
! 85: System.err.println("Error initializing prop filters:");
! 86: System.err.println("Coulnd't initialize ["
! 87: + cls
! 88: + "]: " + ex.getMessage());
! 89: ex.printStackTrace();
! 90: }
! 91: }
1.1 abaird 92: }
93: return manager;
94: }
95:
96:
97: /**
98: * Get the appropriate server object for handling request to given target.
99: * @param key The server's identifier encoded as a <code>host:port</code>
100: * String.
101: * @return An object complying to the HttpServer interface.
102: * @exception HttpException If the given host name couldn't be resolved.
103: */
104:
105: protected synchronized HttpServer lookupServer(String host, int port)
106: throws HttpException
107: {
108: String id = ((port == 80) ? host : (host +":"+port));
109: // Check for an existing server:
110: HttpServer server = (HttpServer) servers.get(id);
111: if ( server != null )
112: return server;
113: // Create and register a new server:
114: server = new HttpBasicServer();
115: server.initialize(this, host, port);
116: servers.put(id, server);
117: return server;
118: }
119:
120: /**
121: * One of our server handler wants to open a connection.
122: * @param block A boolean indicating whether we should block the calling
123: * thread until a token is available (otherwise, the method will just
124: * peek at the connection count, and return the appropriate result).
125: * @return A boolean, <strong>true</strong> if the connection can be
126: * opened straight, <strong>false</strong> otherwise.
127: */
128:
129: protected boolean negotiateConnection(int ccount) {
130: return (ccount < 2);
131: }
132:
133: /**
134: * Run the given request, in synchronous mode.
135: * This method will launch the given request, and block the calling thread
136: * until the response headers are available.
137: * @param request The request to run.
138: * @return An instance of Reply, containing all the reply
139: * informations.
140: * @exception HTTPException If something failed during request processing.
141: */
142:
143: public Reply runRequest(Request request)
144: throws HttpException
145: {
146: URL target = request.getURL();
147: // Locate the appropriate target server:
148: int port = target.getPort();
149: HttpServer server = lookupServer(target.getHost()
150: , (port == -1) ? 80 : port);
151: // Now run through the ingoing filters:
152: RequestFilter filters[] = filteng.run(request);
153: if ( filters != null ) {
154: for (int i = 0 ; i < filters.length ; i++) {
155: filters[i].ingoingFilter(request);
156: }
157: }
158: // Get the server to give back a reply:
159: Reply reply = server.runRequest(request);
160: // Apply the filters on the way back:
161: if ( filters != null ) {
162: for (int i = 0 ; i < filters.length ; i++)
163: filters[i].outgoingFilter(request, reply);
164: }
165: return reply;
166: }
167:
168: /**
169: * Get this manager's reply factory.
170: * The Reply factory is used when prsing incomming reply from servers, it
171: * decides what object will be created to hold the actual reply from the
172: * server.
173: * @return An object compatible with the MimeParserFactory interface.
174: */
175:
176: MimeParserFactory factory = null ;
177:
178: public synchronized MimeParserFactory getReplyFactory() {
179: if ( factory == null )
180: factory = new ReplyFactory();
181: return factory;
182: }
183:
184: /**
185: * Add a new request filter.
186: * Request filters are called <em>before</em> a request is launched, and
187: * <em>after</em> the reply headers are available. They allow applications
188: * to setup specific request headers (such as PICS, or PEP stuff) on the
189: * way in, and check the reply on the way out.
190: * <p>Request filters are application wide: if their scope matches
191: * the current request, then they will always be aplied.
192: * <p>Filter scopes are defined inclusively and exclusively
193: * @param filter The request filter to add.
194: */
195:
196: public void setFilter(URL incs[], URL exs[], RequestFilter filter) {
197: if ( incs != null ) {
198: for (int i = 0 ; i < incs.length ; i++)
199: filteng.setFilter(incs[i], true, filter);
200: }
201: if ( exs != null ) {
202: for (int i = 0 ; i < exs.length ; i++)
203: filteng.setFilter(exs[i], false, filter);
204: }
205: return;
206: }
207:
208: public void setFilter(RequestFilter filter) {
209: filteng.setFilter(filter);
210: }
211:
212: /**
213: * Add a request processor.
214: * Request processors are application wide hooks, able to answer request
215: * by querying a local cache. An application can set as many request
216: * processor as it wants, each of them will be called in trun (in the order
217: * they were registered), if any of them returns a reply, the request
218: * processing will be halted, and the generated reply returned.
219: * <p>Request processors can also be used to query distant cache, through
220: * some home-brew protocols.
221: * @param processor The request processor to be added.
222: */
223:
224: public void addProcessor(RequestProcessor processor) {
225: }
226:
227: /**
228: * Remove a request processor.
229: * Remove the given request processor.
230: * @return A boolean, <strong>true</strong> if the processor was found
231: * and removed, <strong>false</strong> otherwise.
232: */
233:
234: public boolean removeProcessor(RequestProcessor processor) {
235: return false;
236: }
237:
238: /**
239: * Create a new default outgoing request.
240: * This method should <em>always</em> be used to create outgoing requests.
241: * It will initialize the request with appropriate default values for
242: * the various headers, and make sure that the request is enhanced by
243: * the registered request filters.
244: * @return An instance of Request, suitable to be launched.
245: */
246:
247: public Request createRequest() {
248: return (Request) template.getClone() ;
249: }
250:
251: /**
252: * Global settings - Set the max number of allowed connections.
253: * Set the maximum number of simultaneous connections that can remain
254: * opened. The manager will take care of queuing requests if this number
255: * is reached.
256: * <p>This value defaults to the value of the
257: * <code>w3c.www.http.maxConnections</code> property.
258: * @param max_conn The allowed maximum simultaneous open connections.
259: */
260:
261: public void setMaxConnections(int max_conn) {
262: }
263:
264: /**
265: * Global settings - Set an optional proxy to use.
266: * Set the proxy to which all requests should be targeted. If the
267: * <code>w3c.www.http.proxy</code> property is defined, it will be
268: * used as the default value.
269: * @param proxy The URL for the proxy to use.
270: */
271:
272: public void setProxy(URL proxy) {
273: }
274:
275: /**
276: * Global settings - Set the request timeout.
277: * Once a request has been emited, the HttpManager will sit for this
278: * given number of milliseconds before the request is declared to have
279: * timed-out.
280: * <p>This timeout value defaults to the value of the
281: * <code>w3c.www.http.requestTimeout</code> property value.
282: * @param ms The timeout value in milliseconds.
283: */
284:
285: public void setRequestTimeout(int ms) {
286: }
287:
288: /**
289: * Global settings - Define a global request header.
290: * Set a default value for some request header. Once defined, the
291: * header will automatically be defined on <em>all</em> outgoing requests
292: * created through the <code>createRequest</code> request.
293: * @param name The name of the header, case insensitive.
294: * @param value It's default value.
295: */
296:
297: public void setGlobalHeader(String name, String value) {
298: template.setValue(name, value);
299: }
300:
301: public String getGlobalHeader(String name) {
302: return template.getValue(name);
303: }
304:
305: /**
306: * Create a new HttpManager.
307: * This can only be called from this package. The caller must rather
308: * use the <code>getManager</code> method.
309: * @param props The properties from which the manager should initialize
310: * itself, or <strong>null</strong> if none are available.
311: */
312:
313: HttpManager(Properties props) {
314: this.template = new Request(this);
315: this.servers = new Hashtable();
316: this.filteng = new FilterEngine();
317: }
318:
319: HttpManager() {
320: this(System.getProperties());
321: }
322:
323: /**
324: * DEBUGGING !
325: */
326:
327: public static void main(String args[]) {
328: try {
329: // Get the manager, and define some global headers:
330: HttpManager manager = HttpManager.getManager();
331: manager.setGlobalHeader("User-Agent", "Jigsaw/1.0a");
332: manager.setGlobalHeader("Accept", "*/*;q=1.0");
333: manager.setGlobalHeader("Accept-Encoding", "gzip");
334: Request request = manager.createRequest();
335: request.setURL(new URL(args[0]));
336: request.setMethod("GET");
337: Reply reply = manager.runRequest(request);
338: // Display some infos:
339: System.out.println("last-modified: "+reply.getLastModified());
340: System.out.println("length : "+reply.getContentLength());
341: // Display the returned body:
342: InputStream in = reply.getInputStream();
343: byte buf[] = new byte[4096];
344: int cnt = 0;
345: while ((cnt = in.read(buf)) > 0)
346: System.out.print(new String(buf, 0, 0, cnt));
347: System.out.println("-");
348: in.close();
349: } catch (Exception ex) {
350: ex.printStackTrace();
351: }
352: System.exit(1);
353: }
354: }
Webmaster