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

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

Introduction

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

Prototype

public static void touch(File file) throws IOException 

Source Link

Document

Implements the same behaviour as the "touch" utility on Unix.

Usage

From source file:com.linkedin.pinot.core.segment.index.loader.LoadersTest.java

@Test
public void testLoadWithStaleConversionDir() throws Exception {
    // Format converter will leave stale directories around if there was
    // conversion failure. This test case checks loading in that scenario
    SegmentMetadataImpl originalMetadata = new SegmentMetadataImpl(segmentDirectory);
    Assert.assertEquals(originalMetadata.getSegmentVersion(), SegmentVersion.v1);
    Assert.assertFalse(SegmentDirectoryPaths.segmentDirectoryFor(segmentDirectory, SegmentVersion.v3).exists());
    File v3TempDir = new SegmentV1V2ToV3FormatConverter().v3ConversionTempDirectory(segmentDirectory);
    FileUtils.touch(v3TempDir);

    {//from  w  w  w  .  j  a  va 2 s  . com
        IndexSegment indexSegment = Loaders.IndexSegment.load(segmentDirectory, ReadMode.mmap);
        Assert.assertEquals(indexSegment.getSegmentMetadata().getVersion(), originalMetadata.getVersion());
        Assert.assertFalse(
                SegmentDirectoryPaths.segmentDirectoryFor(segmentDirectory, SegmentVersion.v3).exists());
    }
    {
        IndexSegment indexSegment = Loaders.IndexSegment.load(segmentDirectory, ReadMode.mmap, v3LoadingConfig);
        Assert.assertEquals(SegmentVersion.valueOf(indexSegment.getSegmentMetadata().getVersion()),
                SegmentVersion.v3);
        Assert.assertTrue(
                SegmentDirectoryPaths.segmentDirectoryFor(segmentDirectory, SegmentVersion.v3).exists());
        Assert.assertFalse(v3TempDir.exists());
    }
}

From source file:com.pason.plugins.artifactorypolling.ArtifactoryRepository.java

/**
 * See documentation at top of class./* ww  w.ja  v  a  2 s  .c om*/
 * This function will perform the download of the artifacts from artifactory
 */
@Override
public boolean checkout(AbstractBuild<?, ?> build, Launcher launcher, FilePath workspace,
        BuildListener listener, File changelogFile) throws IOException, InterruptedException {
    AbstractBuild<?, ?> lastBuild = build;
    LOGGER.log(FINE, "Current job: " + build.getProject().getName());

    // If this is the first build we need to get the next version to checkout
    if (nextArtifact == null) {
        ArtifactoryAPI api = new ArtifactoryAPI(getDescriptor().getArtifactoryServer());
        ArtifactoryRevisionState serverState = ArtifactoryRevisionState.fromServer(repo, groupID, artifactID,
                versionFilter, api);
        if (!serverState.getArtifacts().isEmpty()) {
            nextArtifact = serverState.getArtifacts().get(0);
        } else {
            LOGGER.log(FINE, "No artifacts found for " + groupID + ":" + artifactID);
            return false;
        }
    }

    CheckoutTask task = new CheckoutTask(getDescriptor().getArtifactoryServer(), repo, groupID, artifactID,
            nextArtifact, localPath, doDownload);

    for (AbstractBuild<?, ?> b = build; b != null; b = b.getPreviousBuild()) {
        if (getVersionsFile(b).exists()) {
            build = b;
            break;
        }
    }

    File file = getVersionsFile(build);
    LOGGER.log(FINE, "Got version file for " + build.getProject().getName());
    ArtifactoryRevisionState revState = ArtifactoryRevisionState.BASE;

    if (file.exists()) {
        revState = ArtifactoryRevisionState.fromFile(file);

        if (!revState.getArtifactID().equals(artifactID) || !revState.getGroupID().equals(groupID)
                || !revState.getRepo().equals(repo)) {
            revState = ArtifactoryRevisionState.BASE;
        }
    }

    // Create a new Revision state with the parameters
    revState = new ArtifactoryRevisionState(repo, groupID, artifactID,
            revState.addOrReplaceArtifact(nextArtifact));
    LOGGER.log(FINE, revState.toJSON().toString());
    File newBuildFile = getVersionsFile(lastBuild);
    FileWriter writer = new FileWriter(newBuildFile);
    revState.toJSON().write(writer);
    writer.close();

    FileUtils.touch(changelogFile);

    return workspace.act(task);
}

From source file:ke.co.tawi.babblesms.server.utils.export.topups.AllTopupsExportUtil.java

/**
 * Used to create a MS Excel file from a list of
 *
 * @param topups//from   w  ww .  ja  v a 2s  .  co  m
 * @param networkHash a map with an UUID as the key and the name of the
 * network as the value
 * @param statusHash a map with an UUID as the key and the name of the
 * transaction status as the value
 * @param delimiter
 * @param excelFile the Microsoft Excel file to be created. It should
 * contain the full path and name of the file e.g. "/tmp/export/topups.xlsx"
 * @return whether the creation of the Excel file was successful or not
 */
public static boolean createExcelExport(final List<IncomingLog> topups,
        final HashMap<String, String> networkHash, final HashMap<String, String> statusHash,
        final String delimiter, final String excelFile) {
    boolean success = true;

    int rowCount = 0; // To keep track of the row that we are on

    Row row;
    Map<String, CellStyle> styles;

    SXSSFWorkbook wb = new SXSSFWorkbook(5000); // keep 5000 rows in memory, exceeding rows will be flushed to disk
    // Each line of the file is approximated to be 200 bytes in size, 
    // therefore 5000 lines are approximately 1 MB in memory
    // wb.setCompressTempFiles(true); // temporary files will be gzipped on disk

    Sheet sheet = wb.createSheet("Airtime Topup");
    styles = createStyles(wb);

    PrintSetup printSetupTopup = sheet.getPrintSetup();
    printSetupTopup.setLandscape(true);
    sheet.setFitToPage(true);

    // Set up the heading to be seen in the Excel sheet
    row = sheet.createRow(rowCount);

    Cell titleCell;

    row.setHeightInPoints(45);
    titleCell = row.createCell(0);
    titleCell.setCellValue("Airtime Topups");
    sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$L$1"));
    titleCell.setCellStyle(styles.get("title"));

    rowCount++;
    row = sheet.createRow(rowCount);
    row.setHeightInPoints(12.75f);

    for (int i = 0; i < TOPUP_TITLES.length; i++) {
        Cell cell = row.createCell(i);
        cell.setCellValue(TOPUP_TITLES[i]);
        cell.setCellStyle(styles.get("header"));
    }

    rowCount++;

    FileUtils.deleteQuietly(new File(excelFile));
    FileOutputStream out;

    try {
        FileUtils.touch(new File(excelFile));

        Cell cell;

        for (IncomingLog topup : topups) {
            row = sheet.createRow(rowCount);

            cell = row.createCell(0);
            cell.setCellValue(topup.getUuid());

            //cell = row.createCell(1);
            //cell.setCellValue(topup.getMessageid());

            cell = row.createCell(2);
            cell.setCellValue(topup.getDestination());

            cell = row.createCell(3);
            cell.setCellValue(networkHash.get(topup.getOrigin()));

            cell = row.createCell(4);
            cell.setCellValue(statusHash.get(topup.getMessage()));

            cell = row.createCell(5);
            cell.setCellValue(topup.getLogTime().toString());

            rowCount++;
        }

        out = new FileOutputStream(excelFile);
        wb.write(out);
        out.close();

    } catch (IOException e) {
        logger.error("IOException while trying to create Excel file '" + excelFile + "' from list of topups.");
        logger.error(ExceptionUtils.getStackTrace(e));
        success = false;
    }

    wb.dispose(); // dispose of temporary files backup of this workbook on disk

    return success;
}

From source file:com.netflix.genie.web.jobs.workflow.impl.JobKickoffTask.java

private boolean canExecute(final String runScriptFile) {
    try {//from  w  w  w.ja  v  a  2  s.c om
        return retryTemplate.execute(c -> {
            FileUtils.touch(new File(runScriptFile));
            return true;
        });
    } catch (Exception e) {
        log.warn("Failed touching the run script file", e);
    }
    return false;
}

From source file:com.bluexml.side.util.deployer.war.DirectWebAppsDeployer.java

@Override
protected void deployProcess(File fileToDeploy, DeployMode mode) throws Exception {
    System.out.println("DirectWebAppsDeployer.deployProcess() :" + this);
    FileFilter fileFilter = getFileFilter(mode);
    File deployedWebbAppFolder = getDeployedWebbAppFolder();
    if (!deployedWebbAppFolder.exists()) {
        this.clean(fileToDeploy);
    }/*w  ww .j av  a  2s . c  o m*/
    if (fileToDeploy.exists() && fileToDeploy.isDirectory()) {
        for (File f : fileToDeploy.listFiles(fileFilter)) {
            List<String> list = deployFile(f).getList();

            deployedFiles.addAll(list);

            // check if files are copied more than one time, this detect file collision
            //            for (String file : deployedFiles) {
            //               int frequency = Collections.frequency(deployedFiles, file);
            //               if (frequency > 1) {
            //                  // conflict detected ...
            //                  monitor.addWarningTextAndLog("Beware the file "+file+"have been overrided by module :"+fileToDeploy, "");
            //               }
            //            }

        }
    } else if (fileToDeploy.exists() && fileToDeploy.isFile() && fileFilter.accept(fileToDeploy)) {
        deployedFiles.addAll(deployFile(fileToDeploy).getList());
    } else {
        monitor.addWarningTextAndLog(Activator.Messages.getString("WarDeployer.5"), "");
    }

    // deploy process is done, we need to mark the deployed webapp      
    File incrementalLastDeploeydFlag = getIncrementalLastDeployedFlag();
    System.out.println("DirectWebAppsDeployer.deployProcess() touch " + incrementalLastDeploeydFlag);
    FileUtils.touch(incrementalLastDeploeydFlag);

    if (webappReloading) {
        System.out.println("DirectWebAppsDeployer.deployProcess() touch " + getWebAppXMLFile());
        // we touch web.xml too to let tomcat reload the webapp, some webapps should not be restarted
        FileUtils.touch(getWebAppXMLFile());
    }

}

From source file:com.github.jengelman.gradle.plugins.integration.TestFile.java

public TestFile touch() {
    try {/*  w w w  .j av  a 2 s  . c om*/
        FileUtils.touch(this);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    assertIsFile();
    return this;
}

From source file:gov.redhawk.sca.efs.server.tests.FileSystemImplTest.java

/**
 * Test method for/*from ww  w  .  ja  v a 2 s  .  com*/
 * {@link gov.redhawk.efs.sca.server.internal.FileSystemImpl#open(java.lang.String, boolean)}
 * .
 * 
 * @throws IOException
 */
@Test
public void testOpen() throws IOException {
    try {
        this.fileSystem.open("badFile", false);
        Assert.fail("Should raise File Exception");
    } catch (final InvalidFileName e) {
        Assert.fail("Should raise File Exception");
    } catch (final FileException e) {
        // PASS
    }
    FileUtils.touch(new File(FileSystemImplTest.root, FileSystemImplTest.TEMP_FILE_NAME));

    CF.File readOnlyFile;
    try {
        readOnlyFile = this.fileSystem.open(FileSystemImplTest.TEMP_FILE_NAME, true);
    } catch (final InvalidFileName e) {
        Assert.fail(e.getMessage() + ": " + e.msg);
        // Will not get here
        return;
    } catch (final FileException e) {
        Assert.fail(e.getMessage() + ": " + e.msg);
        // Will not get here
        return;
    }

    try {
        readOnlyFile.write(new byte[10]); // SUPPRESS CHECKSTYLE MagicNumber
        Assert.fail("Should have IOException for writing to a read only file.");
    } catch (final CF.FilePackage.IOException e) {
        // PASS
    } finally {
        try {
            readOnlyFile.close();
        } catch (final FileException e) {
            Assert.fail("Should have IOException for writing to a read only file.");
        }
    }

    CF.File readWriteFile = null;
    try {
        readWriteFile = this.fileSystem.open(FileSystemImplTest.TEMP_FILE_NAME, false);
    } catch (final InvalidFileName e) {
        Assert.fail(e.getMessage() + ": " + e.msg);
    } catch (final FileException e) {
        Assert.fail(e.getMessage() + ": " + e.msg);
    } finally {
        try {
            if (readWriteFile != null) {
                readWriteFile.close();
            }
        } catch (final FileException e) {
            Assert.fail(e.getMessage() + ": " + e.msg);
        }
    }
}

From source file:edu.pitt.dbmi.facebase.hd.TrueCryptManager.java

/** "/bin/touch" TrueCrypt volume file using not the shell but FileUtils.touch()
 * Creates zero-length file/*from  www.ja v a 2s .  c  o m*/
 * truecrypt binary requires that the file holding the truecrypt volume exists before it will create a truecrypt volume
 *
 * @return true if successful creating the file housing the truecrypt volume.
 */
public boolean touchVolume() {
    log.debug("TrueCryptManager.touchVolume() called");
    try {
        File volumeFile = new File(volume);
        FileUtils.touch(volumeFile);
    } catch (IOException ioe) {
        String errorString = "TrueCryptManager caught an ioe in touchVolume()" + ioe.toString();
        String logString = ioe.getMessage();
        edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString);
        log.error(errorString, ioe);
        return false;
    }
    return true;
}

From source file:com.tascape.qa.th.Utils.java

public static Process cmd(String[] commands, final File file, final File workingDir,
        final String... ignoreRegex) throws IOException {
    FileUtils.touch(file);
    LOG.debug("Saving console output to {}", file.getAbsolutePath());

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.redirectErrorStream(true);//from ww w.  ja  va  2s.  co  m
    pb.directory(workingDir);
    LOG.info("Running command {}:  {}", workingDir == null ? "" : workingDir.getAbsolutePath(),
            pb.command().toString().replaceAll(",", ""));
    final Process p = pb.start();

    Thread t = new Thread(Thread.currentThread().getName() + "-" + p.hashCode()) {
        @Override
        public void run() {
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String console = "console-" + stdIn.hashCode();
            try (PrintWriter pw = new PrintWriter(file)) {
                for (String line = stdIn.readLine(); line != null;) {
                    LOG.trace("{}: {}", console, line);
                    if (null == ignoreRegex || ignoreRegex.length == 0) {
                        pw.println(line);
                    } else {
                        boolean ignore = false;
                        for (String regex : ignoreRegex) {
                            if (!regex.isEmpty() && (line.contains(regex) || line.matches(regex))) {
                                ignore = true;
                                break;
                            }
                        }
                        if (!ignore) {
                            pw.println(line);
                        }
                    }
                    pw.flush();
                    line = stdIn.readLine();
                }
            } catch (IOException ex) {
                LOG.warn(ex.getMessage());
            }
            LOG.trace("command is done");
        }
    };
    t.setDaemon(true);
    t.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            if (p != null) {
                p.destroy();
            }
        }
    });
    return p;
}

From source file:com.mvdb.etl.actions.ActionUtils.java

public static void createMarkerFile(String touchFile, boolean doNotCheckForPriorExistence) {
    touchFile = getAbsoluteFileName(touchFile);
    File file = new File(touchFile);
    if (doNotCheckForPriorExistence == false && file.exists() == true) {
        logger.error("Warning: <" + touchFile + "> already exists. Check why this happend before proceeding.");
        System.exit(1);/*from  ww w .  j a v a  2s . c o m*/
    }
    try {
        FileUtils.touch(file);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error("", e);
        throw new RuntimeException(e);
    }
}