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