Example usage for org.apache.commons.fileupload FileItem getInputStream

List of usage examples for org.apache.commons.fileupload FileItem getInputStream

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getInputStream.

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:com.zlfun.framework.misc.UploadUtils.java

public static byte[] getFileBytes(HttpServletRequest request) {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // ???//from w w w  .  j a va 2  s.  co m
    // ??
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // ??

    //  ?? 
    factory.setSizeThreshold(1024 * 1024);

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    try {
        // ?
        List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

        for (FileItem item : list) {
            // ????
            String name = item.getFieldName();

            // ? ??  ?
            if (item.isFormField()) {
                // ? ?????? 
                String value = new String(item.getString().getBytes("iso-8859-1"), "utf-8");

                request.setAttribute(name, value);
            } // ? ??  
            else {
                /**
                 * ?? ??
                 */
                // ???
                String value = item.getName();
                // ?
                // ????
                value = java.net.URLDecoder.decode(value, "UTF-8");
                int start = value.lastIndexOf("\\");
                // ?  ??1 ???
                String filename = value.substring(start + 1);

                InputStream in = item.getInputStream();
                int length = 0;
                byte[] buf = new byte[1024];
                System.out.println("??" + item.getSize());
                // in.read(buf) ?? buf 
                while ((length = in.read(buf)) != -1) {
                    //  buf  ??  ??
                    out.write(buf, 0, length);
                }

                try {

                    if (in != null) {
                        in.close();
                    }

                } catch (IOException ex) {
                    Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
                }
                return out.toByteArray();

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    return null;

}

From source file:com.sonicle.webtop.core.app.AbstractEnvironmentService.java

public void processUpload(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    ServletFileUpload upload = null;/* w w w . j av  a 2s  . c om*/
    WebTopSession.UploadedFile uploadedFile = null;
    HashMap<String, String> multipartParams = new HashMap<>();

    try {
        String service = ServletUtils.getStringParameter(request, "service", true);
        String cntx = ServletUtils.getStringParameter(request, "context", true);
        String tag = ServletUtils.getStringParameter(request, "tag", null);
        if (!ServletFileUpload.isMultipartContent(request))
            throw new Exception("No upload request");

        IServiceUploadStreamListener istream = getUploadStreamListener(cntx);
        if (istream != null) {
            try {
                MapItem data = new MapItem(); // Empty response data

                // Defines the upload object
                upload = new ServletFileUpload();
                FileItemIterator it = upload.getItemIterator(request);
                while (it.hasNext()) {
                    FileItemStream fis = it.next();
                    if (fis.isFormField()) {
                        InputStream is = null;
                        try {
                            is = fis.openStream();
                            String key = fis.getFieldName();
                            String value = IOUtils.toString(is, "UTF-8");
                            multipartParams.put(key, value);
                        } finally {
                            IOUtils.closeQuietly(is);
                        }
                    } else {
                        // Creates uploaded object
                        uploadedFile = new WebTopSession.UploadedFile(true, service, IdentifierUtils.getUUID(),
                                tag, fis.getName(), -1, findMediaType(fis));

                        // Fill response data
                        data.add("virtual", uploadedFile.isVirtual());
                        data.add("editable", isFileEditableInDocEditor(fis.getName()));

                        // Handle listener, its implementation can stop
                        // file upload throwing a UploadException.
                        InputStream is = null;
                        try {
                            getEnv().getSession().addUploadedFile(uploadedFile);
                            is = fis.openStream();
                            istream.onUpload(cntx, request, multipartParams, uploadedFile, is, data);
                        } finally {
                            IOUtils.closeQuietly(is);
                            getEnv().getSession().removeUploadedFile(uploadedFile, false);
                        }
                    }
                }
                new JsonResult(data).printTo(out);

            } catch (UploadException ex1) {
                new JsonResult(false, ex1.getMessage()).printTo(out);
            } catch (Exception ex1) {
                throw ex1;
            }

        } else {
            try {
                MapItem data = new MapItem(); // Empty response data
                IServiceUploadListener iupload = getUploadListener(cntx);

                // Defines the upload object
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //TODO: valutare come imporre i limiti
                //factory.setSizeThreshold(yourMaxMemorySize);
                //factory.setRepository(yourTempDirectory);
                upload = new ServletFileUpload(factory);
                List<FileItem> files = upload.parseRequest(request);

                // Plupload component (client-side) will upload multiple file 
                // each in its own request. So we can skip loop on files.
                Iterator it = files.iterator();
                while (it.hasNext()) {
                    FileItem fi = (FileItem) it.next();
                    if (fi.isFormField()) {
                        InputStream is = null;
                        try {
                            is = fi.getInputStream();
                            String key = fi.getFieldName();
                            String value = IOUtils.toString(is, "UTF-8");
                            multipartParams.put(key, value);
                        } finally {
                            IOUtils.closeQuietly(is);
                        }
                    } else {
                        // Writes content into a temp file
                        File file = WT.createTempFile(UPLOAD_TEMPFILE_PREFIX);
                        fi.write(file);

                        // Creates uploaded object
                        uploadedFile = new WebTopSession.UploadedFile(false, service, file.getName(), tag,
                                fi.getName(), fi.getSize(), findMediaType(fi));
                        getEnv().getSession().addUploadedFile(uploadedFile);

                        // Fill response data
                        data.add("virtual", uploadedFile.isVirtual());
                        data.add("uploadId", uploadedFile.getUploadId());
                        data.add("editable", isFileEditableInDocEditor(fi.getName()));

                        // Handle listener (if present), its implementation can stop
                        // file upload throwing a UploadException.
                        if (iupload != null) {
                            try {
                                iupload.onUpload(cntx, request, multipartParams, uploadedFile, data);
                            } catch (UploadException ex2) {
                                getEnv().getSession().removeUploadedFile(uploadedFile, true);
                                throw ex2;
                            }
                        }
                    }
                }
                new JsonResult(data).printTo(out);

            } catch (UploadException ex1) {
                new JsonResult(ex1).printTo(out);
            }
        }

    } catch (Exception ex) {
        WebTopApp.logger.error("Error uploading", ex);
        new JsonResult(ex).printTo(out);
    }
}

From source file:dk.dma.msinm.web.rest.LocationRestService.java

/**
 * Parse the KML file of the uploaded .kmz or .kml file and returns a JSON list of locations
 *
 * @param request the servlet request//w w  w. ja va 2  s .c  o m
 * @return the corresponding list of locations
 */
@POST
@javax.ws.rs.Path("/upload-kml")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json;charset=UTF-8")
public List<LocationVo> uploadKml(@Context HttpServletRequest request) throws FileUploadException, IOException {
    FileItemFactory factory = RepositoryService.newDiskFileItemFactory(servletContext);
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);

    for (FileItem item : items) {
        if (!item.isFormField()) {
            try {
                // .kml file
                if (item.getName().toLowerCase().endsWith(".kml")) {
                    // Parse the KML and return the corresponding locations
                    return parseKml(IOUtils.toString(item.getInputStream()));
                }

                // .kmz file
                else if (item.getName().toLowerCase().endsWith(".kmz")) {
                    // Parse the .kmz file as a zip file
                    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(item.getInputStream()));
                    ZipEntry entry;

                    // Look for the first zip entry with a .kml extension
                    while ((entry = zis.getNextEntry()) != null) {
                        if (!entry.getName().toLowerCase().endsWith(".kml")) {
                            continue;
                        }

                        log.info("Unzipping: " + entry.getName());
                        int size;
                        byte[] buffer = new byte[2048];
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                            bytes.write(buffer, 0, size);
                        }
                        bytes.flush();
                        zis.close();

                        // Parse the KML and return the corresponding locations
                        return parseKml(new String(bytes.toByteArray(), "UTF-8"));
                    }
                }

            } catch (Exception ex) {
                log.error("Error extracting kmz", ex);
            }
        }
    }

    // Return an empty result
    return new ArrayList<>();
}

From source file:fll.web.setup.CreateDB.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    String redirect;// www  .jav a  2 s. c  om
    final StringBuilder message = new StringBuilder();
    InitFilter.initDataSource(application);
    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    try {
        connection = datasource.getConnection();

        // must be first to ensure the form parameters are set
        UploadProcessor.processUpload(request);

        if (null != request.getAttribute("chooseDescription")) {
            final String description = (String) request.getAttribute("description");
            try {
                final URL descriptionURL = new URL(description);
                final Document document = ChallengeParser
                        .parse(new InputStreamReader(descriptionURL.openStream(), Utilities.DEFAULT_CHARSET));

                GenerateDB.generateDB(document, connection);

                application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT);

                message.append("<p id='success'><i>Successfully initialized database</i></p>");
                redirect = "/admin/createUsername.jsp";

            } catch (final MalformedURLException e) {
                throw new FLLInternalException("Could not parse URL from choosen description: " + description,
                        e);
            }
        } else if (null != request.getAttribute("reinitializeDatabase")) {
            // create a new empty database from an XML descriptor
            final FileItem xmlFileItem = (FileItem) request.getAttribute("xmldocument");

            if (null == xmlFileItem || xmlFileItem.getSize() < 1) {
                message.append("<p class='error'>XML description document not specified</p>");
                redirect = "/setup";
            } else {
                final Document document = ChallengeParser
                        .parse(new InputStreamReader(xmlFileItem.getInputStream(), Utilities.DEFAULT_CHARSET));

                GenerateDB.generateDB(document, connection);

                application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT);

                message.append("<p id='success'><i>Successfully initialized database</i></p>");
                redirect = "/admin/createUsername.jsp";
            }
        } else if (null != request.getAttribute("createdb")) {
            // import a database from a dump
            final FileItem dumpFileItem = (FileItem) request.getAttribute("dbdump");

            if (null == dumpFileItem || dumpFileItem.getSize() < 1) {
                message.append("<p class='error'>Database dump not specified</p>");
                redirect = "/setup";
            } else {

                ImportDB.loadFromDumpIntoNewDB(new ZipInputStream(dumpFileItem.getInputStream()), connection);

                // remove application variables that depend on the database
                application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT);

                message.append("<p id='success'><i>Successfully initialized database from dump</i></p>");
                redirect = "/admin/createUsername.jsp";
            }

        } else {
            message.append(
                    "<p class='error'>Unknown form state, expected form fields not seen: " + request + "</p>");
            redirect = "/setup";
        }

    } catch (final FileUploadException fue) {
        message.append("<p class='error'>Error handling the file upload: " + fue.getMessage() + "</p>");
        LOG.error(fue, fue);
        redirect = "/setup";
    } catch (final IOException ioe) {
        message.append("<p class='error'>Error reading challenge descriptor: " + ioe.getMessage() + "</p>");
        LOG.error(ioe, ioe);
        redirect = "/setup";
    } catch (final SQLException sqle) {
        message.append("<p class='error'>Error loading data into the database: " + sqle.getMessage() + "</p>");
        LOG.error(sqle, sqle);
        redirect = "/setup";
    } finally {
        SQLFunctions.close(connection);
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + redirect));

}

From source file:javaclasses.adminclass.java

public boolean insertnews(String t, String n, String d, String time, FileItem file) throws IOException {
    connect();/*  w w  w.  j av  a2s.  c o m*/
    try {
        String news;
        news = n.trim();
        st = con.prepareCall("{call prcInsertNews(?,?,?,?,?)}");
        st.setString(1, t);
        st.setString(2, news);
        st.setString(3, d);
        st.setString(4, time);
        st.setBinaryStream(5, file.getInputStream(), (int) file.getSize());
        if (st.execute() == false) {
            disconnect();
            return true;
        }
    } catch (SQLException e) {
        System.out.println(e);
    } catch (NumberFormatException e) {
        System.out.println(e);
    }
    return false;
}

From source file:com.ikon.servlet.admin.CheckTextExtractionServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);//from   ww w  .ja v  a  2s. co m
    InputStream is = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String docUuid = null;
            String repoPath = null;
            String text = null;
            String mimeType = null;
            String extractor = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("docUuid")) {
                        docUuid = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("repoPath")) {
                        repoPath = item.getString("UTF-8");
                    }
                } else {
                    is = item.getInputStream();
                    String name = FilenameUtils.getName(item.getName());
                    mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());

                    if (!name.isEmpty() && item.getSize() > 0) {
                        docUuid = null;
                        repoPath = null;
                    } else if (docUuid.isEmpty() && repoPath.isEmpty()) {
                        mimeType = null;
                    }
                }
            }

            if (docUuid != null && !docUuid.isEmpty()) {
                repoPath = OKMRepository.getInstance().getNodePath(null, docUuid);
            }

            if (repoPath != null && !repoPath.isEmpty()) {
                String name = PathUtils.getName(repoPath);
                mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());
                is = OKMDocument.getInstance().getContent(null, repoPath, false);
            }

            long begin = System.currentTimeMillis();

            if (is != null) {
                if (!MimeTypeConfig.MIME_UNDEFINED.equals(mimeType)) {
                    TextExtractor extClass = RegisteredExtractors.getTextExtractor(mimeType);

                    if (extClass != null) {
                        extractor = extClass.getClass().getCanonicalName();
                        text = RegisteredExtractors.getText(mimeType, null, is);
                    } else {
                        extractor = "Undefined text extractor";
                    }
                }
            }

            ServletContext sc = getServletContext();
            sc.setAttribute("docUuid", docUuid);
            sc.setAttribute("repoPath", repoPath);
            sc.setAttribute("text", text);
            sc.setAttribute("time", System.currentTimeMillis() - begin);
            sc.setAttribute("mimeType", mimeType);
            sc.setAttribute("extractor", extractor);
            sc.getRequestDispatcher("/admin/check_text_extraction.jsp").forward(request, response);
        }
    } catch (DatabaseException e) {
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        sendErrorRedirect(request, response, e);
    } catch (PathNotFoundException e) {
        sendErrorRedirect(request, response, e);
    } catch (AccessDeniedException e) {
        sendErrorRedirect(request, response, e);
    } catch (RepositoryException e) {
        sendErrorRedirect(request, response, e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:edu.um.umflix.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HashMap<String, String> mapValues = new HashMap<String, String>();
    List<Clip> clips = new ArrayList<Clip>();
    List<Byte[]> listData = new ArrayList<Byte[]>();
    int i = 0;/* w w w.  j ava 2  s.  com*/

    try {
        List<FileItem> items = getFileItems(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process normal fields here.

                mapValues.put(item.getFieldName(), item.getString());
                // w.print("Field name: " + item.getFieldName());
                // w.print("Field value: " + item.getString());
            } else {
                // Process <input type="file"> here.

                InputStream movie = item.getInputStream();
                byte[] bytes = IOUtils.toByteArray(movie);
                Byte[] clipBytes = ArrayUtils.toObject(bytes);
                Clip clip = new Clip(Long.valueOf(0), i);
                clips.add(i, clip);
                listData.add(i, clipBytes);
                i++;
                // w.print(movie);

            }
        }
    } catch (FileUploadException e) {
        log.error("Error uploading file, please try again.");
        request.setAttribute("error", "Error uploading file, please try again");
        request.setAttribute("token", mapValues.get("token"));
        request.getRequestDispatcher("/upload.jsp").forward(request, response);
    }
    //Sets duration of clip and saves clipdata
    for (int j = 0; j < clips.size(); j++) {
        int duration = timeToInt(mapValues.get("clipduration" + j));
        clips.get(j).setDuration(Long.valueOf(duration));
        ClipData clipData = new ClipData(listData.get(j), clips.get(j));

        try {
            vManager.uploadClip(mapValues.get("token"), new Role(Role.RoleType.MOVIE_PROVIDER.getRole()),
                    clipData);
            log.info("ClipData uploader!");
        } catch (InvalidTokenException e) {
            log.error("Unknown user, please try again.");
            request.setAttribute("error", "Unknown user, please try again.");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }

    }

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    Date endDate = null;
    Date startDate = null;
    Date premiereDate = null;
    try {
        endDate = formatter.parse(mapValues.get("endDate"));
        startDate = formatter.parse(mapValues.get("startDate"));
        premiereDate = formatter.parse(mapValues.get("premiere"));
    } catch (ParseException e) {
        log.error("Error parsing date");
        request.setAttribute("token", mapValues.get("token"));
        request.setAttribute("error", "Invalid date, please try again");
        request.getRequestDispatcher("/upload.jsp").forward(request, response);
        return;

    }

    License license = new License(false, Long.valueOf(0), mapValues.get("licenseDescription"), endDate,
            Long.valueOf(mapValues.get("maxViews")), Long.valueOf(1), startDate, mapValues.get("licenseName"));
    List<License> licenses = new ArrayList<License>();
    licenses.add(license);

    ArrayList<String> cast = new ArrayList<String>();
    cast.add(mapValues.get("actor"));
    Movie movie = new Movie(cast, clips, mapValues.get("director"), Long.valueOf(mapValues.get("duration")),
            false, mapValues.get("genre"), licenses, premiereDate, mapValues.get("title"));

    try {
        vManager.uploadMovie(mapValues.get("token"), new Role(Role.RoleType.MOVIE_PROVIDER.getRole()), movie);
        log.info("Movie uploaded!");
    } catch (InvalidTokenException e) {
        log.error("Unknown user, please try again.");
        request.setAttribute("error", "Unknown user, please try again.");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
        return;
    }
    request.setAttribute("message", "Movie uploaded successfully.");
    request.setAttribute("token", mapValues.get("token"));
    request.getRequestDispatcher("/upload.jsp").forward(request, response);
}

From source file:com.twinsoft.convertigo.engine.admin.services.roles.Import.java

@Override
protected void doUpload(HttpServletRequest request, Document document, FileItem item) throws Exception {
    String actionImport = request.getParameter("action-import");
    if (actionImport.equals("on")) {
        actionImport = request.getParameter("priority");
    }//  w  ww .ja v  a  2s  .co m

    if (!item.getName().endsWith(".json")) {
        ServiceUtils.addMessage(document, document.getDocumentElement(), "The import of the user file "
                + item.getName() + " has failed. The file is not valid (.json required).", "error", false);
    }

    //We save the users imported file
    try {
        byte[] data = IOUtils.toByteArray(item.getInputStream());
        String json = new String(data, "UTF-8");
        JSONObject users = new JSONObject(json);
        Engine.authenticatedSessionManager.updateUsers(users, actionImport);

    } catch (IOException ioe) {
        String message = "Unable to load the db file:\n" + ioe.getMessage();
        ServiceUtils.addMessage(document, document.getDocumentElement(), message, "message", false);
        throw new EngineException("Unable to load the db file", ioe);
    }

    String message = "The users file has been successfully imported.";
    Engine.logAdmin.info(message);
    ServiceUtils.addMessage(document, document.getDocumentElement(), message, "message", false);
}

From source file:com.openkm.servlet.admin.CheckTextExtractionServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);//from   w  w w .  j av a 2  s. co  m
    InputStream is = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String docUuid = null;
            String repoPath = null;
            String text = null;
            String error = null;
            String mimeType = null;
            String extractor = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("docUuid")) {
                        docUuid = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("repoPath")) {
                        repoPath = item.getString("UTF-8");
                    }
                } else {
                    is = item.getInputStream();
                    String name = FilenameUtils.getName(item.getName());
                    mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());

                    if (!name.isEmpty() && item.getSize() > 0) {
                        docUuid = null;
                        repoPath = null;
                    } else if (docUuid.isEmpty() && repoPath.isEmpty()) {
                        mimeType = null;
                    }
                }
            }

            if (docUuid != null && !docUuid.isEmpty()) {
                repoPath = OKMRepository.getInstance().getNodePath(null, docUuid);
            }

            if (repoPath != null && !repoPath.isEmpty()) {
                String name = PathUtils.getName(repoPath);
                mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());
                is = OKMDocument.getInstance().getContent(null, repoPath, false);
            }

            long begin = System.currentTimeMillis();

            if (is != null) {
                if (!MimeTypeConfig.MIME_UNDEFINED.equals(mimeType)) {
                    TextExtractor extClass = RegisteredExtractors.getTextExtractor(mimeType);

                    if (extClass != null) {
                        try {
                            extractor = extClass.getClass().getCanonicalName();
                            text = RegisteredExtractors.getText(mimeType, null, is);
                        } catch (Exception e) {
                            error = e.getMessage();
                        }
                    } else {
                        extractor = "Undefined text extractor";
                    }
                }
            }

            ServletContext sc = getServletContext();
            sc.setAttribute("docUuid", docUuid);
            sc.setAttribute("repoPath", repoPath);
            sc.setAttribute("text", text);
            sc.setAttribute("time", System.currentTimeMillis() - begin);
            sc.setAttribute("mimeType", mimeType);
            sc.setAttribute("error", error);
            sc.setAttribute("extractor", extractor);
            sc.getRequestDispatcher("/admin/check_text_extraction.jsp").forward(request, response);
        }
    } catch (DatabaseException e) {
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        sendErrorRedirect(request, response, e);
    } catch (PathNotFoundException e) {
        sendErrorRedirect(request, response, e);
    } catch (AccessDeniedException e) {
        sendErrorRedirect(request, response, e);
    } catch (RepositoryException e) {
        sendErrorRedirect(request, response, e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.jena.RDFUploadController.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
    if (!isAuthorizedToDisplayPage(req, response, SimplePermission.USE_ADVANCED_DATA_TOOLS_PAGES.ACTION)) {
        return;//w w w .ja  v a  2s . c o m
    }

    VitroRequest request = new VitroRequest(req);
    if (request.hasFileSizeException()) {
        forwardToFileUploadError(request.getFileSizeException().getLocalizedMessage(), req, response);
        return;
    }

    Map<String, List<FileItem>> fileStreams = request.getFiles();

    LoginStatusBean loginBean = LoginStatusBean.getBean(request);

    try {
        String modelName = req.getParameter("modelName");
        if (modelName != null) {
            loadRDF(request, response);
            return;
        }
    } catch (Exception e) {
        log.error(e, e);
        throw new RuntimeException(e);
    }

    boolean remove = "remove".equals(request.getParameter("mode"));
    String verb = remove ? "Removed" : "Added";

    String languageStr = request.getParameter("language");

    boolean makeClassgroups = ("true".equals(request.getParameter("makeClassgroups")));

    // add directly to the ABox model without reading first into 
    // a temporary in-memory model
    boolean directRead = ("directAddABox".equals(request.getParameter("mode")));

    String uploadDesc = "";

    OntModel uploadModel = (directRead) ? getABoxModel(getServletContext())
            : ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);

    /* ********************* GET RDF by URL ********************** */
    String RDFUrlStr = request.getParameter("rdfUrl");
    if (RDFUrlStr != null && RDFUrlStr.length() > 0) {
        try {
            uploadModel.enterCriticalSection(Lock.WRITE);
            try {
                uploadModel.read(RDFUrlStr, languageStr);
                // languageStr may be null and default would be RDF/XML
            } finally {
                uploadModel.leaveCriticalSection();
            }
            uploadDesc = verb + " RDF from " + RDFUrlStr;
        } catch (JenaException ex) {
            forwardToFileUploadError("Could not parse file to " + languageStr + ": " + ex.getMessage(), req,
                    response);
            return;
        } catch (Exception e) {
            forwardToFileUploadError("Could not load from URL: " + e.getMessage(), req, response);
            return;
        }
    } else {
        /* **************** upload RDF from POST ********************* */
        if (fileStreams.get("rdfStream") != null && fileStreams.get("rdfStream").size() > 0) {
            FileItem rdfStream = fileStreams.get("rdfStream").get(0);
            try {
                if (directRead) {
                    addUsingRDFService(rdfStream.getInputStream(), languageStr, request.getRDFService());
                } else {
                    uploadModel.enterCriticalSection(Lock.WRITE);
                    try {
                        uploadModel.read(rdfStream.getInputStream(), null, languageStr);
                    } finally {
                        uploadModel.leaveCriticalSection();
                    }
                }
                uploadDesc = verb + " RDF from file " + rdfStream.getName();
            } catch (IOException e) {
                forwardToFileUploadError("Could not read file: " + e.getLocalizedMessage(), req, response);
                return;
            } catch (JenaException ex) {
                forwardToFileUploadError("Could not parse file to " + languageStr + ": " + ex.getMessage(), req,
                        response);
                return;
            } catch (Exception e) {
                forwardToFileUploadError("Could not load from file: " + e.getMessage(), req, response);
                return;
            } finally {
                rdfStream.delete();
            }
        }
    }

    /* ********** Do the model changes *********** */
    if (!directRead && uploadModel != null) {

        uploadModel.loadImports();

        long tboxstmtCount = 0L;
        long aboxstmtCount = 0L;

        JenaModelUtils xutil = new JenaModelUtils();

        OntModel tboxModel = getTBoxModel();
        OntModel aboxModel = getABoxModel(getServletContext());
        OntModel tboxChangeModel = null;
        Model aboxChangeModel = null;
        OntModelSelector ontModelSelector = ModelAccess.on(getServletContext()).getOntModelSelector();

        if (tboxModel != null) {
            boolean AGGRESSIVE = true;
            tboxChangeModel = xutil.extractTBox(uploadModel, AGGRESSIVE);
            // aggressively seek all statements that are part of the TBox  
            tboxstmtCount = operateOnModel(request.getUnfilteredWebappDaoFactory(), tboxModel, tboxChangeModel,
                    ontModelSelector, remove, makeClassgroups, loginBean.getUserURI());
        }
        if (aboxModel != null) {
            aboxChangeModel = uploadModel.remove(tboxChangeModel);
            aboxstmtCount = operateOnModel(request.getUnfilteredWebappDaoFactory(), aboxModel, aboxChangeModel,
                    ontModelSelector, remove, makeClassgroups, loginBean.getUserURI());
        }
        request.setAttribute("uploadDesc",
                uploadDesc + ". " + verb + " " + (tboxstmtCount + aboxstmtCount) + "  statements.");
    } else {
        request.setAttribute("uploadDesc", "RDF upload successful.");
    }

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/specific/upload_rdf_result.jsp");
    request.setAttribute("title", "Ingest RDF Data");

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("Could not forward to view: " + e.getLocalizedMessage());
    }
}