Advertisement
Guest User

File Upload

a guest
Jan 30th, 2016
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.08 KB | None | 0 0
  1. package servlets;
  2.  
  3. /*
  4. * To change this license header, choose License Headers in Project Properties.
  5. * To change this template file, choose Tools | Templates
  6. * and open the template in the editor.
  7. */
  8. import com.jaunt.ResponseException;
  9. import java.io.File;
  10. import java.io.FileNotFoundException;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.io.InputStream;
  14. import java.io.OutputStream;
  15. import java.io.PrintWriter;
  16. import java.util.ArrayList;
  17. import java.util.logging.Level;
  18. import java.util.logging.Logger;
  19. import javax.servlet.ServletException;
  20. import javax.servlet.annotation.MultipartConfig;
  21. import javax.servlet.annotation.WebServlet;
  22. import javax.servlet.http.HttpServlet;
  23. import javax.servlet.http.HttpServletRequest;
  24. import javax.servlet.http.HttpServletResponse;
  25. import javax.servlet.http.Part;
  26. import javax.xml.parsers.ParserConfigurationException;
  27. import org.xml.sax.SAXException;
  28. import utilityClasses.ScanItunesSongs;
  29. import utilityClasses.Song;
  30. import utilityClasses.SongNotFoundException;
  31.  
  32. /**
  33. * Servlet to receive the XML file that the user will upload that contains
  34. * his/her music library.
  35. *
  36. * @author Tim
  37. */
  38. @MultipartConfig
  39. @WebServlet(urlPatterns = {"/GetItunesLibrary"})
  40. public class GetItunesLibrary extends HttpServlet {
  41.  
  42. private final static Logger LOGGER = Logger.getLogger(GetItunesLibrary.class.getCanonicalName());
  43.  
  44. /**
  45. * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
  46. * methods.
  47. *
  48. * @param request servlet request
  49. * @param response servlet response
  50. * @throws ServletException if a servlet-specific error occurs
  51. * @throws IOException if an I/O error occurs
  52. */
  53. protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  54. throws ServletException, IOException, ParserConfigurationException, SAXException, ResponseException {
  55. response.setContentType("text/html;charset=UTF-8");
  56.  
  57. //Create path components to save the file
  58. final Part filePart = request.getPart("XMLFile"); // Retrieves <input type="file" name="XMLFile">
  59. final String path = "/home/uploads/";
  60. final String fileName = getFileName(filePart);
  61.  
  62. OutputStream outStream = null;
  63. InputStream fileContent = null;
  64. final PrintWriter out = response.getWriter();
  65. out.println("File name: " + fileName);
  66. try {
  67.  
  68. File xmlFile = new File(path + fileName);
  69. //File xmlFile = new File(fileName);
  70. outStream = new FileOutputStream(xmlFile);
  71. fileContent = filePart.getInputStream();
  72.  
  73. int read = 0;
  74. final byte[] bytes = new byte[1024];
  75.  
  76. while ((read = fileContent.read(bytes)) != -1) {
  77. outStream.write(bytes, 0, read);
  78. }
  79. //File is now saved to the server
  80. ScanItunesSongs scanItunes = new ScanItunesSongs(xmlFile.getAbsolutePath());
  81. scanItunes.scan();
  82. ArrayList<Song> songs = scanItunes.getSongs();
  83. out.println("<!DOCTYPE html>");
  84. out.println("<html>");
  85. out.println("<head>");
  86. out.println("<link href=\"http://s3.amazonaws.com/codecademy-content/courses/ltp/css/bootstrap.css\" rel=\"stylesheet\">\n"
  87. + " <link href=\"C:\\Users\\Tim\\Documents\\IsThisSongClean\\css.css\" rel=\"stylesheet\">\n"
  88. + " <style type=\"text/css\">\n"
  89. + " .jumbotron {\n"
  90. + " height:100%;\n"
  91. + " background-color: rgb(160, 232, 153);\n"
  92. + " border-style: inset;\n"
  93. + " }\n"
  94. + " .wrapper {\n"
  95. + " text-align: center;\n"
  96. + " }\n"
  97. + "\n"
  98. + " .jumbotron h1, h5 {\n"
  99. + " text-align: center;\n"
  100. + "\n"
  101. + " }\n"
  102. + "\n"
  103. + " .jumbotron input {\n"
  104. + " text-align: center;\n"
  105. + " }\n"
  106. + "\n"
  107. + " input[type=\"text\"] {\n"
  108. + " display: block;\n"
  109. + " margin : 0 auto;\n"
  110. + " }\n"
  111. + "\n"
  112. + " .results span {\n"
  113. + " text-align: center;\n"
  114. + " }\n"
  115. + "\n"
  116. + " input, div {\n"
  117. + " border-style: inline;\n"
  118. + " border-color: rgb(102, 163, 96);\n"
  119. + " padding: 0;\n"
  120. + " margin: 0;\n"
  121. + " font: 13px sans-serif;\n"
  122. + " }\n"
  123. + " </style>");
  124. out.println("<title>Servlet GetSongAndArtist</title>");
  125. out.println("</head>");
  126. out.println("<body>");
  127. out.println("<div class=\"jumbotron\"");
  128. out.println("<p> All of your songs are completely clean except for the following:</p>");
  129. for (Song song : songs) {
  130. String s;
  131. try {
  132. boolean isClean = song.isClean();
  133. if (isClean) {
  134. } else {
  135. out.println("<p>" + song.getSong() + " by artist " + song.getArtist() + "</p>");
  136. }
  137.  
  138. } catch (SongNotFoundException snfe) {
  139. out.println("<p> The song " + song.getSong() + " by artist " + song.getArtist() + " could not be found. </p>");
  140. }
  141.  
  142. }
  143. out.println("<a href=\"index.jsp\">Search another song</a>");
  144. out.println("<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>\n"
  145. + " <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>");
  146. out.println("</div>");
  147.  
  148. out.println("</body>");
  149. out.println("</html>");
  150.  
  151. LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", new Object[]{fileName, path});
  152. } catch (FileNotFoundException fnfe) {
  153. out.println("You either did not specify a file to upload or are "
  154. + "trying to upload a file to a protected or nonexistent "
  155. + "location.");
  156. out.println("<br/> ERROR: " + fnfe.getMessage() + "<br>" + fnfe.getLocalizedMessage());
  157.  
  158. LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",
  159. new Object[]{fnfe.getMessage()});
  160. }
  161.  
  162. }
  163.  
  164. // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  165. /**
  166. * Handles the HTTP <code>GET</code> method.
  167. *
  168. * @param request servlet request
  169. * @param response servlet response
  170. * @throws ServletException if a servlet-specific error occurs
  171. * @throws IOException if an I/O error occurs
  172. */
  173. @Override
  174. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  175. throws ServletException, IOException {
  176. try {
  177. processRequest(request, response);
  178. } catch (ParserConfigurationException | SAXException | ResponseException ex) {
  179. Logger.getLogger(GetItunesLibrary.class.getName()).log(Level.SEVERE, null, ex);
  180. }
  181. }
  182.  
  183. /**
  184. * Handles the HTTP <code>POST</code> method.
  185. *
  186. * @param request servlet request
  187. * @param response servlet response
  188. * @throws ServletException if a servlet-specific error occurs
  189. * @throws IOException if an I/O error occurs
  190. */
  191. @Override
  192. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  193. throws ServletException, IOException {
  194. try {
  195. processRequest(request, response);
  196. } catch (ParserConfigurationException ex) {
  197. Logger.getLogger(GetItunesLibrary.class.getName()).log(Level.SEVERE, null, ex);
  198. } catch (SAXException ex) {
  199. Logger.getLogger(GetItunesLibrary.class.getName()).log(Level.SEVERE, null, ex);
  200. } catch (ResponseException ex) {
  201. Logger.getLogger(GetItunesLibrary.class.getName()).log(Level.SEVERE, null, ex);
  202. }
  203. }
  204.  
  205. /**
  206. * Returns a short description of the servlet.
  207. *
  208. * @return a String containing servlet description
  209. */
  210. @Override
  211. public String getServletInfo() {
  212. return "Short description";
  213. }// </editor-fold>
  214.  
  215. private String getFileName(final Part part) {
  216. final String partHeader = part.getHeader("content-disposition");
  217. LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
  218. for (String content : part.getHeader("content-disposition").split(";")) {
  219. if (content.trim().startsWith("filename")) {
  220. return content.substring(
  221. content.indexOf('=') + 1).trim().replace("\"", "");
  222. }
  223. }
  224. return null;
  225. }
  226. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement