1
2
3
4
5
6
7
8
9
10 package org.mule.transport.servlet;
11
12 import org.mule.util.IOUtils;
13
14 import java.io.ByteArrayOutputStream;
15 import java.io.IOException;
16 import java.io.InputStream;
17
18 import javax.servlet.ServletException;
19 import javax.servlet.http.HttpServlet;
20 import javax.servlet.http.HttpServletRequest;
21 import javax.servlet.http.HttpServletResponse;
22
23
24
25
26 public class JarResourceServlet extends HttpServlet
27 {
28 public static final String DEFAULT_PATH_SPEC = "/mule-resource/*";
29
30 public static final String DEFAULT_BASE_PATH = "";
31
32 public static final String DEFAULT_MIME_TYPE = "application/octet-stream";
33
34 private String basepath = DEFAULT_BASE_PATH;
35
36 @Override
37 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
38 {
39 String file = getBasepath() + req.getPathInfo();
40
41 if(file.startsWith("/")) file = file.substring(1);
42 InputStream in = IOUtils.getResourceAsStream(file, getClass(), false, false);
43 if (in == null)
44 {
45 resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
46 resp.getWriter().write("Unable to find file: " + req.getPathInfo());
47 return;
48 }
49 byte[] buffer;
50 try
51 {
52 ByteArrayOutputStream baos = new ByteArrayOutputStream();
53 IOUtils.copyLarge(in, baos);
54
55 buffer = baos.toByteArray();
56
57 String mimetype = DEFAULT_MIME_TYPE;
58 if (getServletContext() != null)
59 {
60 String temp = getServletContext().getMimeType(file);
61 if (temp != null)
62 {
63 mimetype = temp;
64 }
65 }
66
67 resp.setContentType(mimetype);
68 resp.setContentLength(buffer.length);
69 resp.setHeader("Content-Disposition", "attachment; filename=\"" + req.getPathInfo() + "\"");
70 resp.getOutputStream().write(buffer);
71 }
72 finally
73 {
74 in.close();
75 resp.getOutputStream().flush();
76 }
77 }
78
79 public String getBasepath()
80 {
81 return basepath;
82 }
83
84 public void setBasepath(String basepath)
85 {
86 this.basepath = basepath;
87 }
88 }