View Javadoc
1   /*
2    * JBoss, Home of Professional Open Source
3    * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
4    * contributors by the @authors tag. See the copyright.txt in the
5    * distribution for a full listing of individual contributors.
6    *
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   * http://www.apache.org/licenses/LICENSE-2.0
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.jboss.as.quickstart.xml.upload;
18  
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.util.Collection;
22  import java.util.logging.Logger;
23  
24  import javax.inject.Inject;
25  import javax.servlet.RequestDispatcher;
26  import javax.servlet.ServletException;
27  import javax.servlet.annotation.MultipartConfig;
28  import javax.servlet.annotation.WebServlet;
29  import javax.servlet.http.HttpServlet;
30  import javax.servlet.http.HttpServletRequest;
31  import javax.servlet.http.HttpServletResponse;
32  import javax.servlet.http.Part;
33  
34  /**
35   * Simple servlet to handle multipart file upload. <br>
36   * This servlet register itself as handler for '/upload' path in application. When request is made with said context, this
37   * servlet is invoked to handle it. Once it is done, it redirects user agent to application root path.
38   * 
39   * @author baranowb
40   * 
41   */
42  // Mark this class as servlet and indicates that requests to
43  // '/upload' URL in application be handled by this servlet.
44  @WebServlet(urlPatterns = { "/upload" })
45  // configure Servlet 3.0 multipart. Limit file size to 1MB.
46  @MultipartConfig(maxFileSize = 1048576L)
47  public class FileUploadServlet extends HttpServlet {
48  
49      /**
50       * 
51       */
52      private static final long serialVersionUID = 127759768859064589L;
53  
54      private static final Logger logger = Logger.getLogger(FileUploadServlet.class.getName());
55  
56      // name of form fields which are looked up in multipart request
57      public static final String INPUT_NAME = "file";
58  
59      @Inject
60      private FileUploadBean fileUploadBean;
61  
62      // override 'POST' handler. Appliction will use 'POST' to send 'multipart/form-data'
63      @Override
64      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
65  
66          /*
67           * check content type. Require 'multipart/form-data' header in most case contains more than value, some parameters are
68           * present so make a check with String.contains(String). send 406, with error message if it does not contain proper type
69           */
70          final String reqContentType = req.getContentType();
71  
72          if (!reqContentType.contains("multipart/form-data")) {
73              logger.severe("Received request which is not mulipart: " + reqContentType);
74              resp.sendError(406, "Received request which is not mulipart: " + reqContentType);
75              return;
76          }
77  
78          /*
79           * In servlet 3.0, Parts carry form data. Get Parts and perform some name & type checks. Parts contain all data sent in
80           * form not only file, we need only file.
81           */
82          Collection<Part> fileParts = req.getParts();
83          if (fileParts != null && fileParts.size() > 0) {
84              for (Part p : fileParts) {
85                  String partContentType = p.getContentType();
86                  String partName = p.getName();
87                  if (partContentType != null && partContentType.equals("text/xml") && partName != null
88                          && partName.equals(INPUT_NAME)) {
89  
90                      InputStream is = p.getInputStream();
91                      fileUploadBean.parseUpload(is);
92                      break;
93                  }
94              }
95  
96          }
97          /*
98           * Fetch dispatcher for '/'. This will make 'rd' initialized to dispatcher handling for application root.
99           */
100         RequestDispatcher rd = getServletContext().getRequestDispatcher("/");
101 
102         if (rd != null) {
103             /*
104              * Forward the request to default servlet handling calls to application root. In our case FacesServlet
105              */
106             rd.forward(req, resp);
107             return;
108         } else {
109             // this is bad thing, lets throw exception to make user aware of that?
110             throw new IllegalStateException("Container is not well!");
111         }
112 
113     }
114 }