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

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

Introduction

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

Prototype

public void setSizeThreshold(int sizeThreshold) 

Source Link

Document

Sets the size threshold beyond which files are written directly to disk.

Usage

From source file:se.streamsource.streamflow.web.assembler.WebAssembler.java

private void rest(ModuleAssembly module) throws AssemblyException {
    module.objects(StreamflowRestApplication.class, ResourceFinder.class /*,
                                                                         EntityStateSerializer.class,
                                                                         EntityTypeSerializer.class */);

    module.objects(//SPARQLResource.class,
            //IndexResource.class,
            EntitiesResource.class, EntityResource.class);

    module.importedServices(ChallengeAuthenticator.class);

    NamedQueries namedQueries = new NamedQueries();
    NamedQueryDescriptor queryDescriptor = new NamedSolrDescriptor("solrquery", "");
    namedQueries.addQuery(queryDescriptor);

    module.importedServices(NamedEntityFinder.class).importedBy(ServiceSelectorImporter.class)
            .setMetaInfo(ServiceQualifier.withId("solr")).setMetaInfo(namedQueries);

    // Resources//from w w w.j av  a  2s  . c  o m
    module.objects(APIRouter.class, AuthenticationFilter.class, AvailabilityFilter.class);

    new DCIAssembler().assemble(module);

    // Import file handling service for file uploads
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024 * 1000 * 30); // 30 Mb threshold TODO Make this into real service and make this number configurable
    module.importedServices(FileItemFactory.class).importedBy(INSTANCE).setMetaInfo(factory);

    module.importedServices(ResultConverter.class).importedBy(ImportedServiceDeclaration.NEW_OBJECT);
    module.objects(StreamflowResultConverter.class);

    module.importedServices(StreamflowCaseResponseWriter.class)
            .importedBy(ImportedServiceDeclaration.NEW_OBJECT);
    module.objects(StreamflowCaseResponseWriter.class);

    module.objects(StreamflowRestlet.class).visibleIn(Visibility.application);

    // Register all resources
    for (Class aClass : Iterables.filter(ClassScanner.matches(".*Resource"),
            ClassScanner.getClasses(RootResource.class))) {
        module.objects(aClass);
    }
}

From source file:se.streamsource.surface.web.assembler.ContextsAssembler.java

public void assemble(ModuleAssembly module) throws AssemblyException {
    module.importedServices(InteractionConstraintsService.class, NullResponseHandler.class)
            .importedBy(ImportedServiceDeclaration.NEW_OBJECT).visibleIn(Visibility.application);
    module.services(UuidIdentityGeneratorService.class).visibleIn(Visibility.layer);
    module.objects(InteractionConstraintsService.class, CommandQueryClientFactory.class,
            CommandQueryClient.class, CookieResponseHandler.class, AttachmentResponseHandler.class);
    module.values(TransactionDomainEvents.class, DomainEvent.class).visibleIn(Visibility.application);

    module.services(ClientEventSourceService.class).visibleIn(Visibility.application);

    // Import file handling service for file uploads
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024 * 1000 * 30); // 30 Mb threshold TODO Make this into real service and make this number configurable
    module.importedServices(FileItemFactory.class).importedBy(INSTANCE).setMetaInfo(factory);

    module.values(LinksValue.class, LinkValue.class, StringValue.class, TitledLinksValue.class,
            ValueComposite.class, VerifyDTO.class, SaveSignatureDTO.class).visibleIn(Visibility.application);

    // Resources//from w  ww.j  a  v  a 2  s  .co  m
    module.objects(SurfaceRestlet.class, RootResource.class, AccessPointsResource.class,
            AccessPointResource.class, EndUsersResource.class, EndUserResource.class, CaseResource.class,
            FormDraftsResource.class, FormDraftResource.class, DoubleSignatureTasksResource.class,
            DoubleSignatureTaskResource.class,

            AccessPointsContext.class, EndUsersContext.class, FormDraftContext.class);

    module.importedServices(Restlet.class).visibleIn(Visibility.application);
}

From source file:servlet.BPMNAnimationServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    PrintWriter out = null;//  ww  w.ja v a 2 s .c o m
    List<Log> logs = new ArrayList<>();
    Set<XLog> xlogs = new HashSet<>();
    //Set<XLog> optimizedLogs = new HashSet<>();
    String jsonData = "";
    Definitions bpmnDefinition = null;

    if (!ServletFileUpload.isMultipartContent(req)) {
        res.getWriter().println("Does not support!");
        // if not, we stop here
        return;
    }

    /*
     * ------------------------------------------
     * Import event log files
     * logs variable contains list of imported logs
     * ------------------------------------------
     */
    // configures some settings

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(REQUEST_SIZE);

    // constructs the directory path to store upload file
    String uploadPath = getServletContext().getRealPath("") + File.separator + 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
        List<FileItem> formItems = upload.parseRequest(req);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);

                // saves the file on disk
                item.write(storeFile);
                LOGGER.info("Finish writing uploaded file to temp dir: " + filePath);

                LOGGER.info("Start importing file: " + filePath);
                item.getInputStream();
                OpenLogFilePlugin logImporter = new OpenLogFilePlugin();
                XLog xlog = (XLog) logImporter.importFile(storeFile);

                // color field must follow the log file
                item = (FileItem) iter.next();
                assert item.isFormField();
                assert "color".equals(item.getFieldName());
                LOGGER.info("Log color: " + item.getString());
                String color = item.getString();

                // Record the log
                Log log = new Log();
                log.fileName = fileName;
                log.xlog = xlog;
                log.color = item.getString();
                logs.add(log);
                xlogs.add(xlog);
            } else {
                if (item.getFieldName().equals("json")) {
                    jsonData = item.getString();
                }
            }
        }

        /*
        * ------------------------------------------
        * Convert JSON map to BPMN objects
        * ------------------------------------------
        */
        LOGGER.info("Then, convert JSON to BPMN map objects");
        if (!jsonData.equals("")) {
            bpmnDefinition = this.getBPMNfromJson(jsonData);
            LOGGER.info("BPMN Diagram Definition" + bpmnDefinition.toString());
        } else {
            LOGGER.info("JSON data sent to server is empty");
        }

        /*
        * ------------------------------------------
        * Optimize logs and process model
        * ------------------------------------------
        */
        Optimizer optimizer = new Optimizer();
        for (Log log : logs) {
            //optimizedLogs.add(optimizer.optimizeLog(log.xlog));
            log.xlog = optimizer.optimizeLog(log.xlog);
        }
        bpmnDefinition = optimizer.optimizeProcessModel(bpmnDefinition);

        /*
        * ------------------------------------------
        * Check BPMN diagram validity and replay log
        * ------------------------------------------
        */

        //Reading backtracking properties for testing
        String propertyFile = "/editor/animation/properties.xml";
        InputStream is = getServletContext().getResourceAsStream(propertyFile);
        Properties props = new Properties();
        props.loadFromXML(is);
        ReplayParams params = new ReplayParams();
        params.setMaxCost(Double.valueOf(props.getProperty("MaxCost")).doubleValue());
        params.setMaxDepth(Integer.valueOf(props.getProperty("MaxDepth")).intValue());
        params.setMinMatchPercent(Double.valueOf(props.getProperty("MinMatchPercent")).doubleValue());
        params.setMaxMatchPercent(Double.valueOf(props.getProperty("MaxMatchPercent")).doubleValue());
        params.setMaxConsecutiveUnmatch(Integer.valueOf(props.getProperty("MaxConsecutiveUnmatch")).intValue());
        params.setActivityMatchCost(Double.valueOf(props.getProperty("ActivityMatchCost")).doubleValue());
        params.setActivitySkipCost(Double.valueOf(props.getProperty("ActivitySkipCost")).doubleValue());
        params.setEventSkipCost(Double.valueOf(props.getProperty("EventSkipCost")).doubleValue());
        params.setNonActivityMoveCost(Double.valueOf(props.getProperty("NonActivityMoveCost")).doubleValue());
        params.setTraceChunkSize(Integer.valueOf(props.getProperty("TraceChunkSize")).intValue());
        params.setMaxNumberOfNodesVisited(
                Integer.valueOf(props.getProperty("MaxNumberOfNodesVisited")).intValue());
        params.setMaxActivitySkipPercent(
                Double.valueOf(props.getProperty("MaxActivitySkipPercent")).doubleValue());
        params.setMaxNodeDistance(Integer.valueOf(props.getProperty("MaxNodeDistance")).intValue());
        params.setTimelineSlots(Integer.valueOf(props.getProperty("TimelineSlots")).intValue());
        params.setTotalEngineSeconds(Integer.valueOf(props.getProperty("TotalEngineSeconds")).intValue());
        params.setProgressCircleBarRadius(
                Integer.valueOf(props.getProperty("ProgressCircleBarRadius")).intValue());
        params.setSequenceTokenDiffThreshold(
                Integer.valueOf(props.getProperty("SequenceTokenDiffThreshold")).intValue());
        params.setMaxTimePerTrace(Long.valueOf(props.getProperty("MaxTimePerTrace")).longValue());
        params.setMaxTimeShortestPathExploration(
                Long.valueOf(props.getProperty("MaxTimeShortestPathExploration")).longValue());
        params.setExactTraceFitnessCalculation(props.getProperty("ExactTraceFitnessCalculation"));
        params.setBacktrackingDebug(props.getProperty("BacktrackingDebug"));
        params.setExploreShortestPathDebug(props.getProperty("ExploreShortestPathDebug"));
        params.setCheckViciousCycle(props.getProperty("CheckViciousCycle"));
        params.setStartEventToFirstEventDuration(
                Integer.valueOf(props.getProperty("StartEventToFirstEventDuration")).intValue());
        params.setLastEventToEndEventDuration(
                Integer.valueOf(props.getProperty("LastEventToEndEventDuration")).intValue());

        Replayer replayer = new Replayer(bpmnDefinition, params);
        ArrayList<AnimationLog> replayedLogs = new ArrayList();
        if (replayer.isValidProcess()) {
            LOGGER.info("Process " + bpmnDefinition.getId() + " is valid");
            EncodeTraces.getEncodeTraces().read(xlogs); //build a mapping from traceId to charstream
            for (Log log : logs) {

                AnimationLog animationLog = replayer.replay(log.xlog, log.color);
                //AnimationLog animationLog = replayer.replayWithMultiThreading(log.xlog, log.color);
                if (animationLog != null && !animationLog.isEmpty()) {
                    replayedLogs.add(animationLog);
                }
            }

        } else {
            LOGGER.info(replayer.getProcessCheckingMsg());
        }

        /*
        * ------------------------------------------
        * Return Json animation
        * ------------------------------------------
        */
        LOGGER.info("Start sending back JSON animation script to browser");
        if (replayedLogs.size() > 0) {
            out = res.getWriter();
            res.setContentType("text/html"); // Ext2JS's file upload requires this rather than "application/json"
            res.setStatus(200);

            //To be replaced
            AnimationJSONBuilder jsonBuilder = new AnimationJSONBuilder(replayedLogs, replayer, params);
            JSONObject json = jsonBuilder.parseLogCollection();
            json.put("success", true); // Ext2JS's file upload requires this flag
            String string = json.toString();
            //LOGGER.info(string);
            jsonBuilder.clear();

            out.write(string);
        } else {
            /*
            out = res.getWriter();
            res.setContentType("text/html");
            res.setStatus(204);
            out.write("");
            */
            String json = "{success:false, errors: {errormsg: '" + "No logs can be played." + "'}}";
            res.setContentType("text/html; charset=UTF-8");
            res.getWriter().print(json);
        }

    } catch (Exception e) {
        try {
            LOGGER.severe(e.toString());
            /*
            res.setStatus(500);
            res.setContentType("text/plain");
            PrintWriter writer = new PrintWriter(out);
            writer.println("Failed to generate animation JSON script " + e);
            e.printStackTrace(writer);
            e.printStackTrace();
            res.getWriter().write(e.toString());
            */
            String json = "{success:false, errors: {errormsg: '" + e.getMessage() + "'}}";
            res.setContentType("text/html; charset=UTF-8");
            res.getWriter().print(json);
        } catch (Exception el) {
            System.err.println("Original exception was:");
            e.printStackTrace();
            System.err.println("Exception in exception handler was:");
            el.printStackTrace();
        }
    }

}

From source file:servlet.PreProcessServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w ww .  j av a  2  s  .c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    uploadRootPath = getServletContext().getInitParameter("file-upload");
    File upload = new File(uploadRootPath);
    if (upload.exists()) {
        deleteFolderContent(upload);
    }
    createDirectoryIfNotExisting(uploadRootPath);
    String programRootPath = getServletContext().getInitParameter("program-root-path");
    boolean isGeneral = false;
    String copyrightStoplist = "";
    String customizedPackageList = "";
    String projectName = "";
    int topicCount = -1;

    String inputRootFilePath = uploadRootPath;
    String outputFilePath = programRootPath + "preprocessOutput/PreProcessTool";
    File outputFile = new File(outputFilePath);
    if (outputFile.exists()) {
        deleteFolderContent(outputFile);
    }

    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");

        out.println("<html lang=\"en\">");
        out.println("<head>" + "<meta charset=\"utf-8\">"
                + "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
                + "<meta name=\"description\" content=\"\">" + "<meta name=\"author\" content=\"\">"
                + "<link rel=\"icon\" href=\"./image/analysis.jpg\">" + "<title>Programmer Assistor</title>"
                + "<link href=\"./css/bootstrap.min.css\" rel=\"stylesheet\">"
                + "<script src=\"./js/ie-emulation-modes-warning.js\">"
                + "</script><!-- Custom styles for this template -->"
                + "<link href=\"./css/list.css\" rel=\"stylesheet\">" + "</head>");
        out.println("<body>" + "<div class=\"navbar-wrapper\">" + "<div class=\"container\">"
                + "<nav class=\"navbar navbar-inverse navbar-static-top\" role=\"navigation\">"
                + "<div class=\"container\">" + "<div class=\"navbar-header\">"
                + "<a class=\"navbar-brand\" href=\"home.html\">Programmer Assistor</a>" + "</div>"
                + "<div id=\"navbar\" class=\"navbar-collapse collapse\">" + "<ul class=\"nav navbar-nav\">"
                + "<li>" + "<a href=\"home.html\">Home </a>" + "</li>" + "<li>"
                + "<a href=\"help.html\">Help </a>" + "</li>" + "<li>" + "<a href=\"show.html\">Show </a>"
                + "</li>" + "<li>" + "<a href=\"search.html\">Search </a>" + "</li>" + "</ul>" + "</div>"
                + "</div>" + "</nav>" + "</div>" + "</div>");
        out.println("<div class=\"container marketing\">");
        out.println("<div class=\"row featurette files\" id=\"fileList\">");
        out.println("<h2>1. Preprocessing </h2>");
        out.println("<h3>Preprocessed Data Directory: </h3>");
        out.println("<p>");
        out.println(programRootPath + "preprocessOutput/PreProcessTool");
        out.println("</p>");
        out.println("<h3>Uploaded Files: </h3>");

        isMultipart = ServletFileUpload.isMultipartContent(request);

        if (!isMultipart) {
            out.println("<p>the request isn't multipart</p>");
            return;
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File(programRootPath, "temp"));

        ServletFileUpload uploadProcess = new ServletFileUpload(factory);
        uploadProcess.setSizeMax(maxFileSize);

        try {
            List fileItems = uploadProcess.parseRequest(request);

            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    String fileName = fi.getName();
                    file = new File(inputRootFilePath + fileName.replace('/', '-'));//replace all / to -
                    fi.write(file);

                    out.println("<p>");
                    out.println(fileName);
                    out.println("</p>");
                } else {
                    String fieldName = fi.getFieldName();
                    String fieldValue = fi.getString();
                    if (fieldName.equals("general") && fieldValue.equals("on")) {
                        isGeneral = true;
                    } else if (fieldName.equals("project_type")) {
                        if (fieldValue.equals("Drawing")) {
                            libraryTypeCondition.remove("Drawing");
                            libraryTypeCondition.put("Drawing", true);
                        } else if (fieldValue.equals("Modeling")) {
                            libraryTypeCondition.remove("Modeling");
                            libraryTypeCondition.put("Modeling", true);
                        }
                    } else if (fieldName.equals("customizePackageInfoContent")) {
                        String customizePackageInfoContent = fieldValue;
                        customizedPackageList = customizePackageInfoContent.toLowerCase()
                                .replaceAll("\\*|\n|[0-9]|,|;|`|'|\"", "");
                        customizedPackageList = customizedPackageList.replaceAll("\\(|\\)|-|//|:|~|/|\\.", " ");

                    } else if (fieldName.equals("copyrightInfoContent")) {
                        String copyrightInfoContent = fieldValue;
                        copyrightInfoContent = copyrightInfoContent.replaceAll(".java", "java");
                        copyrightStoplist = copyrightInfoContent.toLowerCase()
                                .replaceAll("\\*|\n|[0-9]|,|;|`|'|\"", "");
                        copyrightStoplist = copyrightStoplist.replaceAll("\\(|\\)|-|//|:|~|/|\\.", " ");

                    } else if (fieldName.equals("projectNameContent")) {
                        projectName = fieldValue;
                    } else if (fieldName.equals("topicCountContent")) {
                        topicCount = Integer.parseInt(fieldValue);
                    }
                }
            }

            //                out.println("<p>"+ copyrightStoplist.toString() +"</p>");

        } catch (FileUploadException e) {
            // TODO Auto-generated catch block  
            out.println("The size of files is too much, please upload files less than 50MB");
            e.printStackTrace();
        } catch (Exception ex) {
            out.println(ex);

        }

        PreProcessTool preProcessTool = new PreProcessTool(inputRootFilePath, outputFilePath, isGeneral,
                libraryTypeCondition, copyrightStoplist, customizedPackageList);
        preProcessTool.preProcess();
        out.println("<h3 id = \"success\" class=\"fileHead\"> Successful Uploading and preprocessing!</h3>");

        //topic modeling
        out.println("<p></p>");
        out.println("<h2>2. Topic Modeling: </h2>");
        out.println("<p>The project name: ");
        out.println(projectName);
        out.println("</p>");
        out.println("<p> The number of topics: ");
        out.println(topicCount);
        out.println("</p>");
        out.println("<h3 id=\"topModelingLogHeader\">Start Topic Modeling: </h3>");
        out.println("<script>" + "window.wtx = window.setInterval(function () {"
                + "var div = document.getElementById('topModelingLog'); " + "div.scrollTop = div.scrollHeight; "
                + "div.scrollIntoView(true); " + "}, 100);" + "</script>");
        out.println("<div id=\"topModelingLog\" style=\"height: 300px; overflow:scroll;\">");
        Executor executor = new Executor(projectName, topicCount, new ProcessPrinter(out::println));
        executor.run();
        out.println("</div>");
        out.println("<script>window.clearInterval(window.wtx);</script>");

        //prepare for search
        File compositeFile = new File(programRootPath + "showFile/composition.txt");
        String top3DocumentsFilePath = programRootPath + "showFile/top3Documents.txt";
        Map<String, String> top3Documents = new HashMap<>();
        Map<Integer, String[]> top3DocAndPer = new HashMap<>();

        int totalFileNo = 0;

        try (InputStream inComposite = new FileInputStream(compositeFile.getPath());
                BufferedReader readerComposite = new BufferedReader(new InputStreamReader(inComposite))) {

            String compositeLine = "";
            while ((compositeLine = readerComposite.readLine()) != null) {
                totalFileNo++;
            }
        }

        try (InputStream inComposite = new FileInputStream(compositeFile.getPath());
                BufferedReader readerComposite = new BufferedReader(new InputStreamReader(inComposite))) {

            String compositeLine = "";
            Double[][] topicDocMatrix = new Double[topicCount][totalFileNo];
            String[] fileNameList = new String[totalFileNo];
            int fileNo = 0;
            while ((compositeLine = readerComposite.readLine()) != null) {
                String[] linePart = compositeLine.split("\t| ");
                String[] nameParts = linePart[1].split("/");
                String textName = nameParts[nameParts.length - 1];
                int lastIndexOfStrigula = textName.lastIndexOf('-');
                if (lastIndexOfStrigula >= 0) {
                    String fileName = textName.substring(0, lastIndexOfStrigula);
                    fileNameList[fileNo] = fileName;
                }

                for (int i = 2; i < linePart.length; i++) {
                    topicDocMatrix[i - 2][fileNo] = Double.parseDouble(linePart[i]);
                }

                fileNo++;
            }

            //find top3 document for each topic
            for (int i = 0; i < topicDocMatrix.length; i++) {
                double max1 = 0;
                String file1 = "";
                double max2 = 0;
                String file2 = "";
                double max3 = 0;
                String file3 = "";
                for (int j = 0; j < topicDocMatrix[i].length; j++) {
                    if (topicDocMatrix[i][j] > max1) {
                        max3 = max2;
                        max2 = max1;
                        max1 = topicDocMatrix[i][j];
                        file1 = fileNameList[j];
                    } else if (topicDocMatrix[i][j] > max2) {
                        max3 = max2;
                        max2 = topicDocMatrix[i][j];
                        file2 = fileNameList[j];
                    } else if (topicDocMatrix[i][j] > max3) {
                        max3 = topicDocMatrix[i][j];
                        file3 = fileNameList[j];
                    }
                }
                String[] docAndPerList = new String[3];
                docAndPerList[0] = file1 + "\t" + max1;
                docAndPerList[1] = file2 + "\t" + max2;
                docAndPerList[2] = file3 + "\t" + max3;
                top3DocAndPer.put(i, docAndPerList);
            }

        }

        File top3DocumentsFile = new File(top3DocumentsFilePath);
        if (top3DocumentsFile.createNewFile()) {
            System.out.println("Create successful: " + top3DocumentsFile.getName());
        }
        writeMapIntStrAToFile(top3DocumentsFile, top3DocAndPer);

        out.println("<h3 id = \"success\" class=\"fileHead\">Successful Topic Modeling!</h3>");
        out.println(
                "<h2 id = \"success\" class=\"fileHead\">Now, you can start using the \"Show\" function and the \"Search\" function.</h2>");

        out.println("</div>");
        out.println("<hr class=\"featurette-divider\">");
        out.println("<footer>" + "<p class=\"pull-right\">" + "<a href=\"#\">Back to top</a>" + "</p>"
                + "<p>2017 @Tianxia, Wang</p>" + "</footer>");
        out.println("</div>");
        out.println("<script src=\"./js/jquery.min.js\"></script>");
        out.println("<script src=\"./js/bootstrap.min.js\"></script>");
        out.println("<script src=\"./js/docs.min.js\"></script>");
        out.println("<script src=\"./js/ie10-viewport-bug-workaround.js\"></script>");
        out.println("<script src=\"./js/home.js\"></script>");
        out.println("</body>");
        out.println("</html>");

    }
}

From source file:Servlet.UploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w  ww . j  av  a  2  s.c  om
 * @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 {

    HttpSession tempSession = request.getSession();
    java.lang.System.out.println(tempSession.getAttribute("accountType") + "---------------upload\n");
    if (tempSession.getAttribute("accountType") == null
            || !tempSession.getAttribute("accountType").equals("2")) {
        response.sendRedirect("login.jsp");
    } else {
        System.out.println("------------------IN UPLOADING PROCESS------------------");

        String uploader_id = "", title = "", description = "", importancy = "", category = "", fileName = "",
                date = "";

        File file;
        int maxFileSize = 5000 * 1024;
        int maxMemSize = 5000 * 1024;
        String filePath = "G:\\GoogleDrive\\Class file\\Current\\Me\\Web\\Lab\\Project\\Web Project\\ENotice\\src\\main\\webapp\\files\\";

        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(maxMemSize);
            factory.setRepository(new File("C:\\temp\\"));
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(maxFileSize);
            try {
                List fileItems = upload.parseRequest(request);
                Iterator i = fileItems.iterator();
                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        String fieldName = fi.getFieldName();
                        fileName = fi.getName();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        file = new File(filePath + fileName);
                        fi.write(file);
                    } else if (fi.getFieldName().equals("title")) {
                        title = fi.getString();
                    } else if (fi.getFieldName().equals("description")) {
                        description = fi.getString();
                    } else if (fi.getFieldName().equals("importancy")) {
                        importancy = fi.getString();
                    } else {
                        category = fi.getString();
                    }

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

        //transfering data to Upload notice
        try {
            String uploaderId = (String) tempSession.getAttribute("id");

            System.out.println("id : " + uploaderId);
            System.out.println(title + " " + description + " " + importancy + " " + category + " " + fileName
                    + " " + uploaderId);

            Upload upload = new Upload();
            upload.upload(uploaderId, title, description, importancy, category, fileName);
        } catch (Exception e) {
            System.out.println("Exception in doPost of UploadServlet()");
            e.printStackTrace();
        }

        if (request.getAttribute("fromEdit") == null) {
            //back to upload.jsp
            System.out.println("fromEdit is null!!!");
            System.out.println("position of Notice : " + request.getParameter("positionOfNotice"));
            response.sendRedirect("upload.jsp");
        } else {
            System.out.println("fromEdit is not null!!!");
            RequestDispatcher rd = request.getRequestDispatcher("UploaderNextPrevCombo");
            rd.forward(request, response);
        }
    }
}

From source file:servlets.File_servlets.java

private void add_new_file_handler(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//w ww .  jav  a2 s  .c  om
        DAO daoInstance;
        File uploadedFile;
        Experiment experiment;
        String parent_dir;
        String file_name;

        try {

            if (!ServletFileUpload.isMultipartContent(request)) {
                throw new Exception("Erroneus request.");
            }

            /**
             * *******************************************************
             * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF
             * ERROR --> throws exception if not valid session, GO TO STEP
             * 5b ELSE --> GO TO STEP 2
             * *******************************************************
             */
            Map<String, Cookie> cookies = this.getCookies(request);

            String loggedUser, loggedUserID = null, sessionToken;
            if (cookies != null) {
                loggedUser = cookies.get("loggedUser").getValue();
                sessionToken = cookies.get("sessionToken").getValue();
                loggedUserID = cookies.get("loggedUserID").getValue();
            } else {
                String apicode = request.getParameter("apicode");
                apicode = new String(Base64.decodeBase64(apicode));

                loggedUser = apicode.split(":")[0];
                sessionToken = apicode.split(":")[1];
            }

            if (!checkAccessPermissions(loggedUser, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }

            if (loggedUserID == null) {
                daoInstance = DAOProvider.getDAOByName("User");
                loggedUserID = ((User) daoInstance.findByID(loggedUser, new Object[] { null, false, true }))
                        .getUserID();
            }

            /**
             * *******************************************************
             * STEP 2 Get the Experiment Object from DB. IF ERROR --> throws
             * MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            String experiment_id;
            if (request.getParameter("experiment_id") != null) {
                experiment_id = request.getParameter("experiment_id");
            } else {
                experiment_id = cookies.get("currentExperimentID").getValue();
            }

            parent_dir = "";
            if (request.getParameter("parent_dir") != null) {
                parent_dir = request.getParameter("parent_dir");
            }

            file_name = "";
            if (request.getParameter("file_name") != null) {
                file_name = request.getParameter("file_name");
            }
            /**
             * *******************************************************
             * STEP 3 Check that the user is a valid owner for the
             * experiment.
             * *******************************************************
             */
            daoInstance = DAOProvider.getDAOByName("Experiment");
            experiment = (Experiment) daoInstance.findByID(experiment_id, null);

            if (!experiment.isOwner(loggedUserID) && !experiment.isMember(loggedUserID)
                    && !isValidAdminUser(loggedUser)) {
                throw new AccessControlException(
                        "Cannot add files to selected study. Current user is not a valid member for study "
                                + experiment_id + ".");
            }

            /**
             * *******************************************************
             * STEP 4 Read the uploaded file and store in a temporal dir.
             * *******************************************************
             */
            FileItem tmpUploadedFile = null;
            final String CACHE_PATH = "/tmp/";
            final int CACHE_SIZE = 500 * (int) Math.pow(10, 6);
            final int MAX_REQUEST_SIZE = 600 * (int) Math.pow(10, 6);
            final int MAX_FILE_SIZE = 500 * (int) Math.pow(10, 6); //TODO: READ FROM SETTINGS

            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // Set factory constraints
            factory.setRepository(new File(CACHE_PATH));
            factory.setSizeThreshold(CACHE_SIZE);

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // Set overall request size constraint
            upload.setSizeMax(MAX_REQUEST_SIZE);
            upload.setFileSizeMax(MAX_FILE_SIZE);

            // Parse the request
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    if (!item.getName().equals("")) {
                        tmpUploadedFile = item;
                    }
                }
            }

            if (tmpUploadedFile == null) {
                throw new Exception("The file was not uploaded correctly.");
            }

            /**
             * *******************************************************
             * STEP 5 SAVE THE FILE IN THE SERVER.
             * *******************************************************
             */
            //First check if the file already exists -> error, probably a previous treatmente exists with the same treatment_id
            Path tmpDir = Files.createTempDirectory(null);
            file_name = (file_name.isEmpty() ? tmpUploadedFile.getName() : file_name);
            uploadedFile = new File(tmpDir.toString(), file_name);

            try {
                tmpUploadedFile.write(uploadedFile);

                if (request.getParameter("credentials") != null) {
                    byte[] decoded = Base64.decodeBase64(request.getParameter("credentials"));
                    String[] credentials = new String(decoded).split(":", 2);
                    experiment.setDataDirectoryUser(credentials[0]);
                    experiment.setDataDirectoryPass(credentials[1]);
                } else if (request.getParameter("apikey") != null) {
                    experiment.setDataDirectoryApiKey(request.getParameter("apikey"));
                }

                FileManager.getFileManager(DATA_LOCATION).saveFiles(new File[] { uploadedFile },
                        experiment.getDataDirectoryInformation(), parent_dir);
            } catch (IOException e) {
                // Directory creation failed
                throw new Exception(
                        "Unable to save the uploded file. Please check if the Tomcat user has read/write permissions over the data application directory.");
            } finally {
                tmpUploadedFile.delete();
                uploadedFile.delete();
                Files.delete(tmpDir);
            }
        } catch (Exception e) {
            ServerErrorManager.handleException(e, File_servlets.class.getName(), "add_new_file_handler",
                    e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 5b CATCH ERROR, CLEAN CHANGES. throws SQLException
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());
            } else {
                JsonObject obj = new JsonObject();
                obj.add("success", new JsonPrimitive(true));
                response.getWriter().print(obj.toString());
            }
        }
    } catch (Exception e) {
        ServerErrorManager.handleException(e, File_servlets.class.getName(), "add_new_file_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:servlets.generar.java

protected String[] subirExamen(HttpServletRequest request) throws FileUploadException, Exception {
    String datos[] = new String[2];
    String imgDir = config.getServletContext().getRealPath("/examenes/") + "/";
    File dir = new File(imgDir);
    dir.mkdirs();//from   ww  w.ja v a 2s .  c o  m

    DiskFileItemFactory fabrica = new DiskFileItemFactory();
    fabrica.setSizeThreshold(1024);
    fabrica.setRepository(dir);

    ServletFileUpload upload = new ServletFileUpload(fabrica);
    List<FileItem> partes = upload.parseRequest(request);

    for (FileItem item : partes) {
        if (item.isFormField()) {
            datos[0] = item.getString();
            System.out.println(item.getString());
        } else {
            System.out.println("Subiendo");
            File archivo = new File(imgDir, item.getName());
            item.write(archivo);
            datos[1] = item.getName();

        }
    }
    return datos;
}

From source file:servlets.Handler.java

/**
 * // www  .  j  av a 2 s. c  o  m
 * @param request
 * @return 
 */
private Response send_email(HttpServletRequest request) {

    UserDTO user = (UserDTO) request.getSession().getAttribute("user");
    if (user != null) {

        int maxFileSize = 5000 * 1024;
        int maxMemSize = 5000 * 1024;
        ServletContext context = request.getServletContext();
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            String email = "";
            String subject = "";
            try {
                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("c:\\temp"));

                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(maxFileSize);

                List fileItems = upload.parseRequest(request);
                FileItem fi = (FileItem) fileItems.get(0);
                ;

                subject = request.getParameter("subject");
                email = java.net.URLDecoder.decode(request.getParameter("email"), "UTF-8");
                //ARREGLAR ESTOOOOOOOOOOOOOOOOO
                return this.facade.sendEmail(user, subject, email, fi);

            } catch (FileUploadException ex) {
                ex.printStackTrace();
                return ResponseHelper.getResponse(-3, "No se pudo subir el archivo", null);
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
                System.out.println("email:" + email);
                return ResponseHelper.getResponse(-3, "No se pudo parsear el email", null);
            } catch (Exception ex) {
                ex.printStackTrace();
                return ResponseHelper.getResponse(-3, "No se pudo escribir el archivo en el disco", null);
            }

        } else {
            return ResponseHelper.getResponse(-2, "Cabecera HTTP erronea", null);
        }
    }

    return ResponseHelper.getResponse(-2, "Login is required", null);
}

From source file:servlets.NewFile.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  w w .  j  a  v a  2 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 {

    int maxFileSize = 1000 * 1024;
    int maxMemSize = 1000 * 1024;

    //        String contentType = request.getContentType();
    //         if ((contentType.contains("multipart/form-data"))) {
    //             DiskFileItemFactory factory = new DiskFileItemFactory();
    //         }
    String contentType = request.getContentType();
    response.setContentType("multipart/form-data");
    if ((contentType.contains("multipart/form-data"))) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("."));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxFileSize);
        String path = getServletContext().getRealPath("") + File.separator + "files";
        File uploadDir = new File(path);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            List<FileItem> formItems = upload.parseRequest(request);
            if (formItems != null && formItems.size() > 0) {
                for (FileItem item : formItems) {
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = path + File.separator + fileName;
                        File storeFile = new File(filePath);
                        request.getSession(true).setAttribute("filePath", filePath);
                        // guardamos el fichero en el disco
                        item.write(storeFile);

                    }

                }
            }
        } catch (FileUploadException ex) {
            Logger.getLogger(NewCarta.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(NewCarta.class.getName()).log(Level.SEVERE, null, ex);
        }

        request.getRequestDispatcher("/crearCarta.jsp").forward(request, response);

    }

}

From source file:servlets.Samples_servlets.java

private void send_biocondition_template_document_handler(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    try {//w w  w .j av a  2s . c om

        ArrayList<String> BLOCKED_IDs = new ArrayList<String>();
        boolean ROLLBACK_NEEDED = false;
        DAO dao_instance = null;

        try {
            if (!ServletFileUpload.isMultipartContent(request)) {
                throw new Exception("Erroneus request.");
            }

            String user_id = "";
            String sessionToken = "";
            File xls_file = null;

            /**
             * *******************************************************
             * STEP 1 Get the request params: read the params and the XLS
             * file. IF ERROR --> throws SQL Exception, GO TO STEP ? ELSE
             * --> GO TO STEP 9
             * *******************************************************
             */
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("text/html");

            //Get the data as a JSON format string
            final String CACHE_PATH = "/tmp/";
            final int CACHE_SIZE = 100 * (int) Math.pow(10, 6);
            final int MAX_REQUEST_SIZE = 20 * (int) Math.pow(10, 6);
            final int MAX_FILE_SIZE = 20 * (int) Math.pow(10, 6);

            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // Set factory constraints
            factory.setRepository(new File(CACHE_PATH));
            factory.setSizeThreshold(CACHE_SIZE);

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // Set overall request size constraint
            upload.setSizeMax(MAX_REQUEST_SIZE);
            upload.setFileSizeMax(MAX_FILE_SIZE);

            // Parse the request
            List<FileItem> items = upload.parseRequest(request);

            for (FileItem item : items) {
                if (!item.isFormField()) {
                    if (!item.getName().equals("")) {
                        //First check if the file already exists -> error, probably a previous treatmente exists with the same treatment_id
                        xls_file = new File(CACHE_PATH + "tmp.xls");
                        item.write(xls_file);
                    }
                } else {
                    String name = item.getFieldName();
                    String value = item.getString();
                    if ("loggedUser".equals(name)) {
                        user_id = value;
                    } else if ("sessionToken".equals(name)) {
                        sessionToken = value;
                    }
                }
            }

            /**
             * *******************************************************
             * STEP 2 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP AND
             * IF FILE IS CORRECTLY UPDATED. IF ERROR --> throws exception
             * if not valid session, GO TO STEP 6b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            if (!checkAccessPermissions(user_id, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }
            if (xls_file == null) {
                throw new Exception("XLS file was not uploaded correctly.");
            }

            /**
             * *******************************************************
             * STEP 2 Parse the XLS file and get the information. IF ERROR
             * --> throws Exception, GO TO STEP ? ELSE --> GO TO STEP 3
             * *******************************************************
             */
            Object[] parsingResult = BioCondition_XLS_parser.parseXLSfile(xls_file, user_id);

            ArrayList<BioCondition> biocondition_list = (ArrayList<BioCondition>) parsingResult[0];
            HashMap<String, Batch> batchesTable = (HashMap<String, Batch>) parsingResult[1];
            HashMap<String, Protocol> protocolsTable = (HashMap<String, Protocol>) parsingResult[2];

            /**
             * *******************************************************
             * STEP 3 IF FILE WAS PARSED CORRECTLY ADD THE INFORMATION TO
             * DATABASE. IF ERROR --> throws SQLException, GO TO STEP ? ELSE
             * --> GO TO STEP 4
             * *******************************************************
             */
            dao_instance = DAOProvider.getDAOByName("Batch");
            dao_instance.disableAutocommit();
            ROLLBACK_NEEDED = true;

            //IF WE ARE HERE IT MEANS THAT APARENTLY EVERTHING WAS OK
            //therefore WE SHOULD START ADDING THE INFORMATION INTO THE DB
            for (Batch batch : batchesTable.values()) {
                String batch_id = dao_instance.getNextObjectID(null);
                BLOCKED_IDs.add(batch_id);
                batch.setBatchID(batch_id);
                //THE BATCH ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES (BECAUSE IS THE SAME OBJECT)
                dao_instance.insert(batch);
            }

            dao_instance = DAOProvider.getDAOByName("Protocol");
            //IF WE ARE HERE IT MEANS THAT APARENTLY EVERTHING WAS OK
            //therefore WE SHOULD START ADDING THE INFORMATION INTO THE DB
            for (Protocol protocol : protocolsTable.values()) {
                String protocolID = dao_instance.getNextObjectID(null);
                BLOCKED_IDs.add(protocolID);
                protocol.setProtocolID(protocolID);
                //THE BATCH ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES (BECAUSE IS THE SAME OBJECT)
                dao_instance.insert(protocol);
            }

            dao_instance = DAOProvider.getDAOByName("BioCondition");

            for (BioCondition biocondition : biocondition_list) {
                String newID = dao_instance.getNextObjectID(null);
                BLOCKED_IDs.add(newID);
                biocondition.setBioConditionID(newID);
                //THE biocondition ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES
                dao_instance.insert(biocondition);
            }

            /**
             * *******************************************************
             * STEP 4 COMMIT CHANGES TO DATABASE. throws SQLException IF
             * ERROR --> throws SQL Exception, GO TO STEP 5b ELSE --> GO TO
             * STEP 5
             * *******************************************************
             */
            dao_instance.doCommit();

        } catch (Exception e) {
            ServerErrorManager.handleException(e, Samples_servlets.class.getName(),
                    "send_biocondition_template_document_handler", e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 5b CATCH ERROR, CLEAN CHANGES. throws SQLException
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());

                if (ROLLBACK_NEEDED) {
                    dao_instance.doRollback();
                }
            } else {
                response.getWriter().print("{success: " + true + "}");
            }

            for (String blocked_id : BLOCKED_IDs) {
                BlockedElementsManager.getBlockedElementsManager().unlockID(blocked_id);
            }

            /**
             * *******************************************************
             * STEP 6 Close connection.
             * ********************************************************
             */
            if (dao_instance != null) {
                dao_instance.closeConnection();
            }
        }
        //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE 
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Samples_servlets.class.getName(),
                "send_xls_creation_document_handler", e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}