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:au.org.ala.biocache.writer.ShapeFileRecordWriter.java

public ShapeFileRecordWriter(String filename, OutputStream out, String[] header) {
    //perform the header mappings so that features are only 10 characters long.
    headerMappings = AlaFileUtils.generateShapeHeader(header);
    //set the outputStream
    outputStream = out;//from   w w  w. j  a v a2 s  . c  o  m
    //initialise a temporary file that can used to write the shape file
    temporaryShapeFile = new File(tmpDownloadDirectory + File.separator + System.currentTimeMillis()
            + File.separator + filename + File.separator + filename + ".shp");
    try {
        FileUtils.forceMkdir(temporaryShapeFile.getParentFile());
        //get the indices for the lat and long
        latIdx = ArrayUtils.indexOf(header, "latitude");
        longIdx = ArrayUtils.indexOf(header, "longitude");
        if (latIdx < 0 || longIdx < 0) {
            latIdx = ArrayUtils.indexOf(header, "decimalLatitude.p");
            longIdx = ArrayUtils.indexOf(header, "decimalLongitude.p");
        }

        simpleFeature = createFeatureType(headerMappings.keySet(), null);
        featureBuilder = new SimpleFeatureBuilder(simpleFeature);

        if (latIdx < 0 || longIdx < 0) {
            logger.error("The invalid header..." + StringUtils.join(header, "|"));
            throw new IllegalArgumentException(
                    "A Shape File Export needs to include latitude and longitude in the headers.");
        }

    } catch (java.io.IOException e) {
        logger.error("Unable to create the temporary file necessary for ShapeFile exporting.", e);
    }
}

From source file:de.awtools.basic.file.FindFilesTest.java

@BeforeClass
public static void beforeClass() throws Exception {
    TMP_DIR = new File(SystemUtils.getUserHome(), BUILD_TMP_DIR);
    try {//from   w  w w . j ava2s.co m
        FileUtils.forceMkdir(TMP_DIR);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    AWToolsFileUtils.createFilePath(TMP_DIR.getPath(), TEST_FILE);

    File file1 = new File(TMP_DIR, "findmy.txt");
    File file2 = new File(TMP_DIR, "test/winkler/findmy.txt");
    File file3 = new File(TMP_DIR, "test/winkler/arbeit/findmy.txt");

    file1.createNewFile();
    file2.createNewFile();
    file3.createNewFile();
}

From source file:com.sonar.it.jenkins.orchestrator.container.JenkinsWrapper.java

public void start() {
    if (started.getAndSet(true)) {
        throw new IllegalStateException("App server is already started");
    }// w  w w. ja  v  a  2  s.  c o  m

    LOG.info("Start jenkins on port " + port + " in " + workingDir);
    resultHandler = createResultHandler();
    try {
        FileUtils.forceMkdir(workingDir);
        CommandLine command;
        if (javaHome == null) {
            command = new CommandLine("java");
        } else {
            command = new CommandLine(FileUtils.getFile(javaHome, "bin", "java"));
        }
        command.addArgument("-Xmx512M");
        command.addArgument("-XX:MaxPermSize=128m");
        command.addArgument("-Djava.awt.headless=true");
        command.addArgument("-Djenkins.install.runSetupWizard=false");
        command.addArgument("-DJENKINS_HOME=" + workingDir.getAbsolutePath());
        String jaCoCoArgument = JaCoCoArgumentsBuilder.getJaCoCoArgument(config);
        if (jaCoCoArgument != null) {
            LOG.info("JaCoCo enabled");
            command.addArgument(jaCoCoArgument);
        }

        command.addArgument("-jar");
        command.addArgument("jenkins-war-" + server.getVersion() + ".war");
        command.addArgument("--httpPort=" + port);
        command.addArgument("--ajp13Port=-1");

        executor.setWorkingDirectory(workingDir.getParentFile());
        executor.execute(command, resultHandler);
    } catch (IOException e) {
        throw new IllegalStateException("Can't start jenkins", e);
    }

    waitForJenkinsToStart();
}

From source file:dk.itst.oiosaml.configuration.SAMLConfiguration.java

public static void setHomeProperty(String home) {
    if (home == null) {
        home = System.getProperty("user.home") + "/.oiosaml";
    }//from   w w w.j a va  2s  .co  m

    File h = new File(home);
    if (h.exists() && !h.isDirectory()) {
        throw new IllegalStateException(home + " is not a directory");
    } else if (!h.exists()) {
        log.info("Creating empty config dir in " + home);
        try {
            FileUtils.forceMkdir(h);
        } catch (IOException e) {
            throw new IllegalStateException(h + " could not be created");
        }
    }
    log.info("oiosaml.home set to " + home);
    SAMLConfiguration.home = home;
}

From source file:com.blockwithme.longdb.bdb.BDBBackend.java

@Override
protected BDBDatabase createDatabaseInternal(final String theDB) {
    // TODO - validate that database name should not contain any special
    // chars.//from   w w  w. j ava2  s  . c  om
    try {
        final File dataRoot = new File(config.filePath());
        if (!dataRoot.exists())
            FileUtils.forceMkdir(dataRoot);
        final File databaseDir = new File(dataRoot.getPath() + File.separator + theDB);
        if (databaseDir.exists())
            throw new DBException("Database already exists");

        FileUtils.forceMkdir(databaseDir);
        final BDBDatabase bdb = new BDBDatabase(this, this.connect(theDB), theDB);
        return bdb;
    } catch (final IOException e) {
        LOG.error("Exception Occurred in - " + "createDatabaseInternal(String database=" + theDB + ")", e);
        throw new DBException("Error creating connection.", e);
    }
}

From source file:net.continuumsecurity.runner.StoryRunner.java

private void copyResultsToStampedReportsDir() throws IOException {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd-HH.mm.ss", Locale.getDefault());
    File dirName = new File(REPORTS_DIR + File.separator + formatter.format(new Date()));
    FileUtils.forceMkdir(dirName);
    FileUtils.copyDirectory(new File(LATEST_REPORTS), dirName);
}

From source file:com.enioka.jqm.tools.NoApiPayloadTest.java

@Test
public void testProvidedApi() throws Exception {
    CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-providedapi/target/test.jar",
            TestHelpers.qVip, 42, "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true,
            em);/*w  w w.  j  a  v  a  2  s.c  om*/

    // Create an empty lib directory just to be sure no dependencies will be resolved.
    FileUtils.forceMkdir(new File("../jqm-tests/jqm-test-providedapi/target/lib"));

    JobRequest j = new JobRequest("MarsuApplication", "TestUser");
    JqmClientFactory.getClient().enqueue(j);

    addAndStartEngine();
    TestHelpers.waitFor(1, 10000, em);

    TypedQuery<History> query = em.createQuery("SELECT j FROM History j", History.class);
    ArrayList<History> res = (ArrayList<History>) query.getResultList();

    Assert.assertEquals(1, res.size());
    Assert.assertEquals(State.ENDED, res.get(0).getState());
}

From source file:com.btmatthews.selenium.junit4.rule.ScreenShotOnFailure.java

/**
 * Handle a test case failure by taking a screen shot from the browser and writing it to a file.
 *
 * @param exception   The exception that describes the test case failure.
 * @param description Describes the unit test that failed.
 *//*from   w  w  w .j ava 2  s.  c  o m*/
@Override
protected void failed(final Throwable exception, final Description description) {
    try {
        if (webDriver != null) {
            if (webDriver instanceof TakesScreenshot) {
                final File target = generator.getTargetFilename(description);
                final byte[] source = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.BYTES);
                FileUtils.forceMkdir(target.getParentFile());
                FileUtils.writeByteArrayToFile(target, source);
            }
        } else {
            final File target = generator.getTargetFilename(description);
            FileUtils.forceMkdir(target.getParentFile());
            server.captureEntirePageScreenshot(target.getAbsolutePath(), "");
        }
    } catch (final IOException e) {
        LOGGER.error("I/O error capturing screen shot after failure", e);
    }
}

From source file:com.mgmtp.jfunk.web.util.HtmlValidatorUtil.java

/**
 * Validates an HTML file against the W3C markup validation service.
 * //  w  w w  .  j av  a2s.c  o m
 * @param validationResultDir
 *            target directory for validation result file
 * @param props
 *            properties must include the keys {@link WebConstants#W3C_MARKUP_VALIDATION_URL}
 *            and {@link WebConstants#W3C_MARKUP_VALIDATION_LEVEL}
 * @param file
 *            HTML file which will be validated
 */
public static void validateHtml(final File validationResultDir, final Configuration props, final File file)
        throws IOException {
    Preconditions.checkArgument(StringUtils.isNotBlank(props.get(WebConstants.W3C_MARKUP_VALIDATION_URL)));
    InputStream is = null;
    BufferedReader br = null;
    InputStream fis = null;
    try {
        // Post HTML file to markup validation service as multipart/form-data
        URL url = new URL(props.get(WebConstants.W3C_MARKUP_VALIDATION_URL));
        URLConnection uc = url.openConnection();
        MultipartPostRequest request = new MultipartPostRequest(uc);
        fis = new FileInputStream(file);
        /*
         * See http://validator.w3.org/docs/api.html#requestformat for a description of all
         * parameters
         */
        request.setParameter("uploaded_file", file.getPath(), fis);
        is = request.post();

        // Summary of validation is available in the HTTP headers
        String status = uc.getHeaderField(STATUS);
        int errors = Integer.parseInt(uc.getHeaderField(ERRORS));
        LOG.info("Page " + file.getName() + ": Number of HTML validation errors=" + errors);
        int warnings = Integer.parseInt(uc.getHeaderField(WARNINGS));
        LOG.info("Page " + file.getName() + ": Number of HTML validation warnings=" + warnings);

        // Check if result file has to be written
        String level = props.get(WebConstants.W3C_MARKUP_VALIDATION_LEVEL, "ERROR");
        boolean validate = false;
        if (StringUtils.equalsIgnoreCase(level, "WARNING") && (warnings > 0 || errors > 0)) {
            validate = true;
        } else if (StringUtils.equalsIgnoreCase(level, "ERROR") && errors > 0) {
            validate = true;
        } else if (StringUtils.equalsIgnoreCase("Invalid", status)) {
            validate = true;
        }

        if (validate) {
            br = new BufferedReader(new InputStreamReader(is));
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }
            PrintWriter writer = null;
            String fileName = file.getName().substring(0, file.getName().length() - 5)
                    + "_validation_result.html";
            FileUtils.forceMkdir(validationResultDir);
            File validationResultFile = new File(validationResultDir, fileName);
            try {
                writer = new PrintWriter(validationResultFile, "UTF-8");
                writer.write(sb.toString());
                LOG.info("Validation result saved in file " + validationResultFile.getName());
            } catch (IOException ex) {
                LOG.error("Could not write HTML file " + validationResultFile.getName() + "to directory", ex);
            } finally {
                IOUtils.closeQuietly(writer);
            }
        }
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(fis);
    }
}

From source file:com.michaelfitzmaurice.clocktwerk.TweetResponderTest.java

@Before
public void setup() throws Exception {

    persistenceDir = new File(System.getProperty("java.io.tmpdir"), "test-prevayler");
    FileUtils.forceMkdir(persistenceDir);
    FileUtils.forceDeleteOnExit(persistenceDir);
    lastSeenMentionId = new Long(new Random().nextInt(Integer.MAX_VALUE));
    HashMap<String, Long> prevayledMap = new HashMap<String, Long>();
    prevayledMap.put(LAST_MENTION_HANDLED_ID_KEY, lastSeenMentionId);
    prevayler = PrevaylerFactory.createPrevayler(prevayledMap, persistenceDir.getAbsolutePath());
    paging = new Paging(lastSeenMentionId);

    mockTweetDb = createNiceMock(TweetDatabase.class);
    mockTweetDb.getNextTweet();/*  w  ww.  j a  va 2s . c  o  m*/
    expectLastCall().andReturn(replyText).anyTimes();
    replay(mockTweetDb);

    String twitterUserHandle = "Receiver";
    twitterUser = userFrom("Mr. " + twitterUserHandle, twitterUserHandle);

    String mentionerHandle = "MentionU";
    mentioningUser = userFrom("Miss " + mentionerHandle, mentionerHandle);

    mockTwitterClient = createStrictMock(Twitter.class);
    mockTwitterClient.getScreenName();
    expectLastCall().andReturn(twitterUserHandle);
    replay(mockTwitterClient);
}