1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.module.samples.servlets;
35
36 import info.magnolia.cms.util.ClasspathResourcesUtil;
37 import org.apache.commons.io.IOUtils;
38
39 import javax.servlet.ServletException;
40 import javax.servlet.ServletOutputStream;
41 import javax.servlet.http.HttpServlet;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
44 import java.io.IOException;
45 import java.io.InputStream;
46
47
48
49
50
51
52 public class DisplaySamplesSourcesServlet extends HttpServlet {
53
54
55
56
57 private static final long serialVersionUID = 1L;
58
59 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
60 doGet(request, response);
61 }
62
63 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
64 response.setContentType("text/plain; charset=UTF-8");
65
66 final String path = request.getPathInfo();
67 final String resourcePath;
68 if (path.endsWith(".jsp")) {
69 resourcePath = "/mgnl-files/templates/samples" + path;
70 } else if (path.endsWith(".ftl")) {
71 resourcePath = "/samples" + path;
72 } else {
73 throw new IllegalArgumentException("Filetype not handled: " + path);
74 }
75
76 final InputStream stream = ClasspathResourcesUtil.getStream(resourcePath);
77 if (stream == null) {
78 throw new IllegalArgumentException("Can't find resource: " + resourcePath);
79 }
80
81 final ServletOutputStream out = response.getOutputStream();
82
83 try {
84 IOUtils.copy(stream, out);
85 } finally {
86 stream.close();
87 out.flush();
88 out.close();
89 }
90 }
91 }