- Timestamp:
- 2021-11-03T15:24:04+13:00 (2 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
other-projects/the-macronizer/trunk/src/java/web/servlets/FileUpload.java
r31964 r35719 1 1 package web.servlets; 2 2 3 import java.io.BufferedReader;4 3 import java.io.File; 5 import java.io.FileReader;6 4 import java.io.IOException; 7 import java. lang.StringBuilder;5 import java.util.ArrayList; 8 6 import java.util.List; 7 9 8 import javax.servlet.RequestDispatcher; 10 9 import javax.servlet.ServletConfig; … … 13 12 import javax.servlet.http.HttpServletRequest; 14 13 import javax.servlet.http.HttpServletResponse; 14 15 import monogram.plugin.PluginConfiguration; 16 import monogram.plugin.PluginManager; 17 15 18 import org.apache.commons.fileupload.FileItem; 19 import org.apache.commons.fileupload.FileUploadException; 16 20 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 17 21 import org.apache.commons.fileupload.servlet.ServletFileUpload; 18 import monogram.plugin.PluginConfiguration; 22 import org.apache.log4j.*; 23 19 24 import util.FileUtil; 20 import monogram.plugin.PluginManager;21 import org.apache.log4j.*;22 25 23 26 /** … … 28 31 public class FileUpload extends HttpServlet { 29 32 33 // Create an instance of the logger object defined for the DirectInput servlet in log4j.properties. 34 private static final Logger logger = Logger.getLogger(web.servlets.DirectInput.class.getName()); 35 30 36 private File tmpdir; 31 private String inputFile; 32 private String outputFile; 33 34 //Create an instance of the Logger object created for this class in log4j.properties 35 static Logger logger = Logger.getLogger(web.servlets.DirectInput.class.getName()); 37 private PluginManager pluginManager; 36 38 37 39 @Override 38 public void init(ServletConfig config) throws ServletException { 40 public void init(ServletConfig config) 41 throws ServletException 42 { 39 43 super.init(config); 44 40 45 tmpdir = new File((String) config.getServletContext().getAttribute("tmpdir")); 41 } 42 43 protected void processRequest(HttpServletRequest request, HttpServletResponse response) 44 throws ServletException, IOException { 45 //do nothing 46 } 47 46 pluginManager = new PluginManager(tmpdir); 47 } 48 49 /** 50 * Handles the HTTP <code>GET</code> method. 51 * @param request The servlet request. 52 * @param response The servlet response. 53 * @throws IllegalStateException if a reponse has already been committed. 54 * @throws IOException if an I/O error occurs. 55 */ 48 56 @Override 49 57 protected void doGet(HttpServletRequest request, HttpServletResponse response) 50 throws ServletException, IOException { 51 processRequest(request, response); 58 throws IllegalStateException, IOException 59 { 60 response.sendError(405); // 405 Method Not Allowed 52 61 } 53 62 … … 61 70 @Override 62 71 protected void doPost(HttpServletRequest request, HttpServletResponse response) 63 throws ServletException, IOException { 64 // set DI to false as this is not Directinput. 65 DirectInput.DI = false; 66 final Properties properties = handleRequest(request); 67 final String address = "/jsp" + (properties.getLanguage().equals("en") ? "/en" : "/mi"); 68 final PluginConfiguration configuration = configure(properties); 69 final PluginManager pluginManager = new PluginManager(tmpdir); 70 71 if (configuration.getFile().length() == 0) { 72 configuration.getFile().delete(); 73 request.setAttribute("errorCode", "FILE_NOT_FOUND_ERROR"); 74 forward(address + "/error.jsp", request, response); 75 return; 76 } 77 72 throws IllegalStateException, IOException, ServletException 73 { 74 final OutputType outputType = OutputType.parse(request.getParameter("o")); // TODO: This probably won't work with the multipart request 75 78 76 File restoredFile = null; 79 try { 77 PluginConfiguration configuration = null; 78 Properties properties = null; 79 String forwardPath = "/jsp/mi"; 80 81 try 82 { 83 properties = handleRequest(request); 84 forwardPath = properties.getLanguage() != null ? "/jsp/" + properties.getLanguage() : forwardPath; 85 } 86 catch (Exception ex) 87 { 88 setError(outputType, forwardPath, "INVALID_REQUEST", request, response); 89 } 90 91 try 92 { 93 configuration = configure(properties); 94 95 if (configuration.getFile().length() == 0) 96 { 97 configuration.getFile().delete(); 98 setError(outputType, forwardPath, "FILE_NOT_FOUND_ERROR", request, response); 99 return; 100 } 101 80 102 restoredFile = pluginManager.run(configuration); 81 103 request.setAttribute("file", restoredFile); … … 85 107 request.setAttribute("preserveMacrons", properties.getPreserveExistingMacrons()); 86 108 request.setAttribute("options", properties.getOptions()); 87 forward( address+ "/main.jsp", request, response);88 outputFile = stringFromFile(restoredFile); 89 logger.error("Output:"+outputFile); 90 } catch (UnsupportedOperationException e){109 forward(forwardPath + "/main.jsp", request, response); 110 } 111 catch (UnsupportedOperationException uoex) 112 { 91 113 FileUtil.deleteFile(restoredFile); 92 request.setAttribute("errorCode", "FILE_TYPE_NOT_SUPPORTED_ERROR"); 93 forward(address + "/error.jsp", request, response); 94 } catch (Exception e) { 114 logger.error("Failed to restore macrons on a file", uoex); 115 setError(outputType, forwardPath, "FILE_TYPE_NOT_SUPPORTED_ERROR", request, response); 116 } 117 catch (Exception ex) 118 { 95 119 FileUtil.deleteFile(restoredFile); 96 request.setAttribute("errorCode", "UNEXPECTED_ERROR"); 97 forward(address + "/error.jsp", request, response); 98 } finally { 99 FileUtil.deleteFile(configuration.getFile()); 100 } 101 } 102 120 ex.printStackTrace(); 121 logger.error("Failed to restore macrons on a file", ex); 122 setError(outputType, forwardPath, "UNEXPECTED_ERROR", request, response); 123 } 124 finally 125 { 126 if (configuration != null) 127 { 128 FileUtil.deleteFile(configuration.getFile()); 129 } 130 } 131 } 132 133 private void setError(OutputType outputType, String forwardPath, String errorCode, HttpServletRequest request, HttpServletResponse response) 134 throws IOException, ServletException 135 { 136 switch (outputType) { 137 case Json: 138 // 500 Internal Server Error 139 response.sendError(500, errorCode); 140 break; 141 default: 142 request.setAttribute("errorMessage", errorCode); 143 forward(forwardPath + "/error.jsp", request, response); 144 break; 145 } 146 } 147 148 /** 149 * Forwards a request from a servlet to another resource on the server. 150 * @param path The path to forward to. 151 * @param request The servlet request. 152 * @param response The servlet response. 153 * @throws ServletException 154 * @throws IOException 155 */ 103 156 private void forward(String path, HttpServletRequest request, HttpServletResponse response) 104 throws ServletException, IOException { 157 throws ServletException, IOException 158 { 105 159 final RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(path); 106 160 dispatcher.forward(request, response); 107 161 } 108 162 109 private Properties handleRequest(HttpServletRequest request) { 163 private Properties handleRequest(HttpServletRequest request) 164 throws Exception, FileUploadException, IOException 165 { 110 166 Properties requestData = new Properties(); 111 167 DiskFileItemFactory factory = new DiskFileItemFactory(); 112 168 factory.setSizeThreshold(10 * 1024 * 1024); 113 169 ServletFileUpload upload = new ServletFileUpload(factory); 114 try { 115 //System.out.println("looking at request parameters..."); 116 List<FileItem> items = upload.parseRequest(request); 117 118 for (FileItem item : items) { 119 if (item.isFormField()) { 120 String fieldName = item.getFieldName(); 121 String fieldValue = item.getString(); 122 if (fieldName.equals("charsetEncoding")) { 123 requestData.setCharsetEncoding(fieldValue); 124 } else if (fieldName.equals("fileType")) { 125 requestData.setFileType(fieldValue); 126 } else if (fieldName.equals("preserveExistingMacrons")) { 127 requestData.setPreserveExistingMacrons(fieldValue); 128 } else if (fieldName.equals("lang")) { 129 requestData.setLanguage(fieldValue); 130 } else if (fieldName.equals("options")) { 131 requestData.setOptions(fieldValue); 132 } 133 } else { 134 String fileType = FileUtil.guessFileType(new File(item.getName())); 135 File file = File.createTempFile("mi-tmp-", fileType, tmpdir); 136 item.write(file); 137 requestData.setFile(file); 138 requestData.setFilename(item.getName()); 139 inputFile=stringFromFile(file); 140 // logger.error("Input:"+logText); 170 171 List<FileItem> items = new ArrayList<>(); 172 for (Object element : upload.parseRequest(request)) { 173 items.add(FileItem.class.cast(element)); 174 } 175 176 for (FileItem item : items) 177 { 178 if (item.isFormField()) 179 { 180 String fieldName = item.getFieldName(); 181 String fieldValue = item.getString(); 182 if (fieldName.equals("charsetEncoding")) { 183 requestData.setCharsetEncoding(fieldValue); 184 } else if (fieldName.equals("fileType")) { 185 requestData.setFileType(fieldValue); 186 } else if (fieldName.equals("preserveExistingMacrons")) { 187 requestData.setPreserveExistingMacrons(fieldValue); 188 } else if (fieldName.equals("lang")) { 189 requestData.setLanguage(fieldValue); 190 } else if (fieldName.equals("options")) { 191 requestData.setOptions(fieldValue); 141 192 } 142 193 } 143 } catch (Exception e) { 144 e.printStackTrace(); 145 } 194 else 195 { 196 String fileType = FileUtil.guessFileType(new File(item.getName())); 197 File file = File.createTempFile(FileUtil.TMP_FILE_PREFIX, fileType, tmpdir); 198 item.write(file); 199 requestData.setFile(file); 200 requestData.setFilename(item.getName()); 201 } 202 } 203 146 204 return requestData; 147 205 } 148 206 149 private String stringFromFile(File file)throws IOException{ 150 BufferedReader reader = new BufferedReader(new FileReader(file)); 151 String line = null; 152 StringBuilder sb = new StringBuilder(); 153 try{ 154 while((line=reader.readLine())!=null){ 155 sb.append(line); 156 } 157 } 158 catch (Exception e){ 159 e.printStackTrace(); 160 } 161 finally{ 162 reader.close(); 163 } 164 return sb.toString(); 165 } 207 /* Useful for debugging file operations */ 208 // private String readStringFromFile(File file) 209 // throws FileNotFoundException, IOException 210 // { 211 // BufferedReader reader = new BufferedReader(new FileReader(file)); 212 // String line = null; 213 // StringBuilder sb = new StringBuilder(); 214 215 // try 216 // { 217 // while ((line=reader.readLine()) != null) 218 // { 219 // sb.append(line); 220 // } 221 // } 222 // finally 223 // { 224 // reader.close(); 225 // } 226 227 // return sb.toString(); 228 // } 166 229 167 private PluginConfiguration configure(Properties properties) { 230 private PluginConfiguration configure(Properties properties) 231 { 168 232 final File file = properties.getFile(); 169 233 final String fileType = properties.getFileType().equals("(detect automatically)") ? FileUtil.guessFileType(file) : properties.getFileType(); … … 176 240 configuration.setCharsetEncoding(charsetEncoding); 177 241 configuration.setPreserveExistingMacrons(Boolean.getBoolean(preserveExistingMacrons)); 242 178 243 return configuration; 179 244 } 180 245 181 private class Properties {182 246 private class Properties 247 { 183 248 private File file; 184 249 private String filename; … … 209 274 } 210 275 276 @SuppressWarnings("unused") 211 277 public String getLanguage() { 212 278 return language;
Note:
See TracChangeset
for help on using the changeset viewer.