View Javadoc

1   package org.molwind.servlet;
2   
3   /*
4    * This file is part of Molwind.
5    *
6    * Molwind is free software: you can redistribute it and/or modify
7    * it under the terms of the GNU General Public License as published by
8    * the Free Software Foundation, either version 3 of the License, or
9    * (at your option) any later version.
10   *
11   * Molwind is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14   * GNU General Public License for more details.
15   *
16   * You should have received a copy of the GNU General Public License
17   * along with Molwind. If not, see <http://www.gnu.org/licenses/>.
18   */
19  
20  
21  import org.jdom.*;
22  import java.io.File;
23  import java.io.IOException;
24  import java.util.Enumeration;
25  import java.util.HashMap;
26  
27  import javax.servlet.ServletConfig;
28  import javax.servlet.ServletException;
29  import javax.servlet.http.HttpServlet;
30  import javax.servlet.http.HttpServletRequest;
31  import javax.servlet.http.HttpServletResponse;
32  import javax.servlet.ServletOutputStream;
33  
34  
35  import org.molwind.model.LayeredPosition;
36  import org.molwind.util.MolwindLogger;
37  import org.molwind.util.MolwindServerConfiguration;
38  import org.molwind.view.Tiles;
39  
40  /**
41   * MolwindServlet serves tiles to a WorldWind client.
42   * <p>
43   *
44   * @author <a href="mailto:oliver.karch@molwind.org">Oliver Karch</a>
45   * @author <a href="mailto:sebastian.bremm@molwind.org">Sebastian Bremm</a>
46   * @version 0.2
47   */
48  public class MolwindServlet extends HttpServlet {
49  
50      /**
51       * Name of the parameter, which includes the name of the world.
52       */
53      public static final String PARAM_WORLD = "world";
54  
55      /**
56       * Default name of a Molwind world.
57       */
58      public static final String DEFAULT_WORLD = "default";
59      
60      /**
61       * Name of the parameter, which includes the name of the called command
62       */
63      public static final String PARAM_COMMAND = "command";
64      
65      /**
66       * Default name of a command
67       */
68      public static final String DEFAULT_COMMAND ="defCommand";
69  
70      /**
71       * Generated serial id for this class.
72       */
73      private static final long serialVersionUID = 3602039967061325713L;
74  
75  
76      /**
77       * A HashMap of available commands
78       *
79       */
80      private HashMap<String,Command> commands;
81      
82  
83  
84      /**
85       * Called by the servlet container to indicate that the servlet is being
86       * placed into service.
87       *
88       * @param config
89       *      the {@link javax.servlet.ServletConfig} object, contains
90       *      configuration information for this servlet
91       * @throws javax.servlet.ServletException
92       *      if an exception occurs that interrupts the servlet's normal
93       *      operation
94       */
95      public void init(final ServletConfig config)
96      throws ServletException {
97  	super.init(config);
98  
99  	initCommands( config );
100        
101         String servletContextPath = config.getServletContext().getRealPath("/");
102 
103 
104 	MolwindLogger.getInstance(getServletContext());
105 
106         String configPath = config.getInitParameter("config");
107 
108 
109 
110         MolwindServerConfiguration molwindConfig = null;
111 
112         if (configPath != null) {
113             File theFile = new File(configPath);
114             MolwindLogger.info("Trying to read config from " + theFile);
115 
116             if (theFile.isAbsolute() && theFile.exists()) {
117                 molwindConfig = MolwindServerConfiguration.getInstance(
118                         theFile.getPath());
119             } else {
120                 molwindConfig = MolwindServerConfiguration.getInstance(
121                         (new File(servletContextPath, configPath)).getPath());
122             }
123         } else {
124             molwindConfig = MolwindServerConfiguration.getInstance();
125         }
126 
127         molwindConfig.addWorldPath(servletContextPath);
128         molwindConfig.setServletContext(getServletContext());
129 
130         String uploadPath = config.getInitParameter("upload");
131         if (uploadPath != null) {
132             molwindConfig.addWorldPath(uploadPath);
133         }
134     }
135 
136    
137 
138 
139     
140     
141     
142     
143     private void initCommands( final ServletConfig config ) {
144 	
145 	MolwindLogger.debug("Initialising Command-list:...");
146 	commands = new HashMap<String,Command>();
147 	Enumeration e = config.getInitParameterNames();
148 	while( e.hasMoreElements() ) {
149 	    String pName = (String)e.nextElement();
150 	    
151 	    if( pName.startsWith( PARAM_COMMAND ) ) {
152 		
153 		String cmdClass = config.getInitParameter( pName );
154 	
155 		String[] pNames;
156 		pNames = pName.split( ":" );
157 		
158 		try {
159 		    Class clazz = Class.forName(cmdClass);
160 		    Command cmd = (Command) clazz.newInstance();
161 		    
162 		    if( pNames.length > 0 ){
163 			addCommand( pNames[1], cmd );}
164 		
165 		   
166 		} catch (ClassNotFoundException cnfe) {
167 		    MolwindLogger.warn("Cannot find command "
168 				       + cmdClass, cnfe);
169 		} catch (InstantiationException iex) {
170 		    MolwindLogger.warn("Cannot instantiate "
171 				       + cmdClass, iex);
172 		} catch (IllegalAccessException iax) {
173 		    MolwindLogger.warn("Cannot instantiate "
174 				       + cmdClass, iax);
175 		}
176 	    }
177 	}
178     }
179 
180     /**
181      * Called by the server (via the service method) to allow a servlet to
182      * handle a GET request.
183      *
184      * @param request
185      *      an {@link javax.servlet.http.HttpServletRequest} object, contains
186      *      the request the client has made of the servlet
187      * @param response
188      *      an {@link javax.servlet.http.HttpServletResponse} object, contains
189      *      the response the servlet sends to the client
190      * @throws javax.servlet.ServletException
191      *      if an exception occurs that interrupts the servlet's normal
192      *      operation
193      * @throws java.io.IOException
194      *      is thrown upon i/o error
195      */
196     public void doGet(final HttpServletRequest request,
197             final HttpServletResponse response)
198 	throws ServletException, IOException,NullPointerException {
199        	MolwindLogger.debug("Parsing command: " + request);
200 	Command command = parseCommand(request);
201 	
202 	if(command != null){
203 	    command.execute(request,response);
204 	}
205 	
206       
207 	
208     }
209 
210 
211 
212     /**
213      * Tries to read integer values from the request object.
214      *
215      * @param request
216      *      an {@link javax.servlet.http.HttpServletRequest} object, contains
217      *      the request the client has made of the servlet
218      * @param paramName
219      *      the name of the parameter
220      * @param defaultValue
221      *      the default value
222      * @return
223      *      the parsed integer
224      */
225     private int parseInt(final HttpServletRequest request,
226             final String paramName, final int defaultValue) {
227         int x = defaultValue;
228         String paramString = request.getParameter(paramName);
229 
230         if (paramString != null) {
231             try {
232                 x = Integer.parseInt(paramString);
233             } catch (NumberFormatException nfe) {
234                 MolwindLogger.warn("Request parameter "
235                         + paramName + " is invalid");
236                 x = defaultValue;
237             }
238         }
239 
240         return x;
241     }
242 
243     /**
244      * Tries to read the command from the request object.
245      *
246      * @param request
247      *      an {@link javax.servlet.http.HttpServletRequest} object, contains
248      *      the request the client has made of the servlet
249      * @return
250      *      the parsed command
251      */   
252     private Command parseCommand(final HttpServletRequest request){
253 	String commandName = request.getParameter(PARAM_COMMAND);
254 
255 	if (commandName == null){
256 	    return null;
257 	}else{
258 	    return commands.get(commandName);
259 	}
260 
261     }
262 
263     /**
264      * Tries to read the world name from the request object.
265      *
266      * @param request
267      *      an {@link javax.servlet.http.HttpServletRequest} object, contains
268      *      the request the client has made of the servlet
269      * @return
270      *      the parsed world name
271      */
272     private String parseWorldName(final HttpServletRequest request) {
273         String worldName = request.getParameter(PARAM_WORLD);
274 
275         if (worldName == null) {
276             return DEFAULT_WORLD;
277         } else {
278             return worldName;
279         }
280     }
281 
282     /**
283      * Reads the requested position from the request object.
284      *
285      * @param request
286      *      an {@link javax.servlet.http.HttpServletRequest} object, contains
287      *      the request the client has made of the servlet
288      * @return
289      *      the parsed position
290      */
291     private LayeredPosition parsePosition(final HttpServletRequest request) {
292         int x = parseInt(request, "X", 0);
293         int y = parseInt(request, "Y", 0);
294         int l = parseInt(request, "L", 0);
295         return new LayeredPosition(x, y, l);
296     }
297     
298     /**
299      * Places a Command to the HashMap 
300      *
301      * @param key
302      *      a String used as for the HashMap
303      *
304      * @param 
305      *      an Command to be set in the HashMap
306      *
307      */
308     private void addCommand(String key,Command com){
309 
310 	commands.put(key,com);
311     }
312     
313     /**
314      * Returns a Command by the given key
315      *
316      * @param
317      *     a String for looking up the Hashtable
318      *
319      * @return
320      *     the searched Command
321      */
322     private Command getCommand(String key){
323 	return commands.get(key);
324     }
325 
326 
327 
328 
329 
330 //    public void doGet(HttpServletRequest req, HttpServletResponse res)
331 //    throws ServletException, IOException {
332 //        Enumeration<String> enume = req.getParameterNames();
333 //        int i1=0;
334 //        while(enume.hasMoreElements()){
335 //            sa_req[i1]=enume.nextElement();
336 //            if (sa_req[i1].contains("T")){
337 //                T=(String)req.getParameter(sa_req[i1]);
338 //            }
339 //            i1++;
340 //        }
341 //        if (req.getParameter("path")!=null){
342 //            Install inst=new Install();
343 //            confPath=req.getParameter("path");
344 //            inst.changeWebXml(confPath, path);
345 //        }
346 //        if (start==0){
347 //            Install inst=new Install();
348 //            if (inst.exitsConfig(confPath)){
349 //                start=1;
350 //                crt.initialise(confPath, path);
351 //                PrintWriter out = res.getWriter();
352 //                Welcome welc=new Welcome();
353 //                for (int i2=0; i2<welc.getPage().size(); i2++){
354 //                    for (int i3=0; i3<welc.getPage().get(i2).size(); i3++){
355 //                        out.println(welc.getPage().get(i2).get(i3));
356 //                    }
357 //                }
358 //                out.close();
359 //            }
360 //            else{
361 //                PrintWriter out = res.getWriter();
362 //                for (int i2=0; i2<inst.getPage(
363 //                        confPath,path).size();i2++){
364 //                    for (int i3=0;i3<inst.getPage(confPath,path).get(
365 //                            i2).size(); i3++){
366 //                        out.println(inst.getPage(confPath,path).get(
367 //                                i2).get(i3));
368 //                    }
369 //                }
370 //            }
371 //        }
372 //        else if (req.getParameter("updateServer")!=null){
373 //            crt.updateServer();
374 //            PrintWriter out = res.getWriter();
375 //            out.println("Names of the existing datesets:");
376 //            for(int i=0; i<Config.getWorldCount(); i++){
377 //                out.println(Config.getWorldName(i)+" <br>");
378 //            }
379 //            out.println("Please start the calculation of a dataset by "
380 //                    + "calling the servlet with the parameter: "
381 //                    + "start=\"name of the dataset\"");
382 //            out.close();
383 //        }
384 //        else if (req.getParameter("OUTPUTFORMAT")!=null){
385 //            String re=req.getQueryString();
386 //            String name=req.getParameter("TypeName");
387 //            int a=re.indexOf("name-");
388 //            int b=re.indexOf("-lev-");
389 //            String name=re.substring(a+5,b);
390 //            a=re.indexOf("lev-");
391 //            String lev=re.substring(a+4, a+5);
392 //            ServletContext con = getServletContext();
393 //            RequestDispatcher  rq = con.getRequestDispatcher("/data/"
394 //                    + name+"/pln-"+lev+".gz");
395 //            rq.forward( req, res );
396 //        }
397 //        else if (req.getParameter("start")!=null){
398 //            crt.start((String)req.getParameter("start"));
399 //            PrintWriter out = res.getWriter();
400 //            Welcome welc=new Welcome();
401 //            for (int i2=0; i2<welc.getPage().size(); i2++){
402 //                for (int i3=0; i3<welc.getPage().get(i2).size(); i3++){
403 //                    out.println(welc.getPage().get(i2).get(i3));
404 //                }
405 //            }
406 //            out.close();
407 //        }
408 //        else if (req.getParameter("load")!=null){
409 //            PrintWriter out = res.getWriter();
410 //            if (crt.load((String)req.getParameter("load"))){
411 //                out.write("World "+(String)req.getParameter("load")
412 //                        +" has been reloaded");
413 //            }
414 //            else{
415 //                out.write("World "+(String)req.getParameter("load")
416 //                        +" could not be reloaded");
417 //            }
418 //            out.close();
419 //        }
420 //        else if (req.getParameter("restart")!=null){
421 //            crt.restart((String)req.getParameter("restart"));
422 //            PrintWriter out = res.getWriter();
423 //            out.write("World "+(String)req.getParameter("restart")
424 //                    +" has been restarted");
425 //            out.close();
426 //        }
427 //        else if (req.getParameter("log")!=null){
428 //            PrintWriter out = res.getWriter();
429 //            out.close();
430 //        }
431 //        else if (req.getParameter("xml")!=null){
432 //            if (req.getParameter("xml").equals("images")){
433 //                ServletContext con = getServletContext();
434 //                RequestDispatcher  rq = con.getRequestDispatcher( "data/"
435 //                        +T+"/xml/@images.xml" );
436 //                rq.forward( req, res );
437 //            }
438 //            if (req.getParameter("xml").equals("placenames")){
439 //                ServletContext con = getServletContext();
440 //                RequestDispatcher  rq = con.getRequestDispatcher( "data/"
441 //                        +T+"/xml/^placenames.xml" );
442 //                rq.forward( req, res );
443 //            }
444 //        }
445 //        else if (req.getParameter("names")!=null){
446 //            ServletContext con = getServletContext();
447 //            RequestDispatcher  rq = con.getRequestDispatcher( "data/"
448 //                    +T+"/names/names.gz" );
449 //            rq.forward( req, res );
450 //        }
451 //        else if (req.getParameter("X")!=null){
452 //            res.setContentType("image/jpg");
453 //            int x = Integer.parseInt(req.getParameter("X"));
454 //            int y =  Integer.parseInt(req.getParameter("Y"));
455 //            int l =  Integer.parseInt(req.getParameter("L"));
456 //            if (crt.exists(x, y, l, T)){
457 //                String key= Integer.toString(x)+"-"+Integer.toString(y)
458 //                        +"-"+Integer.toString(l);
459 //                ServletContext con = getServletContext();
460 //                RequestDispatcher  rq = con.getRequestDispatcher( "data/"
461 //                        +T+"/images/"+key+".jpg" );
462 //                rq.forward( req, res );
463 //            }
464 //            else{
465 //                ImageIO.write(crt.getImage(x, y, l, T),
466 //                        "jpg", res.getOutputStream());
467 //            }
468 //        }
469 //        else{
470 //            PrintWriter out = res.getWriter();
471 //            Welcome welc=new Welcome();
472 //            for (int i2=0; i2<welc.getPage().size(); i2++){
473 //                for (int i3=0; i3<welc.getPage().get(i2).size(); i3++){
474 //                    out.println(welc.getPage().get(i2).get(i3));
475 //                }
476 //            }
477 //            out.close();
478 //        }
479 //    }
480 
481 }