01: /*
02: * Created on Dec 23, 2004
03: */
04: package uk.org.ponder.servletutil;
05:
06: import java.io.InputStream;
07: import java.io.OutputStream;
08: import java.net.URL;
09: import java.net.URLConnection;
10:
11: import uk.org.ponder.saxalizer.XMLProvider;
12: import uk.org.ponder.streamutil.StreamCloseUtil;
13: import uk.org.ponder.util.Logger;
14: import uk.org.ponder.util.UniversalRuntimeException;
15: import uk.org.ponder.webapputil.ErrorObject;
16:
17: /** A utility class for clients of an InformationServlet. Accepts an object
18: * to represent the request argument and a URL to dispatch it to, and does the
19: * work of encoding it, performing the dispatch and decoding the response back
20: * into an object.
21: * @author Antranig Basman (antranig@caret.cam.ac.uk)
22: *
23: */
24: public class HTTPRequestDispatcher {
25: private String requestURL;
26: private XMLProvider xmlprovider;
27:
28: public void setRequestURL(String URL) {
29: this .requestURL = URL;
30: }
31:
32: public void setXMLProvider(XMLProvider xmlprovider) {
33: this .xmlprovider = xmlprovider;
34: }
35:
36: public Object handleRequest(String requestURL, Object arg) {
37: try {
38: URL URL = new URL(requestURL);
39: URLConnection huc = URL.openConnection();
40: huc.setDoOutput(true);
41: huc.setRequestProperty("Content-Type",
42: "application/xml; charset=UTF-8");
43:
44: OutputStream os = null;
45: try {
46: os = huc.getOutputStream();
47: xmlprovider.writeXML(arg, os);
48: String debugstring = xmlprovider.toString(arg);
49: Logger.log.info("HTTPRequestDispatcher sending data:\n"
50: + debugstring);
51: } finally {
52: StreamCloseUtil.closeOutputStream(os);
53: }
54:
55: InputStream is = null;
56: try {
57: is = huc.getInputStream();
58: Object togo = xmlprovider.readXML(null, is);
59: if (togo instanceof ErrorObject) {
60: ErrorObject error = (ErrorObject) togo;
61: Logger.log
62: .warn("Remote exception intercepted in HTTPRequestDispatcher:\n"
63: + error.message
64: + error.stacktrace.pack());
65: throw new UniversalRuntimeException(
66: "Remote exception occurred during dispatching: "
67: + error.message);
68:
69: }
70: return togo;
71: } finally {
72: StreamCloseUtil.closeInputStream(is);
73: }
74: } catch (Throwable t) {
75: throw UniversalRuntimeException.accumulate(t,
76: "Error performing remote request to URL "
77: + requestURL);
78: }
79:
80: }
81: }
|