Swing окно застревает при передаче нескольких файлов - PullRequest
0 голосов
/ 29 января 2020

Я создаю приложение для проверки кода, которое принимает файлы формата .resource и обменивается результатами. Он работает для 3-4 папок в файле формата .resource, но когда размер папки увеличивается, окно застревает.

public class CodeReviewWindow extends JDialog {

    private final JButton jbtOk = new JButton("Choose File");
    private final JButton jbtCancel = new JButton("Cancel");

    private final JLabel jlblStatus = new JLabel(" ");

    public CodeReviewWindow() {
        this(null, true);
    }

    public CodeReviewWindow(final JFrame parent, boolean modal) {
        super(parent, modal);
        JPanel p2 = new JPanel();
        p2.add(jbtOk);
        p2.add(jbtCancel);

        JPanel p5 = new JPanel(new BorderLayout());
        p5.add(p2, BorderLayout.CENTER);
        p5.add(jlblStatus, BorderLayout.NORTH);
        jlblStatus.setForeground(Color.RED);
        jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);

        setLayout(new BorderLayout());
        add(p5, BorderLayout.CENTER);
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });


        jbtOk.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());

                int returnValue = jfc.showOpenDialog(null);
                Map<String, List<RuleViolation>> mapOfRuleViolation = new HashMap<>();
                BufferedInputStream bis = null;
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = jfc.getSelectedFile();
                    if (selectedFile.getName().endsWith(".resource")) {
                        try {
                            ZipFile zipFile = new ZipFile(selectedFile.getAbsolutePath());

                            Enumeration<? extends ZipEntry> entries = zipFile.entries();
                            while (entries.hasMoreElements()) {
                                ZipEntry entry = entries.nextElement();
                                File file = new File(entry.getName());
                                String name = file.getName();
                                if (entry.isDirectory()) {
                                    continue;
                                } else {
                                    if (name.endsWith(".js")) {
                                        bis = new BufferedInputStream(zipFile.getInputStream(entry));
                                        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                                        InputStream ruleSetsInputStream = classLoader.getResourceAsStream("xml/javascript.xml");
                                        File ruleSet = PmdReviewService.stream2file(ruleSetsInputStream, "javascript", ".xml");
                                        PMDConfiguration pmdConfiguration = new PMDConfiguration();
                                        pmdConfiguration.setReportFormat("text");
                                        pmdConfiguration.setRuleSets(ruleSet.getPath());
                                        pmdConfiguration.setThreads(4);
                                        SourceCodeProcessor sourceCodeProcessor = new SourceCodeProcessor(pmdConfiguration);
                                        RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.getRulesetFactory(pmdConfiguration, new ResourceLoader());
                                        RuleSets ruleSets = RulesetsFactoryUtils.getRuleSetsWithBenchmark(pmdConfiguration.getRuleSets(), ruleSetFactory);

                                        PmdReviewService pmdReviewService = new PmdReviewService(sourceCodeProcessor, ruleSets);
                                        List<RuleViolation> review = pmdReviewService.review(bis, file);
                                        mapOfRuleViolation.put(file.getName(), review);

                                        Document document = new Document();
                                        try {
                                            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name.replace(".js", "") + ".pdf"));
                                            document.open();
                                            document.add(new Paragraph("Code Review For " + name + " on " + new Date()));

                                            //ZapfDingbatsList List Example
                                            ZapfDingbatsList zapfDingbatsList = new ZapfDingbatsList(43, 30);
                                            for (RuleViolation ruleViolation : review) {
                                                zapfDingbatsList.add(new ListItem("Begin Line : " + ruleViolation.getBeginColumn() +
                                                        "\nIssue : " + ruleViolation.getDescription()));
                                            }

                                            document.add(zapfDingbatsList);
                                            document.close();
                                            writer.close();
                                            bis.close();
                                        } catch (DocumentException e1) {
                                            e1.printStackTrace();
                                        } catch (FileNotFoundException e1) {
                                            e1.printStackTrace();
                                        }
                                    }
                                }
                            }

                            zipFile.close();
                        } catch (IOException ex) {
                            System.err.println(ex);
                        } finally {
                            setVisible(false);
                            parent.dispose();
                            System.exit(0);
                        }
                    }

                }
            }
        });
        jbtCancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
                parent.dispose();
                System.exit(0);
            }
        });
    }
}


public class StaticCodeAnalysis extends JFrame {


    private CodeReviewWindow passDialog;

    public StaticCodeAnalysis() {
        passDialog = new CodeReviewWindow(this, true);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                passDialog.setVisible(true);
            }
        });
    }

    public static void main(String[] args) {
        StaticCodeAnalysis staticCodeAnalysis = new StaticCodeAnalysis();

    }

}

Пробовал Используя SwingWorker, теперь приложение не застревает, но никогда возвращает что угодно, если в папке доступно более 7 файлов.

SwingWorker swingWorker = new SwingWorker() {

    @Override
    protected Object doInBackground() throws Exception {
        Random random = new Random();
        int progress = 0;
        setProgress(0);
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File file = new File(entry.getName());
            String name = file.getName();
            if (entry.isDirectory()) {
                continue;
            } else {
                // Same logic
                    BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                    InputStream ruleSetsInputStream = classLoader.getResourceAsStream("xml/javascript.xml");
                    File ruleSet = PmdReviewService.stream2file(ruleSetsInputStream, "javascript", ".xml");
                    PMDConfiguration pmdConfiguration = new PMDConfiguration();
                    pmdConfiguration.setReportFormat("text");
                    pmdConfiguration.setRuleSets(ruleSet.getPath());
                    pmdConfiguration.setThreads(4);
                    SourceCodeProcessor sourceCodeProcessor = new SourceCodeProcessor(pmdConfiguration);
                    RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.getRulesetFactory(pmdConfiguration, new ResourceLoader());
                    RuleSets ruleSets = RulesetsFactoryUtils.getRuleSetsWithBenchmark(pmdConfiguration.getRuleSets(), ruleSetFactory);

                    PmdReviewService pmdReviewService = new PmdReviewService(sourceCodeProcessor, ruleSets);
                    // Make random progress.
                    progress += random.nextInt(10);
                    setProgress(Math.min(progress, 100));
                    List<RuleViolation> review = pmdReviewService.review(bis, file);
                    mapOfRuleViolation.put(file.getName(), review);

                    Document document = new Document();
                    try {
                        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name.replace(".js", "") + ".pdf"));
                        document.open();
                        document.add(new Paragraph("Code Review For " + name + " on " + new Date()));

                        //ZapfDingbatsList List Example
                        ZapfDingbatsList zapfDingbatsList = new ZapfDingbatsList(43, 30);
                        for (RuleViolation ruleViolation : review) {
                            zapfDingbatsList.add(new ListItem("Begin Line : " + ruleViolation.getBeginColumn() +
                                    "\nIssue : " + ruleViolation.getDescription()));
                        }

                        document.add(zapfDingbatsList);
                        document.close();
                        writer.close();
                        bis.close();
                    } catch (DocumentException e1) {
                        e1.printStackTrace();
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    @Override
    protected void done() {
        try {
            zipFile.close();
            setProgress(100);
            setVisible(false);
            parent.dispose();
            System.exit(0);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        super.done();
    }
};

swingWorker.execute();
...