Example usage for org.apache.commons.io FileUtils cleanDirectory

List of usage examples for org.apache.commons.io FileUtils cleanDirectory

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils cleanDirectory.

Prototype

public static void cleanDirectory(File directory) throws IOException 

Source Link

Document

Cleans a directory without deleting it.

Usage

From source file:org.intermine.task.BuildDbTask.java

/**
 * {@inheritDoc}//from  w ww .j a  v a2s .c o  m
 */
@Override
public void execute() {
    try {
        try {
            FileUtils.cleanDirectory(tempDir);
        } catch (Exception e) {
            throw new BuildException("Could not clean up directory " + tempDir
                    + " before execution (this is required to stop Torque generation from "
                    + " picking up extraneous files)", e);
        }

        if (tempDir == null) {
            throw new BuildException("tempDir attribute is not set");
        }
        if (databaseAlias == null) {
            throw new BuildException("Could not find database attribute for: '" + os + ".db'");
        }
        if (database == null) {
            throw new BuildException("Could not access database: " + databaseAlias);
        }
        if (schemaFile == null) {
            throw new BuildException("schemaFile attribute is not set");
        }

        {
            Connection c = null;
            try {
                c = database.getConnection();
                c.setAutoCommit(true);
                DatabaseUtil.removeAllTables(c);
                DatabaseUtil.removeSequence(c, SERIAL_SEQUENCE_NAME);
                DatabaseUtil.removeSequence(c, ObjectStoreInterMineImpl.UNIQUE_INTEGER_SEQUENCE_NAME);
            } catch (SQLException e) {
                LOG.warn("Failed to remove all tables from database: " + e);
            } finally {
                if (c != null) {
                    try {
                        c.close();
                    } catch (SQLException e) {
                        LOG.error("Failed to close connection", e);
                    }
                }
            }
        }

        SQL sql = new SQL();
        sql.setControlTemplate("sql/base/Control.vm");
        sql.setOutputDirectory(tempDir);
        sql.setUseClasspath(true);
        //sql.setBasePathToDbProps("sql/base/");
        sql.setSqlDbMap(tempDir + "/sqldb.map");
        sql.setOutputFile("report.sql.generation");
        sql.setTargetDatabase(database.getPlatform().toLowerCase()); // "postgresql"
        InputStream schemaFileInputStream = getClass().getClassLoader().getResourceAsStream(schemaFile);
        if (schemaFileInputStream == null) {
            throw new BuildException("cannot open schema file (" + schemaFile + ")");
        }

        File tempFile;

        try {
            tempFile = File.createTempFile("schema", "xml", tempDir);

            PrintWriter writer = new PrintWriter(new FileWriter(tempFile));
            BufferedReader reader = new BufferedReader(new InputStreamReader(schemaFileInputStream));

            while (true) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                } else {
                    writer.println(line);
                }
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new BuildException("cannot create temporary file for BuildDbTask: " + e.getMessage());
        }

        sql.setXmlFile(tempFile.getPath());

        sql.execute();

        InsertSQL isql = new InsertSQL();
        isql.setDriver(database.getDriver()); // "org.postgresql.Driver"
        isql.setUrl(database.getURL()); // "jdbc:postgresql://localhost/test"
        isql.setUserid(database.getUser()); // "mark"
        isql.setPassword(database.getPassword()); // ""
        isql.setAutocommit(true);
        TorqueSQLExec.OnError ea = new TorqueSQLExec.OnError();
        ea.setValue("continue"); // "abort", "continue" or "stop"
        isql.setOnerror(ea);
        isql.setSqlDbMap(tempDir + "/sqldb.map");
        isql.setSrcDir(tempDir.toString());
        try {
            isql.execute();
        } catch (BuildException e) {
            throw new BuildException(e.getMessage() + " - for database: " + databaseAlias, e.getCause());
        }

        ea.setValue("abort"); // "abort", "continue" or "stop"
        isql.execute();

        Connection c = null;
        try {
            c = database.getConnection();
            c.setAutoCommit(true);
            c.createStatement().execute("CREATE SEQUENCE " + SERIAL_SEQUENCE_NAME);
        } catch (SQLException e) {
            // probably happens because the SEQUENCE already exists
            LOG.info("Failed to create SEQUENCE: " + e);
        } finally {
            if (c != null) {
                try {
                    c.close();
                } catch (SQLException e) {
                    LOG.error("Failed to close connection", e);
                }
            }
        }

        c = null;
        try {
            c = database.getConnection();
            c.setAutoCommit(true);
            c.createStatement()
                    .execute("CREATE SEQUENCE " + ObjectStoreInterMineImpl.UNIQUE_INTEGER_SEQUENCE_NAME);
        } catch (SQLException e) {
            // probably happens because the SEQUENCE already exists
            LOG.info("Failed to create SEQUENCE: " + e);
        } finally {
            if (c != null) {
                try {
                    c.close();
                } catch (SQLException e) {
                    LOG.error("Failed to close connection", e);
                }
            }
        }

        c = null;
        try {
            c = database.getConnection();
            c.setAutoCommit(true);
            c.createStatement().execute("ALTER TABLE " + CLOB_TABLE_NAME + " ALTER COLUMN " + CLOBVAL_COLUMN
                    + " SET STORAGE PLAIN");
        } catch (SQLException e) {
            // probably happens because the SEQUENCE already exists
            LOG.info("Failed to alter table " + CLOB_TABLE_NAME + ": " + e);
        } finally {
            if (c != null) {
                try {
                    c.close();
                } catch (SQLException e) {
                    LOG.error("Failed to close connection", e);
                }
            }
        }

        tempFile.delete();

        //create bagvalues table in userprofile
        if (model.contains("userprofile")) {
            c = null;
            try {
                c = database.getConnection();
                c.setAutoCommit(true);
                DatabaseUtil.createBagValuesTables(c);
            } catch (SQLException e) {
                LOG.info("Failed to create bagvalues table: " + e);
            } finally {
                if (c != null) {
                    try {
                        c.close();
                    } catch (SQLException e) {
                        LOG.error("Failed to close connection", e);
                    }
                }
            }
        }
    } finally {
        database.shutdown();
    }
}

From source file:org.interreg.docexplore.ServerConfigPanel.java

public ServerConfigPanel(final File config, final File serverDir) throws Exception {
    super(new LooseGridLayout(0, 1, 5, 5, true, false, SwingConstants.LEFT, SwingConstants.TOP, true, false));

    this.serverDir = serverDir;
    this.books = new Vector<Book>();
    this.bookList = new JList(new DefaultListModel());

    JPanel listPanel = new JPanel(new BorderLayout());
    listPanel.setBorder(BorderFactory.createTitledBorder(XMLResourceBundle.getBundledString("cfgBooksLabel")));
    bookList.setOpaque(false);//  www  . ja v  a  2 s  .co  m
    bookList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    bookList.setCellRenderer(new ListCellRenderer() {
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            Book book = (Book) value;
            JLabel label = new JLabel("<html><b>" + book.name + "</b> - " + book.nPages + " pages</html>");
            label.setOpaque(true);
            if (isSelected) {
                label.setBackground(TextToolbar.styleHighLightedBackground);
                label.setForeground(Color.white);
            }
            if (book.deleted)
                label.setForeground(Color.red);
            else if (!book.used)
                label.setForeground(Color.gray);
            return label;
        }
    });
    bookList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting())
                return;
            setFields((Book) bookList.getSelectedValue());
        }
    });
    JScrollPane scrollPane = new JScrollPane(bookList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setPreferredSize(new Dimension(500, 300));
    scrollPane.getVerticalScrollBar().setUnitIncrement(10);
    listPanel.add(scrollPane, BorderLayout.CENTER);

    JPanel importPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    importPanel.add(new JButton(new AbstractAction(XMLResourceBundle.getBundledString("cfgImportLabel")) {
        public void actionPerformed(ActionEvent e) {
            final File inFile = DocExploreTool.getFileDialogs().openFile(DocExploreTool.getIBookCategory());
            if (inFile == null)
                return;

            try {
                final File tmpDir = new File(serverDir, "tmp");
                tmpDir.mkdir();

                GuiUtils.blockUntilComplete(new ProgressRunnable() {
                    float[] progress = { 0 };

                    public void run() {
                        try {
                            ZipUtils.unzip(inFile, tmpDir, progress);
                        } catch (Exception ex) {
                            ErrorHandler.defaultHandler.submit(ex);
                        }
                    }

                    public float getProgress() {
                        return (float) progress[0];
                    }
                }, ServerConfigPanel.this);

                File tmpFile = new File(tmpDir, "index.tmp");
                ObjectInputStream input = new ObjectInputStream(new FileInputStream(tmpFile));
                String bookFile = input.readUTF();
                String bookName = input.readUTF();
                String bookDesc = input.readUTF();
                input.close();

                new PresentationImporter().doImport(ServerConfigPanel.this, bookName, bookDesc,
                        new File(tmpDir, bookFile));
                FileUtils.cleanDirectory(tmpDir);
                FileUtils.deleteDirectory(tmpDir);
                updateBooks();
            } catch (Exception ex) {
                ErrorHandler.defaultHandler.submit(ex);
            }
        }
    }));
    listPanel.add(importPanel, BorderLayout.SOUTH);
    add(listPanel);

    JPanel setupPanel = new JPanel(
            new LooseGridLayout(0, 1, 5, 5, true, false, SwingConstants.LEFT, SwingConstants.TOP, true, false));
    setupPanel.setBorder(
            BorderFactory.createTitledBorder(XMLResourceBundle.getBundledString("cfgBookInfoLabel")));
    usedBox = new JCheckBox(XMLResourceBundle.getBundledString("cfgUseLabel"));
    usedBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Book book = (Book) bookList.getSelectedValue();
            if (book != null) {
                book.used = usedBox.isSelected();
                bookList.repaint();
            }
        }
    });
    setupPanel.add(usedBox);

    JPanel fieldPanel = new JPanel(new LooseGridLayout(0, 2, 5, 5, false, false, SwingConstants.LEFT,
            SwingConstants.TOP, true, false));
    fieldPanel.add(new JLabel(XMLResourceBundle.getBundledString("cfgTitleLabel")));
    nameField = new JTextField(50);
    nameField.getDocument().addDocumentListener(new DocumentListener() {
        public void removeUpdate(DocumentEvent e) {
            changedUpdate(e);
        }

        public void insertUpdate(DocumentEvent e) {
            changedUpdate(e);
        }

        public void changedUpdate(DocumentEvent e) {
            Book book = (Book) bookList.getSelectedValue();
            if (book == null)
                return;
            book.name = nameField.getText();
            bookList.repaint();
        }
    });
    fieldPanel.add(nameField);

    fieldPanel.add(new JLabel(XMLResourceBundle.getBundledString("cfgDescriptionLabel")));
    descField = new JTextPane();
    //descField.setWrapStyleWord(true);
    descField.getDocument().addDocumentListener(new DocumentListener() {
        public void removeUpdate(DocumentEvent e) {
            changedUpdate(e);
        }

        public void insertUpdate(DocumentEvent e) {
            changedUpdate(e);
        }

        public void changedUpdate(DocumentEvent e) {
            Book book = (Book) bookList.getSelectedValue();
            if (book == null)
                return;
            book.desc = descField.getText();
        }
    });
    scrollPane = new JScrollPane(descField, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setPreferredSize(new Dimension(420, 50));
    scrollPane.getVerticalScrollBar().setUnitIncrement(10);
    fieldPanel.add(scrollPane);

    setupPanel.add(fieldPanel);

    exportButton = new JButton(new AbstractAction(XMLResourceBundle.getBundledString("cfgExportLabel")) {
        public void actionPerformed(ActionEvent e) {
            File file = DocExploreTool.getFileDialogs().saveFile(DocExploreTool.getIBookCategory());
            if (file == null)
                return;
            final Book book = (Book) bookList.getSelectedValue();
            final File indexFile = new File(serverDir, "index.tmp");
            try {
                final File outFile = file;
                ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(indexFile));
                out.writeUTF(book.bookFile.getName());
                out.writeUTF(book.name);
                out.writeUTF(book.desc);
                out.close();

                GuiUtils.blockUntilComplete(new ProgressRunnable() {
                    float[] progress = { 0 };

                    public void run() {
                        try {
                            ZipUtils.zip(serverDir, new File[] { indexFile, book.bookFile, book.bookDir },
                                    outFile, progress, 0, 1, 9);
                        } catch (Exception ex) {
                            ErrorHandler.defaultHandler.submit(ex);
                        }
                    }

                    public float getProgress() {
                        return (float) progress[0];
                    }
                }, ServerConfigPanel.this);
            } catch (Exception ex) {
                ErrorHandler.defaultHandler.submit(ex);
            }
            if (indexFile.exists())
                indexFile.delete();
        }
    });
    deleteButton = new JButton(new AbstractAction(XMLResourceBundle.getBundledString("cfgDeleteRestoreLabel")) {
        public void actionPerformed(ActionEvent e) {
            Book book = (Book) bookList.getSelectedValue();
            if (book == null)
                return;
            book.deleted = !book.deleted;
            bookList.repaint();
        }
    });

    JPanel actionsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    actionsPanel.add(exportButton);
    actionsPanel.add(deleteButton);
    setupPanel.add(actionsPanel);

    add(setupPanel);

    JPanel optionsPanel = new JPanel(new LooseGridLayout(0, 2, 5, 5, false, false, SwingConstants.LEFT,
            SwingConstants.TOP, true, false));
    optionsPanel
            .setBorder(BorderFactory.createTitledBorder(XMLResourceBundle.getBundledString("cfgOptionsLabel")));
    JPanel timeoutPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    timeoutField = new JTextField(5);
    timeoutPanel.add(timeoutField);
    timeoutPanel.add(new JLabel(XMLResourceBundle.getBundledString("cfgTimeoutLabel")));
    optionsPanel.add(timeoutPanel);
    add(optionsPanel);

    updateBooks();
    setFields(null);

    final String xml = config.exists() ? StringUtils.readFile(config) : "<config></config>";
    String idle = StringUtils.getTagContent(xml, "idle");
    if (idle != null)
        try {
            timeoutField.setText("" + Integer.parseInt(idle));
        } catch (Throwable e) {
        }
}

From source file:org.itstechupnorth.walrus.unpack.ArchiveArticleProcessorTest.java

@Override
protected void setUp() throws Exception {
    directory = new File("target/tests/processors");
    directory.mkdirs();/* w  ww  .j a  v  a2  s  .com*/
    FileUtils.cleanDirectory(directory);
    processor = new ArchiveArticleProcessor(directory, 4);
}

From source file:org.jahia.configuration.configurators.JahiaGlobalConfigurator.java

private void cleanDirectory(File toDelete) {
    if (toDelete.exists()) {
        try {//  www . j  a  v  a 2s .  c  om
            FileUtils.cleanDirectory(toDelete);
        } catch (IOException e) {
            getLogger().error(
                    "Error deleting content of the folder '" + toDelete + "'. Cause: " + e.getMessage(), e);
        }
    }
}

From source file:org.jahia.configuration.deployers.jboss.DriverDeploymentHelper.java

public static boolean deploy(File targetServerDirectory, File driverJar) throws IOException {
    String driverKey = getDriverKey(driverJar.getName());
    String driverType = getDriverType(driverKey, driverJar.getName());
    File targetDir = new File(targetServerDirectory, "/modules/org/jahia/jdbc/" + driverType + "/main");
    boolean inPlace = targetDir.equals(driverJar.getParentFile());
    if (targetDir.isDirectory()) {
        // special case for the second JAR of the Oracle driver
        // second test is for the case driver JAR is already in-place (used only in configurators to configure module.xml)
        if (!"oracle".equals(driverType) && !inPlace) {
            FileUtils.cleanDirectory(targetDir);
        }/* ww  w .  j  a  v  a  2  s  .  c om*/
    } else {
        if (!targetDir.mkdirs()) {
            throw new IOException("Unable to create target directory: " + targetDir);
        }
    }

    if (!inPlace) {
        FileUtils.copyFileToDirectory(driverJar, targetDir);
    }

    File moduleXml = new File(targetDir, "module.xml");
    String existingContent = moduleXml.isFile() ? FileUtils.readFileToString(moduleXml, FILE_CONTENT_ENCODING)
            : null;
    FileUtils.writeStringToFile(moduleXml,
            generateModuleXmlContent(existingContent, driverJar.getName(), driverType), FILE_CONTENT_ENCODING);

    return Boolean.TRUE;
}

From source file:org.jahia.services.content.impl.jackrabbit.RepositoryMigrator.java

private void swapRepositoryHome(File repoHomeCopy) throws IOException {
    String repoHomePath = repoHome.getAbsolutePath();
    try {/*from  ww w  . j a  v a  2  s .c om*/
        if (keepBackup) {
            File backupDir = new File(repoHome.getParentFile(), "repository-original");
            FileUtils.moveDirectory(repoHome, backupDir);
            logger.info("Backup of the source repository folder at {}", backupDir);
        } else {
            try {
                FileUtils.deleteDirectory(repoHome);
            } catch (IOException e) {
                logger.warn("Issue while deleting the " + repoHomePath + " directory, we will try to empty it");
                FileUtils.cleanDirectory(repoHome);
            }
        }

        FileUtils.moveDirectory(repoHomeCopy, repoHome);
    } catch (IOException e) {
        logger.error("The migration was successful, except the last step: we are unable to delete directory {}."
                + " Jahia server will be stopped now.", repoHomePath);
        String repoHomeCopyPath = repoHomeCopy.getAbsolutePath();
        logger.error(
                "Please delete the directory {} manually (perhaps an OS reboot is required to free the file locks)"
                        + " and copy the content of {} to {}",
                new String[] { repoHomePath, repoHomeCopyPath, repoHomePath });
        logger.error(
                "Also delete the following folders if they are present:\n{}\\index\n{}\\workspaces\\default\\index\n{}\\workspaces\\live\\index",
                new String[] { repoHomePath, repoHomePath, repoHomePath });

        logger.error("Start Jahia server afterwards.",
                new String[] { repoHomePath, repoHomeCopyPath, repoHomePath });
        System.exit(1);
    }

    logger.info("Replaced repository with the migrated copy");
}

From source file:org.jahia.services.render.filter.StaticAssetsFilter.java

private void performPurgeIfNeeded() {
    if (!generatedResourcesFolder.isDirectory()) {
        return;//from ww w  . j a v  a2 s.c o  m
    }
    File marker = new File(SettingsBean.getInstance().getJahiaVarDiskPath(), "[generated-resources].dodelete");
    if (marker.exists()) {
        logger.info("Cleaning existing generated resources folder {}", generatedResourcesFolder);
        try {
            FileUtils.cleanDirectory(generatedResourcesFolder);
            FileUtils.deleteQuietly(marker);
        } catch (IOException e) {
            logger.warn(
                    "Unable to purge content of the generated resources folder: " + generatedResourcesFolder,
                    e);
        }
    }
}

From source file:org.jamon.integration.TestBase.java

protected void clearWorkDir() throws IOException {
    FileUtils.cleanDirectory(new File(WORK_DIR));
}

From source file:org.jasig.cas.services.JsonServiceRegistryDaoTests.java

@BeforeClass
public static void prepTests() throws Exception {
    FileUtils.cleanDirectory(RESOURCE.getFile());
}

From source file:org.jasig.resource.aggr.ResourcesAggregatorImplTest.java

/**
 * Delete our temp directory after test execution.
 * @throws Exception/*from w  w  w  .j  a v  a 2  s  .c o m*/
 */
@After
public void cleanupTempDir() throws Exception {
    String testOutputDirectoryName = tempDirLocal.get();
    tempDirLocal.remove();
    File testOutputDirectory = new File(testOutputDirectoryName);
    FileUtils.cleanDirectory(testOutputDirectory);
    FileUtils.deleteDirectory(testOutputDirectory);
}