Search in sources :

Example 21 with FileItemStream

use of org.apache.commons.fileupload.FileItemStream in project jeeshop by remibantos.

the class Medias method upload.

@POST
@Consumes("multipart/form-data")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ADMIN)
@Path("/{type}/{id}/{locale}/upload")
public void upload(@Context HttpServletRequest request, @NotNull @PathParam("type") String itemType, @NotNull @PathParam("id") Long itemId, @NotNull @PathParam("locale") String locale) {
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            java.nio.file.Path itemBasePath = getBasePath().resolve(itemType).resolve(itemId.toString()).resolve(locale);
            if (!Files.exists(itemBasePath))
                Files.createDirectories(itemBasePath);
            java.nio.file.Path filePath = itemBasePath.resolve(item.getName());
            Files.copy(item.openStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            LOG.info("File written to " + filePath);
        }
    } catch (IOException | FileUploadException e) {
        LOG.error("Could not handle upload of file with type: " + itemType + " and id: " + itemId, e);
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) WebApplicationException(org.rembx.jeeshop.rest.WebApplicationException) FileItemStream(org.apache.commons.fileupload.FileItemStream) IOException(java.io.IOException) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException) RolesAllowed(javax.annotation.security.RolesAllowed)

Example 22 with FileItemStream

use of org.apache.commons.fileupload.FileItemStream in project alfresco-remote-api by Alfresco.

the class PostSnapshotCommandProcessor method process.

/* (non-Javadoc)
     * @see org.alfresco.repo.web.scripts.transfer.CommandProcessor#process(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.WebScriptResponse)
     */
public int process(WebScriptRequest req, WebScriptResponse resp) {
    int result = Status.STATUS_OK;
    // Unwrap to a WebScriptServletRequest if we have one
    WebScriptServletRequest webScriptServletRequest = null;
    WebScriptRequest current = req;
    do {
        if (current instanceof WebScriptServletRequest) {
            webScriptServletRequest = (WebScriptServletRequest) current;
            current = null;
        } else if (current instanceof WrappingWebScriptRequest) {
            current = ((WrappingWebScriptRequest) req).getNext();
        } else {
            current = null;
        }
    } while (current != null);
    if (webScriptServletRequest == null) {
        logger.debug("bad request, not assignable from");
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }
    // We can't use the WebScriptRequest version of getParameter, since that may cause the content stream
    // to be parsed. Get hold of the raw HttpServletRequest and work with that.
    HttpServletRequest servletRequest = webScriptServletRequest.getHttpServletRequest();
    // Read the transfer id from the request
    String transferId = servletRequest.getParameter("transferId");
    if ((transferId == null) || !ServletFileUpload.isMultipartContent(servletRequest)) {
        logger.debug("bad request, not multipart");
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }
    try {
        logger.debug("about to upload manifest file");
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(servletRequest);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField() && TransferCommons.PART_NAME_MANIFEST.equals(item.getFieldName())) {
                logger.debug("got manifest file");
                receiver.saveSnapshot(transferId, item.openStream());
            }
        }
        logger.debug("success");
        resp.setStatus(Status.STATUS_OK);
        OutputStream out = resp.getOutputStream();
        resp.setContentType("text/xml");
        resp.setContentEncoding("utf-8");
        receiver.generateRequsite(transferId, out);
        out.close();
    } catch (Exception ex) {
        logger.debug("exception caught", ex);
        if (transferId != null) {
            logger.debug("ending transfer", ex);
            receiver.end(transferId);
        }
        if (ex instanceof TransferException) {
            throw (TransferException) ex;
        }
        throw new TransferException(MSG_CAUGHT_UNEXPECTED_EXCEPTION, ex);
    }
    return result;
}
Also used : WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) TransferException(org.alfresco.service.cmr.transfer.TransferException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) OutputStream(java.io.OutputStream) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) TransferException(org.alfresco.service.cmr.transfer.TransferException)

Example 23 with FileItemStream

use of org.apache.commons.fileupload.FileItemStream in project alfresco-remote-api by Alfresco.

the class PostContentCommandProcessor method process.

/*
     * (non-Javadoc)
     * 
     * @see org.alfresco.repo.web.scripts.transfer.CommandProcessor#process(org.alfresco.web.scripts.WebScriptRequest,
     * org.alfresco.web.scripts.WebScriptResponse)
     */
public int process(WebScriptRequest req, WebScriptResponse resp) {
    logger.debug("post content start");
    // Unwrap to a WebScriptServletRequest if we have one
    WebScriptServletRequest webScriptServletRequest = null;
    WebScriptRequest current = req;
    do {
        if (current instanceof WebScriptServletRequest) {
            webScriptServletRequest = (WebScriptServletRequest) current;
            current = null;
        } else if (current instanceof WrappingWebScriptRequest) {
            current = ((WrappingWebScriptRequest) req).getNext();
        } else {
            current = null;
        }
    } while (current != null);
    if (webScriptServletRequest == null) {
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }
    HttpServletRequest servletRequest = webScriptServletRequest.getHttpServletRequest();
    // Read the transfer id from the request
    String transferId = servletRequest.getParameter("transferId");
    if ((transferId == null) || !ServletFileUpload.isMultipartContent(servletRequest)) {
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(servletRequest);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (!item.isFormField()) {
                logger.debug("got content Mime Part : " + name);
                receiver.saveContent(transferId, item.getName(), item.openStream());
            }
        }
        // WebScriptServletRequest alfRequest = (WebScriptServletRequest)req;
        // String[] names = alfRequest.getParameterNames();
        // for(String name : names)
        // {
        // FormField item = alfRequest.getFileField(name);
        // 
        // if(item != null)
        // {
        // logger.debug("got content Mime Part : " + name);
        // receiver.saveContent(transferId, item.getName(), item.getInputStream());
        // }
        // else
        // {
        // //TODO - should this be an exception?
        // logger.debug("Unable to get content for Mime Part : " + name);
        // }
        // }
        logger.debug("success");
        resp.setStatus(Status.STATUS_OK);
    } catch (Exception ex) {
        logger.debug("exception caught", ex);
        if (transferId != null) {
            logger.debug("ending transfer", ex);
            receiver.end(transferId);
        }
        if (ex instanceof TransferException) {
            throw (TransferException) ex;
        }
        throw new TransferException(MSG_CAUGHT_UNEXPECTED_EXCEPTION, ex);
    }
    resp.setStatus(Status.STATUS_OK);
    return Status.STATUS_OK;
}
Also used : WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) TransferException(org.alfresco.service.cmr.transfer.TransferException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) TransferException(org.alfresco.service.cmr.transfer.TransferException)

Example 24 with FileItemStream

use of org.apache.commons.fileupload.FileItemStream in project zuul by Netflix.

the class FilterScriptManagerServlet method handlePostBody.

private String handlePostBody(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    org.apache.commons.fileupload.FileItemIterator it = null;
    try {
        it = upload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream stream = it.next();
            InputStream input = stream.openStream();
            // NOTE: we are going to pull the entire stream into memory
            // this will NOT work if we have huge scripts, but we expect these to be measured in KBs, not MBs or larger
            byte[] uploadedBytes = getBytesFromInputStream(input);
            input.close();
            if (uploadedBytes.length == 0) {
                setUsageError(400, "ERROR: Body contained no data.", response);
                return null;
            }
            return new String(uploadedBytes);
        }
    } catch (FileUploadException e) {
        throw new IOException(e.getMessage());
    }
    return null;
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) InputStream(java.io.InputStream) Matchers.anyString(org.mockito.Matchers.anyString) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 25 with FileItemStream

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

the class Upload method fileUploadWorker.

/**  Process an HTTP upload of RDF files (triples or quads)
     *   Stream straight into a graph or dataset -- unlike SPARQL_Upload the destination
     *   is known at the start of the multipart file body
     */
public static UploadDetails fileUploadWorker(HttpAction action, StreamRDF dest) {
    String base = ActionLib.wholeRequestURL(action.request);
    ServletFileUpload upload = new ServletFileUpload();
    //log.info(format("[%d] Upload: Field=%s ignored", action.id, fieldName)) ;
    // Overall counting.
    StreamRDFCounting countingDest = StreamRDFLib.count(dest);
    try {
        FileItemIterator iter = upload.getItemIterator(action.request);
        while (iter.hasNext()) {
            FileItemStream fileStream = iter.next();
            if (fileStream.isFormField()) {
                // Ignore?
                String fieldName = fileStream.getFieldName();
                InputStream stream = fileStream.openStream();
                String value = Streams.asString(stream, "UTF-8");
                ServletOps.errorBadRequest(format("Only files accepted in multipart file upload (got %s=%s)", fieldName, value));
            }
            //Ignore the field name.
            //String fieldName = fileStream.getFieldName();
            InputStream stream = fileStream.openStream();
            // Process the input stream
            String contentTypeHeader = fileStream.getContentType();
            ContentType ct = ContentType.create(contentTypeHeader);
            Lang lang = null;
            if (!matchContentType(ctTextPlain, ct))
                lang = RDFLanguages.contentTypeToLang(ct.getContentType());
            if (lang == null) {
                String name = fileStream.getName();
                if (name == null || name.equals(""))
                    ServletOps.errorBadRequest("No name for content - can't determine RDF syntax");
                lang = RDFLanguages.filenameToLang(name);
                if (name.endsWith(".gz"))
                    stream = new GZIPInputStream(stream);
            }
            if (lang == null)
                // Desperate.
                lang = RDFLanguages.RDFXML;
            String printfilename = fileStream.getName();
            if (printfilename == null || printfilename.equals(""))
                printfilename = "<none>";
            // Before
            // action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s", 
            //                        action.id, printfilename,  ct.getContentType(), ct.getCharset(), lang.getName())) ;
            // count just this step
            StreamRDFCounting countingDest2 = StreamRDFLib.count(countingDest);
            try {
                ActionSPARQL.parse(action, countingDest2, stream, lang, base);
                UploadDetails details1 = new UploadDetails(countingDest2.count(), countingDest2.countTriples(), countingDest2.countQuads());
                action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s : %s", action.id, printfilename, ct.getContentType(), ct.getCharset(), lang.getName(), details1.detailsStr()));
            } catch (RiotParseException ex) {
                action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s : %s", action.id, printfilename, ct.getContentType(), ct.getCharset(), lang.getName(), ex.getMessage()));
                throw ex;
            }
        }
    } catch (ActionErrorException ex) {
        throw ex;
    } catch (Exception ex) {
        ServletOps.errorOccurred(ex.getMessage());
    }
    // Overall results.
    UploadDetails details = new UploadDetails(countingDest.count(), countingDest.countTriples(), countingDest.countQuads());
    return details;
}
Also used : RiotParseException(org.apache.jena.riot.RiotParseException) WebContent.matchContentType(org.apache.jena.riot.WebContent.matchContentType) ContentType(org.apache.jena.atlas.web.ContentType) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) Lang(org.apache.jena.riot.Lang) IOException(java.io.IOException) RiotParseException(org.apache.jena.riot.RiotParseException) GZIPInputStream(java.util.zip.GZIPInputStream) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) StreamRDFCounting(org.apache.jena.riot.lang.StreamRDFCounting) FileItemIterator(org.apache.commons.fileupload.FileItemIterator)

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