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

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

Introduction

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

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

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

Usage

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Get an uploaded file item.//w w w. j a v a 2 s . c o m
 * 
 * @param request
 * @param response
 * @throws IOException
 */
public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String parameter = request.getParameter(UConsts.PARAM_SHOW);
    FileItem item = findFileItem(getSessionFileItems(request), parameter);
    if (item != null) {
        logger.debug("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter
                + " returning: " + item.getContentType() + ", " + item.getName() + ", " + item.getSize()
                + " bytes");
        response.setContentType(item.getContentType());
        copyFromInputStreamToOutputStream(item.getInputStream(), response.getOutputStream());
    } else {
        logger.info("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter
                + " file isn't in session.");
        renderJSONResponse(request, response, XML_ERROR_ITEM_NOT_FOUND);
    }
}

From source file:com.ephesoft.gxt.admin.server.UploadImageFileServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String batchClassId = null;/*from w  w w  .j a va 2 s.  co m*/
    String docName = null;
    String fileName = null;
    String isAdvancedTableInfo = null;
    InputStream instream = null;
    OutputStream out = null;
    PrintWriter printWriter = resp.getWriter();
    if (ServletFileUpload.isMultipartContent(req)) {

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

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding(AdminConstants.CHARACTER_ENCODING_UTF8);
        List<FileItem> items;
        BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
        String uploadPath = null;
        try {
            items = upload.parseRequest(req);
            if (req.getParameter("isAdvancedTableInfo") != null) {
                isAdvancedTableInfo = req.getParameter("isAdvancedTableInfo").toString();
            }
            batchClassId = req.getParameter("batchClassId");
            docName = req.getParameter("docName");
            log.debug("Executing Servlet for batchClassId" + batchClassId + " docName: " + docName);
            String fileExtension = null;

            for (FileItem item : items) {

                // process only file upload - discard other form item types

                if (!item.isFormField()) {
                    fileName = item.getName();
                    log.debug("Executing Servlet for fileName from item:" + fileName);

                    // Checks for invalid characters present in uploaded filename.
                    fileName = checkFileNameForInvalidChars(fileName);
                    log.debug("FileName of File after removing invalid characters :" + fileName);
                    if (fileName != null) {
                        fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
                        fileExtension = fileName.substring(fileName.lastIndexOf(EXTENSION_CHAR) + 1);
                    }
                    instream = item.getInputStream();
                    printWriter.write(fileName);
                    printWriter.write(AdminConstants.PATTERN_DELIMITER);
                }
            }
            if (batchClassId == null || docName == null) {
                log.error(
                        "Error while loading image... Either batchClassId or doc type is null. Batch Class Id :: "
                                + batchClassId + " Doc Type :: " + docName);
                printWriter.write("Error while loading image... Either batchClassId or doc type is null.");
            } else {
                batchClassId = batchClassId.trim();
                docName = docName.trim();
                if (isAdvancedTableInfo != null
                        && isAdvancedTableInfo.equalsIgnoreCase(String.valueOf(Boolean.TRUE))) {
                    uploadPath = batchSchemaService.getAdvancedTestTableFolderPath(batchClassId, true);
                } else {
                    uploadPath = batchSchemaService.getTestAdvancedKvExtractionFolderPath(batchClassId, true);
                }
                uploadPath += File.separator + docName.trim() + File.separator;
                File uploadFolder = new File(uploadPath);

                if (!uploadFolder.exists()) {
                    try {
                        boolean tempPath = uploadFolder.mkdirs();
                        if (!tempPath) {
                            log.error(
                                    "Unable to create the folders in the temp directory specified. Change the path and permissions in dcma-batch.properties");
                            printWriter.write(
                                    "Unable to create the folders in the temp directory specified. Change the path and permissions in dcma-batch.properties");
                            return;
                        }
                    } catch (Exception e) {
                        log.error("Unable to create the folders in the temp directory.", e);
                        printWriter
                                .write("Unable to create the folders in the temp directory." + e.getMessage());
                        return;
                    }
                }
                uploadPath += File.separator + fileName;
                uploadPath = uploadPath.substring(0, uploadPath.lastIndexOf(EXTENSION_CHAR) + 1)
                        .concat(fileExtension.toLowerCase());
                out = new FileOutputStream(uploadPath);
                byte buf[] = new byte[1024];
                int len;
                while ((len = instream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                ImageProcessService imageProcessService = this.getSingleBeanOfType(ImageProcessService.class);
                int numberOfPages = 0;
                // deleteFiles(uploadFolder,fileName);
                if (fileExtension.equalsIgnoreCase(FileType.PDF.getExtension())) {
                    numberOfPages = PDFUtil.getPDFPageCount(uploadPath);

                    // code to convert pdf into tiff by checking the OS on which the application is running.
                    BatchInstanceThread batchInstanceThread = new BatchInstanceThread();
                    if (null != isAdvancedTableInfo
                            && isAdvancedTableInfo.equalsIgnoreCase(String.valueOf(Boolean.TRUE))
                            && numberOfPages != 1) {
                        printWriter.write(" MultiPage_error not supported for Advanced Table Extraction.");
                        log.error("MultiPage File not supported for Advanced Table Extraction.");
                    } else {

                        imageProcessService.convertPdfToSinglePagePNGOrTifUsingGSAPI(new File(uploadPath), "",
                                new File(uploadPath), batchInstanceThread, numberOfPages == 1, true, false,
                                batchClassId);
                        String outputParams = ApplicationConfigProperties.getApplicationConfigProperties()
                                .getProperty(GHOSTSCRIPT_PNG_PARAMS);
                        imageProcessService.convertPdfToSinglePagePNGOrTifUsingGSAPI(outputParams,
                                new File(uploadPath), "", new File(uploadPath), batchInstanceThread,
                                numberOfPages == 1, false, false);
                        batchInstanceThread.execute();
                    }
                } else if (fileExtension.equalsIgnoreCase(FileType.TIF.getExtension())
                        || fileExtension.equalsIgnoreCase(FileType.TIFF.getExtension())) {
                    numberOfPages = TIFFUtil.getTIFFPageCount(uploadPath);
                    if (null != isAdvancedTableInfo
                            && isAdvancedTableInfo.equalsIgnoreCase(String.valueOf(Boolean.TRUE))
                            && numberOfPages != 1) {
                        printWriter.write(" MultiPage_error File not supported for Advanced Table Extraction.");
                        log.error("MultiPage File not supported for Advanced Table Extraction.");
                    } else {
                        if (numberOfPages != 1) {
                            BatchInstanceThread batchInstanceThread = new BatchInstanceThread();
                            imageProcessService.convertPdfOrMultiPageTiffToPNGOrTifUsingIM("",
                                    new File(uploadPath), "", new File(uploadPath), batchInstanceThread, false,
                                    false);
                            imageProcessService.convertPdfOrMultiPageTiffToPNGOrTifUsingIM("",
                                    new File(uploadPath), "", new File(uploadPath), batchInstanceThread, false,
                                    true);
                            batchInstanceThread.execute();
                        } else {
                            imageProcessService.generatePNGForImage(new File(uploadPath));
                        }
                    }
                    log.info("Png file created successfully for file: " + uploadPath);
                }
            }
        } catch (FileUploadException e) {
            log.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
        } catch (DCMAException e) {
            log.error("Unable to generate PNG." + e, e);
            printWriter.write("Unable to generate PNG.Please try again.");
        } catch (DCMAApplicationException exception) {
            log.error("Unable to upload Multipage file." + exception, exception);
            printWriter.write("Unable to upload Multipage file.");
        } finally {
            if (out != null) {
                out.close();
            }
            if (instream != null) {
                instream.close();
            }
        }
        printWriter.write("file_seperator:" + File.separator);
        printWriter.write("|");
    }
}

From source file:com.look.UploadPostServlet.java

/***************************************************************************
 * Processes request data and saves into instance variables
 * @param request HttpServletRequest from client
 * @return True if successfully handled, false otherwise
 */// w  w  w .j a v a2 s .co m
private boolean handleRequest(HttpServletRequest request) {
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            boolean success = true;
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    // Process form file field (input type="file").
                    String fieldName = item.getFieldName();
                    String filename = item.getName();
                    if (filename.equals("")) {
                        //only update responseMessage if there isn't one yet
                        if (responseMessage.equals("")) {
                            responseMessage = "Please choose an image";
                        }
                        success = false;
                    }
                    String clientFileName = FilenameUtils.getName("TEMP_" + item.getName().replaceAll(" ", ""));

                    imageExtension = FilenameUtils.getExtension(clientFileName);
                    imageURL = clientFileName + "." + imageExtension;
                    fileContent = item.getInputStream();
                } else {
                    String fieldName = item.getFieldName();
                    String value = item.getString();
                    //only title is required
                    if (value.equals("") && (fieldName.equals("title"))) {
                        responseMessage = "Please enter a title";
                        success = false;
                    }
                    switch (fieldName) {
                    case TITLE_FIELD_NAME:
                        title = value;
                        break;
                    case DESCRIPTION_FIELD_NAME:
                        description = value;
                        break;
                    case TAGS_FIELD_NAME:
                        tags = value;
                        if (!tags.equals("")) {
                            tagList = new LinkedList<>(Arrays.asList(tags.split(" ")));
                            for (int i = 0; i < tagList.size(); i++) {
                                String tag = tagList.get(i);
                                if (tag.charAt(0) != '#') {
                                    if (responseMessage.equals("")) {
                                        responseMessage = "Tags must begin with #";
                                        success = false;
                                    }
                                    tagList.remove(i);
                                } else if (!StringUtils.isAlphanumeric(tag.substring(1))) {
                                    log.info(tag.substring(1));
                                    if (responseMessage.equals("")) {
                                        responseMessage = "Tags must only contain numbers and letters";
                                        success = false;
                                    }
                                    tagList.remove(i);
                                } else if (tag.length() > 20) {
                                    if (responseMessage.equals("")) {
                                        responseMessage = "Tags must be 20 characters or less";
                                        success = false;
                                    }
                                    tagList.remove(i);
                                } else {
                                    //tag is valid, remove the '#' for storage
                                    tagList.set(i, tag.substring(1));
                                }
                            }
                        }
                        //now have list of alphanumeric tags of 20 chars or less
                        break;
                    }
                }
            }
            if (!success) {
                return false;
            }
        } catch (FileUploadException | IOException ex) {
            Logger.getLogger(UploadPostServlet.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    } else {
        request.setAttribute("message", "File upload request not found");
        return false;
    }

    return true;
}

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

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    Session dbSession = null;//from   www . j  a  va2  s.c o m
    updateSessionManager(request);

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            MimeType mt = new MimeType();
            byte data[] = null;

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

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("mt_id")) {
                        mt.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("mt_name")) {
                        mt.setName(item.getString("UTF-8").toLowerCase());
                    } else if (item.getFieldName().equals("mt_extensions")) {
                        String[] extensions = item.getString("UTF-8").split(" ");
                        for (int i = 0; i < extensions.length; i++) {
                            mt.getExtensions().add(extensions[i].toLowerCase());
                        }
                    }
                } else {
                    is = item.getInputStream();
                    data = IOUtils.toByteArray(is);
                    mt.setImageMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    is.close();
                }
            }

            if (action.equals("create")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                long id = MimeTypeDAO.create(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_CREATE", Long.toString(id), null, mt.toString());
                list(userId, request, response);
            } else if (action.equals("edit")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                MimeTypeDAO.update(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_EDIT", Long.toString(mt.getId()), null,
                        mt.toString());
                list(userId, request, response);
            } else if (action.equals("delete")) {
                MimeTypeDAO.delete(mt.getId());
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_DELETE", Long.toString(mt.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("import")) {
                dbSession = HibernateUtil.getSessionFactory().openSession();
                importMimeTypes(userId, request, response, data, dbSession);
                list(userId, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } finally {
        HibernateUtil.close(dbSession);
    }
}

From source file:edu.ucla.loni.server.Upload.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {/*from w ww .j  a  v  a 2s. c  om*/
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(req);

            // Go through the items and get the root and package
            String rootPath = "";
            String packageName = "";

            for (FileItem item : items) {
                if (item.isFormField()) {
                    if (item.getFieldName().equals("root")) {
                        rootPath = item.getString();
                    } else if (item.getFieldName().equals("packageName")) {
                        packageName = item.getString();
                    }
                }
            }

            if (rootPath.equals("")) {
                res.getWriter().println("error :: Root directory has not been found.");
                return;
            }

            Directory root = Database.selectDirectory(rootPath);

            // Go through items and process urls and files
            for (FileItem item : items) {
                // Uploaded File
                if (item.isFormField() == false) {
                    String filename = item.getName();
                    ;
                    if (filename.equals("") == true)
                        continue;
                    try {
                        InputStream in = item.getInputStream();
                        //determine if it is pipefile or zipfile
                        //if it is pipefile => feed directly to writeFile function
                        //otherwise, uncompresse it first and then one-by-one feed to writeFile
                        if (filename.endsWith(".zip")) {
                            ZipInputStream zip = new ZipInputStream(in);
                            ZipEntry entry = zip.getNextEntry();
                            while (entry != null) {
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                if (baos != null) {
                                    byte[] arr = new byte[4096];
                                    int index = 0;
                                    while ((index = zip.read(arr, 0, 4096)) != -1) {
                                        baos.write(arr, 0, index);
                                    }
                                }
                                InputStream is = new ByteArrayInputStream(baos.toByteArray());
                                writeFile(root, packageName, is);
                                entry = zip.getNextEntry();
                            }
                            zip.close();
                        } else {
                            writeFile(root, packageName, in);

                        }

                        in.close();
                    } catch (Exception e) {
                        res.getWriter().println("Failed to upload " + filename + ". " + e.getMessage());
                    }
                }
                // URLs               
                if (item.isFormField() && item.getFieldName().equals("urls")
                        && item.getString().equals("") == false) {
                    String urlListAsStr = item.getString();
                    String[] urlList = urlListAsStr.split("\n");

                    for (String urlStr : urlList) {
                        try {
                            URL url = new URL(urlStr);
                            URLConnection urlc = url.openConnection();

                            InputStream in = urlc.getInputStream();

                            writeFile(root, packageName, in);

                            in.close();
                        } catch (Exception e) {
                            res.getWriter().println("Failed to upload " + urlStr);
                            return;
                        }
                    }
                }
            }
        } catch (Exception e) {
            res.getWriter().println("Error occurred while creating file. Error Message : " + e.getMessage());
        }
    }
}

From source file:com.lock.unlockInfo.servlet.SubmitUnlockImg.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpResponseModel responseModel = new HttpResponseModel();
    try {//from   w  w w.  j  a v  a 2 s  .  co  m
        boolean isMultipart = ServletFileUpload.isMultipartContent(request); // ???
        if (isMultipart) {
            Hashtable<String, String> htSubmitParam = new Hashtable<String, String>(); // ??
            List<String> fileList = new ArrayList<String>();// 

            // DiskFileItemFactory??
            // ????List
            // list???
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = iterator.next();
                if (item.isFormField()) {
                    // ?
                    String sFieldName = item.getFieldName();
                    String sFieldValue = item.getString("UTF-8");
                    htSubmitParam.put(sFieldName, sFieldValue);
                } else {
                    // ,???
                    String newFileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString()
                            + ".jpg";
                    File filePath = new File(
                            getServletConfig().getServletContext().getRealPath(Constants.File_Upload));
                    if (!filePath.exists()) {
                        filePath.mkdirs();
                    }
                    File file = new File(filePath, newFileName);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //?
                    BufferedInputStream bis = new BufferedInputStream(item.getInputStream());
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                    byte[] b = new byte[1024];
                    int length = 0;
                    while ((length = bis.read(b)) > 0) {
                        bos.write(b, 0, length);
                    }
                    bos.close();
                    bis.close();
                    //?url
                    String fileUrl = request.getRequestURL().toString();
                    fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("/")); //?URL
                    fileUrl = fileUrl + Constants.File_Upload + "/" + newFileName;
                    /**/
                    fileList.add(fileUrl);
                }
            }

            //
            String unlockInfoId = htSubmitParam.get("UnlockInfoId");
            String imgType = htSubmitParam.get("ImgType");
            String newFileUrl = fileList.get(0);

            UnlockInfoService unlockInfoService = (UnlockInfoService) context.getBean("unlockInfoService");
            UnlockInfo unlockInfo = unlockInfoService.queryByPK(Long.valueOf(unlockInfoId));
            if (imgType.equals("customerIdImg")) {
                unlockInfo.setCustomerIdImg(newFileUrl);
            } else if (imgType.equals("customerDrivingLicenseImg")) {
                unlockInfo.setCustomerDrivingLicenseImg(newFileUrl);
            } else if (imgType.equals("customerVehicleLicenseImg")) {
                unlockInfo.setCustomerVehicleLicenseImg(newFileUrl);
            } else if (imgType.equals("customerBusinessLicenseImg")) {
                unlockInfo.setCustomerBusinessLicenseImg(newFileUrl);
            } else if (imgType.equals("customerIntroductionLetterImg")) {
                unlockInfo.setCustomerIntroductionLetterImg(newFileUrl);
            } else if (imgType.equals("unlockWorkOrderImg")) {
                unlockInfo.setUnlockWorkOrderImg(newFileUrl);
            }
            /**/
            unlockInfoService.update(unlockInfo);
        }
    } catch (Exception e) {
        e.printStackTrace();
        responseModel.responseCode = "0";
        responseModel.responseMessage = e.toString();
    }
    /* ??? */
    response.setHeader("content-type", "text/json;charset=utf-8");
    response.getOutputStream().write(responseModel.toByteArray());
}

From source file:edu.umd.cs.submitServer.servlets.ImportProject.java

/**
 * The doPost method of the servlet. <br>
 * //from  w ww .ja v  a2  s. c o m
 * This method is called when a form has its tag value method equals to
 * post.
 * 
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection conn = null;
    FileItem fileItem = null;
    boolean transactionSuccess = false;
    try {
        conn = getConnection();

        // MultipartRequestFilter is required
        MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
        Course course = (Course) request.getAttribute(COURSE);
        StudentRegistration canonicalStudentRegistration = StudentRegistration.lookupByStudentRegistrationPK(
                multipartRequest.getIntParameter("canonicalStudentRegistrationPK", 0), conn);

        fileItem = multipartRequest.getFileItem();

        conn.setAutoCommit(false);
        /*
         * 20090608: changed TRANSACTION_READ_COMMITTED to
         * TRANSACTION_REPEATABLE_READ to make transaction compatible with
         * innodb in MySQL 5.1, which defines READ_COMMITTED as unsafe for
         * use with standard binary logging. For more information, see:
         * <http
         * ://dev.mysql.com/doc/refman/5.1/en/set-transaction.html#isolevel_read
         * -committed>
         */
        conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);

        Project project = Project.importProject(fileItem.getInputStream(), course, canonicalStudentRegistration,
                conn);

        conn.commit();
        transactionSuccess = true;

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

    } catch (ClassNotFoundException e) {
        throw new ServletException(e);
    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn);
    }
}

From source file:com.kk.dic.action.Upload.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    out = response.getWriter();//  w w w .  j a v a2s  .c  om
    Connection con;
    PreparedStatement pstm = null;
    String fname = "";
    String keyword = "";
    String cd = "";
    String a = (String) request.getSession().getAttribute("email");
    System.out.println("User Name : " + a);
    try {
        boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
        if (!isMultipartContent) {
            return;
        }
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        out.print("one");
        try {
            List<FileItem> fields = upload.parseRequest(request);
            Iterator<FileItem> it = fields.iterator();
            if (!it.hasNext()) {
                return;
            }

            while (it.hasNext()) {
                FileItem fileItem = it.next();
                if (fileItem.getFieldName().equals("name")) {
                    fname = fileItem.getString();
                    System.out.println("File Name" + fname);
                } else if (fileItem.getFieldName().equals("keyword")) {
                    keyword = fileItem.getString();
                    System.out.println("File Keyword" + keyword);
                } else {

                }
                boolean isFormField = fileItem.isFormField();
                if (isFormField) {
                } else {
                    out.print("one");
                    try {
                        con = Dbconnection.getConnection();
                        pstm = con.prepareStatement(
                                "insert into files (file, keyword, filetype, filename, CDate, owner, size, data, frank, file_key)values(?,?,?,?,?,?,?,?,?,?)");
                        out.println("getD " + fileItem.getName());
                        String str = getStringFromInputStream(fileItem.getInputStream());
                        // secretkey generating
                        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
                        keyGen.init(128);
                        SecretKey secretKey = keyGen.generateKey();
                        System.out.println("secret key:" + secretKey);
                        //converting secretkey to String
                        byte[] be = secretKey.getEncoded();//encoding secretkey
                        String skey = Base64.encode(be);
                        System.out.println("converted secretkey to string:" + skey);
                        String cipher = new encryption().encrypt(str, secretKey);
                        System.out.println(str);
                        //for get extension from given file
                        String b = fileItem.getName().substring(fileItem.getName().lastIndexOf('.'));
                        System.out.println("File Extension" + b);
                        pstm.setBinaryStream(1, fileItem.getInputStream());
                        pstm.setString(2, keyword);
                        pstm.setString(3, b);
                        pstm.setString(4, fname);
                        pstm.setDate(5, getCurrentDate());
                        pstm.setString(6, a);
                        pstm.setLong(7, fileItem.getSize());
                        pstm.setString(8, cipher);
                        pstm.setString(9, "0");
                        pstm.setString(10, skey);
                        /*Cloud Start*/
                        File f = new File("D:/" + fileItem.getName());
                        out.print("<br/>" + f.getName());
                        FileWriter fw = new FileWriter(f);
                        fw.write(cipher);
                        fw.close();
                        Ftpcon ftpcon = new Ftpcon();
                        ftpcon.upload(f, fname);
                        /*Cloud End*/
                        int i = pstm.executeUpdate();
                        if (i == 1) {
                            response.sendRedirect("upload.jsp?msg=success");
                        } else {
                            response.sendRedirect("upload.jsp?msgg=failed");
                        }
                        con.close();
                    } catch (Exception e) {
                        out.println(e);
                    }
                }
            }
        } catch (Exception ex) {
            out.print(ex);
            Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
        }
    } finally {
        out.close();
    }
}

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

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = "";
    String userId = request.getRemoteUser();
    updateSessionManager(request);/*w  w  w  .j  a  v  a  2  s  . co  m*/

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            String fileName = null;
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Set<String> properties = new HashSet<String>();
            Omr om = new Omr();

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

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("om_id")) {
                        om.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("om_name")) {
                        om.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("om_properties")) {
                        properties.add(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("om_active")) {
                        om.setActive(true);
                    }
                } else {
                    is = item.getInputStream();
                    fileName = item.getName();
                }
            }

            om.setProperties(properties);

            if (action.equals("create") || action.equals("edit")) {
                // Store locally template file to be used later
                if (is != null && is.available() > 0) { // Case update only name
                    byte[] data = IOUtils.toByteArray(is);
                    File tmp = FileUtils.createTempFile();
                    FileOutputStream fos = new FileOutputStream(tmp);
                    IOUtils.write(data, fos);
                    IOUtils.closeQuietly(fos);

                    // Store template file
                    om.setTemplateFileName(FilenameUtils.getName(fileName));
                    om.setTemplateFileMime(MimeTypeConfig.mimeTypes.getContentType(fileName));
                    om.setTemplateFilContent(data);
                    IOUtils.closeQuietly(is);

                    // Create training files
                    Map<String, File> trainingMap = OMRHelper.trainingTemplate(tmp);
                    File ascFile = trainingMap.get(OMRHelper.ASC_FILE);
                    File configFile = trainingMap.get(OMRHelper.CONFIG_FILE);

                    // Store asc file
                    om.setAscFileName(om.getTemplateFileName() + ".asc");
                    om.setAscFileMime(MimeTypeConfig.MIME_TEXT);
                    is = new FileInputStream(ascFile);
                    om.setAscFileContent(IOUtils.toByteArray(is));
                    IOUtils.closeQuietly(is);

                    // Store config file
                    om.setConfigFileName(om.getTemplateFileName() + ".config");
                    om.setConfigFileMime(MimeTypeConfig.MIME_TEXT);
                    is = new FileInputStream(configFile);
                    om.setConfigFileContent(IOUtils.toByteArray(is));
                    IOUtils.closeQuietly(is);

                    // Delete temporal files
                    FileUtils.deleteQuietly(tmp);
                    FileUtils.deleteQuietly(ascFile);
                    FileUtils.deleteQuietly(configFile);
                }

                if (action.equals("create")) {
                    long id = OmrDAO.getInstance().create(om);

                    // Activity log
                    UserActivity.log(userId, "ADMIN_OMR_CREATE", Long.toString(id), null, om.toString());
                } else if (action.equals("edit")) {
                    OmrDAO.getInstance().updateTemplate(om);
                    om = OmrDAO.getInstance().findByPk(om.getId());

                    // Activity log
                    UserActivity.log(userId, "ADMIN_OMR_EDIT", Long.toString(om.getId()), null, om.toString());
                }

                list(userId, request, response);
            } else if (action.equals("delete")) {
                OmrDAO.getInstance().delete(om.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_DELETE", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("editAsc")) {
                Omr omr = OmrDAO.getInstance().findByPk(om.getId());
                omr.setAscFileContent(IOUtils.toByteArray(is));
                omr.setAscFileMime(MimeTypeConfig.MIME_TEXT);
                omr.setAscFileName(omr.getTemplateFileName() + ".asc");
                OmrDAO.getInstance().update(omr);
                omr = OmrDAO.getInstance().findByPk(om.getId());
                IOUtils.closeQuietly(is);

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_EDIT_ASC", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("editFields")) {
                Omr omr = OmrDAO.getInstance().findByPk(om.getId());
                omr.setFieldsFileContent(IOUtils.toByteArray(is));
                omr.setFieldsFileMime(MimeTypeConfig.MIME_TEXT);
                omr.setFieldsFileName(omr.getTemplateFileName() + ".fields");
                OmrDAO.getInstance().update(omr);
                omr = OmrDAO.getInstance().findByPk(om.getId());
                IOUtils.closeQuietly(is);

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_EDIT_FIELDS", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("check")) {
                File form = FileUtils.createTempFile();
                OutputStream formFile = new FileOutputStream(form);
                formFile.write(IOUtils.toByteArray(is));
                IOUtils.closeQuietly(formFile);
                formFile.close();
                Map<String, String> results = OMRHelper.process(form, om.getId());
                FileUtils.deleteQuietly(form);
                IOUtils.closeQuietly(is);
                UserActivity.log(userId, "ADMIN_OMR_CHECK_TEMPLATE", Long.toString(om.getId()), null, null);
                results(userId, request, response, action, results, om.getId());
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:com.founder.fix.fixflow.service.impl.FlowCenterServiceImpl.java

public void saveUserIcon(Map<String, Object> filter) throws IOException {
    FileItem is = (FileItem) filter.get("icon");
    String userId = (String) filter.get("userId");
    String path = StringUtil.getString(filter.get("path"));
    String ex = FileUtil.getFileEx(is.getName());
    path = path + "/icon/" + userId + "." + ex;

    File newFile = new File(path);
    FileUtil.makeFile(newFile);/*from   w ww  . ja v a 2  s .co  m*/
    BufferedInputStream bis = null;
    FileOutputStream fos = null;
    int BUFFER_SIZE = 4096;
    byte[] buf = new byte[BUFFER_SIZE];
    int size = 0;
    InputStream file = is.getInputStream();
    bis = new BufferedInputStream(file);
    fos = new FileOutputStream(newFile);

    try {
        while ((size = bis.read(buf)) != -1) {
            fos.write(buf, 0, size);
            fos.flush();
        }
    } finally {
        file.close();
        fos.close();
        bis.close();
    }
}