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