1 package org.apache.turbine;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.BufferedReader;
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.FileNotFoundException;
26 import java.io.FileReader;
27 import java.io.IOException;
28 import java.io.Reader;
29 import java.io.UnsupportedEncodingException;
30 import java.util.Iterator;
31 import java.util.Properties;
32
33 import javax.servlet.ServletConfig;
34 import javax.servlet.ServletContext;
35 import javax.servlet.ServletException;
36 import javax.servlet.http.HttpServlet;
37 import javax.servlet.http.HttpServletRequest;
38 import javax.servlet.http.HttpServletResponse;
39
40 import org.apache.commons.configuration.Configuration;
41 import org.apache.commons.configuration.ConfigurationFactory;
42 import org.apache.commons.configuration.PropertiesConfiguration;
43 import org.apache.commons.lang.StringUtils;
44 import org.apache.commons.lang.exception.ExceptionUtils;
45 import org.apache.commons.logging.Log;
46 import org.apache.commons.logging.LogFactory;
47 import org.apache.log4j.PropertyConfigurator;
48 import org.apache.turbine.modules.PageLoader;
49 import org.apache.turbine.pipeline.Pipeline;
50 import org.apache.turbine.pipeline.PipelineData;
51 import org.apache.turbine.pipeline.TurbinePipeline;
52 import org.apache.turbine.services.Initable;
53 import org.apache.turbine.services.InitializationException;
54 import org.apache.turbine.services.ServiceManager;
55 import org.apache.turbine.services.TurbineServices;
56 import org.apache.turbine.services.rundata.RunDataService;
57 import org.apache.turbine.services.template.TemplateService;
58 import org.apache.turbine.services.template.TurbineTemplate;
59 import org.apache.turbine.util.RunData;
60 import org.apache.turbine.util.ServerData;
61 import org.apache.turbine.util.TurbineConfig;
62 import org.apache.turbine.util.TurbineException;
63 import org.apache.turbine.util.uri.URIConstants;
64
65 import com.thoughtworks.xstream.XStream;
66 import com.thoughtworks.xstream.io.xml.DomDriver;
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105 public class Turbine
106 extends HttpServlet
107 {
108
109 private static final long serialVersionUID = -6317118078613623990L;
110
111
112
113
114
115 public static final String REDIRECTED_PATHINFO_NAME = "redirected";
116
117
118 public static final String BASEDIR_KEY = "basedir";
119
120
121
122
123
124
125 private static boolean firstInit = true;
126
127
128
129
130 private static Pipeline pipeline = null;
131
132
133 private static Throwable initFailure = null;
134
135
136
137
138 private static boolean firstDoGet = true;
139
140
141
142
143
144 private static ServerData serverData = null;
145
146
147 private static String applicationRoot;
148
149
150 private static ServletConfig servletConfig;
151
152
153 private static ServletContext servletContext;
154
155
156
157
158
159
160 private static String webappRoot;
161
162
163 private static Configuration configuration = null;
164
165
166 private String inputEncoding = null;
167
168
169 private static Log log = LogFactory.getLog(Turbine.class);
170
171
172
173
174
175
176
177
178
179 public final void init() throws ServletException
180 {
181 synchronized (this.getClass())
182 {
183 super.init();
184 ServletConfig config = getServletConfig();
185
186 if (!firstInit)
187 {
188 log.info("Double initialization of Turbine was attempted!");
189 return;
190 }
191
192
193 firstInit = false;
194
195 try
196 {
197 ServletContext context = config.getServletContext();
198
199 configure(config, context);
200
201 TemplateService templateService = TurbineTemplate.getService();
202 if (templateService == null)
203 {
204 throw new TurbineException(
205 "No Template Service configured!");
206 }
207
208 if (getRunDataService() == null)
209 {
210 throw new TurbineException(
211 "No RunData Service configured!");
212 }
213
214 }
215 catch (Exception e)
216 {
217
218 initFailure = e;
219 log.fatal("Turbine: init() failed: ", e);
220 throw new ServletException("Turbine: init() failed", e);
221 }
222
223 log.info("Turbine: init() Ready to Rumble!");
224 }
225 }
226
227
228
229
230
231
232
233
234
235
236
237 private void configure(ServletConfig config, ServletContext context)
238 throws Exception
239 {
240
241
242
243
244
245 applicationRoot = findInitParameter(context, config,
246 TurbineConstants.APPLICATION_ROOT_KEY,
247 TurbineConstants.APPLICATION_ROOT_DEFAULT);
248
249 webappRoot = config.getServletContext().getRealPath("/");
250
251
252
253 if (applicationRoot == null || applicationRoot.equals(TurbineConstants.WEB_CONTEXT))
254 {
255 applicationRoot = webappRoot;
256
257 }
258
259
260 setApplicationRoot(applicationRoot);
261
262
263
264 createRuntimeDirectories(context, config);
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294 String confFile= findInitParameter(context, config,
295 TurbineConfig.CONFIGURATION_PATH_KEY,
296 null);
297
298 String confPath;
299 String confStyle = "unset";
300
301 if (StringUtils.isNotEmpty(confFile))
302 {
303 confPath = getRealPath(confFile);
304 ConfigurationFactory configurationFactory = new ConfigurationFactory(confPath);
305 configurationFactory.setBasePath(getApplicationRoot());
306 configuration = configurationFactory.getConfiguration();
307 confStyle = "XML";
308 }
309 else
310 {
311 confFile = findInitParameter(context, config,
312 TurbineConfig.PROPERTIES_PATH_KEY,
313 TurbineConfig.PROPERTIES_PATH_DEFAULT);
314
315 confPath = getRealPath(confFile);
316
317
318
319
320 configuration = new PropertiesConfiguration(confPath);
321 confStyle = "Properties";
322 }
323
324
325
326
327
328 String log4jFile = configuration.getString(TurbineConstants.LOG4J_CONFIG_FILE,
329 TurbineConstants.LOG4J_CONFIG_FILE_DEFAULT);
330
331 if (StringUtils.isNotEmpty(log4jFile) &&
332 !log4jFile.equalsIgnoreCase("none"))
333 {
334 log4jFile = getRealPath(log4jFile);
335
336
337
338
339
340 Properties p = new Properties();
341 try
342 {
343 p.load(new FileInputStream(log4jFile));
344 p.setProperty(TurbineConstants.APPLICATION_ROOT_KEY, getApplicationRoot());
345 PropertyConfigurator.configure(p);
346
347
348
349 log = LogFactory.getLog(this.getClass());
350
351 log.info("Configured log4j from " + log4jFile);
352 }
353 catch (FileNotFoundException fnf)
354 {
355 System.err.println("Could not open Log4J configuration file "
356 + log4jFile + ": ");
357 fnf.printStackTrace();
358 }
359 }
360
361
362 log.info("Loaded configuration (" + confStyle + ") from " + confFile + " (" + confPath + ")");
363
364 setTurbineServletConfig(config);
365 setTurbineServletContext(context);
366
367 getServiceManager().setApplicationRoot(applicationRoot);
368
369
370
371
372
373
374 configuration.setProperty(TurbineConstants.APPLICATION_ROOT_KEY, applicationRoot);
375 configuration.setProperty(TurbineConstants.WEBAPP_ROOT_KEY, webappRoot);
376
377
378 inputEncoding = configuration.getString(
379 TurbineConstants.PARAMETER_ENCODING_KEY,
380 TurbineConstants.PARAMETER_ENCODING_DEFAULT);
381
382 if (log.isDebugEnabled())
383 {
384 log.debug("Input Encoding has been set to " + inputEncoding);
385 }
386
387 getServiceManager().setConfiguration(configuration);
388
389
390
391
392
393 getServiceManager().init();
394
395
396
397
398 String descriptorPath =
399 configuration.getString(
400 "pipeline.default.descriptor",
401 TurbinePipeline.CLASSIC_PIPELINE);
402
403 descriptorPath = getRealPath(descriptorPath);
404
405 log.debug("Using descriptor path: " + descriptorPath);
406 Reader reader = new BufferedReader(new FileReader(descriptorPath));
407 XStream pipelineMapper = new XStream(new DomDriver());
408 pipeline = (Pipeline) pipelineMapper.fromXML(reader);
409
410 log.debug("Initializing pipeline");
411
412 pipeline.initialize();
413 }
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432 private static void createRuntimeDirectories(ServletContext context,
433 ServletConfig config)
434 {
435 String path = findInitParameter(context, config,
436 TurbineConstants.LOGGING_ROOT_KEY,
437 TurbineConstants.LOGGING_ROOT_DEFAULT);
438
439 File logDir = new File(getRealPath(path));
440 if (!logDir.exists())
441 {
442
443 if (!logDir.mkdirs())
444 {
445 System.err.println("Cannot create directory for logs!");
446 }
447 }
448 }
449
450
451
452
453
454
455
456 protected static final String findInitParameter(ServletContext context,
457 ServletConfig config, String name, String defaultValue)
458 {
459 String path = null;
460
461
462 boolean usingNamespace = name.startsWith(TurbineConstants.CONFIG_NAMESPACE);
463 while (true)
464 {
465 path = config.getInitParameter(name);
466 if (StringUtils.isEmpty(path))
467 {
468 path = context.getInitParameter(name);
469 if (StringUtils.isEmpty(path))
470 {
471
472 if (usingNamespace)
473 {
474 path = defaultValue;
475 }
476 else
477 {
478
479 name = TurbineConstants.CONFIG_NAMESPACE + '.' + name;
480 usingNamespace = true;
481 continue;
482 }
483 }
484 }
485 break;
486 }
487
488 return path;
489 }
490
491
492
493
494
495
496
497 public final void init(PipelineData data)
498 {
499 synchronized (Turbine.class)
500 {
501 if (firstDoGet)
502 {
503
504
505
506
507
508 saveServletInfo(data);
509
510
511 TurbineServices services = (TurbineServices)TurbineServices.getInstance();
512
513 for (Iterator i = services.getServiceNames(); i.hasNext();)
514 {
515 String serviceName = (String)i.next();
516 Object service = services.getService(serviceName);
517
518 if (service instanceof Initable)
519 {
520 try
521 {
522 ((Initable)service).init(data);
523 }
524 catch (InitializationException e)
525 {
526 log.warn("Could not initialize Initable " + serviceName + " with PipelineData", e);
527 }
528 }
529 }
530
531
532 firstDoGet = false;
533 log.info("Turbine: first Request successful");
534 }
535 }
536 }
537
538
539
540
541
542
543 public static Configuration getConfiguration()
544 {
545 return configuration;
546 }
547
548
549
550
551
552
553 public static String getServerName()
554 {
555 return getDefaultServerData().getServerName();
556 }
557
558
559
560
561
562
563 public static String getServerScheme()
564 {
565 return getDefaultServerData().getServerScheme();
566 }
567
568
569
570
571
572
573 public static String getServerPort()
574 {
575 return Integer.toString(getDefaultServerData().getServerPort());
576 }
577
578
579
580
581
582
583
584
585 public static String getScriptName()
586 {
587 return getDefaultServerData().getScriptName();
588 }
589
590
591
592
593
594
595 public static String getContextPath()
596 {
597 return getDefaultServerData().getContextPath();
598 }
599
600
601
602
603
604
605
606
607
608
609
610
611 public static ServerData getDefaultServerData()
612 {
613 if (serverData == null)
614 {
615 String serverName
616 = configuration.getString(TurbineConstants.DEFAULT_SERVER_NAME_KEY);
617 if (serverName == null)
618 {
619 log.error("ServerData Information requested from Turbine before first request!");
620 }
621 else
622 {
623 log.info("ServerData Information retrieved from configuration.");
624 }
625
626 serverData = new ServerData(serverName,
627 configuration.getInt(TurbineConstants.DEFAULT_SERVER_PORT_KEY,
628 URIConstants.HTTP_PORT),
629 configuration.getString(TurbineConstants.DEFAULT_SERVER_SCHEME_KEY,
630 URIConstants.HTTP),
631 configuration.getString(TurbineConstants.DEFAULT_SCRIPT_NAME_KEY),
632 configuration.getString(TurbineConstants.DEFAULT_CONTEXT_PATH_KEY));
633 }
634 return serverData;
635 }
636
637
638
639
640
641
642 public static void setTurbineServletConfig(ServletConfig config)
643 {
644 servletConfig = config;
645 }
646
647
648
649
650
651
652 public static ServletConfig getTurbineServletConfig()
653 {
654 return servletConfig;
655 }
656
657
658
659
660
661
662 public static void setTurbineServletContext(ServletContext context)
663 {
664 servletContext = context;
665 }
666
667
668
669
670
671
672 public static ServletContext getTurbineServletContext()
673 {
674 return servletContext;
675 }
676
677
678
679
680
681 public final void destroy()
682 {
683
684 getServiceManager().shutdownServices();
685 System.gc();
686
687 firstInit = true;
688 firstDoGet = true;
689 log.info("Turbine: Done shutting down!");
690 }
691
692
693
694
695
696
697
698
699
700 public final void doGet(HttpServletRequest req, HttpServletResponse res)
701 throws IOException, ServletException
702 {
703 PipelineData pipelineData = null;
704
705 try
706 {
707
708 if (initFailure != null)
709 {
710 throw initFailure;
711 }
712
713
714
715
716 if (req.getCharacterEncoding() == null)
717 {
718 if (log.isDebugEnabled())
719 {
720 log.debug("Changing Input Encoding to " + inputEncoding);
721 }
722
723 try
724 {
725 req.setCharacterEncoding(inputEncoding);
726 }
727 catch (UnsupportedEncodingException uee)
728 {
729 log.warn("Could not change request encoding to " + inputEncoding, uee);
730 }
731 }
732
733
734
735 pipelineData = getRunDataService().getRunData(req, res, getServletConfig());
736
737
738
739
740
741
742
743
744 if (firstDoGet)
745 {
746 init(pipelineData);
747 }
748
749
750
751
752 pipeline.invoke(pipelineData);
753
754 }
755 catch (Exception e)
756 {
757 handleException(pipelineData, res, e);
758 }
759 catch (Throwable t)
760 {
761 handleException(pipelineData, res, t);
762 }
763 finally
764 {
765
766 getRunDataService().putRunData((RunData)pipelineData);
767 }
768 }
769
770
771
772
773
774
775
776
777
778 public final void doPost(HttpServletRequest req, HttpServletResponse res)
779 throws IOException, ServletException
780 {
781 doGet(req, res);
782 }
783
784
785
786
787
788
789 public final String getServletInfo()
790 {
791 return "Turbine Servlet";
792 }
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807 private final void handleException(PipelineData pipelineData, HttpServletResponse res,
808 Throwable t)
809 {
810 RunData data = getRunData(pipelineData);
811
812 log.error("Turbine.handleException: ", t);
813
814 String mimeType = "text/plain";
815 try
816 {
817
818
819 data.setStackTrace(ExceptionUtils.getStackTrace(t), t);
820
821
822 data.setScreen(configuration.getString(
823 TurbineConstants.SCREEN_ERROR_KEY,
824 TurbineConstants.SCREEN_ERROR_DEFAULT));
825
826
827 if (data.getTemplateInfo() != null)
828 {
829 data.getTemplateInfo()
830 .setScreenTemplate(configuration.getString(
831 TurbineConstants.TEMPLATE_ERROR_KEY,
832 TurbineConstants.TEMPLATE_ERROR_VM));
833 }
834
835
836 data.setAction("");
837
838 PageLoader.getInstance().exec(pipelineData,
839 configuration.getString(TurbineConstants.PAGE_DEFAULT_KEY,
840 TurbineConstants.PAGE_DEFAULT_DEFAULT));
841
842 data.getResponse().setContentType(data.getContentType());
843 data.getResponse().setStatus(data.getStatusCode());
844 }
845
846
847 catch (java.lang.NoSuchFieldError e)
848 {
849 try
850 {
851 data.getResponse().setContentType(mimeType);
852 data.getResponse().setStatus(200);
853 }
854 catch (Exception ignored)
855 {
856
857 }
858
859 try
860 {
861 data.getResponse().getWriter().print("java.lang.NoSuchFieldError: "
862 + "Please recompile all of your source code.");
863 }
864 catch (IOException ignored)
865 {
866
867 }
868
869 log.error(data.getStackTrace(), e);
870 }
871
872 catch (Throwable reallyScrewedNow)
873 {
874 StringBuffer msg = new StringBuffer();
875 msg.append("Horrible Exception: ");
876 if (data != null)
877 {
878 msg.append(data.getStackTrace());
879 }
880 else
881 {
882 msg.append(t);
883 }
884 try
885 {
886 res.setContentType(mimeType);
887 res.setStatus(200);
888 res.getWriter().print(msg.toString());
889 }
890 catch (Exception ignored)
891 {
892
893 }
894
895 log.error(reallyScrewedNow.getMessage(), reallyScrewedNow);
896 }
897 }
898
899
900
901
902
903
904
905
906 public static synchronized void saveServletInfo(PipelineData data)
907 {
908
909
910
911
912
913
914
915 ServerData requestServerData = (ServerData) data.get(Turbine.class, ServerData.class);
916 serverData = (ServerData) requestServerData.clone();
917 }
918
919
920
921
922
923
924 public static void setApplicationRoot(String val)
925 {
926 applicationRoot = val;
927 }
928
929
930
931
932
933
934
935
936
937
938 public static String getApplicationRoot()
939 {
940 return applicationRoot;
941 }
942
943
944
945
946
947
948
949
950
951 public static String getRealPath(String path)
952 {
953 if (path.startsWith("/"))
954 {
955 path = path.substring(1);
956 }
957
958 return new File(getApplicationRoot(), path).getAbsolutePath();
959 }
960
961
962
963
964
965
966 private ServiceManager getServiceManager()
967 {
968 return TurbineServices.getInstance();
969 }
970
971
972
973
974
975
976
977 private RunData getRunData(PipelineData pipelineData)
978 {
979 RunData data = null;
980 data = (RunData)pipelineData;
981 return data;
982 }
983
984
985
986
987
988
989
990 public String getDefaultInputEncoding() {
991 return inputEncoding;
992 }
993
994
995
996
997
998 private static RunDataService getRunDataService()
999 {
1000 return (RunDataService) TurbineServices
1001 .getInstance().getService(RunDataService.SERVICE_NAME);
1002 }
1003 }