1 package org.astrogrid.filestore.server.streamer;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.InputStream;
6 import javax.servlet.http.HttpServletRequest;
7 import javax.servlet.http.HttpServletResponse;
8 import javax.servlet.http.HttpServlet;
9 import javax.servlet.ServletException;
10 import javax.servlet.ServletOutputStream;
11
12 /***
13 * An HTTP servlet to stream data sets to an authorized caller.
14 * The servlet uses a ticket named in the request arguments to identify
15 * authorized callers. The ticket allows one download of a specific data-set;
16 * i.e. the servlet will accept it only once.
17 *
18 * The servlet accepts get and Post requests; it executes both in the
19 * same way.
20 *
21 * No CGI parameters are read from the request; instead, the
22 * servlet determines its single parameter, the name of the ticket,
23 * by analysing the request URL. The last part of the URL, following
24 * the final slash in the path part, is assumed to be the ticket name.
25 * E.g. a possible URL is http://server/astrogrid-myspace/streams/123456
26 * for the ticket named 123456.
27 *
28 * @author Guy Rixon
29 */
30 public class StreamServlet extends HttpServlet {
31
32 /*** Creates a new instance of StreamServlet */
33 public StreamServlet() {}
34
35 /***
36 * Respond to HTTP-get requests.
37 */
38 public void doGet(HttpServletRequest request,
39 HttpServletResponse response)
40 throws ServletException {
41
42
43
44 StreamTicket ticket = null;
45 try {
46 String requestUrl = request.getRequestURI();
47 System.out.println("Request URL:" + requestUrl);
48 int lastSlashIndex = requestUrl.lastIndexOf("/");
49 String ticketName = requestUrl.substring(lastSlashIndex+1);
50 System.out.println("Name of ticket: " + ticketName);
51 StreamTicketList ticketList = new StreamTicketList();
52 ticket = ticketList.use(ticketName);
53 }
54 catch (Exception e1) {
55 throw new ServletException("The ticket is invalid", e1);
56 }
57
58
59 InputStream in = null;
60 int lengthInBytes = 0;
61 try {
62 File dataFile = new File(ticket.getTarget());
63 lengthInBytes = (int)dataFile.length();
64 in = new FileInputStream(dataFile);
65 }
66 catch (Exception e2) {
67 throw new ServletException("The data cannot be found", e2);
68 }
69
70
71 try {
72 response.setContentType(ticket.getMimeType());
73 response.setContentLength(lengthInBytes);
74 response.flushBuffer();
75 ServletOutputStream out = response.getOutputStream();
76 byte[] byteBuffer = new byte[1024*1024];
77 int n;
78 for (;;) {
79 n = in.read(byteBuffer);
80 if (n == -1) break;
81 out.write(byteBuffer);
82 }
83 response.flushBuffer();
84 }
85 catch (Exception e3) {
86 throw new ServletException("The data cannot be streamed.", e3);
87 }
88 }
89
90 /***
91 * Respond to HTTP-post requests.
92 */
93 public void doPost(HttpServletRequest request,
94 HttpServletResponse response)
95 throws ServletException {
96 this.doGet(request, response);
97 }
98
99 }