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:de.tudarmstadt.ukp.dkpro.core.api.resources.ResourceUtils.java

/**
 * Make a given classpath location available as a folder. A temporary folder is created and
 * deleted upon a regular shutdown of the JVM. This method must not be used for creating
 * executable binaries. For this purpose, getUrlAsExecutable should be used.
 *
 * @param aClasspathBase//ww w .  j a  v a 2 s. c o  m
 *            a classpath location as used by
 *            {@link PathMatchingResourcePatternResolver#getResources(String)}
 * @param aCache
 *            use the cache or not.
 * @see PathMatchingResourcePatternResolver
 */
public static File getClasspathAsFolder(String aClasspathBase, boolean aCache) throws IOException {
    synchronized (classpathFolderCache) {
        File folder = classpathFolderCache.get(aClasspathBase);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        if (!aCache || (folder == null) || !folder.exists()) {
            folder = File.createTempFile("dkpro-package", "");
            folder.delete();
            FileUtils.forceMkdir(folder);

            Resource[] roots = resolver.getResources(aClasspathBase);
            for (Resource root : roots) {
                String base = root.getURL().toString();
                Resource[] resources = resolver.getResources(base + "/**/*");
                for (Resource resource : resources) {
                    if (!resource.isReadable()) {
                        // This is true for folders/packages
                        continue;
                    }

                    // Relativize
                    String res = resource.getURL().toString();
                    if (!res.startsWith(base)) {
                        throw new IOException("Resource location does not start with base location");
                    }
                    String relative = resource.getURL().toString().substring(base.length());

                    // Make sure the target folder exists
                    File target = new File(folder, relative).getAbsoluteFile();
                    if (target.getParentFile() != null) {
                        FileUtils.forceMkdir(target.getParentFile());
                    }

                    // Copy data
                    InputStream is = null;
                    OutputStream os = null;
                    try {
                        is = resource.getInputStream();
                        os = new FileOutputStream(target);
                        IOUtils.copyLarge(is, os);
                    } finally {
                        IOUtils.closeQuietly(is);
                        IOUtils.closeQuietly(os);
                    }

                    // WORKAROUND: folders get written as files if inside jars
                    // delete files of size zero
                    if (target.length() == 0) {
                        FileUtils.deleteQuietly(target);
                    }
                }
            }

            if (aCache) {
                classpathFolderCache.put(aClasspathBase, folder);
            }
        }

        return folder;
    }
}

From source file:edu.isi.wings.execution.engine.api.impl.pegasus.PegasusExecutionEngine.java

@Override
public void execute(RuntimePlan exe) {
    String pegasusHome = props.getProperty("pegasus.home") + File.separator;
    String siteCatalog = props.getProperty("pegasus.site-catalog");
    String site = props.getProperty("pegasus.site", "local");
    String storageDir = props.getProperty("pegasus.storage-dir", FileUtils.getTempDirectoryPath())
            + File.separator;/*from  ww w  .  j  a  v a2  s .  com*/

    try {
        // Create base directory
        File baseDir = new File(storageDir + exe.getName());
        FileUtils.forceMkdir(baseDir);

        this.baseDir = baseDir.getAbsolutePath() + File.separator;
        this.adapter = new PegasusWorkflowAdapter(this.props);

        String submitDir = this.baseDir + "submit" + File.separator;

        // Construct Pegasus Workflow, and submit it for execution
        this.adapter.runWorkflow(exe, siteCatalog, site, this.baseDir);

        // Start Monitoring thread
        this.monitoringThread = new Thread(
                new ExecutionMonitoringThread(this, exe, logger, monitor, submitDir, pegasusHome));
        this.monitoringThread.start();

    } catch (Exception e) {
        exe.onEnd(this.logger, RuntimeInfo.Status.FAILURE, e.getMessage());
        log.error(e.getMessage(), e);
    }

}

From source file:com.turn.griffin.GriffinLibCacheUtil.java

public GriffinLibCacheUtil(String myServerId) {

    Preconditions.checkState(!StringUtils.isBlank(myServerId), "Server Id is not defined");
    this.myServerId = myServerId;

    /* Create lib cached dir */
    if (!new File(getLibCacheDirectory()).exists()) {
        try {// w w w. jav a 2s.c  o m
            FileUtils.forceMkdir(new File(getLibCacheDirectory()));
        } catch (IOException ioe) {
            logger.error(String.format("Unable to create local file repository %s", getLibCacheDirectory()),
                    ioe);
            Preconditions.checkState(false);
        }
    }

    this.globalLatestFileInfo = this.getLatestLocalFileInfo();

}

From source file:com.redhat.victims.VictimsConfig.java

/**
 * Get the configured cache directory. If the directory does not exist, it
 * will be created.//  w  w w  .  ja  v a  2 s  .  c  om
 * 
 * @return
 * @throws VictimsException
 */
public static File home() throws VictimsException {
    File directory = new File(getPropertyValue(Key.HOME));
    if (!directory.exists()) {
        try {
            FileUtils.forceMkdir(directory);
        } catch (IOException e) {
            throw new VictimsException("Could not create home directory.", e);
        }
    }
    return directory;
}

From source file:hoot.services.ingest.MultipartSerializer.java

protected void _serializeFGDB(List<FileItem> fileItemsList, String jobId, Map<String, String> uploadedFiles,
        Map<String, String> uploadedFilesPaths) throws Exception {
    Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
    Map<String, String> folderMap = new HashMap<String, String>();

    while (fileItemsIterator.hasNext()) {
        FileItem fileItem = fileItemsIterator.next();
        String fileName = fileItem.getName();

        String relPath = FilenameUtils.getPath(fileName);
        if (relPath.endsWith("/")) {
            relPath = relPath.substring(0, relPath.length() - 1);
        }/*  w w  w .j a v a 2  s.  com*/
        fileName = FilenameUtils.getName(fileName);

        String fgdbFolderPath = homeFolder + "/upload/" + jobId + "/" + relPath;

        String pathVal = folderMap.get(fgdbFolderPath);
        if (pathVal == null) {
            File folderPath = new File(fgdbFolderPath);
            FileUtils.forceMkdir(folderPath);
            folderMap.put(fgdbFolderPath, relPath);
        }

        if (fileName == null) {
            ResourceErrorHandler.handleError("A valid file name was not specified.", Status.BAD_REQUEST, log);
        }

        String uploadedPath = fgdbFolderPath + "/" + fileName;
        File file = new File(uploadedPath);
        fileItem.write(file);
    }

    Iterator it = folderMap.entrySet().iterator();
    while (it.hasNext()) {
        String nameOnly = "";
        Map.Entry pairs = (Map.Entry) it.next();
        String fgdbName = pairs.getValue().toString();
        String[] nParts = fgdbName.split("\\.");

        for (int i = 0; i < nParts.length - 1; i++) {
            if (nameOnly.length() > 0) {
                nameOnly += ".";
            }
            nameOnly += nParts[i];
        }
        uploadedFiles.put(nameOnly, "GDB");
        uploadedFilesPaths.put(nameOnly, fgdbName);
    }
}

From source file:eu.openanalytics.rsb.component.DirectoryDepositHandlerTestCase.java

@Test
public void handleJobWithZipFile() throws Exception {
    final File jobParentFile = new File(FileUtils.getTempDirectory(), UUID.randomUUID().toString());
    FileUtils.forceMkdir(jobParentFile);

    final File zipJobFile = File.createTempFile("test-", ".zip", jobParentFile);
    FileUtils.copyInputStreamToFile(/*from  ww w  .j  av  a 2  s  .co  m*/
            Thread.currentThread().getContextClassLoader().getResourceAsStream("data/r-job-sample.zip"),
            zipJobFile);

    testHandleJob(jobParentFile, zipJobFile);
}

From source file:de.tudarmstadt.ukp.csniper.treevisualizer.TreeVisualizer.java

@Override
public void initialize(UimaContext aContext) throws ResourceInitializationException {
    super.initialize(aContext);

    try {//  w  w  w  .j  a v  a2 s.  co  m
        FileUtils.forceMkdir(targetLocation);
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }
}

From source file:com.l2jfree.lang.L2System.java

public static void dumpHeap(boolean live) {
    try {/*from   w  ww. j a v a2  s . co  m*/
        FileUtils.forceMkdir(new File("log/heapdumps"));

        final L2TextBuilder tb = new L2TextBuilder();
        tb.append("log/heapdumps/HeapDump_");
        tb.append(new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date()));
        tb.append("_uptime-").append(L2Config.getShortUptime());
        if (live)
            tb.append("_live");
        tb.append(".hprof");

        final String dumpFile = tb.moveToString();

        HotSpotDiagnosticMXBeanHolder.INSTANCE.dumpHeap(dumpFile, live);

        _log.info("L2System: JVM Heap successfully dumped to `" + dumpFile + "`!");
    } catch (Exception e) {
        _log.warn("L2System: Failed to dump heap:", e);
    }
}

From source file:de.thb.ue.backend.service.ParticipantService.java

@Override
public List<Participant> add(int amount, Evaluation evaluation)
        throws EvaluationException, ParticipantException {
    List<Participant> createdParticipants = new ArrayList<>(amount);
    List<BufferedImage> qrcs = new ArrayList<>(amount);
    for (int i = 0; i < amount; i++) {
        String voteToken = UUID.randomUUID().toString();
        createdParticipants.add(new Participant(evaluation, false, voteToken, ""));
        try {//w ww . ja  v  a2s  .c  o  m
            qrcs.add(QRCGeneration.generateQRC(
                    "{\"voteToken\":\"" + voteToken + "\",\"host\":\"" + hostadress + "\"}",
                    QRCGeneration.SIZE_SMALL, ErrorCorrectionLevel.Q, QRCGeneration.ENCODING_UTF_8));
        } catch (WriterException | IOException e) {
            throw new ParticipantException(ParticipantException.ERROR_CREATING_QRC_PDF, e.getMessage());
        }
    }
    participantRepo.save(createdParticipants);
    File workingDirectory = new File(
            (workingDirectoryPath.isEmpty() ? "" : (workingDirectoryPath + File.separatorChar))
                    + evaluation.getUid());

    if (!workingDirectory.exists()) {
        try {
            FileUtils.forceMkdir(workingDirectory);
        } catch (IOException e) {
            log.error("Can't create directory for " + evaluation.getUid());
        }
    }

    PDFGeneration.createQRCPDF(qrcs, evaluation.getUid(), evaluation.getSubject().getName(),
            evaluation.getSemesterType(), LocalDate.now().getYear(), workingDirectory);
    return createdParticipants;
}

From source file:de.codecentric.elasticsearch.plugin.kerberosrealm.KerberosRealmEmbeddedTests.java

@Test
public void testTransportClient() throws Exception {
    embeddedKrbServer.getSimpleKdcServer().createPrincipal("spock/admin@CCK.COM", "secret");
    embeddedKrbServer.getSimpleKdcServer().createPrincipal("elasticsearch/transport@CCK.COM", "testpwd");
    FileUtils.forceMkdir(new File("testtmp/config/keytab/"));
    embeddedKrbServer.getSimpleKdcServer().exportPrincipal("elasticsearch/transport@CCK.COM",
            new File("testtmp/config/keytab/es_server.keytab")); //server, acceptor

    final Settings esServerSettings = Settings.builder()
            .put(PREFIX + SettingConstants.ACCEPTOR_KEYTAB_PATH, "keytab/es_server.keytab")
            //relative to config
            .put(PREFIX + SettingConstants.ACCEPTOR_PRINCIPAL, "elasticsearch/transport@CCK.COM")
            .put(PREFIX + SettingConstants.STRIP_REALM_FROM_PRINCIPAL, true)
            .putArray(PREFIX + SettingConstants.ROLES + ".cc_kerberos_realm_role", "spock/admin@CCK.COM")
            //.put(PREFIX+SettingConstants.KRB5_FILE_PATH,"") //if already set by kerby here
            //.put(PREFIX+SettingConstants.KRB_DEBUG, true)
            .build();/*  w  w  w  . j  a  v  a 2  s  .c o m*/

    this.startES(esServerSettings);

    final NodesInfoResponse nodeInfos = client().admin().cluster().prepareNodesInfo().get();
    final NodeInfo[] nodes = nodeInfos.getNodes();
    assertTrue(nodes.length > 2);

    final Settings settings = Settings.builder().put("cluster.name", clustername)
            .putArray("plugin.types", ShieldPlugin.class.getName()).build();

    try (TransportClient client = TransportClient.builder().settings(settings).build()) {
        client.addTransportAddress(nodes[0].getTransport().address().publishAddress());
        try (KerberizedClient kc = new KerberizedClient(client, "spock/admin@CCK.COM", "secret",
                "elasticsearch/transport@CCK.COM")) {

            ClusterHealthResponse response = kc.admin().cluster().prepareHealth().execute().actionGet();
            assertThat(response.isTimedOut(), is(false));

            response = kc.admin().cluster().prepareHealth().execute().actionGet();
            assertThat(response.isTimedOut(), is(false));

            response = kc.admin().cluster().prepareHealth().execute().actionGet();
            assertThat(response.isTimedOut(), is(false));
            assertThat(response.status(), is(RestStatus.OK));
            assertThat(response.getStatus(), is(ClusterHealthStatus.GREEN));
        }
    }
}