Example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload.

Prototype

public ServletFileUpload(FileItemFactory fileItemFactory) 

Source Link

Document

Constructs an instance of this class which uses the supplied factory to create FileItem instances.

Usage

From source file:com.globalsight.everest.webapp.pagehandler.tm.management.RemoveTmHandler.java

/**
 * Invoke this PageHandler.//www  .  j av a  2  s  .c o  m
 * 
 * @param p_pageDescriptor
 *            the page desciptor
 * @param p_request
 *            the original request sent from the browser
 * @param p_response
 *            the original response object
 * @param p_context
 *            context the Servlet context
 */
public void invokePageHandler(WebPageDescriptor p_pageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, EnvoyServletException {
    HttpSession session = p_request.getSession();
    SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER);
    m_userId = (String) session.getAttribute(WebAppConstants.USER_NAME);
    String action = (String) p_request.getParameter(TM_ACTION);
    ResourceBundle bundle = PageHandler.getBundle(session);
    String errorMsg = null;
    StringBuilder errors = new StringBuilder();

    try {
        if (TM_ACTION_DELETE.equals(action) || TM_ACTION_DELETE_LANGUAGE.equals(action)
                || TM_ACTION_DELETE_TULISTING.equals(action)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024000);
            ServletFileUpload upload = new ServletFileUpload(factory);

            List<FileItem> fileItems = upload.parseRequest(p_request);

            String tmIdArray = (String) p_request.getParameter(TM_TM_ID);
            String language = null;
            File tmxFile = null;
            for (FileItem item : fileItems) {
                if (TM_TM_ID.equals(item.getFieldName())) {
                    tmIdArray = item.getString();
                } else if ("tmxFile".equals(item.getFieldName())) {
                    tmxFile = File.createTempFile("GSTUListing", null);
                    String fileName = item.getName();
                    item.write(tmxFile);
                } else if ("LanguageList".equals(item.getFieldName())) {
                    language = item.getString();
                }
            }

            String[] tmIds = tmIdArray.split(",");
            if (!TM_ACTION_DELETE_LANGUAGE.equals(action)) {
                language = null;
            }

            long tmId = -1l;
            errorMsg = removeTM(sessionMgr, tmIds, bundle, language, tmxFile);
        } else if (TM_ACTION_CANCEL.equals(action)) {
            TmRemover tmRemover = (TmRemover) sessionMgr.getAttribute(TM_REMOVER);
            tmRemover.cancelProcess();
        }
    } catch (Throwable ex) {
        logger.error("Tm removal error", ex);
        sessionMgr.setAttribute(TM_ERROR, ex.getMessage());
    }

    sessionMgr.setAttribute(TM_ERROR, errorMsg);

    super.invokePageHandler(p_pageDescriptor, p_request, p_response, p_context);
}

From source file:CourseFileManagementSystem.Upload.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.write("<html><head></head><body>");
    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();//  ww w  . j a  v  a  2  s.  c om
        return;
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String temp_folder = " ";
    try {
        String dataFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;
        temp_folder = dataFolder;
        File uploadD = new File(dataFolder);
        if (!uploadD.exists()) {
            uploadD.mkdir();
        }

        ResultList rs5 = DB.query(
                "SELECT * FROM course AS c, section AS s, year_semester AS ys, upload_checklist AS uc WHERE s.courseCode = c.courseCode "
                        + "AND s.semesterID = ys.semesterID AND s.courseID = c.courseID AND s.sectionID="
                        + sectionID);
        rs5.next();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // creates the directory if it does not exist
        String path1 = getServletContext().getContextPath() + "/" + DATA_DIRECTORY + "/";
        String temp_semester = rs5.getString("year") + "-" + rs5.getString("semester");
        String real_path = temp_folder + File.separator + temp_semester;
        File semester = new File(real_path);

        if (!semester.exists()) {
            semester.mkdir();
        }
        path1 += temp_semester + "/";
        real_path += File.separator;

        String temp_course = rs5.getString("courseCode") + rs5.getString("courseID") + "-"
                + rs5.getString("courseName");
        String real_path1 = real_path + temp_course;
        File course = new File(real_path1);
        if (!course.exists()) {
            course.mkdir();
        }
        path1 += temp_course + "/";
        real_path1 += File.separator;

        String temp_section = "section-" + rs5.getString("sectionNo");
        String real_path2 = real_path1 + temp_section;
        File section = new File(real_path2);
        if (!section.exists()) {
            section.mkdir();
        }
        path1 += temp_section + "/";
        real_path2 += File.separator;
        String sectionPath = path1;

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        if (items != null && items.size() > 0) {
            // iterates over form's fields
            for (FileItem item : items) {
                // processes only fields that are not form fields
                if (!item.isFormField() && !item.getName().equals("")) {
                    String DBPath = "";
                    System.out.println(item.getName() + " file is for " + item.getFieldName());
                    Scanner field_name = new Scanner(item.getFieldName()).useDelimiter("[^0-9]+");
                    int id = field_name.nextInt();
                    fileName = new File(item.getName()).getName();
                    ResultList rs = DB.query("SELECT * FROM upload_checklist WHERE checklistID =" + id);
                    rs.next();
                    String temp_file = rs.getString("label");
                    String real_path3 = real_path2 + temp_file;
                    File file_type = new File(real_path3);
                    if (!file_type.exists())
                        file_type.mkdir();
                    DBPath = sectionPath + "/" + temp_file + "/";
                    String context_path = DBPath;
                    real_path3 += File.separator;
                    String filePath = real_path3 + fileName;
                    DBPath += fileName;
                    String temp_DBPath = DBPath;

                    int count = 0;
                    File f = new File(filePath);
                    String temp_fileName = f.getName();
                    String fileNameWithOutExt = FilenameUtils.removeExtension(temp_fileName);
                    String extension = FilenameUtils.getExtension(filePath);
                    String newFullPath = filePath;
                    String tempFileName = " ";

                    while (f.exists()) {
                        ++count;
                        tempFileName = fileNameWithOutExt + "_(" + count + ").";
                        newFullPath = real_path3 + tempFileName + extension;
                        temp_DBPath = context_path + tempFileName + extension;
                        f = new File(newFullPath);
                    }

                    filePath = newFullPath;
                    System.out.println("New path: " + filePath);
                    DBPath = temp_DBPath;
                    String changeFilePath = filePath.replace('/', '\\');
                    String changeFilePath1 = changeFilePath.replace("Course_File_Management_System\\", "");
                    File uploadedFile = new File(changeFilePath1);
                    System.out.println("Change filepath = " + changeFilePath1);
                    System.out.println("DBPath = " + DBPath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                    String query = "INSERT INTO files (fileDirectory) values('" + DBPath + "')";
                    DB.update(query);
                    ResultList rs3 = DB.query("SELECT label FROM upload_checklist WHERE id=" + id);
                    while (rs3.next()) {
                        String label = rs3.getString("label");
                        out.write("<a href=\"Upload?fileName=" + changeFilePath1 + "\">Download " + label
                                + "</a>");
                        out.write("<br><br>");
                    }
                    ResultList rs4 = DB.query("SELECT * FROM files ORDER BY fileID DESC LIMIT 1");
                    rs4.next();
                    String query2 = "INSERT INTO lecturer_upload (fileID, sectionID, checklistID) values("
                            + rs4.getString("fileID") + ", " + sectionID + ", " + id + ")";
                    DB.update(query2);
                }
            }
        }
    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
    response.sendRedirect(request.getHeader("Referer"));
}

From source file:com.rubinefocus.admin.servlet.UploadAdminImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*ww w .ja v a  2 s. c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    File f = new File(this.getServletContext().getRealPath("admin/assets/images/adminPic"));
    String savePath = f.getPath();
    savePath = savePath.replace("%20", " ");
    savePath = savePath.replace("build", "");
    String fileName = "";

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // process only if its multipart content
    if (isMultipart) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            // Parse the request
            List<FileItem> multiparts = upload.parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    fileName = new File(item.getName()).getName();
                    File file = new File(savePath + "/" + fileName);

                    if (file.exists()) {
                        String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);
                        String ext = FilenameUtils.getExtension(fileName);
                        fileName = fileNameWithOutExt
                                + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date()) + "." + ext;
                        fileName = fileName.replace(" ", "");
                        fileName = fileName.replace("-", "");
                        fileName = fileName.replace(":", "");
                        item.write(new File(savePath + File.separator + fileName));

                    } else {
                        item.write(new File(savePath + File.separator + fileName));

                    }
                    Gson gson = new Gson();
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");

                    response.getWriter().write(gson.toJson(fileName));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:it.unisa.tirocinio.servlet.UploadInformationFilesServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w ww  .  ja  va 2s .c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, JSONException {

    try {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        out = response.getWriter();
        isMultipart = ServletFileUpload.isMultipartContent(request);
        StudentDBOperation getSerialNumberObj = new StudentDBOperation();
        ConcreteStudent aStudent = null;
        String serialNumber = null;
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        File fileToStore = null;
        String studentSubfolderPath = filePath;
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                if (fieldName.equals("cvfile")) {
                    fileToStore = new File(studentSubfolderPath + fileSeparator + "CV.pdf");
                } else if (fieldName.equals("examsfile")) {
                    fileToStore = new File(studentSubfolderPath + fileSeparator + "ES.pdf");
                }
                fi.write(fileToStore);
                // out.println("Uploaded Filename: " + fieldName + "<br>");
            } else {
                //out.println("It's not formfield");
                //out.println(fi.getString());
                aStudent = getSerialNumberObj.getSerialNumberbyFK_Account(Integer.parseInt(fi.getString()));
                serialNumber = reverseSerialNumber(aStudent.getPrimaryKey());
                studentSubfolderPath += fileSeparator + serialNumber;
                new File(studentSubfolderPath).mkdir();
            }
        }
        message.put("status", 1);
        out.print(message.toString());
    } catch (IOException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileUploadException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

From source file:ai.h2o.servicebuilder.MakePythonWarServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Long startTime = System.currentTimeMillis();
    File tmpDir = null;/*from  ww w. j a  v  a  2 s  .  co  m*/
    try {
        //create temp directory
        tmpDir = createTempDirectory("makeWar");
        logger.debug("tmpDir " + tmpDir);

        //  create output directories
        File webInfDir = new File(tmpDir.getPath(), "WEB-INF");
        if (!webInfDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF)");
        File outDir = new File(webInfDir.getPath(), "classes");
        if (!outDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/classes)");
        File libDir = new File(webInfDir.getPath(), "lib");
        if (!libDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/lib)");

        // get input files
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        String pojofile = null;
        String jarfile = null;
        String mojofile = null;
        String pythonfile = null;
        String predictorClassName = null;
        String pythonenvfile = null;
        ArrayList<String> pojos = new ArrayList<String>();
        ArrayList<String> rawfiles = new ArrayList<String>();
        for (FileItem i : items) {
            String field = i.getFieldName();
            String filename = i.getName();
            if (filename != null && filename.length() > 0) {
                if (field.equals("pojo")) { // pojo file name, use this or a mojo file
                    pojofile = filename;
                    pojos.add(pojofile);
                    predictorClassName = filename.replace(".java", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added pojo model {}", filename);
                }
                if (field.equals("jar")) {
                    jarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("python")) {
                    pythonfile = "WEB-INF" + File.separator + "python.py";
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(webInfDir, "python.py"));
                }
                if (field.equals("pythonextra")) { // optional extra files for python
                    pythonfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("mojo")) { // a raw model zip file, a mojo file (optional)
                    mojofile = filename;
                    rawfiles.add(mojofile);
                    predictorClassName = filename.replace(".zip", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added mojo model {}", filename);
                }
                if (field.equals("envfile")) { // optional conda environment file
                    pythonenvfile = filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.debug("using conda environment file {}", pythonenvfile);
                }
            }
        }
        logger.debug("jar {}  pojo {}  mojo {}  python {}  envfile {}", jarfile, pojofile, mojofile, pythonfile,
                pythonenvfile);
        if ((pojofile == null || jarfile == null) && (mojofile == null || jarfile == null))
            throw new Exception("need either pojo and genmodel jar, or raw file and genmodel jar ");

        if (pojofile != null) {
            // Compile the pojo
            runCmd(tmpDir,
                    Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                            "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfile, "-d", outDir.getPath(),
                            pojofile),
                    "Compilation of pojo failed");
            logger.info("compiled pojo {}", pojofile);
        }

        if (servletPath == null)
            throw new Exception("servletPath is null");

        FileUtils.copyDirectoryToDirectory(new File(servletPath, "extra"), tmpDir);
        String extraPath = "extra" + File.separator;
        String webInfPath = extraPath + File.separator + "WEB-INF" + File.separator;
        String srcPath = extraPath + "src" + File.separator;
        copyExtraFile(servletPath, extraPath, tmpDir, "pyindex.html", "index.html");
        copyExtraFile(servletPath, extraPath, tmpDir, "jquery.js", "jquery.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "predict.js", "predict.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "custom.css", "custom.css");
        copyExtraFile(servletPath, webInfPath, webInfDir, "web-pythonpredict.xml", "web.xml");
        FileUtils.copyDirectoryToDirectory(new File(servletPath, webInfPath + "lib"), webInfDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "bootstrap"), tmpDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "fonts"), tmpDir);

        // change the class name in the predictor template file to the predictor we have
        String modelCode = null;
        if (!pojos.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), pojos);
            modelCode = "null";
        } else if (!rawfiles.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), rawfiles);
            modelCode = "MojoModel.load(fileName)";
        }
        InstantiateJavaTemplateFile(tmpDir, modelCode, predictorClassName, "null",
                pythonenvfile == null ? "" : pythonenvfile, srcPath + "ServletUtil-TEMPLATE.java",
                "ServletUtil.java");

        copyExtraFile(servletPath, srcPath, tmpDir, "PredictPythonServlet.java", "PredictPythonServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "InfoServlet.java", "InfoServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "StatsServlet.java", "StatsServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "PingServlet.java", "PingServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Transform.java", "Transform.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Logging.java", "Logging.java");

        // compile extra
        runCmd(tmpDir,
                Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                        "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp",
                        "WEB-INF/lib/*:WEB-INF/classes:extra/WEB-INF/lib/*", "-d", outDir.getPath(),
                        "InfoServlet.java", "StatsServlet.java", "PredictPythonServlet.java",
                        "ServletUtil.java", "PingServlet.java", "Transform.java", "Logging.java"),
                "Compilation of servlet failed");

        // create the war jar file
        Collection<File> filesc = FileUtils.listFilesAndDirs(webInfDir, TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.add(new File(tmpDir, "index.html"));
        filesc.add(new File(tmpDir, "jquery.js"));
        filesc.add(new File(tmpDir, "predict.js"));
        filesc.add(new File(tmpDir, "custom.css"));
        filesc.add(new File(tmpDir, "modelnames.txt"));
        for (String m : pojos) {
            filesc.add(new File(tmpDir, m));
        }
        for (String m : rawfiles) {
            filesc.add(new File(tmpDir, m));
        }
        Collection<File> dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "bootstrap"),
                TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);
        dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "fonts"), TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);

        File[] files = filesc.toArray(new File[] {});
        if (files.length == 0)
            throw new Exception("Can't list compiler output files (out)");

        byte[] resjar = createJarArchiveByteArray(files, tmpDir.getPath() + File.separator);
        if (resjar == null)
            throw new Exception("Can't create war of compiler output");
        logger.info("war created from {} files, size {}", files.length, resjar.length);

        // send jar back
        ServletOutputStream sout = response.getOutputStream();
        response.setContentType("application/octet-stream");
        String outputFilename = predictorClassName.length() > 0 ? predictorClassName : "h2o-predictor";
        response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".war");
        response.setContentLength(resjar.length);
        sout.write(resjar);
        sout.close();
        response.setStatus(HttpServletResponse.SC_OK);

        Long elapsedMs = System.currentTimeMillis() - startTime;
        logger.info("Done python war creation in {}", elapsedMs);
    } catch (Exception e) {
        logger.error("doPost failed", e);
        // send the error message back
        String message = e.getMessage();
        if (message == null)
            message = "no message";
        logger.error(message);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(message);
        response.getWriter().write(Arrays.toString(e.getStackTrace()));
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        // if the temp directory is still there we delete it
        if (tmpDir != null && tmpDir.exists()) {
            try {
                FileUtils.deleteDirectory(tmpDir);
            } catch (IOException e) {
                logger.error("Can't delete tmp directory");
            }
        }
    }

}

From source file:isl.FIMS.servlet.imports.ImportVocabulary.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.initVars(request);
    String username = getUsername(request);

    Config conf = new Config("AdminVoc");

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    StringBuilder xml = new StringBuilder(
            this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request));
    String file = request.getParameter("file");

    if (ServletFileUpload.isMultipartContent(request)) {
        // configures some settings
        String filePath = this.export_import_Folder;
        java.util.Date date = new java.util.Date();
        Timestamp t = new Timestamp(date.getTime());
        String currentDir = filePath + t.toString().replaceAll(":", "");
        File saveDir = new File(currentDir);
        if (!saveDir.exists()) {
            saveDir.mkdir();/*from   w w  w. j  ava  2  s.  c om*/
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        factory.setRepository(saveDir);

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(REQUEST_SIZE);
        // constructs the directory path to store upload file
        String uploadPath = currentDir;

        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();
            // iterates over form's fields
            File storeFile = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    filePath = uploadPath + File.separator + fileName;
                    storeFile = new File(filePath);
                    // saves the file on disk
                    item.write(storeFile);
                }
            }
            ArrayList<String> content = Utils.readFile(storeFile);
            DMSConfig vocConf = new DMSConfig(this.DBURI, this.systemDbCollection + "Vocabulary/", this.DBuser,
                    this.DBpassword);
            Vocabulary voc = new Vocabulary(file, this.lang, vocConf);
            String[] terms = voc.termValues();

            for (int i = 0; i < content.size(); i++) {
                String addTerm = content.get(i);
                if (!Arrays.asList(terms).contains(addTerm)) {
                    voc.addTerm(addTerm);
                }

            }
            Utils.deleteDir(currentDir);
            response.sendRedirect("AdminVoc?action=list&file=" + file + "&menuId=AdminVoc");
        } catch (Exception ex) {
        }

    }

    xml.append("<FileName>").append(file).append("</FileName>\n");
    xml.append("<EntityType>").append("AdminVoc").append("</EntityType>\n");

    xml.append(this.xmlEnd());
    String xsl = conf.IMPORT_Vocabulary;
    try {
        XMLTransform xmlTrans = new XMLTransform(xml.toString());
        xmlTrans.transform(out, xsl);
    } catch (DMSException e) {
        e.printStackTrace();
    }
    out.close();
}

From source file:com.gae.ImageUpServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    //DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    //ReturnValue value = new ReturnValue();
    MemoryFileItemFactory factory = new MemoryFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    resp.setContentType("image/jpeg");
    ServletOutputStream out = resp.getOutputStream();
    try {/*from w w w  .  ja  va  2 s  . c  o  m*/
        List<FileItem> list = upload.parseRequest(req);
        //FileItem list = upload.parseRequest(req);
        for (FileItem item : list) {
            if (!(item.isFormField())) {
                filename = item.getName();
                if (filename != null && !"".equals(filename)) {
                    int size = (int) item.getSize();
                    byte[] data = new byte[size];
                    InputStream in = item.getInputStream();
                    in.read(data);
                    ImagesService imagesService = ImagesServiceFactory.getImagesService();
                    Image newImage = ImagesServiceFactory.makeImage(data);
                    byte[] newImageData = newImage.getImageData();

                    //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]);   
                    //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]);   

                    out.write(newImageData);
                    out.flush();

                    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
                    Key key = KeyFactory.createKey(kind, skey);
                    Blob blobImage = new Blob(newImageData);
                    DirectBeans_textjson dbeans = new DirectBeans_textjson();
                    /*  ?Date?     */
                    //Entity entity = dbeans.setentity("add", kind, true, key, id, val);

                    //ReturnValue value = dbeans.Called.setentity("add", kind, true, key, id, val);
                    //Entity entity = value.entity;
                    //DirectBeans.ReturnValue value = new DirectBeans.ReturnValue();
                    DirectBeans_textjson.entityVal eval = dbeans.setentity("add", kind, true, key, id, val);
                    Entity entity = eval.entity;

                    /*  ?Date                         */
                    //for(int i=0; i<id.length; i++ ){
                    //   if(id[i].equals("image")){
                    //      //filetitle = val[i];
                    //      //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), val[i]);   
                    //   }
                    //}                

                    entity.setProperty("image", blobImage);
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd:HHmmss");
                    sdf.setTimeZone(TimeZone.getTimeZone("JST"));
                    entity.setProperty("moddate", sdf.format(date));
                    //DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
                    ds.put(entity);
                    out.println("? KEY:" + key);
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:ai.h2o.servicebuilder.MakeWarServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Long startTime = System.currentTimeMillis();
    File tmpDir = null;/*  ww w. j a  va2  s  .c  o  m*/
    try {
        //create temp directory
        tmpDir = createTempDirectory("makeWar");
        logger.info("tmpDir {}", tmpDir);

        //  create output directories
        File webInfDir = new File(tmpDir.getPath(), "WEB-INF");
        if (!webInfDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF)");
        File outDir = new File(webInfDir.getPath(), "classes");
        if (!outDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/classes)");
        File libDir = new File(webInfDir.getPath(), "lib");
        if (!libDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/lib)");

        // get input files
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        String pojofile = null;
        String jarfile = null;
        String prejarfile = null;
        String deepwaterjarfile = null;
        String rawfile = null;
        String predictorClassName = null;
        String transformerClassName = null;
        ArrayList<String> pojos = new ArrayList<String>();
        ArrayList<String> rawfiles = new ArrayList<String>();
        for (FileItem i : items) {
            String field = i.getFieldName();
            String filename = i.getName();
            if (filename != null && filename.length() > 0) { // file fields
                if (field.equals("pojo")) {
                    pojofile = filename;
                    pojos.add(pojofile);
                    predictorClassName = filename.replace(".java", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added pojo model {}", filename);
                }
                if (field.equals("jar")) {
                    jarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("deepwater")) {
                    deepwaterjarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("prejar")) {
                    prejarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("mojo")) { // a raw model zip file, a mojo file
                    rawfile = filename;
                    rawfiles.add(rawfile);
                    predictorClassName = filename.replace(".zip", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added mojo model {}", filename);
                }
            } else { // form text field
                if (field.equals("preclass")) {
                    transformerClassName = i.getString();
                }
            }
        }
        logger.debug("genmodeljar {}  deepwaterjar {}  pojo {}  raw {}", jarfile, deepwaterjarfile, pojofile,
                rawfile);
        if ((pojofile == null || jarfile == null) && (rawfile == null || jarfile == null))
            throw new Exception("need either pojo and genmodel jar, or raw file and genmodel jar ");

        logger.info("prejar {}  preclass {}", prejarfile, transformerClassName);
        if (prejarfile != null && transformerClassName == null
                || prejarfile == null && transformerClassName != null)
            throw new Exception("need both prejar and preclass");

        if (pojofile != null) {
            // Compile the pojo
            String jarfiles = jarfile;
            if (deepwaterjarfile != null)
                jarfiles += ":" + deepwaterjarfile;
            runCmd(tmpDir,
                    Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                            "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfiles, "-d", outDir.getPath(),
                            pojofile),
                    "Compilation of pojo failed");
            logger.info("compiled pojo {}", pojofile);
        }

        if (servletPath == null)
            throw new Exception("servletPath is null");

        FileUtils.copyDirectoryToDirectory(new File(servletPath, "extra"), tmpDir);
        String extraPath = "extra" + File.separator;
        String webInfPath = extraPath + File.separator + "WEB-INF" + File.separator;
        String srcPath = extraPath + "src" + File.separator;

        if (transformerClassName == null)
            copyExtraFile(servletPath, extraPath, tmpDir, "index.html", "index.html");
        else
            copyExtraFile(servletPath, extraPath, tmpDir, "jarindex.html", "index.html");
        copyExtraFile(servletPath, extraPath, tmpDir, "jquery.js", "jquery.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "predict.js", "predict.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "custom.css", "custom.css");
        copyExtraFile(servletPath, webInfPath, webInfDir, "web-predict.xml", "web.xml");
        FileUtils.copyDirectoryToDirectory(new File(servletPath, webInfPath + "lib"), webInfDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "bootstrap"), tmpDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "fonts"), tmpDir);

        // change the class name in the predictor template file to the predictor we have
        String replaceTransform;
        if (transformerClassName == null)
            replaceTransform = "null";
        else
            replaceTransform = "new " + transformerClassName + "()";

        String modelCode = null;
        if (!pojos.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), pojos);
            modelCode = "null";
        } else if (!rawfiles.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), rawfiles);
            modelCode = "MojoModel.load(fileName)";
        }
        InstantiateJavaTemplateFile(tmpDir, modelCode, predictorClassName, replaceTransform, null,
                srcPath + "ServletUtil-TEMPLATE.java", "ServletUtil.java");

        copyExtraFile(servletPath, srcPath, tmpDir, "PredictServlet.java", "PredictServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "PredictBinaryServlet.java", "PredictBinaryServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "InfoServlet.java", "InfoServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "StatsServlet.java", "StatsServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "PingServlet.java", "PingServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Transform.java", "Transform.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Logging.java", "Logging.java");

        // compile extra
        List<String> cmd = Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source",
                JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp",
                "WEB-INF/lib/*:WEB-INF/classes:extra/WEB-INF/lib/*", "-d", outDir.getPath(),
                "PredictServlet.java", "PredictBinaryServlet.java", "InfoServlet.java", "StatsServlet.java",
                "ServletUtil.java", "PingServlet.java", "Transform.java", "Logging.java");
        runCmd(tmpDir, cmd, "Compilation of extra failed");

        // create the war jar file
        Collection<File> filesc = FileUtils.listFilesAndDirs(webInfDir, TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.add(new File(tmpDir, "index.html"));
        filesc.add(new File(tmpDir, "jquery.js"));
        filesc.add(new File(tmpDir, "predict.js"));
        filesc.add(new File(tmpDir, "custom.css"));
        filesc.add(new File(tmpDir, "modelnames.txt"));
        for (String m : pojos) {
            filesc.add(new File(tmpDir, m));
        }
        for (String m : rawfiles) {
            filesc.add(new File(tmpDir, m));
        }
        Collection<File> dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "bootstrap"),
                TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);
        dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "fonts"), TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);

        File[] files = filesc.toArray(new File[] {});
        if (files.length == 0)
            throw new Exception("Can't list compiler output files (out)");

        byte[] resjar = createJarArchiveByteArray(files, tmpDir.getPath() + File.separator);
        if (resjar == null)
            throw new Exception("Can't create war of compiler output");
        logger.info("war created from {} files, size {}", files.length, resjar.length);

        // send jar back
        ServletOutputStream sout = response.getOutputStream();
        response.setContentType("application/octet-stream");
        String outputFilename = predictorClassName.length() > 0 ? predictorClassName : "h2o-predictor";
        response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".war");
        response.setContentLength(resjar.length);
        sout.write(resjar);
        sout.close();
        response.setStatus(HttpServletResponse.SC_OK);

        Long elapsedMs = System.currentTimeMillis() - startTime;
        logger.info("Done war creation in {} ms", elapsedMs);
    } catch (Exception e) {
        logger.error("doPost failed ", e);
        // send the error message back
        String message = e.getMessage();
        if (message == null)
            message = "no message";
        logger.error(message);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(message);
        response.getWriter().write(Arrays.toString(e.getStackTrace()));
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        // if the temp directory is still there we delete it
        if (tmpDir != null && tmpDir.exists()) {
            try {
                FileUtils.deleteDirectory(tmpDir);
            } catch (IOException e) {
                logger.error("Can't delete tmp directory");
            }
        }
    }

}

From source file:UploadImageEdit.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w w  .  j  a  v  a2  s. c o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException, IOException_Exception {
    // Check that we have a file upload request
    PrintWriter writer = response.getWriter();
    String productName = "";
    String description = "";
    String price = "";
    String pictureName = "";
    String productId = "";

    Cookie cookie = null;
    Cookie[] cookies = null;
    String selectedCookie = "";
    // Get an array of Cookies associated with this domain
    cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            if (cookie.getName().equals("JuraganDiskon")) {
                selectedCookie = cookie.getValue();
            }
        }
    } else {
        writer.println("<h2>No cookies founds</h2>");
    }

    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here

        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // sets maximum size of upload file
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // this path is relative to application's directory
    String uploadPath = new File(new File(getServletContext().getRealPath("")).getParent()).getParent()
            + "/web/" + UPLOAD_DIRECTORY;

    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            int k = 0;
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    k++;
                    writer.println("if = " + k);

                    String fileName = new File(item.getName()).getName();
                    pictureName = fileName;
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    // saves the file on disk
                    item.write(storeFile);
                    request.setAttribute("message", "Upload has been done successfully!");
                    writer.println("pictureName = " + pictureName);
                } else {
                    k++;
                    writer.println("else = " + k);

                    // Get the field name
                    String fieldName = item.getName();
                    // Get the field value
                    String value = item.getString();
                    if (k == 0) {

                    } else if (k == 1) {
                        productId = value.trim();
                        writer.println("productId = " + productId);
                    } else if (k == 2) {
                        productName = value;
                        writer.println("productName = " + productName);
                    } else if (k == 3) {
                        description = value;
                        writer.println("description = " + description);
                    } else if (k == 4) {
                        price = value;
                        writer.println("price = " + price);
                    }

                }

            }
        }

    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
    String update = editTheProduct(Integer.valueOf(productId), productName, price, description, pictureName,
            selectedCookie);
    writer.println(update);

    //redirects client to message page
    getServletContext().getRequestDispatcher("/yourProduct.jsp").forward(request, response);

}

From source file:co.com.rempe.impresiones.negocio.servlets.SubirArchivosServlet.java

private Respuesta subirArchivo(HttpServletRequest request) throws FileUploadException, Exception {
    Respuesta respuesta = new Respuesta();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    // req es la HttpServletRequest que recibimos del formulario.
    // Los items obtenidos sern cada uno de los campos del formulario,
    // tanto campos normales como ficheros subidos.
    //        System.out.println("Items-------");
    List items = upload.parseRequest(request);
    System.out.println(items);//from  w  w  w .j  a v  a  2  s.c  om

    //        System.out.println("Request-----------------");
    System.out.println(request);
    // Se recorren todos los items, que son de tipo FileItem
    for (Object item : items) {
        FileItem uploaded = (FileItem) item;
        // Hay que comprobar si es un campo de formulario. Si no lo es, se guarda el fichero
        // subido donde nos interese
        //            System.out.println("Item---------------");
        System.out.println(uploaded.isFormField());
        if (!uploaded.isFormField()) {
            // No es campo de formulario, guardamos el fichero en algn sitio

            //El sisguiente bloque simplemente es para divorciar el nombre del archivo de las rutas
            //posibles que pueda traernos el getName() sobre el objeto de  la clase FileItem,
            //pues he descuvierto que el explorer especificamente es el nico que enva
            //la ruta adjuntada al nombre, por lo cual es importante corregirlo.
            String nombreArchivo = uploaded.getName();
            String cadena = nombreArchivo;
            System.out.println(cadena);
            while (cadena.contains("\\")) {
                cadena = cadena.replace("\\", "&");
            }
            //                System.out.println(cadena);
            String[] ruta = cadena.split("&");
            for (int i = 0; i < ruta.length; i++) {
                String string = ruta[i];
                System.out.println(string);
            }
            nombreArchivo = ruta[ruta.length - 1];
            //                System.out.println("Ruta archivo: " + nombreArchivo);
            //Fin correccin nombre.

            String nombreArchivoEscrito = System.currentTimeMillis() + "-" + nombreArchivo;
            String rutaEscritura = new File(request.getRealPath("archivos-subidos"), nombreArchivoEscrito)
                    .toString();
            File fichero = new File(rutaEscritura);

            ArchivosAdjuntos archivo = new ArchivosAdjuntos();
            archivo.setNombreArchivo(nombreArchivo);
            archivo.setRutaArchivo(rutaEscritura);
            archivo.setTamanioArchivo(uploaded.getSize());
            if (nombreArchivo.endsWith(".pdf") || nombreArchivo.endsWith(".png")
                    || nombreArchivo.endsWith(".jpg") || nombreArchivo.endsWith(".bmp")
                    || nombreArchivo.endsWith(".svg")) {
                //                    System.out.println("Archivo subido: " + uploaded.getName());
                uploaded.write(fichero);
                respuesta.setCodigo(1);
                respuesta.setDatos(archivo);
                respuesta.setMensaje("Se ha subido exitosamente el archivo: " + uploaded.getName());
            } else {
                respuesta.setCodigo(0);
                respuesta.setDatos(archivo);
                respuesta.setMensaje("El formato del archivo " + nombreArchivo + " es invalido!");
            }
        }
        //            else {
        //                // es un campo de formulario, podemos obtener clave y valor
        //                String key = uploaded.getFieldName();
        //                String valor = uploaded.getString();
        //                System.out.println("Archivo subido: " + key);
        //            }
    }
    return respuesta;
}