Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory.

Prototype

public DiskFileItemFactory() 

Source Link

Document

Constructs an unconfigured instance of this class.

Usage

From source file:com.founder.fix.fixflow.explorer.util.FileHandle.java

public static Iterator<FileItem> createFactory(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    try {//  www. j  a  v a2 s. c  o  m
        // ?? servletFileUplaod
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        // ?request??inputFileInput
        List<FileItem> fileItemList = servletFileUpload.parseRequest(request);
        return fileItemList.iterator();
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("?!");
    }
}

From source file:com.primeleaf.krystal.web.action.console.NewDocumentAction.java

@SuppressWarnings("rawtypes")
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);
    String classId = request.getParameter("classid") != null ? request.getParameter("classid") : "0";

    if (request.getMethod().equalsIgnoreCase("POST")) {
        try {/*w ww. ja  v a 2 s .com*/
            String userName = loggedInUser.getUserName();
            String sessionid = (String) session.getId();

            String tempFilePath = System.getProperty("java.io.tmpdir");

            if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) {
                tempFilePath += System.getProperty("file.separator");
            }
            tempFilePath += userName + "_" + sessionid;

            //variables
            String fileName = "", ext = "", comments = "";
            File file = null;
            // 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(HTTPConstants.CHARACTER_ENCODING);

            //Create a file upload progress listener
            FileUploadProgressListener listener = new FileUploadProgressListener();
            upload.setProgressListener(listener);
            //put the listener in session
            session.setAttribute("LISTENER", listener);
            session.setAttribute("UPLOAD_ERROR", null);
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0));

            DocumentClass documentClass = null;

            Hashtable<String, String> indexRecord = new Hashtable<String, String>();
            String name = "";
            String value = "";

            List listItems = upload.parseRequest((HttpServletRequest) request);

            Iterator iter = listItems.iterator();
            FileItem fileItem = null;
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();
                if (fileItem.isFormField()) {
                    name = fileItem.getFieldName();
                    value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING);
                    if (name.equals("classid")) {
                        classId = value;
                    }
                    if (name.equals("txtNote")) {
                        comments = value;
                    }
                } else {
                    try {
                        fileName = fileItem.getName();
                        file = new File(fileName);
                        fileName = file.getName();
                        ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                        file = new File(tempFilePath + "." + ext);
                        fileItem.write(file);
                    } catch (Exception ex) {
                        session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage());
                        return null;
                    }
                }
            } //if

            if (file.length() <= 0) { //code for checking minimum size of file
                session.setAttribute("UPLOAD_ERROR", "Zero length document");
                return null;
            }
            documentClass = DocumentClassDAO.getInstance().readDocumentClassById(Integer.parseInt(classId));
            if (documentClass == null) {
                session.setAttribute("UPLOAD_ERROR", "Invalid document class");
                return null;
            }
            AccessControlManager aclManager = new AccessControlManager();
            ACL acl = aclManager.getACL(documentClass, loggedInUser);

            if (!acl.canCreate()) {
                session.setAttribute("UPLOAD_ERROR", "Access Denied");
                return null;
            }

            long usedStorage = DocumentDAO.getInstance().documentSize();
            long availableStorage = ServerConstants.MAX_STORAGE - usedStorage;

            if (file.length() > availableStorage) {
                session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0));
                session.setAttribute("UPLOAD_ERROR", "Document upload failed. Storage limit exceeded.");
                return null;
            }
            String indexValue = "";
            String indexName = "";
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(50));

            for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) {
                indexName = indexDefinition.getIndexColumnName();
                Iterator iter1 = listItems.iterator();
                while (iter1.hasNext()) {
                    FileItem item1 = (FileItem) iter1.next();
                    if (item1.isFormField()) {
                        name = item1.getFieldName();
                        value = item1.getString(HTTPConstants.CHARACTER_ENCODING);
                        if (name.equals(indexName)) {
                            indexValue = value;
                            String errorMessage = "";
                            if (indexValue != null) {
                                if (indexDefinition.isMandatory()) {
                                    if (indexValue.trim().length() <= 0) {
                                        errorMessage = "Invalid input for "
                                                + indexDefinition.getIndexDisplayName();
                                        session.setAttribute("UPLOAD_ERROR", errorMessage);
                                        return null;
                                    }
                                }
                                if (IndexDefinition.INDEXTYPE_NUMBER
                                        .equalsIgnoreCase(indexDefinition.getIndexType())) {
                                    if (indexValue.trim().length() > 0) {
                                        if (!GenericValidator.matchRegexp(indexValue,
                                                HTTPConstants.NUMERIC_REGEXP)) {
                                            errorMessage = "Invalid input for "
                                                    + indexDefinition.getIndexDisplayName();
                                            session.setAttribute("UPLOAD_ERROR", errorMessage);
                                            return null;
                                        }
                                    }
                                } else if (IndexDefinition.INDEXTYPE_DATE
                                        .equalsIgnoreCase(indexDefinition.getIndexType())) {
                                    if (indexValue.trim().length() > 0) {
                                        if (!GenericValidator.isDate(indexValue, "yyyy-MM-dd", true)) {
                                            errorMessage = "Invalid input for "
                                                    + indexDefinition.getIndexDisplayName();
                                            session.setAttribute("UPLOAD_ERROR", errorMessage);
                                            return null;
                                        }
                                    }
                                }
                                if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking index field length
                                    errorMessage = "Document index size exceeded for " + "Index Name : "
                                            + indexDefinition.getIndexDisplayName() + " [ " + "Index Length : "
                                            + indexDefinition.getIndexMaxLength() + " , " + "Actual Length : "
                                            + indexValue.length() + " ]";
                                    session.setAttribute("UPLOAD_ERROR", errorMessage);
                                    return null;
                                }
                            }
                            indexRecord.put(indexName, indexValue);
                        }
                    }
                } //while iter
            } //while indexCfgList
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(70));

            DocumentRevision documentRevision = new DocumentRevision();
            documentRevision.setClassId(documentClass.getClassId());
            documentRevision.setDocumentId(0);
            documentRevision.setRevisionId("1.0");
            documentRevision.setDocumentFile(file);
            documentRevision.setUserName(loggedInUser.getUserName());
            documentRevision.setIndexRecord(indexRecord);
            documentRevision.setComments(comments);

            DocumentManager documentManager = new DocumentManager();
            documentManager.storeDocument(documentRevision, documentClass);

            //Log the entry to audit logs 
            AuditLogManager.log(new AuditLogRecord(documentRevision.getDocumentId(),
                    AuditLogRecord.OBJECT_DOCUMENT, AuditLogRecord.ACTION_CREATED, userName,
                    request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "", "Document created"));

            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(100));
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        return null;
    } else {
        try {
            ArrayList<DocumentClass> availableDocumentClasses = DocumentClassDAO.getInstance()
                    .readDocumentClasses(" ACTIVE = 'Y'");
            ArrayList<DocumentClass> documentClasses = new ArrayList<DocumentClass>();
            AccessControlManager aclManager = new AccessControlManager();
            for (DocumentClass documentClass : availableDocumentClasses) {
                ACL acl = aclManager.getACL(documentClass, loggedInUser);
                if (acl.canCreate()) {
                    documentClasses.add(documentClass);
                }
            }
            int documentClassId = 0;
            try {
                documentClassId = Integer.parseInt(classId);
            } catch (Exception ex) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
                return (new NewDocumentView(request, response));
            }
            if (documentClassId > 0) {
                DocumentClass selectedDocumentClass = DocumentClassDAO.getInstance()
                        .readDocumentClassById(documentClassId);
                request.setAttribute("DOCUMENTCLASS", selectedDocumentClass);
            }
            request.setAttribute("CLASSID", documentClassId);
            request.setAttribute("CLASSLIST", documentClasses);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return (new NewDocumentView(request, response));
}

From source file:at.ac.tuwien.dsg.cloudlyra.utils.Uploader.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w w w . j  a  v  a 2s  .  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 {
    InputStream dafFileContent = null;
    String dafName = "";
    String dafType = "";

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    dafName = new File(item.getName()).getName();
                    dafFileContent = item.getInputStream();

                } else {

                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();

                    if (fieldName.equals("type")) {
                        dafType = fieldValue;
                    }

                    // String log = "att name: " + fieldname + " - value: " + fieldvalue;
                    // Logger.getLogger(Uploader.class.getName()).log(Level.INFO, log);

                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    if (!dafName.equals("")) {

        DafStore dafStore = new DafStore();
        dafStore.insertDAF(dafName, dafType, dafFileContent);
        Logger.getLogger(Uploader.class.getName()).log(Level.INFO, dafName);
    }

    response.sendRedirect("daf.jsp");
}

From source file:UploadImageEdit.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*ww w .ja  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:com.mycom.products.mywebsite.backend.util.UploadHandler.java

@Override
@ResponseBody/*from  ww w.  j av  a 2  s .c  o m*/
@RequestMapping(method = RequestMethod.POST)
protected final void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();
        return;
    }
    JSONObject json = new JSONObject();
    SimpleDateFormat fmtYMD = new SimpleDateFormat("/" + "yyyyMMdd");
    Date today = new Date();
    String uploadPath = EntryPoint.getUploadPath() + "/";

    try {
        List<FileItem> items = uploadHandler.parseRequest(request);
        if (items != null && items.size() > 0) {
            String saveDir = "", fileCategory = "";
            for (FileItem item : items) {
                if (item.isFormField()) {
                    fileCategory = item.getString();
                }
            }
            saveDir = fileCategory + fmtYMD.format(today);
            // creates the directory if it does not exist
            File uploadDir = new File(uploadPath + saveDir);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            List<HashMap<String, String>> uploadFiles = new ArrayList<>();
            for (FileItem item : items) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    if (saveDir.length() == 0) {
                        json.put("messageCode", "V1001");
                        json.put("messageParams", "File upload type");
                        json.put("status", HttpStatus.BAD_REQUEST);
                        response.setContentType("application/json");
                        writer.write(json.toString());
                        writer.flush();
                    }
                    String originalFileName = "", saveFileName = "", format = "", fileSize = "";
                    // set the default format to png when it is profileImage
                    if (fileCategory.equals("profilePicture")) {
                        format = ".png";
                    }
                    // can't predict fileName and format would be included.
                    // For instance, blob won't be.
                    try {
                        originalFileName = item.getName().substring(0, item.getName().lastIndexOf("."));
                    } catch (Exception e) {
                        // Nothing to do. Skip
                    }
                    try {
                        format = item.getName().substring(item.getName().lastIndexOf("."),
                                item.getName().length());
                    } catch (Exception e) {
                        // Nothing to do. Skip
                    }

                    fileSize = getReadableFileSize(item.getSize());
                    UUID uuid = UUID.randomUUID();
                    saveFileName = new File(uuid.toString() + format).getName();
                    String filePath = uploadPath + saveDir + "/" + saveFileName;
                    if (fileCategory.equals("profilePicture")) {
                        saveProfileImage(item, filePath);
                    }
                    // Time to save in DB
                    LoggedUserBean loginUser;
                    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                    if (principal instanceof LoggedUserBean) {
                        loginUser = (LoggedUserBean) principal;
                    } else {
                        throw new SecurityException("Unauthorize File Upload process was attempted.");
                    }
                    StaticContentBean content = new StaticContentBean();
                    content.setFileName(originalFileName + format);
                    content.setFilePath(filePath);
                    content.setFileSize(fileSize);
                    content.setFileType(FileType.valueOf(getFileType(format)));
                    long lastInsertedId = contentService.insert(content, loginUser.getId());
                    // else .... other file types go here

                    HashMap<String, String> fileItem = new HashMap<>();
                    fileItem.put("contentId", "" + lastInsertedId);
                    uploadFiles.add(fileItem);

                }
            }
            json.put("uploadFiles", uploadFiles);
            json.put("status", HttpStatus.OK);
            response.setContentType("application/json");
            writer.write(json.toString());
            writer.flush();
        }
    } catch (FileUploadException e) {
        throw new RuntimeException("File upload Error !", e);
    } catch (Exception e) {
        throw new RuntimeException("File upload Error !", e);
    } finally {
        writer.close();
    }
}

From source file:com.eduAnalytics.servlet.FileUploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w ww  .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 {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String action = request.getParameter("action");
    boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
    if (!isMultipartContent) {
        System.out.println("You are not trying to upload<br/>");
        return;
    }
    System.out.println("You are trying to upload<br/>");

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List<FileItem> fields = upload.parseRequest(request);
        System.out.println("Number of fields: " + fields.size() + "<br/><br/>");
        Iterator<FileItem> it = fields.iterator();
        if (!it.hasNext()) {
            System.out.println("No fields found");
            return;
        }
        while (it.hasNext()) {
            FileItem fileItem = it.next();
            boolean isFormField = fileItem.isFormField();
            if (isFormField) {
                System.out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName()
                        + "<br/>STRING: " + fileItem.getString());
                System.out.println("</td>");
            } else {
                AdminDAO adminDAO = new AdminDAO();
                int successEntries = 0;
                if (action.equals("addDiscipline")) {
                    successEntries = adminDAO.uploadDiscipline(fileItem.getString());
                } else if (action.equals("addCourse")) {
                    successEntries = adminDAO.uploadCourse(fileItem.getString());
                }
                System.out.println("servlet entries " + successEntries);
                response.setContentType("text/plain");
                out.print(successEntries);
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:it.geosolutions.geofence.gui.server.UploadServlet.java

@SuppressWarnings("unchecked")
@Override/*from w  ww  . java 2  s .  c  om*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // process only multipart requests
    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);

        File uploadedFile = null;
        // Parse the request
        try {
            List<FileItem> items = upload.parseRequest(req);

            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField()) {
                    continue;
                }

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                uploadedFile = File.createTempFile(fileName, "");
                // if (uploadedFile.createNewFile()) {
                item.write(uploadedFile);
                resp.setStatus(HttpServletResponse.SC_CREATED);
                resp.flushBuffer();

                // uploadedFile.delete();
                // } else
                // throw new IOException(
                // "The file already exists in repository.");
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while creating the file : " + e.getMessage());
        }

        try {
            String wkt = calculateWKT(uploadedFile);
            resp.getWriter().print(wkt);
        } catch (Exception exc) {
            resp.getWriter().print("Error : " + exc.getMessage());
            logger.error("ERROR ********** " + exc);
        }

        uploadedFile.delete();

    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:gov.nist.appvet.tool.synchtest.Service.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Get received HTTP parameters and file upload
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List items = null;// w w w .java 2 s .  c  om
    FileItem fileItem = null;

    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    // Get received items
    Iterator iter = items.iterator();
    FileItem item = null;

    while (iter.hasNext()) {
        item = (FileItem) iter.next();
        if (item.isFormField()) {
            // Get HTML form parameters
            String incomingParameter = item.getFieldName();
            String incomingValue = item.getString();
            if (incomingParameter.equals("appid")) {
                appId = incomingValue;
                log.info("Received app ID: " + appId);
            }
            /** CHANGE (START): Get other tools-specific form parameters **/
            /** CHANGE (END): Get other tools-specific form parameters **/
        } else {
            // item should now hold the received file
            if (item != null) {
                fileItem = item;
                log.info("Received file: " + fileItem.getName());
            }
        }
    }

    if (appId == null) {
        // All tool services require an AppVet app ID
        log.error("Received null app ID. Returning HTTP 400");
        HttpUtil.sendHttp400(response, "No app ID specified");
        return;
    }

    if (fileItem != null) {
        // Get app file
        fileName = FileUtil.getFileName(fileItem.getName());
        if (!fileName.endsWith(".apk")) {
            log.error("Received invalid app file. Returning HTTP 400");
            HttpUtil.sendHttp400(response, "Invalid app file: " + fileItem.getName());
            return;
        }
        // Create app directory
        appDirPath = Properties.TEMP_DIR + "/" + appId;
        File appDir = new File(appDirPath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        // Create report path
        reportFilePath = Properties.TEMP_DIR + "/" + appId + "/" + reportName + "."
                + Properties.reportFormat.toLowerCase();

        appFilePath = Properties.TEMP_DIR + "/" + appId + "/" + fileName;
        log.debug("App file path: " + appFilePath);
        if (!FileUtil.saveFileUpload(fileItem, appFilePath)) {
            log.error("Could not save file. Returning HTTP 500");
            HttpUtil.sendHttp500(response, "Could not save uploaded file");
            return;
        }
        log.debug("Saved app file");
    } else {
        HttpUtil.sendHttp400(response, "No app was received.");
        return;
    }

    // Use if reading command from ToolProperties.xml. Otherwise,
    // comment-out if using custom command (called by customExecute())
    //command = getCommand();

    /*
     * CHANGE: Select either execute() to execute a native OS command or
     * customExecute() to execute your own custom code. Make sure that the
     * unused method call is commented-out.
     */
    reportBuffer = new StringBuffer();
    boolean succeeded = customExecute(reportBuffer);
    if (!succeeded) {
        log.error("Error detected: " + reportBuffer.toString());
        String errorReport = ReportUtil.getHtmlReport(response, fileName, ToolStatus.ERROR,
                reportBuffer.toString());
        // Send report to AppVet
        if (Properties.protocol.equals(Protocol.SYNCHRONOUS.name())) {
            // Send back ASCII in HTTP Response
            ReportUtil.sendInHttpResponse(response, errorReport, ToolStatus.ERROR);
        }
        return;
    }

    // Analyze report and generate tool status
    log.info("Analyzing report for " + appFilePath);
    //      ToolStatus risk = ReportUtil.analyzeReport(reportBuffer
    //            .toString());
    ToolStatus risk = ToolStatus.LOW; // Just set to LOW for testing
    log.info("Result: " + risk.name());
    String reportContent = null;

    // Get report
    if (Properties.reportFormat.equals(ReportFormat.HTML.name())) {
        reportContent = ReportUtil.getHtmlReport(response, fileName, risk, reportBuffer.toString());
    }
    //      else if (Properties.reportFormat.equals(ReportFormat.TXT.name())) {
    //         reportContent = getTxtReport();
    //      } else if (Properties.reportFormat.equals(ReportFormat.PDF.name())) {
    //         reportContent = getPdfReport();
    //      } else if (Properties.reportFormat.equals(ReportFormat.JSON.name())) {
    //         reportContent = getJsonReport();
    //      }

    // If report is null or empty, stop processing
    if (reportContent == null || reportContent.isEmpty()) {
        log.error("Tool report is null or empty");
        return;
    } else {
        log.info("Report generated");
    }

    // Send report to AppVet
    if (Properties.protocol.equals(Protocol.SYNCHRONOUS.name())) {
        // Send back ASCII in HTTP Response
        ReportUtil.sendPDFInHttpResponse(response, reportContent, risk);
    }

    // Clean up
    if (!Properties.keepApps) {
        if (FileUtil.deleteDirectory(new File(appDirPath))) {
            log.debug("Deleted " + appFilePath);
        } else {
            log.error("Could not delete " + appFilePath);
        }
    }
    log.info("Done processing app " + appId);
    reportBuffer = null;
    System.gc();
}

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

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

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

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

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

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

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

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

            long begin = System.currentTimeMillis();

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

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

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

From source file:com.example.web.Create_story.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    int count = 1;
    String storyid, storystep;/*from   ww  w. j a v  a 2  s  . c om*/
    String fileName = "";
    int f = 0;
    String action = "";
    String first = request.getParameter("first");
    String user = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("user"))
                user = cookie.getValue();
        }
    }
    String title = request.getParameter("title");
    String header = request.getParameter("header");
    String text_field = request.getParameter("text_field");

    String latitude = request.getParameter("lat");
    String longitude = request.getParameter("lng");
    storyid = (request.getParameter("storyid"));
    storystep = (request.getParameter("storystep"));
    String message = "";
    int valid = 1;
    String query;
    ResultSet rs;
    Connection conn;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "tworld";
    String driver = "com.mysql.jdbc.Driver";

    isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/"));
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        try {
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    fileName = fi.getName();
                    String contentType = fi.getContentType();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    String[] spliting = fileName.split("\\.");
                    // Write the file
                    System.out.println(sizeInBytes + " " + maxFileSize);
                    System.out.println(spliting[spliting.length - 1]);
                    if (!fileName.equals("")) {
                        if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg")
                                || spliting[spliting.length - 1].equals("png")
                                || spliting[spliting.length - 1].equals("jpeg"))) {

                            if (fileName.lastIndexOf("\\") >= 0) {
                                file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                            } else {
                                file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                            }
                            fi.write(file);
                            System.out.println("Uploaded Filename: " + fileName + "<br>");
                        } else {
                            valid = 0;
                            message = "not a valid image";
                        }
                    }
                }
                BufferedReader br = null;
                StringBuilder sb = new StringBuilder();

                String line;
                try {
                    br = new BufferedReader(new InputStreamReader(fi.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                } catch (IOException e) {
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                        }
                    }
                }
                if (f == 0)
                    action = sb.toString();
                else if (f == 1)
                    storyid = sb.toString();
                else if (f == 2)
                    storystep = sb.toString();
                else if (f == 3)
                    title = sb.toString();
                else if (f == 4)
                    header = sb.toString();
                else if (f == 5)
                    text_field = sb.toString();
                else if (f == 6)
                    latitude = sb.toString();
                else if (f == 7)
                    longitude = sb.toString();
                else if (f == 8)
                    first = sb.toString();
                f++;

            }
        } catch (Exception ex) {
            System.out.println("hi");
            System.out.println(ex);

        }
    }
    if (latitude == null)
        latitude = "";
    if (latitude.equals("") && first == null) {

        request.setAttribute("message", "please enter a marker");
        request.setAttribute("storyid", storyid);
        request.setAttribute("s_page", "3");
        request.setAttribute("storystep", storystep);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    } else if (valid == 1) {
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, "admin", "admin");
            if (first != null) {
                if (first.equals("first_step")) {
                    do {
                        query = "select * from story_database where story_id='" + count + "' ";
                        Statement st = conn.createStatement();
                        rs = st.executeQuery(query);
                        count++;
                    } while (rs.next());

                    int a = count - 1;
                    request.setAttribute("storyid", a);
                    storyid = Integer.toString(a);
                    request.setAttribute("storystep", 2);

                }
            }
            query = "select * from story_database where `story_id`='" + storyid + "' && `step_num`='"
                    + storystep + "' ";
            Statement st = conn.createStatement();
            rs = st.executeQuery(query);

            if (!rs.next()) {

                PreparedStatement pst = (PreparedStatement) conn.prepareStatement(
                        "insert into `tworld`.`story_database`(`story_id`, `step_num`, `content`, `latitude`, `longitude`, `title`, `header`, `max_steps`, `username`,`image_name`) values(?,?,?,?,?,?,?,?,?,?)");

                pst.setInt(1, Integer.parseInt(storyid));
                pst.setInt(2, Integer.parseInt(storystep));
                pst.setString(3, text_field);
                pst.setString(4, latitude);
                pst.setString(5, longitude);
                pst.setString(6, title);
                pst.setString(7, header);
                pst.setInt(8, Integer.parseInt(storystep));
                pst.setString(9, user);
                if (fileName.equals(""))
                    pst.setString(10, "");
                else
                    pst.setString(10, fileName);
                pst.executeUpdate();
                pst.close();

                pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?");
                pst.setInt(1, Integer.parseInt(storystep));
                pst.setInt(2, Integer.parseInt(storyid));
                pst.executeUpdate();
                pst.close();
            } else {
                PreparedStatement pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `content`=?, `latitude`=?, `longitude`=?, `title`=?, `header`=?, `max_steps`=?, `username`=? WHERE `story_id` = ? && `step_num`=?");

                pst.setString(1, text_field);
                pst.setString(2, latitude);
                pst.setString(3, longitude);
                pst.setString(4, title);
                pst.setString(5, header);

                pst.setInt(6, Integer.parseInt(storystep));
                pst.setString(7, user);
                pst.setInt(8, Integer.parseInt(storyid));
                pst.setInt(9, Integer.parseInt(storystep));

                pst.executeUpdate();
                pst.close();

                pst = (PreparedStatement) conn.prepareStatement(
                        "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?");
                pst.setInt(1, Integer.parseInt(storystep));
                pst.setInt(2, Integer.parseInt(storyid));
                pst.executeUpdate();
                pst.close();
            }
            request.setAttribute("storyid", storyid);
            storystep = Integer.toString(Integer.parseInt(storystep) + 1);
            request.setAttribute("storystep", storystep);

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {

            //            Logger.getLogger(MySignInServlet.class.getName()).log(Level.SEVERE, null, ex);  
        }
        request.setAttribute("s_page", "3");
        request.getRequestDispatcher("/index.jsp").forward(request, response);

    } else {
        request.setAttribute("storyid", storyid);
        request.setAttribute("message", message);
        request.setAttribute("storystep", storystep);

        request.setAttribute("s_page", "3");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}