Search in sources :

Example 1 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project pratilipi by Pratilipi.

the class GenericApi method executeApi.

final Object executeApi(GenericApi api, Method apiMethod, JsonObject requestPayloadJson, Class<? extends GenericRequest> apiMethodParameterType, HttpServletRequest request) {
    try {
        GenericRequest apiRequest = new Gson().fromJson(requestPayloadJson, apiMethodParameterType);
        if (apiRequest instanceof GenericFileUploadRequest) {
            GenericFileUploadRequest gfuRequest = (GenericFileUploadRequest) apiRequest;
            try {
                ServletFileUpload upload = new ServletFileUpload();
                FileItemIterator iterator = upload.getItemIterator(request);
                while (iterator.hasNext()) {
                    FileItemStream fileItemStream = iterator.next();
                    if (!fileItemStream.isFormField()) {
                        gfuRequest.setName(fileItemStream.getName());
                        gfuRequest.setData(IOUtils.toByteArray(fileItemStream.openStream()));
                        gfuRequest.setMimeType(fileItemStream.getContentType());
                        break;
                    }
                }
            } catch (IOException | FileUploadException e) {
                throw new UnexpectedServerException();
            }
        }
        JsonObject errorMessages = apiRequest.validate();
        if (errorMessages.entrySet().size() > 0)
            return new InvalidArgumentException(errorMessages);
        else
            return apiMethod.invoke(api, apiRequest);
    } catch (JsonSyntaxException e) {
        logger.log(Level.SEVERE, "Invalid JSON in request body.", e);
        return new InvalidArgumentException("Invalid JSON in request body.");
    } catch (UnexpectedServerException e) {
        return e;
    } catch (InvocationTargetException e) {
        Throwable te = e.getTargetException();
        if (te instanceof InvalidArgumentException || te instanceof InsufficientAccessException || te instanceof UnexpectedServerException) {
            return te;
        } else {
            logger.log(Level.SEVERE, "Failed to execute API.", te);
            return new UnexpectedServerException();
        }
    } catch (IllegalAccessException | IllegalArgumentException e) {
        logger.log(Level.SEVERE, "Failed to execute API.", e);
        return new UnexpectedServerException();
    }
}
Also used : GenericFileUploadRequest(com.pratilipi.api.shared.GenericFileUploadRequest) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) InsufficientAccessException(com.pratilipi.common.exception.InsufficientAccessException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) UnexpectedServerException(com.pratilipi.common.exception.UnexpectedServerException) InvalidArgumentException(com.pratilipi.common.exception.InvalidArgumentException) JsonSyntaxException(com.google.gson.JsonSyntaxException) FileItemStream(org.apache.commons.fileupload.FileItemStream) GenericRequest(com.pratilipi.api.shared.GenericRequest) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 2 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project nhin-d by DirectProject.

the class PoliciesController method checkLexiconFile.

/*********************************
     *
     * Check Lexicon File Method
     *
     *********************************/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/checkLexiconFile", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String checkLexiconFile(@RequestHeader(value = "X-Requested-With", required = false) String requestedWith, HttpServletResponse response, Object command, @RequestHeader(value = "lexicon", required = false) String lexicon, MultipartHttpServletRequest request) throws FileUploadException, IOException, Exception {
    final org.nhindirect.policy.PolicyLexicon parseLexicon;
    String jsonResponse = "";
    String uploadToString = "";
    if (log.isDebugEnabled()) {
        log.debug("Checking uploaded lexicon file for format and validation");
    }
    // Grab uploaded file from the post submission
    UploadedFile ufile = new UploadedFile();
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = request.getFile(itr.next());
    try {
        ufile.length = mpf.getBytes().length;
        ufile.bytes = mpf.getBytes();
        ufile.type = mpf.getContentType();
        ufile.name = mpf.getOriginalFilename();
    } catch (IOException e) {
    }
    // Convert upload content to string
    uploadToString = new String(ufile.bytes);
    uploadToString = JSONObject.escape(uploadToString);
    lexicon = request.getParameter("lexicon");
    org.nhind.config.PolicyLexicon lex = null;
    // Check the file for three types of policies
    if (lexicon.isEmpty()) {
        lex = org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1;
    } else {
        try {
            // Convert string of file contents to lexicon object
            lex = org.nhind.config.PolicyLexicon.fromString(lexicon);
        } catch (Exception e) {
            log.error("Invalid lexicon name.");
        }
    }
    // Determine lexicon type
    if (lex.equals(org.nhind.config.PolicyLexicon.JAVA_SER)) {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.JAVA_SER;
    } else if (lex.equals(org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1)) {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.SIMPLE_TEXT_V1;
    } else {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.XML;
    }
    InputStream inStr = null;
    try {
        // Convert policy file upload to byte stream
        inStr = new ByteArrayInputStream(ufile.bytes);
        // Initialize parser engine
        final PolicyLexiconParser parser = PolicyLexiconParserFactory.getInstance(parseLexicon);
        // Attempt to parse the lexicon file for validity
        parser.parse(inStr);
    } catch (PolicyParseException e) {
        log.error("Syntax error in policy file " + " : " + e.getMessage());
        jsonResponse = "{\"Status\":\"File was not a valid file.\",\"Content\":\"" + uploadToString + "\"}";
    } finally {
        IOUtils.closeQuietly(inStr);
    }
    if (jsonResponse.isEmpty()) {
        jsonResponse = "{\"Status\":\"Success\",\"Content\":\"" + uploadToString + "\"}";
    }
    return jsonResponse;
}
Also used : PolicyLexicon(org.nhindirect.policy.PolicyLexicon) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PolicyParseException(org.nhindirect.policy.PolicyParseException) MalformedURLException(java.net.MalformedURLException) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) FileUploadException(org.apache.commons.fileupload.FileUploadException) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) ByteArrayInputStream(java.io.ByteArrayInputStream) PolicyLexiconParser(org.nhindirect.policy.PolicyLexiconParser) PolicyParseException(org.nhindirect.policy.PolicyParseException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 3 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project spring-framework by spring-projects.

the class CommonsMultipartFile method transferTo.

@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
    if (!isAvailable()) {
        throw new IllegalStateException("File has already been moved - cannot be transferred again");
    }
    if (dest.exists() && !dest.delete()) {
        throw new IOException("Destination file [" + dest.getAbsolutePath() + "] already exists and could not be deleted");
    }
    try {
        this.fileItem.write(dest);
        if (logger.isDebugEnabled()) {
            String action = "transferred";
            if (!this.fileItem.isInMemory()) {
                action = isAvailable() ? "copied" : "moved";
            }
            logger.debug("Multipart file '" + getName() + "' with original filename [" + getOriginalFilename() + "], stored " + getStorageDescription() + ": " + action + " to [" + dest.getAbsolutePath() + "]");
        }
    } catch (FileUploadException ex) {
        throw new IllegalStateException(ex.getMessage());
    } catch (IOException ex) {
        throw ex;
    } catch (Exception ex) {
        logger.error("Could not transfer to file", ex);
        throw new IOException("Could not transfer to file: " + ex.getMessage());
    }
}
Also used : IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 4 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project spring-framework by spring-projects.

the class CommonsMultipartResolver method parseRequest.

/**
	 * Parse the given servlet request, resolving its multipart elements.
	 * @param request the request to parse
	 * @return the parsing result
	 * @throws MultipartException if multipart resolution failed.
	 */
protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
    String encoding = determineEncoding(request);
    FileUpload fileUpload = prepareFileUpload(encoding);
    try {
        List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
        return parseFileItems(fileItems, encoding);
    } catch (FileUploadBase.SizeLimitExceededException ex) {
        throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
    } catch (FileUploadBase.FileSizeLimitExceededException ex) {
        throw new MaxUploadSizeExceededException(fileUpload.getFileSizeMax(), ex);
    } catch (FileUploadException ex) {
        throw new MultipartException("Failed to parse multipart servlet request", ex);
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) MaxUploadSizeExceededException(org.springframework.web.multipart.MaxUploadSizeExceededException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileUploadBase(org.apache.commons.fileupload.FileUploadBase) MultipartException(org.springframework.web.multipart.MultipartException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileUpload(org.apache.commons.fileupload.FileUpload) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 5 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project felix by apache.

the class ServletRequestWrapper method handleMultipart.

private void handleMultipart() throws IOException {
    // Create a new file upload handler
    final ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(this.multipartConfig.multipartMaxRequestSize);
    upload.setFileSizeMax(this.multipartConfig.multipartMaxFileSize);
    upload.setFileItemFactory(new DiskFileItemFactory(this.multipartConfig.multipartThreshold, new File(this.multipartConfig.multipartLocation)));
    // Parse the request
    List<FileItem> items = null;
    try {
        items = upload.parseRequest(new ServletRequestContext(this));
    } catch (final FileUploadException fue) {
        throw new IOException("Error parsing multipart request", fue);
    }
    parts = new ArrayList<>();
    for (final FileItem item : items) {
        parts.add(new Part() {

            @Override
            public InputStream getInputStream() throws IOException {
                return item.getInputStream();
            }

            @Override
            public String getContentType() {
                return item.getContentType();
            }

            @Override
            public String getName() {
                return item.getFieldName();
            }

            @Override
            public String getSubmittedFileName() {
                return item.getName();
            }

            @Override
            public long getSize() {
                return item.getSize();
            }

            @Override
            public void write(String fileName) throws IOException {
                try {
                    item.write(new File(fileName));
                } catch (IOException e) {
                    throw e;
                } catch (Exception e) {
                    throw new IOException(e);
                }
            }

            @Override
            public void delete() throws IOException {
                item.delete();
            }

            @Override
            public String getHeader(String name) {
                return item.getHeaders().getHeader(name);
            }

            @Override
            public Collection<String> getHeaders(String name) {
                final List<String> values = new ArrayList<>();
                final Iterator<String> iter = item.getHeaders().getHeaders(name);
                while (iter.hasNext()) {
                    values.add(iter.next());
                }
                return values;
            }

            @Override
            public Collection<String> getHeaderNames() {
                final List<String> names = new ArrayList<>();
                final Iterator<String> iter = item.getHeaders().getHeaderNames();
                while (iter.hasNext()) {
                    names.add(iter.next());
                }
                return names;
            }
        });
    }
}
Also used : InputStream(java.io.InputStream) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Part(javax.servlet.http.Part) Iterator(java.util.Iterator) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

FileUploadException (org.apache.commons.fileupload.FileUploadException)84 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)62 FileItem (org.apache.commons.fileupload.FileItem)54 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)48 IOException (java.io.IOException)34 HashMap (java.util.HashMap)27 ArrayList (java.util.ArrayList)21 List (java.util.List)20 File (java.io.File)19 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)18 FileItemStream (org.apache.commons.fileupload.FileItemStream)18 InputStream (java.io.InputStream)17 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)16 ServletException (javax.servlet.ServletException)12 Map (java.util.Map)9 Iterator (java.util.Iterator)8 ApplicationContext (org.springframework.context.ApplicationContext)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 ServletRequestContext (org.apache.commons.fileupload.servlet.ServletRequestContext)6