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:fsi_admin.JSmtpConn.java

@SuppressWarnings("rawtypes")
private boolean adjuntarArchivo(StringBuffer msj, BodyPart messagebodypart, MimeMultipart multipart,
        Vector archivos) {/*ww w.  j a  v a2  s  .  c o m*/
    if (!archivos.isEmpty()) {
        FileItem actual = null;

        try {
            for (int i = 0; i < archivos.size(); i++) {
                InputStream inputStream = null;
                try {
                    actual = (FileItem) archivos.elementAt(i);
                    inputStream = actual.getInputStream();
                    byte[] sourceBytes = IOUtils.toByteArray(inputStream);
                    String name = actual.getName();

                    messagebodypart = new MimeBodyPart();

                    ByteArrayDataSource rawData = new ByteArrayDataSource(sourceBytes);
                    DataHandler data = new DataHandler(rawData);

                    messagebodypart.setDataHandler(data);
                    messagebodypart.setFileName(name);
                    multipart.addBodyPart(messagebodypart);
                    ////////////////////////////////////////////////
                    /*
                    messagebodypart = new MimeBodyPart();
                    DataSource source = new FileDataSource(new File(actual.getName()));
                                
                    byte[] sourceBytes = actual.get();
                    OutputStream sourceOS = source.getOutputStream();
                    sourceOS.write(sourceBytes);
                               
                    messagebodypart.setDataHandler(new DataHandler(source));
                    messagebodypart.setFileName(actual.getName());
                    multipart.addBodyPart(messagebodypart);
                    */
                    ///////////////////////////////////////////////////////

                } finally {
                    if (inputStream != null)
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                }
            }
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            msj.append("Error de Mensajeria al cargar adjunto SMTP: " + e.getMessage());
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            msj.append("Error de Entrada/Salida al cargar adjunto SMTP: " + e.getMessage());
            return false;
        }

    } else
        return true;
}

From source file:com.znsx.cms.web.controller.LicenseController.java

@InterfaceDescription(logon = false, method = "Upload_License", cmd = "2151")
@RequestMapping("/upload_license.json")
public void uploadLicense(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // ?//from  w  ww. ja va  2  s .c om
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        // 
        ResourceVO resource = null;
        // ?Filedata?
        boolean uploadFlag = false;
        // ?
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            String fieldName = item.getFieldName();

            // ??sessionId
            if ("sessionId".equals(fieldName)) {
                String sessionId = item.getString();
                if (StringUtils.isBlank(sessionId)) {
                    throw new BusinessException(ErrorCode.PARAMETER_NOT_FOUND, "missing [sessionId]");
                }
                // ?sessionId
                resource = userManager.checkSession(sessionId);
            }
            // ?
            if ("Filedata".equals(fieldName)) {
                uploadFlag = true;
                InputStream in = item.getInputStream();
                License lic = LicenceUtil.parseLicense(in);

                licenseManager.checkLicense(lic);
                String id = licenseManager.upload(lic);

                // ??
                SysLog log = new SysLog();
                log.setResourceId(resource.getId());
                log.setResourceName(resource.getName());
                log.setResourceType(resource.getType());
                log.setTargetId(id.toString());
                log.setTargetName("License");
                log.setTargetType("License");
                log.setLogTime(System.currentTimeMillis());
                log.setOperationType("uploadLicense");
                log.setOperationName("License");
                log.setOperationCode("2151");
                log.setSuccessFlag(ErrorCode.SUCCESS);
                log.setCreateTime(System.currentTimeMillis());
                log.setOrganId(resource.getOrganId());
                sysLogManager.batchLog(log);
            }
        }
        if (!uploadFlag) {
            throw new BusinessException(ErrorCode.MISSING_PARAMETER_FILEDATA,
                    "Parameter [Filedata] not found !");
        }
    } else {
        throw new BusinessException(ErrorCode.NOT_MULTIPART_REQUEST, "Not multipart request !");
    }

    // 
    BaseDTO dto = new BaseDTO();
    dto.setCmd("2151");
    dto.setMethod("Upload_License");
    writePage(response, dto);
}

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   w w w.j  av  a 2 s .  com*/
    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:com.exedio.copernica.ItemForm.java

private void save() {
    final ArrayList<SetValue<?>> setValues = new ArrayList<SetValue<?>>();

    for (Iterator<?> i = getFields().iterator(); i.hasNext();) {
        final Field field = (Field) i.next();
        if (field.key instanceof DataField) {
            final DataField attribute = (DataField) field.key;
            final Media media = Media.get(attribute);
            final FileItem fileItem = getParameterFile(attribute.getName());

            if (fileItem != null) {
                String contentType = fileItem.getContentType();
                if (contentType != null) {
                    // fix for MSIE behaviour
                    if ("image/pjpeg".equals(contentType))
                        contentType = "image/jpeg";

                    try {
                        final InputStream data = fileItem.getInputStream();
                        media.set(item, data, contentType);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }/*from  w w w.  ja  v  a2 s  .  co  m*/
                }
            }
        }
        if (field.error == null) {
            final FunctionField<?> attribute = (FunctionField<?>) field.key;
            setValues.add(Cope.mapAndCast(attribute, field.getContent()));
        }
    }
    try {
        item.set(setValues.toArray(new SetValue<?>[setValues.size()]));
    } catch (MandatoryViolationException e) {
        final Field field = getFieldByKey(e.getFeature());
        field.error = "error.notnull:" + e.getFeature().toString();
    } catch (FinalViolationException e) {
        throw new RuntimeException(e);
    } catch (UniqueViolationException e) {
        final Field field = getFieldByKey(e.getFeature().getFields().iterator().next());
        field.error = e.getClass().getName();
    } catch (StringLengthViolationException e) {
        final Field field = getFieldByKey(e.getFeature());
        field.error = e.getClass().getName();
    }
}

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;//from  w  w w .j a v  a 2s.co 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:edu.umd.cs.submitServer.servlets.UploadTestSetup.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO sanity checks on the format of the test setup
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
    Connection conn = null;//from   ww  w.j a  v  a 2s. c om
    FileItem fileItem = null;
    boolean transactionSuccess = false;
    try {
        conn = getConnection();

        fileItem = multipartRequest.getFileItem();
        if (fileItem == null)
            throw new ServletException("fileItem is null; this is not good");

        Project project = (Project) request.getAttribute(PROJECT);
        // could be null
        String comment = multipartRequest.getOptionalCheckedParameter("comment");

        // get size in bytes
        long sizeInBytes = fileItem.getSize();
        if (sizeInBytes == 0) {
            throw new ServletException("Trying upload file of size 0");
        }

        // copy the fileItem into a byte array
        InputStream is = fileItem.getInputStream();
        ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) sizeInBytes);
        IO.copyStream(is, bytes);

        byte[] byteArray = bytes.toByteArray();

        FormatDescription desc = FormatIdentification.identify(byteArray);
        if (desc == null || !desc.getMimeType().equals("application/zip")) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "You MUST submit test-setups that are either zipped or jarred");
            return;
        }
        Submission canonicalSubmission = Submission
                .lookupMostRecent(project.getCanonicalStudentRegistrationPK(), project.getProjectPK(), conn);
        // start transaction here
        conn.setAutoCommit(false);
        conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        TestSetup.submit(byteArray, project, comment, conn);
        conn.commit();
        transactionSuccess = true;
        if (canonicalSubmission != null
                && canonicalSubmission.getBuildStatus() != Submission.BuildStatus.BROKEN) {
            WaitingBuildServer.offerSubmission(project, canonicalSubmission);
        }

        String redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK="
                + project.getProjectPK();
        response.sendRedirect(redirectUrl);

    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn);
        releaseConnection(conn);
        if (fileItem != null)
            fileItem.delete();
    }
}

From source file:com.themodernway.server.core.servlet.ContentUploadServlet.java

@Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    try {//  w w w. j  av a2s .  co  m
        final IFolderItem fold = getRoot();

        if (null == fold) {
            if (logger().isErrorEnabled()) {
                logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't find storage root.");
            }
            sendErrorCode(request, response, HttpServletResponse.SC_NOT_FOUND);

            return;
        }
        if (false == fold.isWritable()) {
            if (logger().isErrorEnabled()) {
                logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't write storage root.");
            }
            sendErrorCode(request, response, HttpServletResponse.SC_NOT_FOUND);

            return;
        }
        final String path = getPathNormalized(toTrimOrElse(request.getPathInfo(), FileUtils.SINGLE_SLASH));

        if (null == path) {
            if (logger().isErrorEnabled()) {
                logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't find path info.");
            }
            sendErrorCode(request, response, HttpServletResponse.SC_NOT_FOUND);

            return;
        }
        final ServletFileUpload upload = new ServletFileUpload(getDiskFileItemFactory());

        upload.setSizeMax(getFileSizeLimit());

        final List<FileItem> items = upload.parseRequest(request);

        for (final FileItem item : items) {
            if (false == item.isFormField()) {
                if (item.getSize() > fold.getFileSizeLimit()) {
                    item.delete();

                    if (logger().isErrorEnabled()) {
                        logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "File size exceeds limit.");
                    }
                    sendErrorCode(request, response, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);

                    return;
                }
                final IFileItem file = fold.file(FileUtils.concat(path, item.getName()));

                if (null != file) {
                    try (InputStream read = item.getInputStream()) {
                        fold.create(file.getPath(), read);
                    } catch (final IOException e) {
                        item.delete();

                        final IServletExceptionHandler handler = getServletExceptionHandler();

                        if ((null == handler) || (false == handler.handle(request, response,
                                getServletResponseErrorCodeManagerOrDefault(), e))) {
                            if (logger().isErrorEnabled()) {
                                logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't write file.", e);
                            }
                            sendErrorCode(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        }
                        return;
                    }
                } else {
                    item.delete();

                    if (logger().isErrorEnabled()) {
                        logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "Can't find file.");
                    }
                    sendErrorCode(request, response, HttpServletResponse.SC_NOT_FOUND);

                    return;
                }
            }
            item.delete();
        }
    } catch (IOException | FileUploadException e) {
        final IServletExceptionHandler handler = getServletExceptionHandler();

        if ((null == handler) || (false == handler.handle(request, response,
                getServletResponseErrorCodeManagerOrDefault(), e))) {
            if (logger().isErrorEnabled()) {
                logger().error(LoggingOps.THE_MODERN_WAY_MARKER, "captured overall exception for security.", e);
            }
            sendErrorCode(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:net.morphbank.mbsvc3.webservices.Uploader.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    MorphbankConfig.SYSTEM_LOGGER.info("starting post");
    MorphbankConfig.ensureWorkingConnection();
    this.resetVariables();
    MorphbankConfig.SYSTEM_LOGGER.info("<!-- persistence: " + MorphbankConfig.getPersistenceUnit() + " -->");
    MorphbankConfig.SYSTEM_LOGGER.info("<!-- filepath: " + folderPath + " -->");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    response.setContentType("text/html");

    try {//ww  w. ja va  2  s  .  c  o m
        //         String folderPath = "";
        // Process the uploaded items
        List<?> /* FileItem */ items = upload.parseRequest(request);
        Iterator<?> iter = items.iterator();
        boolean testPassed = false;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                processFormField(item);
            } else {
                if (testPassed = checkFilesBeforeUpload(item)) {
                    String fileName = item.getName();
                    //                  folderPath = saveTempFile(item);
                    saveTempFile(item);
                    InputStream stream = item.getInputStream();
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing file " + fileName);
                    processRequest(stream, out, fileName, folderPath);
                    MorphbankConfig.SYSTEM_LOGGER.info("Processing complete");

                }
            }
        }
        this.htmlPresentation(request, response, folderPath, testPassed);
        out.close();
    } catch (FileUploadException e) {
        e.printStackTrace();
        out.close();
    }
}

From source file:com.hightern.fckeditor.connector.Dispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * /*from w  w  w .j ava  2  s  .  c o m*/
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
@SuppressWarnings("unchecked")
UploadResponse doPost(final HttpServletRequest request) {
    Dispatcher.logger.debug("Entering Dispatcher#doPost");

    final Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isFileUploadEnabled(request)) {
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    } else if (!Command.isValidForPost(context.getCommandStr())) {
        uploadResponse = UploadResponse.getInvalidCommandError();
    } else if (!ResourceType.isValidType(context.getTypeStr())) {
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    } else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) {
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    } else {

        // call the Connector#fileUpload
        final ResourceType type = context.getDefaultResourceType();
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            final List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            final FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            final String fileName = FilenameUtils.getName(uplFile.getName());
            Dispatcher.logger.debug("Parameter NewFile: {}", fileName);
            // check the extension
            if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                    && !UtilsFile.isImage(uplFile.getInputStream())) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else {
                final String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                Dispatcher.logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                final String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(),
                        sanitizedFileName, uplFile.getInputStream());
                final String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request),
                        type, context.getCurrentFolderStr(), newFileName);

                if (sanitizedFileName.equals(newFileName)) {
                    uploadResponse = UploadResponse.getOK(fileUrl);
                } else {
                    uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                    Dispatcher.logger.debug("Parameter NewFile (renamed): {}", newFileName);
                }
            }

            uplFile.delete();
        } catch (final InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (final WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (final IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (final FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    Dispatcher.logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}

From source file:com.safetys.framework.fckeditor.connector.Dispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * //from  w  w w  .j a  va  2s.  c  o m
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
@SuppressWarnings("unchecked")
UploadResponse doPost(final HttpServletRequest request) {
    Dispatcher.logger.debug("Entering Dispatcher#doPost");

    final Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isFileUploadEnabled(request)) {
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    } else if (!Command.isValidForPost(context.getCommandStr())) {
        uploadResponse = UploadResponse.getInvalidCommandError();
    } else if (!ResourceType.isValidType(context.getTypeStr())) {
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    } else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) {
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    } else {

        // call the Connector#fileUpload
        final ResourceType type = context.getDefaultResourceType();
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            final List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            final FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            final String fileName = FilenameUtils.getName(uplFile.getName());
            Dispatcher.logger.debug("Parameter NewFile: {}", fileName);
            // check the extension
            if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                    && !UtilsFile.isImage(uplFile.getInputStream())) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else {
                final String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                Dispatcher.logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                final String newFileName = this.connector.fileUpload(type, context.getCurrentFolderStr(),
                        sanitizedFileName, uplFile.getInputStream());
                final String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request),
                        type, context.getCurrentFolderStr(), newFileName);

                if (sanitizedFileName.equals(newFileName)) {
                    uploadResponse = UploadResponse.getOK(fileUrl);
                } else {
                    uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                    Dispatcher.logger.debug("Parameter NewFile (renamed): {}", newFileName);
                }
            }

            uplFile.delete();
        } catch (final InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (final WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (final IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (final FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    Dispatcher.logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}