Search in sources :

Example 31 with FileItemStream

use of org.apache.commons.fileupload.FileItemStream in project opencast by opencast.

the class StaticFileRestService method postStaticFile.

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
@Path("")
@RestQuery(name = "postStaticFile", description = "Post a new static resource", bodyParameter = @RestParameter(description = "The static resource file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = { @RestResponse(description = "Returns the id of the uploaded static resource", responseCode = HttpServletResponse.SC_CREATED), @RestResponse(description = "No filename or file to upload found", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "The upload size is too big", responseCode = HttpServletResponse.SC_BAD_REQUEST) }, returnDescription = "")
public Response postStaticFile(@Context HttpServletRequest request) {
    if (maxUploadSize > 0 && request.getContentLength() > maxUploadSize) {
        logger.warn("Preventing upload of static file as its size {} is larger than the max size allowed {}", request.getContentLength(), maxUploadSize);
        return Response.status(Status.BAD_REQUEST).build();
    }
    ProgressInputStream inputStream = null;
    try {
        String filename = null;
        if (ServletFileUpload.isMultipartContent(request)) {
            boolean isDone = false;
            for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext(); ) {
                FileItemStream item = iter.next();
                if (item.isFormField()) {
                    continue;
                } else {
                    logger.debug("Processing file item");
                    filename = item.getName();
                    inputStream = new ProgressInputStream(item.openStream());
                    inputStream.addPropertyChangeListener(new PropertyChangeListener() {

                        @Override
                        public void propertyChange(PropertyChangeEvent evt) {
                            long totalNumBytesRead = (Long) evt.getNewValue();
                            if (totalNumBytesRead > maxUploadSize) {
                                logger.warn("Upload limit of {} bytes reached, returning a bad request.", maxUploadSize);
                                throw new WebApplicationException(Status.BAD_REQUEST);
                            }
                        }
                    });
                    isDone = true;
                }
                if (isDone)
                    break;
            }
        } else {
            logger.warn("Request is not multi part request, returning a bad request.");
            return Response.status(Status.BAD_REQUEST).build();
        }
        if (filename == null) {
            logger.warn("Request was missing the filename, returning a bad request.");
            return Response.status(Status.BAD_REQUEST).build();
        }
        if (inputStream == null) {
            logger.warn("Request was missing the file, returning a bad request.");
            return Response.status(Status.BAD_REQUEST).build();
        }
        String uuid = staticFileService.storeFile(filename, inputStream);
        try {
            return Response.created(getStaticFileURL(uuid)).entity(uuid).build();
        } catch (NotFoundException e) {
            logger.error("Previous stored file with uuid {} couldn't beren found: {}", uuid, ExceptionUtils.getStackTrace(e));
            return Response.serverError().build();
        }
    } catch (WebApplicationException e) {
        return e.getResponse();
    } catch (Exception e) {
        logger.error("Unable to store file because: {}", ExceptionUtils.getStackTrace(e));
        return Response.serverError().build();
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
Also used : PropertyChangeEvent(java.beans.PropertyChangeEvent) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) PropertyChangeListener(java.beans.PropertyChangeListener) WebApplicationException(javax.ws.rs.WebApplicationException) ProgressInputStream(org.opencastproject.util.ProgressInputStream) FileItemStream(org.apache.commons.fileupload.FileItemStream) NotFoundException(org.opencastproject.util.NotFoundException) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) ConfigurationException(org.osgi.service.cm.ConfigurationException) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 32 with FileItemStream

use of org.apache.commons.fileupload.FileItemStream in project opencast by opencast.

the class WorkingFileRepositoryRestEndpoint method restPutInCollection.

@POST
@Produces(MediaType.TEXT_HTML)
@Path(WorkingFileRepository.COLLECTION_PATH_PREFIX + "{collectionId}")
@RestQuery(name = "putInCollection", description = "Store a file in working repository under ./collectionId/filename", returnDescription = "The URL to access the stored file", pathParameters = { @RestParameter(name = "collectionId", description = "the colection identifier", isRequired = true, type = STRING) }, restParameters = { @RestParameter(name = "file", description = "the filename", isRequired = true, type = FILE) }, reponses = { @RestResponse(responseCode = SC_OK, description = "OK, file stored") })
public Response restPutInCollection(@PathParam("collectionId") String collectionId, @Context HttpServletRequest request) throws Exception {
    if (ServletFileUpload.isMultipartContent(request)) {
        for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext(); ) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                continue;
            }
            URI url = this.putInCollection(collectionId, item.getName(), item.openStream());
            return Response.ok(url.toString()).build();
        }
    }
    return Response.serverError().status(400).build();
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) URI(java.net.URI) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 33 with FileItemStream

use of org.apache.commons.fileupload.FileItemStream in project opencast by opencast.

the class WorkingFileRepositoryRestEndpoint method restPut.

@POST
@Produces(MediaType.TEXT_HTML)
@Path(WorkingFileRepository.MEDIAPACKAGE_PATH_PREFIX + "{mediaPackageID}/{mediaPackageElementID}")
@RestQuery(name = "put", description = "Store a file in working repository under ./mediaPackageID/mediaPackageElementID", returnDescription = "The URL to access the stored file", pathParameters = { @RestParameter(name = "mediaPackageID", description = "the mediapackage identifier", isRequired = true, type = STRING), @RestParameter(name = "mediaPackageElementID", description = "the mediapackage element identifier", isRequired = true, type = STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "OK, file stored") }, restParameters = { @RestParameter(name = "file", description = "the filename", isRequired = true, type = FILE) })
public Response restPut(@PathParam("mediaPackageID") String mediaPackageID, @PathParam("mediaPackageElementID") String mediaPackageElementID, @Context HttpServletRequest request) throws Exception {
    if (ServletFileUpload.isMultipartContent(request)) {
        for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext(); ) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                continue;
            }
            URI url = this.put(mediaPackageID, mediaPackageElementID, item.getName(), item.openStream());
            return Response.ok(url.toString()).build();
        }
    }
    return Response.serverError().status(400).build();
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) URI(java.net.URI) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 34 with FileItemStream

use of org.apache.commons.fileupload.FileItemStream in project pwm by pwm-project.

the class PwmRequest method readFileUploads.

public Map<String, FileUploadItem> readFileUploads(final int maxFileSize, final int maxItems) throws IOException, ServletException, PwmUnrecoverableException {
    final Map<String, FileUploadItem> returnObj = new LinkedHashMap<>();
    try {
        if (ServletFileUpload.isMultipartContent(this.getHttpServletRequest())) {
            final ServletFileUpload upload = new ServletFileUpload();
            final FileItemIterator iter = upload.getItemIterator(this.getHttpServletRequest());
            while (iter.hasNext() && returnObj.size() < maxItems) {
                final FileItemStream item = iter.next();
                final InputStream inputStream = item.openStream();
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                final long length = IOUtils.copyLarge(inputStream, baos, 0, maxFileSize + 1);
                if (length > maxFileSize) {
                    final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, "upload file size limit exceeded");
                    LOGGER.error(this, errorInformation);
                    respondWithError(errorInformation);
                    return Collections.emptyMap();
                }
                final byte[] outputFile = baos.toByteArray();
                final FileUploadItem fileUploadItem = new FileUploadItem(item.getName(), item.getContentType(), new ImmutableByteArray(outputFile));
                returnObj.put(item.getFieldName(), fileUploadItem);
            }
        }
    } catch (Exception e) {
        LOGGER.error("error reading file upload: " + e.getMessage());
    }
    return Collections.unmodifiableMap(returnObj);
}
Also used : InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletException(javax.servlet.ServletException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) ErrorInformation(password.pwm.error.ErrorInformation) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) ImmutableByteArray(password.pwm.http.bean.ImmutableByteArray) FileItemIterator(org.apache.commons.fileupload.FileItemIterator)

Example 35 with FileItemStream

use of org.apache.commons.fileupload.FileItemStream in project canvas_course_manager by tl-its-umich-edu.

the class CourseSupportProcess method getAttachmentContent.

private String getAttachmentContent() {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    StringBuilder csv = new StringBuilder();
    try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream inputStream = item.openStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String strLine;
            while ((strLine = br.readLine()) != null) {
                String csvContent = strLine.trim();
                csv.append(csvContent);
                csv.append(Utils.CONSTANT_LINE_FEED);
            }
            M_log.debug(csv);
        }
    } catch (FileUploadException | IOException e) {
        M_log.error("Error getting attachment content from the UI due to " + e.getMessage());
        return null;
    } catch (Exception e) {
        M_log.error("Error getting attachment content from the UI due to " + e.getMessage());
        return null;
    }
    return csv.toString();
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

FileItemStream (org.apache.commons.fileupload.FileItemStream)45 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)44 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)36 IOException (java.io.IOException)28 InputStream (java.io.InputStream)22 FileUploadException (org.apache.commons.fileupload.FileUploadException)19 NotFoundException (org.opencastproject.util.NotFoundException)7 HashMap (java.util.HashMap)6 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)6 IngestException (org.opencastproject.ingest.api.IngestException)6 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 GZIPInputStream (java.util.zip.GZIPInputStream)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 POST (javax.ws.rs.POST)5 Path (javax.ws.rs.Path)5 Produces (javax.ws.rs.Produces)5 WebApplicationException (javax.ws.rs.WebApplicationException)5 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)5 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)5