Search in sources :

Example 41 with FileItemIterator

use of org.apache.commons.fileupload.FileItemIterator in project getting-started-java by GoogleCloudPlatform.

the class UpdateBookServlet method doPost.

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
    assert ServletFileUpload.isMultipartContent(req);
    CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");
    String newImageUrl = null;
    Map<String, String> params = new HashMap<String, String>();
    try {
        FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream()));
            } else if (!Strings.isNullOrEmpty(item.getName())) {
                newImageUrl = storageHelper.uploadFile(item, getServletContext().getInitParameter("bookshelf.bucket"));
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }
    try {
        Book oldBook = dao.readBook(Long.decode(params.get("id")));
        Book book = new Book.Builder().author(params.get("author")).description(params.get("description")).publishedDate(params.get("publishedDate")).title(params.get("title")).imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl).id(Long.decode(params.get("id"))).createdBy(oldBook.getCreatedBy()).createdById(oldBook.getCreatedById()).build();
        dao.updateBook(book);
        resp.sendRedirect("/read?id=" + params.get("id"));
    } catch (Exception e) {
        throw new ServletException("Error updating book", e);
    }
}
Also used : CloudStorageHelper(com.example.getstarted.util.CloudStorageHelper) HashMap(java.util.HashMap) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException) ServletException(javax.servlet.ServletException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) Book(com.example.getstarted.objects.Book) BookDao(com.example.getstarted.daos.BookDao) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 42 with FileItemIterator

use of org.apache.commons.fileupload.FileItemIterator in project BIMserver by opensourceBIM.

the class BulkUploadServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (request.getHeader("Origin") != null && !getBimServer().getServerSettingsCache().isHostAllowed(request.getHeader("Origin"))) {
        response.setStatus(403);
        return;
    }
    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    String token = (String) request.getSession().getAttribute("token");
    ObjectNode result = OBJECT_MAPPER.createObjectNode();
    response.setContentType("text/json");
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        long poid = -1;
        String comment = null;
        if (isMultipart) {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(request);
            InputStream in = null;
            String name = "";
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (item.isFormField()) {
                    if ("token".equals(item.getFieldName())) {
                        token = Streams.asString(item.openStream());
                    } else if ("poid".equals(item.getFieldName())) {
                        poid = Long.parseLong(Streams.asString(item.openStream()));
                    } else if ("comment".equals(item.getFieldName())) {
                        comment = Streams.asString(item.openStream());
                    }
                } else {
                    name = item.getName();
                    in = item.openStream();
                    if (poid != -1) {
                        ServiceInterface service = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                        SProject mainProject = service.getProjectByPoid(poid);
                        ZipInputStream zipInputStream = new ZipInputStream(in);
                        ZipEntry nextEntry = zipInputStream.getNextEntry();
                        while (nextEntry != null) {
                            String fullfilename = nextEntry.getName();
                            if (fullfilename.toLowerCase().endsWith(".ifc") || fullfilename.toLowerCase().endsWith("ifcxml") || fullfilename.toLowerCase().endsWith(".ifczip")) {
                                BufferedInputStream bufferedInputStream = new BufferedInputStream(zipInputStream);
                                byte[] initialBytes = ByteUtils.extractHead(bufferedInputStream, 4096);
                                InputStreamDataSource inputStreamDataSource = new InputStreamDataSource(new FakeClosingInputStream(bufferedInputStream));
                                inputStreamDataSource.setName(name);
                                DataHandler ifcFile = new DataHandler(inputStreamDataSource);
                                if (fullfilename.contains("/")) {
                                    String path = fullfilename.substring(0, fullfilename.lastIndexOf("/"));
                                    String filename = fullfilename.substring(fullfilename.lastIndexOf("/") + 1);
                                    String extension = filename.substring(filename.lastIndexOf(".") + 1);
                                    try {
                                        String schema = service.determineIfcVersion(initialBytes, fullfilename.toLowerCase().endsWith(".ifczip"));
                                        SProject project = getOrCreatePath(service, mainProject, mainProject, path, schema);
                                        SDeserializerPluginConfiguration deserializer = service.getSuggestedDeserializerForExtension(extension, project.getOid());
                                        service.checkinSync(project.getOid(), comment, deserializer.getOid(), -1L, filename, ifcFile, false);
                                    } catch (Exception e) {
                                        LOGGER.error(e.getMessage() + " (" + fullfilename + ")");
                                    }
                                }
                            } else {
                                if (!nextEntry.isDirectory()) {
                                    LOGGER.info("Unknown fileextenstion " + fullfilename);
                                }
                            }
                            nextEntry = zipInputStream.getNextEntry();
                        }
                    // DataHandler ifcFile = new DataHandler(inputStreamDataSource);
                    // 
                    // if (token != null) {
                    // if (topicId == -1) {
                    // long newTopicId = service.checkin(poid, comment, deserializerOid, -1L, name, ifcFile, merge, sync);
                    // result.put("topicId", newTopicId);
                    // } else {
                    // ServiceInterface service = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                    // long newTopicId = service.checkinInitiated(topicId, poid, comment, deserializerOid, -1L, name, ifcFile, merge, true);
                    // result.put("topicId", newTopicId);
                    // }
                    // }
                    } else {
                        result.put("exception", "No poid");
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("", e);
        // sendException(response, e);
        return;
    }
    response.getWriter().write(result.toString());
}
Also used : SDeserializerPluginConfiguration(org.bimserver.interfaces.objects.SDeserializerPluginConfiguration) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) FakeClosingInputStream(org.bimserver.utils.FakeClosingInputStream) BufferedInputStream(java.io.BufferedInputStream) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) ZipEntry(java.util.zip.ZipEntry) DataHandler(javax.activation.DataHandler) SProject(org.bimserver.interfaces.objects.SProject) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) UserException(org.bimserver.shared.exceptions.UserException) ServerException(org.bimserver.shared.exceptions.ServerException) InputStreamDataSource(org.bimserver.utils.InputStreamDataSource) ZipInputStream(java.util.zip.ZipInputStream) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) BufferedInputStream(java.io.BufferedInputStream) ServiceInterface(org.bimserver.shared.interfaces.ServiceInterface) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FakeClosingInputStream(org.bimserver.utils.FakeClosingInputStream)

Example 43 with FileItemIterator

use of org.apache.commons.fileupload.FileItemIterator in project BIMserver by opensourceBIM.

the class UploadServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (request.getHeader("Origin") != null && !getBimServer().getServerSettingsCache().isHostAllowed(request.getHeader("Origin"))) {
        response.setStatus(403);
        return;
    }
    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    String token = (String) request.getSession().getAttribute("token");
    ObjectNode result = OBJECT_MAPPER.createObjectNode();
    response.setContentType("text/json");
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        long poid = -1;
        String comment = null;
        if (isMultipart) {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(request);
            InputStream in = null;
            String name = "";
            long deserializerOid = -1;
            boolean merge = false;
            boolean sync = false;
            String compression = null;
            String action = null;
            long topicId = -1;
            try {
                while (iter.hasNext()) {
                    FileItemStream item = iter.next();
                    if (item.isFormField()) {
                        if ("action".equals(item.getFieldName())) {
                            action = Streams.asString(item.openStream());
                        } else if ("token".equals(item.getFieldName())) {
                            token = Streams.asString(item.openStream());
                        } else if ("poid".equals(item.getFieldName())) {
                            poid = Long.parseLong(Streams.asString(item.openStream()));
                        } else if ("comment".equals(item.getFieldName())) {
                            comment = Streams.asString(item.openStream());
                        } else if ("topicId".equals(item.getFieldName())) {
                            topicId = Long.parseLong(Streams.asString(item.openStream()));
                        } else if ("sync".equals(item.getFieldName())) {
                            sync = Streams.asString(item.openStream()).equals("true");
                        } else if ("merge".equals(item.getFieldName())) {
                            merge = Streams.asString(item.openStream()).equals("true");
                        } else if ("compression".equals(item.getFieldName())) {
                            compression = Streams.asString(item.openStream());
                        } else if ("deserializerOid".equals(item.getFieldName())) {
                            deserializerOid = Long.parseLong(Streams.asString(item.openStream()));
                        }
                    } else {
                        name = item.getName();
                        in = item.openStream();
                        if ("file".equals(action)) {
                            ServiceInterface serviceInterface = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                            SFile file = new SFile();
                            byte[] data = IOUtils.toByteArray(in);
                            file.setData(data);
                            file.setSize(data.length);
                            file.setFilename(name);
                            file.setMime(item.getContentType());
                            result.put("fileId", serviceInterface.uploadFile(file));
                        } else if (poid != -1) {
                            InputStream realStream = null;
                            if ("gzip".equals(compression)) {
                                realStream = new GZIPInputStream(in);
                            } else if ("deflate".equals(compression)) {
                                realStream = new InflaterInputStream(in);
                            } else {
                                realStream = in;
                            }
                            // When uploading in async mode, we want to return as soon as the whole stream has been read (that's not when the checkin process has finished!)
                            TriggerOnCloseInputStream triggerOnCloseInputStream = new TriggerOnCloseInputStream(realStream);
                            InputStreamDataSource inputStreamDataSource = new InputStreamDataSource(triggerOnCloseInputStream);
                            inputStreamDataSource.setName(name);
                            DataHandler ifcFile = new DataHandler(inputStreamDataSource);
                            if (token != null) {
                                ServiceInterface service = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL).get(ServiceInterface.class);
                                if (topicId == -1) {
                                    if (sync) {
                                        SLongCheckinActionState checkinSync = service.checkinSync(poid, comment, deserializerOid, -1L, name, ifcFile, merge);
                                        result = (ObjectNode) getBimServer().getJsonHandler().getJsonConverter().toJson(checkinSync);
                                        service.cleanupLongAction(checkinSync.getTopicId());
                                    } else {
                                        // When async, we can return as soon as all the data has been read
                                        long newTopicId = service.checkinAsync(poid, comment, deserializerOid, -1L, name, ifcFile, merge);
                                        triggerOnCloseInputStream.await();
                                        result.put("topicId", newTopicId);
                                    }
                                } else {
                                    if (sync) {
                                        SLongCheckinActionState checkinSync = service.checkinInitiatedSync(topicId, poid, comment, deserializerOid, -1L, name, ifcFile, merge);
                                        result = (ObjectNode) getBimServer().getJsonHandler().getJsonConverter().toJson(checkinSync);
                                        service.cleanupLongAction(checkinSync.getTopicId());
                                    } else {
                                        service.checkinInitiatedAsync(topicId, poid, comment, deserializerOid, -1L, name, ifcFile, merge);
                                        triggerOnCloseInputStream.await();
                                        result.put("topicId", topicId);
                                    }
                                }
                            }
                        } else {
                            result.put("exception", "No poid");
                        }
                    }
                }
            } catch (MalformedStreamException e) {
                LOGGER.error(comment);
                LOGGER.error("", e);
            }
        }
    } catch (Exception e) {
        LOGGER.error("", e);
        sendException(response, e);
        return;
    }
    response.getWriter().write(result.toString());
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) InputStream(java.io.InputStream) InflaterInputStream(java.util.zip.InflaterInputStream) SLongCheckinActionState(org.bimserver.interfaces.objects.SLongCheckinActionState) DataHandler(javax.activation.DataHandler) ServletException(javax.servlet.ServletException) MalformedStreamException(org.apache.commons.fileupload.MultipartStream.MalformedStreamException) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) InputStreamDataSource(org.bimserver.utils.InputStreamDataSource) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) ServiceInterface(org.bimserver.shared.interfaces.ServiceInterface) SFile(org.bimserver.interfaces.objects.SFile) MalformedStreamException(org.apache.commons.fileupload.MultipartStream.MalformedStreamException) FileItemIterator(org.apache.commons.fileupload.FileItemIterator)

Example 44 with FileItemIterator

use of org.apache.commons.fileupload.FileItemIterator in project flow by vaadin.

the class StreamReceiverHandler method handleMultipartFileUploadFromInputStream.

private boolean handleMultipartFileUploadFromInputStream(VaadinSession session, VaadinRequest request, StreamReceiver streamReceiver, StateNode owner) throws IOException {
    boolean success = true;
    long contentLength = getContentLength(request);
    // Parse the request
    FileItemIterator iter;
    try {
        iter = getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            boolean itemSuccess = handleStream(session, streamReceiver, owner, contentLength, item);
            success = success && itemSuccess;
        }
    } catch (FileUploadException e) {
        success = false;
        getLogger().warn("File upload failed.", e);
    }
    return success;
}
Also used : FileItemStream(org.apache.commons.fileupload.FileItemStream) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 45 with FileItemIterator

use of org.apache.commons.fileupload.FileItemIterator in project application by collectionspace.

the class WebUIRequest method initRequest.

private void initRequest(UIUmbrella umbrella, HttpServletRequest request, HttpServletResponse response, List<String> p) throws IOException, UIException {
    this.request = request;
    this.response = response;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();
        // Parse the request
        FileItemIterator iter;
        try {
            iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String name = item.getFieldName();
                // InputStream stream = item.openStream();
                if (item.isFormField()) {
                // System.out.println("Form field " + name + " with value "
                // + Streams.asString(stream) + " detected.");
                } else {
                    // System.out.println("File field " + name + " with file name "
                    // + item.getName() + " detected.");
                    // Process the input stream
                    contentHeaders = item.getHeaders();
                    uploadName = item.getName();
                    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                    if (item != null) {
                        InputStream stream = item.openStream();
                        IOUtils.copy(stream, byteOut);
                        new TeeInputStream(stream, byteOut);
                    }
                    bytebody = byteOut.toByteArray();
                }
            }
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        body = IOUtils.toString(request.getInputStream(), "UTF-8");
    }
    this.ppath = p.toArray(new String[0]);
    if (!(umbrella instanceof WebUIUmbrella))
        throw new UIException("Bad umbrella");
    this.umbrella = (WebUIUmbrella) umbrella;
    session = calculateSessionId();
}
Also used : FileItemStream(org.apache.commons.fileupload.FileItemStream) TeeInputStream(org.apache.commons.io.input.TeeInputStream) InputStream(java.io.InputStream) UIException(org.collectionspace.csp.api.ui.UIException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) TeeInputStream(org.apache.commons.io.input.TeeInputStream) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

FileItemIterator (org.apache.commons.fileupload.FileItemIterator)47 FileItemStream (org.apache.commons.fileupload.FileItemStream)45 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)37 IOException (java.io.IOException)29 InputStream (java.io.InputStream)21 FileUploadException (org.apache.commons.fileupload.FileUploadException)20 NotFoundException (org.opencastproject.util.NotFoundException)7 HashMap (java.util.HashMap)6 HttpServletRequest (javax.servlet.http.HttpServletRequest)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 POST (javax.ws.rs.POST)5 Path (javax.ws.rs.Path)5 Produces (javax.ws.rs.Produces)5 WebApplicationException (javax.ws.rs.WebApplicationException)5 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)5 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)5 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)5