View Javadoc

1   /*
2    * $Id: ServletHelper.java,v 1.14 2004/11/12 10:44:54 mch Exp $
3    *
4    * (C) Copyright Astrogrid...
5    */
6   
7   package org.astrogrid.datacenter.service;
8   
9   import java.io.PrintWriter;
10  import java.io.StringWriter;
11  import java.net.MalformedURLException;
12  import java.net.URISyntaxException;
13  import javax.servlet.http.HttpServletRequest;
14  import org.apache.commons.logging.Log;
15  import org.apache.commons.logging.LogFactory;
16  import org.astrogrid.community.Account;
17  import org.astrogrid.config.SimpleConfig;
18  import org.astrogrid.datacenter.query.condition.CircleCondition;
19  import org.astrogrid.datacenter.returns.ReturnSpec;
20  import org.astrogrid.datacenter.returns.ReturnTable;
21  import org.astrogrid.slinger.targets.TargetMaker;
22  
23  /***
24   * A set of dataserver methods for helping serving data in HTML form, eg for servlets
25   * or JSPs
26   * <p>
27   * @author M Hill
28   */
29  
30  public class ServletHelper
31  {
32     
33     protected static Log log = LogFactory.getLog(ServletHelper.class);
34  
35     private static String urlStem = null;
36     
37     /*** Provides static access to the url stem (eg http://grendel12.roe.ac.uk/pal-6df)" target="alexandria_uri">http://grendel12.roe.ac.uk/pal-6df) which
38      * will have to have been set from a servlet call to setUrlStem beforehand. May be a
39      * static way of doing this? Returns stem without final slash */
40     public static String getUrlStem() {
41        if (urlStem != null) {
42           return urlStem;
43        }
44        //might be set in config for authority stuff
45        String configStem = SimpleConfig.getSingleton().getString("datacenter.url", null);
46        if (configStem != null) {
47           if (!configStem.endsWith("/")) {
48              configStem = configStem+"/";
49           }
50        }
51        return configStem;
52     }
53  
54     public static void setUrlStem(HttpServletRequest request) {
55        setUrlStem(
56           request.getScheme()+"://"+request.getServerName() +":" + request.getServerPort()+request.getContextPath()
57        );
58     }
59  
60     public static void setUrlStem(String aStem) {
61        if (!aStem.endsWith("/")) {
62           aStem = aStem+"/";
63        }
64        log.info("Service Stem set to '"+aStem+"'");
65        if (urlStem == null) {
66           urlStem = aStem;
67        }
68        else if (!urlStem.equals(aStem)) {
69           log.error("Trying to set service URL stem to "+aStem+" when already "+urlStem+"; ignoring new stem");
70        }
71     }
72  
73     /***
74      * Gets the user details from the request */
75     public static Account getUser(HttpServletRequest request)  {
76        Account user = Account.ANONYMOUS;
77        //for information only
78        if (request.getParameter("UserName") != null) {
79           user = new Account(request.getParameter("UserName"), "Unknown", null);
80        }
81        return user;
82     }
83  
84     /***
85      * Convenience routine for JSPs; decides where target should be from
86      * the parameters in the given request.  The parameter names should match
87      * those assigned in resultsForm.xml */
88     public static ReturnSpec makeReturnSpec(HttpServletRequest request)  {
89  
90        ReturnTable returns = new ReturnTable(null);
91  
92        fillReturnSpec(returns, request);
93        
94        return returns;
95     }
96  
97     /***
98      * Convenience routine for JSPs; decides where target should be from
99      * the parameters in the given request.  The parameter names should match
100     * those assigned in resultsForm.xml */
101    public static void fillReturnSpec(ReturnTable tableSpec, HttpServletRequest request)  {
102 
103       String targetResponse = request.getParameter("TargetResponse");
104       if ((targetResponse != null) && targetResponse.trim().toLowerCase().equals("true")) {
105          //target is the http response
106          tableSpec.setTarget(null);
107       }
108       else {
109          String targetUri = request.getParameter("TargetURI");   //direction - eg URI
110          if ((targetUri != null) && (targetUri.trim().length()>0)) {
111                
112             try {
113                tableSpec.setTarget(TargetMaker.makeIndicator(targetUri));
114             }
115             catch (URISyntaxException e) {
116                throw new IllegalArgumentException("Invalid target: "+targetUri+" ("+e+")");
117             }
118             catch (MalformedURLException e) {
119                throw new IllegalArgumentException("Invalid target: "+targetUri+" ("+e+")");
120             }
121          }
122          else {
123             //throw new IllegalArgumentException("Bad Target; TargetResponse not 'true' and TargetURI not set");
124             //assume targetresponse true (for things like cone searches)
125             tableSpec.setTarget(null);
126          }
127       }
128       
129       String format = request.getParameter("Format");
130       if ( (format != null) && (format.trim().length()>0)) {
131          tableSpec.setFormat(format);
132       }
133       
134       String compression = request.getParameter("Compression");
135       if ( (compression != null) && (compression.trim().length()>0)) {
136          tableSpec.setCompression(compression);
137       }
138 
139       String limit = request.getParameter("Limit");
140       if ( (limit != null) && (limit.trim().length()>0)) {
141          tableSpec.setLimit(Integer.parseInt(limit));
142       }
143 
144    }
145    
146    /*** Creates a Circle function condition from parameters in the given request.
147     * Accepts POS=(ra,dec) and RA=ra&DEC=dec, and SIZE and SR for search radius.
148     * Accepts all-lower case as well as all-upper case
149     */
150    public static CircleCondition makeCircleCondition(HttpServletRequest request) {
151       
152       String radiusparam = request.getParameter("SIZE");
153       if (radiusparam == null) { radiusparam = request.getParameter("size"); }
154       if (radiusparam == null) { radiusparam = request.getParameter("SR"); }
155       if (radiusparam == null) { radiusparam = request.getParameter("sr"); }
156       if (radiusparam == null) { radiusparam = request.getParameter("RADIUS"); }
157       if (radiusparam == null) { radiusparam = request.getParameter("radius"); }
158       if (radiusparam == null) {
159          throw new IllegalArgumentException("No Radius given as SIZE or SR or RADIUS");
160       }
161       double radius = Double.parseDouble(radiusparam);
162       
163       double ra;
164       double dec;
165 
166       String pos = request.getParameter("POS");
167       if (pos == null)     {  request.getParameter("pos"); }
168       if (pos != null) {
169          int comma = pos.indexOf(",");
170          ra = Double.parseDouble(pos.substring(0,comma));
171          dec = Double.parseDouble(pos.substring(comma+1));
172          return new CircleCondition(ra, dec, radius);
173       }
174 
175       String raparam = request.getParameter("RA");
176       if (raparam == null) {  raparam = request.getParameter("ra"); }
177       if (raparam == null) {  raparam = request.getParameter("Ra"); }
178       if (raparam == null) {
179          throw new IllegalArgumentException("No RA given");
180       }
181       
182       String decparam = request.getParameter("DEC");
183       if (decparam == null) { decparam = request.getParameter("dec"); }
184       if (decparam == null) { decparam = request.getParameter("Dec"); }
185       if (raparam == null) {
186          throw new IllegalArgumentException("No DEC given");
187       }
188       
189       ra = Double.parseDouble(raparam);
190       dec = Double.parseDouble(decparam);
191       
192       return new CircleCondition(ra, dec, radius);
193    }
194    
195    
196    /*** Convenience routine for returning the correct 'HTML' snippet that
197     * refreshes the page given by the URL - which should point to the same page
198     * that contains the snippet */
199    public static String makeRefreshSnippet(int secs, String url) {
200          return("(Refreshes every "+secs+" seconds)"+
201                 "<META HTTP-EQUIV='Refresh' CONTENT='"+secs+";URL="+url+"'>");
202    }
203 
204    /*** Returns the stylesheet to be used for the center's html pages in the form
205     * of a 'link' element.  Returns an empty string if none configured */
206    public static String getCssLink() {
207       String cssName = SimpleConfig.getProperty("datacenter.stylesheet",  "default.css");
208       if (cssName.length() == 0) {
209          return "";
210       }
211       else {
212          return "<LINK href='"+cssName+"' rel='stylesheet' type='text/css'>";
213       }
214    }
215 
216    /*** Convenience routine that returns the complete <HEAD> element for the
217     * standard datacenter page */
218    public static String getHeadElement(String title) {
219       return "<HEAD>\n"+
220              "  <TITLE>"+title+" ("+DataServer.getDatacenterName()+")</TITLE>\n"+
221              "  "+getCssLink()+"\n"+
222              "</HEAD>\n";
223    }
224 
225    
226    /***
227     * Returns an error as string suitable for display in a browser as an html
228     * page
229     */
230    public static String exceptionAsHtmlPage(String title, Throwable th, String details) {
231       return
232          "<html>\n"+
233          "<head><title>ERROR: "+makeSafeForHtml(title)+"</title></head>\n"+
234          "<body>\n"+
235          exceptionAsHtml(title, th, details)+
236          "</body>\n"+
237          "</html>\n";
238    }
239 
240    /*** Returns exception suitable for a paragraph in an hmtl page */
241    public static String exceptionAsHtml(String title, Throwable th, String details) {
242 
243       String s =
244          "<h1>ERROR REPORT</h1>\n"+
245          "<h2>"+makeSafeForHtml(title)+"</h2>\n";
246       if (th != null) {
247          StringWriter sw = new StringWriter();
248          th.printStackTrace(new PrintWriter(sw));
249          String stack = sw.toString();
250 
251          s = s +
252          "<p><b>"+makeSafeForHtml(th.toString())+"</b></p>\n"+
253          "<p>\n"+
254          "<pre>"+makeSafeForHtml(stack)+"</pre>\n"+
255          "</p>\n"+
256          "<p>\n"+
257          "<pre>"+makeSafeForHtml(details)+"</pre>\n"+
258          "</p>\n";
259       }
260       return s;
261    }
262 
263    /***
264     * Deals with special characters */
265    public static String makeSafeForHtml(String s) {
266       if (s==null) {
267          return "";
268       }
269       s = s.replaceAll(">", "&gt;").replaceAll("<", "&lt;");
270       return s.replaceAll("\n","<br/>");
271    }
272    
273    /*** Convenience routine for exceptionAsHtml(String, Exception, String)   */
274    public static String exceptionAsHtmlPage(String title, Throwable th) {
275       return exceptionAsHtmlPage(title, th, "");
276    }
277 }
278 
279 
280 
281 
282 
283 
284 
285 
286 
287 
288 
289