Ignore:
Timestamp:
2021-11-03T16:18:48+13:00 (2 years ago)
Author:
cstephen
Message:

Refactor FileUpload logic

Location:
other-projects/the-macronizer/trunk/src/java/web/servlets
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • other-projects/the-macronizer/trunk/src/java/web/servlets/DirectInput.java

    r35719 r35720  
    8585
    8686        final String fragment = request.getParameter("fragment");
    87         final Boolean showAdvancedOptions = request.getParameter("options") != null && request.getParameter("options").equals("true");
    88         final Boolean shouldPreserveMacrons = request.getParameter("preserveExistingMacrons") != null && request.getParameter("preserveExistingMacrons").equals("true");
     87        final Boolean showAdvancedOptions = Boolean.parseBoolean(request.getParameter("options"));
     88        final Boolean shouldPreserveMacrons = Boolean.parseBoolean(request.getParameter("preserveExistingMacrons"));
    8989        final OutputType outputType = OutputType.parse(request.getParameter("o"));
    9090
    9191        // Note that the lang parameter might be null if the request hasn't been made from an internal JSP page
    92         final String lang = request.getParameter("lang");
    93         final String forwardPath = lang != null ? "/jsp/" + lang : "/jsp/mi";
     92        final String forwardPath = request.getParameter("lang") != null
     93            ? "/jsp/" + request.getParameter("lang")
     94            : "/jsp/mi";
    9495
    9596        try
  • other-projects/the-macronizer/trunk/src/java/web/servlets/FileUpload.java

    r35719 r35720  
    7272        throws IllegalStateException, IOException, ServletException
    7373    {
    74         final OutputType outputType = OutputType.parse(request.getParameter("o")); // TODO: This probably won't work with the multipart request
    75        
     74        List<FileItem> formItems = null;
     75        Properties properties = null;
    7676        File restoredFile = null;
    7777        PluginConfiguration configuration = null;
    78         Properties properties = null;
    79         String forwardPath = "/jsp/mi";
    8078
    8179        try
    8280        {
    83             properties = handleRequest(request);
    84             forwardPath = properties.getLanguage() != null ? "/jsp/" + properties.getLanguage() : forwardPath;
     81            formItems = parseFormItems(request);
     82            properties = getRequestProperties(formItems);
    8583        }
    8684        catch (Exception ex)
    8785        {
    88             setError(outputType, forwardPath, "INVALID_REQUEST", request, response);
     86            throw new ServletException("Expected a multipart/form-data request.", ex);
    8987        }
    9088
    9189        try
    9290        {
     91            Boolean foundFile = getRequestFile(formItems, properties);
     92            if (!foundFile)
     93            {
     94                setError(properties, "FILE_NOT_FOUND_ERROR", request, response, true);
     95                return;
     96            }
     97        }
     98        catch (Exception ex)
     99        {
     100            ex.printStackTrace();
     101            logger.error("Failed to get uploaded file", ex);
     102            setError(properties, "UNEXPECTED_ERROR", request, response, false);
     103        }
     104
     105        try
     106        {
    93107            configuration = configure(properties);
    94108
     
    96110            {
    97111                configuration.getFile().delete();
    98                 setError(outputType, forwardPath, "FILE_NOT_FOUND_ERROR", request, response);
     112                setError(properties, "FILE_NOT_FOUND_ERROR", request, response, false);
    99113                return;
    100114            }
     
    106120            request.setAttribute("filename", properties.getFilename());
    107121            request.setAttribute("preserveMacrons", properties.getPreserveExistingMacrons());
    108             request.setAttribute("options", properties.getOptions());
    109             forward(forwardPath + "/main.jsp", request, response);
     122            request.setAttribute("options", properties.getShowAdvancedOptions());
     123
     124            forward(properties.getJspForwardPath() + "/main.jsp", request, response);
    110125        }
    111126        catch (UnsupportedOperationException uoex)
     
    113128            FileUtil.deleteFile(restoredFile);
    114129            logger.error("Failed to restore macrons on a file", uoex);
    115             setError(outputType, forwardPath, "FILE_TYPE_NOT_SUPPORTED_ERROR", request, response);
     130            setError(properties, "FILE_TYPE_NOT_SUPPORTED_ERROR", request, response, false);
    116131        }
    117132        catch (Exception ex)
     
    120135            ex.printStackTrace();
    121136            logger.error("Failed to restore macrons on a file", ex);
    122             setError(outputType, forwardPath, "UNEXPECTED_ERROR", request, response);
     137            setError(properties, "UNEXPECTED_ERROR", request, response, false);
    123138        }
    124139        finally
     
    127142            {
    128143                FileUtil.deleteFile(configuration.getFile());
    129             }
    130         }
    131     }
    132 
    133     private void setError(OutputType outputType, String forwardPath, String errorCode, HttpServletRequest request, HttpServletResponse response)
     144                // We don't clean up the file held by the properties object,
     145                // as the configuration holds a reference to said file
     146            }
     147        }
     148    }
     149
     150    private void setError(
     151        Properties properties,
     152        String errorCode,
     153        HttpServletRequest request,
     154        HttpServletResponse response,
     155        Boolean isClientError)
    134156        throws IOException, ServletException
    135157    {
    136         switch (outputType) {
     158        switch (properties.getOutputType()) {
    137159            case Json:
    138160                // 500 Internal Server Error
    139                 response.sendError(500, errorCode);
     161                response.sendError(isClientError ? 400 : 500, errorCode);
    140162                break;
    141163            default:
    142164                request.setAttribute("errorMessage", errorCode);
    143                 forward(forwardPath + "/error.jsp", request, response);
     165                forward(properties.getJspForwardPath()+ "/error.jsp", request, response);
    144166                break;
    145167        }
     
    161183    }
    162184
    163     private Properties handleRequest(HttpServletRequest request)
    164         throws Exception, FileUploadException, IOException
    165     {
    166         Properties requestData = new Properties();
     185    /**
     186     * Parses multipart items from a request.
     187     * @param request The request
     188     * @return The parsed multipart items.
     189     * @throws FileUploadException
     190     */
     191    private List<FileItem> parseFormItems(HttpServletRequest request)
     192        throws FileUploadException
     193    {
    167194        DiskFileItemFactory factory = new DiskFileItemFactory();
    168195        factory.setSizeThreshold(10 * 1024 * 1024);
     
    174201        }
    175202
    176         for (FileItem item : items)
     203        return items;
     204    }
     205   
     206    /**
     207     * Gets the properties of the request by checking the submitted form items.
     208     * @param formItems The multipart form items.
     209     * @return The properties.
     210     */
     211    private Properties getRequestProperties(List<FileItem> formItems)
     212    {
     213        Properties properties = new Properties();
     214
     215        for (FileItem item : formItems)
     216        {
     217            if (!item.isFormField())
     218            {
     219                continue;
     220            }
     221
     222            String fieldName = item.getFieldName();
     223            String fieldValue = item.getString();
     224
     225            switch (fieldName)
     226            {
     227                case "charsetEncoding":
     228                    properties.setCharsetEncoding(fieldValue);
     229                    break;
     230                case "fileType":
     231                    properties.setFileType(fieldValue);
     232                    break;
     233                case "preserveExistingMacrons":
     234                    properties.setPreserveExistingMacrons(fieldValue);
     235                    break;
     236                case "lang":
     237                    properties.setLanguage(fieldValue);
     238                    break;
     239                case "options":
     240                    properties.setShowAdvancedOptions(fieldValue);
     241                    break;
     242                case "o":
     243                    properties.setOutputType(fieldValue);
     244                    break;
     245            }
     246        }
     247
     248        return properties;
     249    }
     250
     251    /**
     252     * Gets the first file contained in the submitted form items.
     253     * @param formItems The multipart form items.
     254     * @return The file, or <code>null</code> if the request contained no files.
     255     * @throws Exception
     256     * @throws IOException
     257     */
     258    private Boolean getRequestFile(List<FileItem> formItems, Properties properties)
     259        throws Exception, IOException
     260    {
     261        for (FileItem item : formItems)
    177262        {
    178263            if (item.isFormField())
    179264            {
    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);
    192                 }
    193             }
    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 
    204         return requestData;
     265                continue;
     266            }
     267
     268            String fileType = FileUtil.guessFileType(new File(item.getName()));
     269            File file = File.createTempFile(FileUtil.TMP_FILE_PREFIX, fileType, tmpdir);
     270            item.write(file);
     271
     272            properties.setFile(file);
     273            properties.setFilename(item.getName());
     274
     275            return true;
     276        }
     277
     278        return false;
    205279    }
    206280   
     
    233307        final String fileType = properties.getFileType().equals("(detect automatically)") ? FileUtil.guessFileType(file) : properties.getFileType();
    234308        final String charsetEncoding = properties.getCharsetEncoding().equals("(detect automatically)") ? "utf8" : properties.getCharsetEncoding();
    235         final String preserveExistingMacrons = properties.getPreserveExistingMacrons();
    236309
    237310        final PluginConfiguration configuration = new PluginConfiguration();
     
    239312        configuration.setFileType(fileType);
    240313        configuration.setCharsetEncoding(charsetEncoding);
    241         configuration.setPreserveExistingMacrons(Boolean.getBoolean(preserveExistingMacrons));
     314        configuration.setPreserveExistingMacrons(properties.getPreserveExistingMacrons());
    242315
    243316        return configuration;
     
    250323        private String fileType;
    251324        private String charsetEncoding;
    252         private String preserveExistingMacrons;
     325        private Boolean preserveExistingMacrons;
    253326        private String language;
    254         private String options;
     327        private Boolean showAdvancedOptions;
     328        private OutputType outputType;
    255329
    256330        public File getFile() {
     
    270344        }
    271345
    272         public String getPreserveExistingMacrons() {
     346        public Boolean getPreserveExistingMacrons() {
    273347            return preserveExistingMacrons;
    274348        }
    275349
    276         @SuppressWarnings("unused")
    277350        public String getLanguage() {
    278351            return language;
    279352        }
    280353
    281         public String getOptions() {
    282             return options;
     354        public Boolean getShowAdvancedOptions() {
     355            return showAdvancedOptions;
     356        }
     357
     358        public OutputType getOutputType() {
     359            return outputType;
     360        }
     361
     362        public String getJspForwardPath() {
     363            return getLanguage() != null
     364                ? "/jsp/" + getLanguage()
     365                : "/jsp/mi";
    283366        }
    284367
     
    300383
    301384        public void setPreserveExistingMacrons(String preserveExistingMacrons) {
    302             this.preserveExistingMacrons = preserveExistingMacrons;
     385            this.preserveExistingMacrons = Boolean.parseBoolean(preserveExistingMacrons);
    303386        }
    304387
     
    307390        }
    308391
    309         public void setOptions(String options) {
    310             this.options = options;
     392        public void setShowAdvancedOptions(String options) {
     393            this.showAdvancedOptions = Boolean.parseBoolean(options);
     394        }
     395
     396        public void setOutputType(String outputType) {
     397            this.outputType = OutputType.parse(outputType);
    311398        }
    312399    }
Note: See TracChangeset for help on using the changeset viewer.