View Javadoc

1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package org.jboss.netty.example.http.upload;
17  
18  import org.jboss.netty.buffer.ChannelBuffer;
19  import org.jboss.netty.buffer.ChannelBuffers;
20  import org.jboss.netty.channel.Channel;
21  import org.jboss.netty.channel.ChannelFuture;
22  import org.jboss.netty.channel.ChannelFutureListener;
23  import org.jboss.netty.channel.ChannelHandlerContext;
24  import org.jboss.netty.channel.ChannelStateEvent;
25  import org.jboss.netty.channel.Channels;
26  import org.jboss.netty.channel.ExceptionEvent;
27  import org.jboss.netty.channel.MessageEvent;
28  import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
29  import org.jboss.netty.handler.codec.http.cookie.Cookie;
30  import org.jboss.netty.handler.codec.http.cookie.ServerCookieDecoder;
31  import org.jboss.netty.handler.codec.http.cookie.ServerCookieEncoder;
32  import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
33  import org.jboss.netty.handler.codec.http.HttpChunk;
34  import org.jboss.netty.handler.codec.http.HttpHeaders;
35  import org.jboss.netty.handler.codec.http.HttpRequest;
36  import org.jboss.netty.handler.codec.http.HttpResponse;
37  import org.jboss.netty.handler.codec.http.HttpResponseStatus;
38  import org.jboss.netty.handler.codec.http.HttpVersion;
39  import org.jboss.netty.handler.codec.http.QueryStringDecoder;
40  import org.jboss.netty.handler.codec.http.multipart.Attribute;
41  import org.jboss.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
42  import org.jboss.netty.handler.codec.http.multipart.DiskAttribute;
43  import org.jboss.netty.handler.codec.http.multipart.DiskFileUpload;
44  import org.jboss.netty.handler.codec.http.multipart.FileUpload;
45  import org.jboss.netty.handler.codec.http.multipart.HttpDataFactory;
46  import org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
47  import org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.EndOfDataDecoderException;
48  import org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDecoderException;
49  import org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.IncompatibleDataDecoderException;
50  import org.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder.NotEnoughDataDecoderException;
51  import org.jboss.netty.handler.codec.http.multipart.InterfaceHttpData;
52  import org.jboss.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType;
53  import org.jboss.netty.util.CharsetUtil;
54  
55  import java.io.IOException;
56  import java.net.URI;
57  import java.util.Collections;
58  import java.util.List;
59  import java.util.Map;
60  import java.util.Map.Entry;
61  import java.util.Set;
62  
63  public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
64  
65      private static final HttpDataFactory factory =
66              new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if size exceed MINSIZE
67  
68      static {
69          //To limit to roughly 5MB each attribute, including fileupload
70          //factory.setMaxLimit(5000000);
71          DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file
72                                                           // on exit (in normal
73                                                           // exit)
74          DiskFileUpload.baseDirectory = null; // system temp directory
75          DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on
76                                                          // exit (in normal exit)
77          DiskAttribute.baseDirectory = null; // system temp directory
78      }
79  
80      private final StringBuilder responseContent = new StringBuilder();
81      private HttpPostRequestDecoder decoder;
82      private HttpRequest request;
83      private boolean readingChunks;
84  
85      @Override
86      public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
87          if (decoder != null) {
88              decoder.cleanFiles();
89          }
90      }
91  
92      @Override
93      public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
94          if (!readingChunks) {
95              // clean previous FileUpload if Any
96              if (decoder != null) {
97                  decoder.cleanFiles();
98                  decoder = null;
99              }
100 
101             HttpRequest request = this.request = (HttpRequest) e.getMessage();
102             URI uri = new URI(request.getUri());
103             if (!uri.getPath().startsWith("/form")) {
104                 // Write Menu
105                 writeMenu(e);
106                 return;
107             }
108             responseContent.setLength(0);
109             responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
110             responseContent.append("===================================\r\n");
111             responseContent.append("VERSION: " + request.getProtocolVersion().getText() + "\r\n");
112             responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n");
113             responseContent.append("\r\n\r\n");
114 
115             // new method
116             for (Entry<String, String> entry: request.headers()) {
117                 responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
118             }
119             responseContent.append("\r\n\r\n");
120 
121             // new method
122             Set<Cookie> cookies;
123             String value = request.headers().get(HttpHeaders.Names.COOKIE);
124             if (value == null) {
125                 cookies = Collections.emptySet();
126             } else {
127                 cookies = ServerCookieDecoder.STRICT.decode(value);
128             }
129             for (Cookie cookie: cookies) {
130                 responseContent.append("COOKIE: " + cookie + "\r\n");
131             }
132             responseContent.append("\r\n\r\n");
133 
134             QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
135             Map<String, List<String>> uriAttributes = decoderQuery.getParameters();
136             for (Entry<String, List<String>> attr: uriAttributes.entrySet()) {
137                 for (String attrVal: attr.getValue()) {
138                     responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
139                 }
140             }
141             responseContent.append("\r\n\r\n");
142 
143             // if GET Method: should not try to create a HttpPostRequestDecoder
144             try {
145                 decoder = new HttpPostRequestDecoder(factory, request);
146             } catch (ErrorDataDecoderException e1) {
147                 e1.printStackTrace();
148                 responseContent.append(e1.getMessage());
149                 writeResponse(e.getChannel());
150                 Channels.close(e.getChannel());
151                 return;
152             } catch (IncompatibleDataDecoderException e1) {
153                 // GET Method: should not try to create a HttpPostRequestDecoder
154                 // So OK but stop here
155                 responseContent.append(e1.getMessage());
156                 responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
157                 writeResponse(e.getChannel());
158                 return;
159             }
160 
161             responseContent.append("Is Chunked: " + request.isChunked() + "\r\n");
162             responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
163             if (request.isChunked()) {
164                 // Chunk version
165                 responseContent.append("Chunks: ");
166                 readingChunks = true;
167             } else {
168                 // Not chunk version
169                 readHttpDataAllReceive(e.getChannel());
170                 responseContent.append("\r\n\r\nEND OF NOT CHUNKED CONTENT\r\n");
171                 writeResponse(e.getChannel());
172             }
173         } else {
174             // New chunk is received
175             HttpChunk chunk = (HttpChunk) e.getMessage();
176             try {
177                 decoder.offer(chunk);
178             } catch (ErrorDataDecoderException e1) {
179                 e1.printStackTrace();
180                 responseContent.append(e1.getMessage());
181                 writeResponse(e.getChannel());
182                 Channels.close(e.getChannel());
183                 return;
184             }
185             responseContent.append('o');
186             // example of reading chunk by chunk (minimize memory usage due to Factory)
187             readHttpDataChunkByChunk();
188             // example of reading only if at the end
189             if (chunk.isLast()) {
190                 readHttpDataAllReceive(e.getChannel());
191                 writeResponse(e.getChannel());
192                 readingChunks = false;
193             }
194         }
195     }
196 
197     /**
198      * Example of reading all InterfaceHttpData from finished transfer
199      */
200     private void readHttpDataAllReceive(Channel channel) {
201         List<InterfaceHttpData> datas;
202         try {
203             datas = decoder.getBodyHttpDatas();
204         } catch (NotEnoughDataDecoderException e1) {
205             // Should not be!
206             e1.printStackTrace();
207             responseContent.append(e1.getMessage());
208             writeResponse(channel);
209             Channels.close(channel);
210             return;
211         }
212         for (InterfaceHttpData data: datas) {
213             writeHttpData(data);
214         }
215         responseContent.append("\r\n\r\nEND OF CONTENT AT FINAL END\r\n");
216     }
217 
218     /**
219      * Example of reading request by chunk and getting values from chunk to
220      * chunk
221      */
222     private void readHttpDataChunkByChunk() {
223         try {
224             while (decoder.hasNext()) {
225                 InterfaceHttpData data = decoder.next();
226                 if (data != null) {
227                     // new value
228                     writeHttpData(data);
229                 }
230             }
231         } catch (EndOfDataDecoderException e1) {
232             // end
233             responseContent.append("\r\n\r\nEND OF CONTENT CHUNK BY CHUNK\r\n\r\n");
234         }
235     }
236 
237     private void writeHttpData(InterfaceHttpData data) {
238         if (data.getHttpDataType() == HttpDataType.Attribute) {
239             Attribute attribute = (Attribute) data;
240             String value;
241             try {
242                 value = attribute.getValue();
243             } catch (IOException e1) {
244                 // Error while reading data from File, only print name and error
245                 e1.printStackTrace();
246                 responseContent.append("\r\nBODY Attribute: " +
247                         attribute.getHttpDataType().name() + ": " +
248                         attribute.getName() + " Error while reading value: " +
249                         e1.getMessage() + "\r\n");
250                 return;
251             }
252             if (value.length() > 100) {
253                 responseContent.append("\r\nBODY Attribute: " +
254                         attribute.getHttpDataType().name() + ": " + attribute.getName() + " data too long\r\n");
255             } else {
256                 responseContent.append(
257                         "\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ": " + attribute + "\r\n");
258             }
259         } else {
260             responseContent.append(
261                     "\r\nBODY FileUpload: " + data.getHttpDataType().name() + ": " + data + "\r\n");
262             if (data.getHttpDataType() == HttpDataType.FileUpload) {
263                 FileUpload fileUpload = (FileUpload) data;
264                 if (fileUpload.isCompleted()) {
265                     if (fileUpload.length() < 10000) {
266                         responseContent.append("\tContent of file\r\n");
267                         try {
268                             responseContent.append(fileUpload.getString(fileUpload.getCharset()));
269                         } catch (IOException e1) {
270                             // do nothing for the example
271                             e1.printStackTrace();
272                         }
273                         responseContent.append("\r\n");
274                     } else {
275                         responseContent.append(
276                                 "\tFile too long to be printed out:" + fileUpload.length() + "\r\n");
277                     }
278                     // fileUpload.isInMemory();// tells if the file is in Memory
279                     // or on File
280                     // fileUpload.renameTo(dest); // enable to move into another
281                     // File dest
282                     // decoder.removeFileUploadFromClean(fileUpload); //remove
283                     // the File of to delete file
284                 } else {
285                     responseContent.append("\tFile to be continued but should not!\r\n");
286                 }
287             }
288         }
289     }
290 
291     private void writeResponse(Channel channel) {
292         // Convert the response content to a ChannelBuffer.
293         ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
294         responseContent.setLength(0);
295 
296         // Decide whether to close the connection or not.
297         boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(
298                 request.headers().get(HttpHeaders.Names.CONNECTION)) ||
299                 request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) &&
300                 !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.headers().get(HttpHeaders.Names.CONNECTION));
301 
302         // Build the response object.
303         HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
304         response.setContent(buf);
305         response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
306 
307         if (!close) {
308             // There's no need to add 'Content-Length' header
309             // if this is the last response.
310             response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf.readableBytes()));
311         }
312 
313         Set<Cookie> cookies;
314         String value = request.headers().get(HttpHeaders.Names.COOKIE);
315         if (value == null) {
316             cookies = Collections.emptySet();
317         } else {
318             cookies = ServerCookieDecoder.STRICT.decode(value);
319         }
320         if (!cookies.isEmpty()) {
321             response.headers().add(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookies));
322         }
323         // Write the response.
324         ChannelFuture future = channel.write(response);
325         // Close the connection after the write operation is done if necessary.
326         if (close) {
327             future.addListener(ChannelFutureListener.CLOSE);
328         }
329     }
330 
331     private void writeMenu(MessageEvent e) {
332         // print several HTML forms
333         // Convert the response content to a ChannelBuffer.
334         responseContent.setLength(0);
335 
336         // create Pseudo Menu
337         responseContent.append("<html>");
338         responseContent.append("<head>");
339         responseContent.append("<title>Netty Test Form</title>\r\n");
340         responseContent.append("</head>\r\n");
341         responseContent.append("<body bgcolor=white><style>td{font-size: 12pt;}</style>");
342 
343         responseContent.append("<table border=\"0\">");
344         responseContent.append("<tr>");
345         responseContent.append("<td>");
346         responseContent.append("<h1>Netty Test Form</h1>");
347         responseContent.append("Choose one FORM");
348         responseContent.append("</td>");
349         responseContent.append("</tr>");
350         responseContent.append("</table>\r\n");
351 
352         // GET
353         responseContent.append("<CENTER>GET FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
354         responseContent.append("<FORM ACTION=\"/formget\" METHOD=\"GET\">");
355         responseContent.append("<input type=hidden name=getform value=\"GET\">");
356         responseContent.append("<table border=\"0\">");
357         responseContent.append("<tr><td>Fill with value:<br> <input type=text name=\"info\" size=10></td></tr>");
358         responseContent.append("<tr><td>Fill with value:<br> <input type=text name=\"secondinfo\" size=20>");
359         responseContent.append("<tr><td>Fill with value:<br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
360         responseContent.append("</td></tr>");
361         responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
362         responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
363         responseContent.append("</table></FORM>\r\n");
364         responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
365 
366         // POST
367         responseContent.append("<CENTER>POST FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
368         responseContent.append("<FORM ACTION=\"/formpost\" METHOD=\"POST\">");
369         responseContent.append("<input type=hidden name=getform value=\"POST\">");
370         responseContent.append("<table border=\"0\">");
371         responseContent.append("<tr><td>Fill with value:<br> <input type=text name=\"info\" size=10></td></tr>");
372         responseContent.append("<tr><td>Fill with value:<br> <input type=text name=\"secondinfo\" size=20>");
373         responseContent.append("<tr><td>Fill with value:<br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
374         responseContent.append("<tr><td>Fill with file (only file name will be transmitted): <br> ");
375         responseContent.append("<input type=file name=\"myfile\">");
376         responseContent.append("</td></tr>");
377         responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
378         responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
379         responseContent.append("</table></FORM>\r\n");
380         responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
381 
382         // POST with enctype="multipart/form-data"
383         responseContent.append("<CENTER>POST MULTIPART FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
384         responseContent.append("<FORM ACTION=\"/formpostmultipart\" ENCTYPE=\"multipart/form-data\" METHOD=\"POST\">");
385         responseContent.append("<input type=hidden name=getform value=\"POST\">");
386         responseContent.append("<table border=\"0\">");
387         responseContent.append("<tr><td>Fill with value:<br> <input type=text name=\"info\" size=10></td></tr>");
388         responseContent.append("<tr><td>Fill with value:<br> <input type=text name=\"secondinfo\" size=20>");
389         responseContent.append("<tr><td>Fill with value:<br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
390         responseContent.append("<tr><td>Fill with file: <br> <input type=file name=\"myfile\">");
391         responseContent.append("</td></tr>");
392         responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
393         responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
394         responseContent.append("</table></FORM>\r\n");
395         responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
396 
397         responseContent.append("</body>");
398         responseContent.append("</html>");
399 
400         ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
401         // Build the response object.
402         HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
403         response.setContent(buf);
404         response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");
405         response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf.readableBytes()));
406         // Write the response.
407         e.getChannel().write(response);
408     }
409 
410     @Override
411     public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
412         e.getCause().printStackTrace();
413         e.getChannel().close();
414     }
415 }