1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.vectomatic.svg.edit.server;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.net.URL;
24
25 import javax.servlet.ServletConfig;
26 import javax.servlet.ServletException;
27 import javax.servlet.http.HttpServlet;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
30
31
32
33
34
35 public class FetchServlet extends HttpServlet {
36 private static final long serialVersionUID = 1L;
37 private static final int MAX_SIZE = 1024 * 256;
38 private static final String PARAM_URL = "url";
39 private static final String PARAM_TYPE = "type";
40 private static final String HTTP_PROTOCOL = "http";
41
42
43
44
45 public FetchServlet() {
46 }
47
48 @Override
49 public void init(ServletConfig config) throws ServletException {
50 }
51
52
53
54
55 @Override
56 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
57 URL url = new URL(request.getParameter(PARAM_URL));
58 String contentType = request.getParameter(PARAM_TYPE);
59 System.out.println("Fetching: " + url.toExternalForm() + " contentType: " + contentType);
60
61 if (!HTTP_PROTOCOL.equals(url.getProtocol())) {
62 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported protocol: " + url.getProtocol());
63 } else {
64 InputStream istream = null;
65 OutputStream ostream = null;
66 try {
67
68 istream = url.openStream();
69 if (contentType != null) {
70 response.setContentType(contentType);
71 }
72 ostream = response.getOutputStream();
73
74 byte[] buffer = new byte[4096];
75 int length, totalLength = 0;
76 while ((totalLength < MAX_SIZE) && ((length = istream.read(buffer)) != -1)) {
77 ostream.write(buffer, 0, length);
78 totalLength += length;
79 }
80 } finally {
81 if (istream != null) {
82 istream.close();
83 }
84 if (ostream != null) {
85 ostream.close();
86 } else {
87 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cannot fetch: " + url.getProtocol());
88 }
89 }
90 }
91 }
92 }