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

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

Introduction

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

Prototype

public static void forceMkdir(File directory) throws IOException 

Source Link

Document

Makes a directory, including any necessary but nonexistent parent directories.

Usage

From source file:hu.bme.mit.sette.common.tasks.RunResultParser.java

public final void parse() throws Exception {
    if (!RunnerProjectUtils.getRunnerLogFile(getRunnerProjectSettings()).exists()) {
        throw new SetteGeneralException("Run the tool on the runner project first");
    }/*w w w .  java  2s .co  m*/

    // foreach containers
    for (SnippetContainer container : getSnippetProject().getModel().getContainers()) {
        // skip container with higher java version than supported
        if (container.getRequiredJavaVersion().compareTo(getTool().getSupportedJavaVersion()) > 0) {
            // TODO error/warning handling
            System.err.println("Skipping container: " + container.getJavaClass().getName()
                    + " (required Java version: " + container.getRequiredJavaVersion() + ")");
            continue;
        }

        // foreach snippets
        for (Snippet snippet : container.getSnippets().values()) {
            SnippetInputsXml inputsXml = parseSnippet(snippet);
            try {
                // TODO further validation
                inputsXml.validate();

                File inputsXmlFile = RunnerProjectUtils.getSnippetInputsFile(getRunnerProjectSettings(),
                        snippet);

                FileUtils.forceMkdir(inputsXmlFile.getParentFile());

                if (inputsXmlFile.exists()) {
                    FileUtils.forceDelete(inputsXmlFile);
                }

                Serializer serializer = new Persister(new AnnotationStrategy(),
                        new Format("<?xml version=\"1.0\" encoding= \"UTF-8\" ?>"));
                serializer.write(inputsXml, inputsXmlFile);
            } catch (ValidatorException e) {
                System.err.println(e.getFullMessage());
            }
        }
    }
}

From source file:edu.uci.ics.pregelix.example.jobrun.RunJobTestSuite.java

public void setUp() throws Exception {
    ClusterConfig.setStorePath(PATH_TO_CLUSTER_STORE);
    ClusterConfig.setClusterPropertiesPath(PATH_TO_CLUSTER_PROPERTIES);
    cleanupStores();//  w ww  .j a  v  a 2  s. c o m
    PregelixHyracksIntegrationUtil.init();
    LOGGER.info("Hyracks mini-cluster started");
    FileUtils.forceMkdir(new File(ACTUAL_RESULT_DIR));
    FileUtils.cleanDirectory(new File(ACTUAL_RESULT_DIR));
    startHDFS();
}

From source file:ca.uviccscu.lp.utils.Utils.java

@Deprecated
public static boolean checkDir(File f) {
    l.trace("Checking dir: " + f.getAbsolutePath());
    try {//from  w ww  .  j a  va2 s  .c o m
        boolean a = f.isDirectory();
        if (a) {
            if (f.listFiles().length != 0) {
                l.error("Directory not empty");
                //JDialog jd = new JDialog((JFrame) null, true);
                int resp = JOptionPane.showConfirmDialog(null,
                        "Directory nonempty: " + f.getAbsolutePath() + ". Proceed? (will wipe)",
                        "Confirm deletion", JOptionPane.YES_NO_OPTION);
                if (resp == JOptionPane.YES_OPTION) {
                    FileUtils.deleteDirectory(f);
                } else {
                    l.fatal("Delete denied");
                    System.exit(1);
                }
            }
        }
        FileUtils.forceMkdir(f);
        File test = new File(f.getAbsolutePath() + File.separator + "test.file");
        boolean c = test.createNewFile();
        return c;
    } catch (Exception e) {
        l.fatal("Az directory creation error", e);
        return false;
    }
}

From source file:net.firejack.platform.generate.service.BaseGeneratorService.java

protected void generate(iPad base, String template, File dir, String extension) throws IOException {
    String filePosition = base.getFilePosition();
    if (StringUtils.isNotBlank(filePosition)) {
        filePosition = render.replace(filePosition);
        dir = new File(dir, filePosition);
    }/*from w  ww.ja v a  2s  . com*/
    FileUtils.forceMkdir(dir);
    generator.compose(template, base, new File(dir, base.getName() + extension));
}

From source file:com.norconex.jef4.status.FileJobStatusStore.java

private void resolveDirs() {
    String path = statusDir;//from w w  w  .  ja va  2 s.  co  m
    if (StringUtils.isBlank(statusDir)) {
        LOG.info("No status directory specified.");
        path = JEFUtil.FALLBACK_WORKDIR.getAbsolutePath();
    } else {
        path = new File(path).getAbsolutePath();
    }
    LOG.debug("Status serialization directory: " + path);
    jobdirLatest = path + File.separatorChar + "latest" + File.separatorChar + "status";
    jobdirBackupBase = path + "/backup";
    File dir = new File(jobdirLatest);
    if (!dir.exists()) {
        try {
            FileUtils.forceMkdir(dir);
        } catch (IOException e) {
            throw new JEFException("Cannot create status directory: " + dir, e);
        }
    }
}

From source file:ml.shifu.shifu.util.CommonUtilsTest.java

public void syncTest() throws IOException {
    ModelConfig config = ModelConfig.createInitModelConfig(".", ALGORITHM.NN, "test", false);
    config.setModelSetName("testModel");

    jsonMapper.writerWithDefaultPrettyPrinter().writeValue(new File("ModelConfig.json"), config);

    ColumnConfig col = new ColumnConfig();
    col.setColumnName("ColumnA");
    List<ColumnConfig> columnConfigList = new ArrayList<ColumnConfig>();
    columnConfigList.add(col);/* w  w w.j ava  2 s .co  m*/

    config.getDataSet().setSource(SourceType.LOCAL);
    ;

    jsonMapper.writerWithDefaultPrettyPrinter().writeValue(new File("ColumnConfig.json"), columnConfigList);

    File file = null;
    file = new File("models");
    if (!file.exists()) {
        FileUtils.forceMkdir(file);
    }

    file = new File("models/model1.nn");
    if (!file.exists()) {
        if (file.createNewFile()) {
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(file), Constants.DEFAULT_CHARSET));
            writer.write("test string");
            writer.close();
        } else {
            LOG.warn("Create file {} failed", file.getAbsolutePath());
        }
    }

    file = new File("EvalSets/test");
    if (!file.exists()) {
        FileUtils.forceMkdir(file);
    }

    file = new File("EvalSets/test/EvalConfig.json");
    if (!file.exists()) {
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(file), Constants.DEFAULT_CHARSET));
        writer.write("test string");
        writer.close();
    }

    CommonUtils.copyConfFromLocalToHDFS(config, new PathFinder(config));

    file = new File("ModelSets");
    Assert.assertTrue(file.exists());

    file = new File("ModelSets/testModel");
    Assert.assertTrue(file.exists());

    file = new File("ModelSets/testModel/ModelConfig.json");
    Assert.assertTrue(file.exists());

    file = new File("ModelSets/testModel/ColumnConfig.json");
    Assert.assertTrue(file.exists());

    file = new File("ModelSets/testModel/ReasonCodeMap.json");
    Assert.assertTrue(file.exists());

    file = new File("ModelSets/testModel/models/model1.nn");
    Assert.assertTrue(file.exists());

    file = new File("ModelSets/testModel/EvalSets/test/EvalConfig.json");
    Assert.assertTrue(file.exists());

    file = new File("ModelSets");
    if (file.exists()) {
        FileUtils.deleteDirectory(file);
    }

    file = new File("ColumnConfig.json");
    FileUtils.deleteQuietly(file);

    file = new File("ModelConfig.json");
    FileUtils.deleteQuietly(file);

    FileUtils.deleteDirectory(new File("models"));
    FileUtils.deleteDirectory(new File("EvalSets"));
}

From source file:com.norconex.jef4.log.FileLogManager.java

private void resolveDirs() {
    String path = logdir;//from  w ww.ja v  a2 s.c  o  m
    if (StringUtils.isBlank(logdir)) {
        path = JEFUtil.FALLBACK_WORKDIR.getAbsolutePath();
    } else {
        path = new File(path).getAbsolutePath();
    }

    LOG.debug("Log directory: " + path);
    logdirLatest = path + File.separatorChar + "latest" + File.separatorChar + "logs";
    logdirBackupBase = path + "/backup";
    File dir = new File(logdirLatest);
    if (!dir.exists()) {
        if (!dir.exists()) {
            try {
                FileUtils.forceMkdir(dir);
            } catch (IOException e) {
                throw new JEFException("Cannot create log directory: " + logdirLatest, e);
            }
        }
    }
}

From source file:marytts.language.de.JPhonemiser.java

public void startup() throws Exception {
    super.startup();
    phonemiseDenglish = new PhonemiseDenglish(this);
    inflection = new Inflection();

    if (MaryProperties.getBoolean("de.phonemiser.logunknown")) {
        String logBasepath = MaryProperties.maryBase() + File.separator + "log" + File.separator;
        File logDir = new File(logBasepath);
        try {/*from  ww  w . j av  a2s .  c o  m*/
            if (!logDir.isDirectory()) {
                logger.info("Creating log directory " + logDir.getCanonicalPath());
                FileUtils.forceMkdir(logDir);
            }
            logUnknownFileName = MaryProperties.getFilename("de.phonemiser.logunknown.filename",
                    logBasepath + "de_unknown.txt");
            unknown2Frequency = new HashMap<String, Integer>();
            logEnglishFileName = MaryProperties.getFilename("de.phonemiser.logenglish.filename",
                    logBasepath + "de_english-words.txt");
            english2Frequency = new HashMap<String, Integer>();
        } catch (IOException e) {
            logger.info("Could not create log directory " + logDir.getCanonicalPath() + " Logging disabled!",
                    e);
        }
    }
    if (MaryProperties.getBoolean("de.phonemiser.useenglish")) {
        InputStream usLexStream = MaryProperties.getStream("en_US.lexicon");
        if (usLexStream != null) {
            try {
                usEnglishLexicon = new FSTLookup(usLexStream, MaryProperties.getProperty("en_US.lexicon"));
            } catch (Exception e) {
                logger.info("Cannot load English lexicon '" + MaryProperties.getProperty("en_US.lexicon") + "'",
                        e);
            }
        }
    }
}

From source file:io.stallion.boot.NewJavaPluginRunAction.java

public void makeNewApp(String javaFolder) throws Exception {
    targetFolder = javaFolder;//from w  w w.j  av  a2s  .  c om

    templating = new JinjaTemplating(targetFolder, false);

    setGroupId(promptForInputOfLength("What is the maven group name? ", 5));
    setPluginName(
            promptForInputOfLength("What is the plugin package name (will be appended to the groupid)? ", 2));
    setArtifactId(promptForInputOfLength("What maven artifact id? ", 5));

    setPluginNameTitleCase(getPluginName().substring(0, 1).toUpperCase() + getPluginName().substring(1));
    setJavaPackageName(getGroupId() + "." + getPluginName());

    File dir = new File(javaFolder);
    if (!dir.isDirectory()) {
        FileUtils.forceMkdir(dir);
    }

    String sourceFolder = "/src/main/java/" + getJavaPackageName().replaceAll("\\.", "/");
    List<String> paths = list(targetFolder + "/src/main/resources", targetFolder + "/src/main/resources/sql",
            targetFolder + "/src/test/resources",
            targetFolder + "/src/main/java/" + getJavaPackageName().replaceAll("\\.", "/"),
            targetFolder + "/src/test/java/" + getJavaPackageName().replaceAll("\\.", "/"));
    for (String path : paths) {
        File file = new File(path);
        if (!file.isDirectory()) {
            FileUtils.forceMkdir(file);
        }
    }
    new File(targetFolder + "/src/main/resources/sql/migrations.txt").createNewFile();

    Map ctx = map(val("config", this));
    copyTemplate("/templates/wizard/pom.xml.jinja", "pom.xml", ctx);
    copyTemplate("/templates/wizard/PluginBooter.java.jinja",
            sourceFolder + "/" + pluginNameTitleCase + "Plugin.java", ctx);
    copyTemplate("/templates/wizard/PluginSettings.java.jinja",
            sourceFolder + "/" + pluginNameTitleCase + "Settings.java", ctx);
    copyTemplate("/templates/wizard/MainRunner.java.jinja", sourceFolder + "/MainRunner.java", ctx);
    copyTemplate("/templates/wizard/Endpoints.java.jinja", sourceFolder + "/Endpoints.java", ctx);
    copyTemplate("/templates/wizard/build.py.jinja", "build.py", ctx);
    copyTemplate("/templates/wizard/run-dev.jinja", "run-dev.sh", ctx);

    Files.setPosixFilePermissions(FileSystems.getDefault().getPath(targetFolder + "/build.py"),
            set(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ,
                    PosixFilePermission.OWNER_WRITE));
    Files.setPosixFilePermissions(FileSystems.getDefault().getPath(targetFolder + "/run-dev.sh"),
            set(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ,
                    PosixFilePermission.OWNER_WRITE));
    copyFile("/templates/wizard/app.bundle", "src/main/resources/assets/app.bundle");
    copyFile("/templates/wizard/app.js", "src/main/resources/assets/app.js");
    copyFile("/templates/wizard/app.scss", "src/main/resources/assets/app.scss");
    copyFile("/templates/wizard/file1.js", "src/main/resources/assets/common/file1.js");
    copyFile("/templates/wizard/file2.js", "src/main/resources/assets/common/file2.js");
    copyFile("/assets/vendor/jquery-1.11.3.js", "src/main/resources/assets/vendor/jquery-1.11.3.js");
    copyFile("/assets/basic/stallion.js", "src/main/resources/assets/vendor/stallion.js");
    copyFile("/templates/wizard/app.jinja", "src/main/resources/templates/app.jinja");

}

From source file:com.etsy.arbiter.OozieWorkflowGenerator.java

/**
 * Generate Oozie workflows from Arbiter workflows
 *
 * @param outputBase The directory in which to output the Oozie workflows
 * @param workflows The workflows to convert
 * @param generateGraphviz Indicate if Graphviz graphs should be generated for workflows
 * @param graphvizFormat The format in which Graphviz graphs should be generated if enabled
 *//*from  w w w  . j ava 2s . c  o  m*/
public void generateOozieWorkflows(String outputBase, List<Workflow> workflows, boolean generateGraphviz,
        String graphvizFormat) throws IOException, ParserConfigurationException, TransformerException {
    File outputBaseFile = new File(outputBase);
    FileUtils.forceMkdir(outputBaseFile);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    Date currentDate = new Date();
    String currentDateString = DATE_FORMAT.format(currentDate);

    for (Workflow workflow : workflows) {
        String outputDir = outputBase + "/" + workflow.getName();
        File outputDirFile = new File(outputDir);
        FileUtils.forceMkdir(outputDirFile);
        DirectedAcyclicGraph<Action, DefaultEdge> workflowGraph = null;

        try {
            workflowGraph = WorkflowGraphBuilder.buildWorkflowGraph(workflow, config, outputDir,
                    generateGraphviz, graphvizFormat);
        } catch (WorkflowGraphException w) {
            LOG.error("Unable to generate workflow", w);
            System.exit(1);
        }

        if (generateGraphviz) {
            GraphvizGenerator.generateGraphviz(workflowGraph, outputDir + "/" + workflow.getName() + ".dot",
                    graphvizFormat);
        }

        Document xmlDoc = builder.newDocument();

        Directives directives = new Directives();
        createRootElement(workflow.getName(), directives);

        Action kill = getActionByType(workflowGraph, "kill");
        Action end = getActionByType(workflowGraph, "end");
        Action start = getActionByType(workflowGraph, "start");
        Action errorHandler = workflow.getErrorHandler();
        Action finalTransition = kill == null ? end : kill;

        Action errorTransition = errorHandler == null ? (kill == null ? end : kill) : errorHandler;
        DepthFirstIterator<Action, DefaultEdge> iterator = new DepthFirstIterator<>(workflowGraph, start);

        while (iterator.hasNext()) {
            Action a = iterator.next();
            Action transition = getTransition(workflowGraph, a);
            switch (a.getType()) {
            case "start":
                if (transition == null) {
                    throw new RuntimeException("No transition found for start action");
                }
                directives.add("start").attr("to", transition.getName()).up();
                break;
            case "end":
                // Skip and add at the end
                break;
            case "fork":
                directives.add("fork").attr("name", a.getName());
                for (DefaultEdge edge : workflowGraph.outgoingEdgesOf(a)) {
                    Action target = workflowGraph.getEdgeTarget(edge);
                    directives.add("path").attr("start", target.getName()).up();
                }
                directives.up();
                break;
            case "join":
                if (transition == null) {
                    throw new RuntimeException(
                            String.format("No transition found for join action %s", a.getName()));
                }
                directives.add("join").attr("name", a.getName()).attr("to", transition.getName()).up();
                break;
            default:
                createActionElement(a, workflowGraph, transition,
                        a.equals(errorHandler) ? finalTransition : errorTransition, directives);
                directives.up();
                break;
            }
        }
        if (kill != null) {
            directives.add("kill").attr("name", kill.getName()).add("message")
                    .set(kill.getNamedArgs().get("message")).up().up();
        }
        if (end != null) {
            directives.add("end").attr("name", end.getName()).up();
        }

        try {
            new Xembler(directives).apply(xmlDoc);
        } catch (ImpossibleModificationException e) {
            throw new RuntimeException(e);
        }
        writeDocument(outputDirFile, xmlDoc, transformer, workflow.getName(), currentDateString);
    }
}