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:net.lmxm.ute.executers.tasks.FileSystemDeleteTaskExecuterTest.java

/**
 * Test delete files single file./*  www.  ja va 2 s.c o m*/
 */
@Test
public void testDeleteFilesSingleFile() {
    try {
        final File file = File.createTempFile("UTE", ".TEST");
        file.deleteOnExit();
        FileUtils.touch(file);

        assertTrue(file.exists());

        executer.deleteFiles(file.getAbsolutePath(), null, STOP_ON_ERROR);

        assertFalse(file.exists());
    } catch (final IOException e) {
        fail();
    }
}

From source file:com.eviware.soapui.actions.MockAsWarActionTest.java

private void setSoapUiHomeDirectory() throws IOException {
    File mockSoapHomeDir = new File(warTestDir, "soapuihometestdir");
    mockSoapHomeDir.mkdirs();//from  w  w w.  j  a v a2s .c  o  m

    File lib = new File(mockSoapHomeDir, "lib");
    lib.mkdir();
    File sampleJarFile = new File(lib, "soapui.jar");
    FileUtils.touch(sampleJarFile);

    soapuiOriginalHome = System.getProperty(SOAPUI_HOME);
    System.setProperty(SOAPUI_HOME, lib.getPath());
}

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

/**
 * Creates a Microsoft Excel Workbook containing Topup activity provided in
 * a CSV text file. The format of the created file will be Office Open XML
 * (OOXML).//from  ww w  .j av  a 2s  . c o  m
 * <p>
 * It expects the CSV to have the following columns from left to right:<br
 * />
 * topup.uuid, topup.msisdn, topup.amount, network.name, topupStatus.status,
 * topup.topupTime
 * <p>
 * This method has been created to allow for large Excel files to be created
 * without overwhelming memory.
 *
 *
 * @param topupCSVFile a valid CSV text file. It should contain the full
 * path and name of the file e.g. "/tmp/export/topups.csv"
 * @param delimiter the delimiter used in the CSV file
 * @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 String topupCSVFile, 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));

        // Read the CSV file and populate the Excel sheet with it
        LineIterator lineIter = FileUtils.lineIterator(new File(topupCSVFile));
        String line;
        String[] lineTokens;
        int size;

        while (lineIter.hasNext()) {
            row = sheet.createRow(rowCount);
            line = lineIter.next();
            lineTokens = StringUtils.split(line, delimiter);
            size = lineTokens.length;

            for (int cellnum = 0; cellnum < size; cellnum++) {
                Cell cell = row.createCell(cellnum);
                cell.setCellValue(lineTokens[cellnum]);
            }

            rowCount++;
        }

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

    } catch (FileNotFoundException e) {
        logger.error("FileNotFoundException while trying to create Excel file '" + excelFile
                + "' from CSV file '" + topupCSVFile + "'.");
        logger.error(ExceptionUtils.getStackTrace(e));
        success = false;

    } catch (IOException e) {
        logger.error("IOException while trying to create Excel file '" + excelFile + "' from CSV file '"
                + topupCSVFile + "'.");
        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.walmart.gatling.commons.ScriptExecutor.java

@Override
public void onReceive(Object message) {
    log.debug("Script worker received task: {}", message);
    if (message instanceof Master.Job) {
        Cancellable abortLoop = getContext().system().scheduler().schedule(Duration.Zero(),
                Duration.create(60, TimeUnit.SECONDS), () -> {
                    Master.Job job = (Master.Job) message;
                    runCancelJob(job);//from   w  w w.ja  v  a 2  s .  c  om
                }, getContext().system().dispatcher());
        ActorRef sender = getSender();
        ExecutorService pool = Executors.newFixedThreadPool(1);
        ExecutionContextExecutorService ctx = ExecutionContexts.fromExecutorService(pool);
        Future<Object> f = future(() -> runJob(message), ctx);
        f.onSuccess(new OnSuccess<Object>() {
            @Override
            public void onSuccess(Object result) throws Throwable {
                log.info("Notify Worker job status {}", result);
                sender.tell(result, getSelf());
                abortLoop.cancel();
            }
        }, ctx);
        f.onFailure(new OnFailure() {
            @Override
            public void onFailure(Throwable throwable) throws Throwable {
                log.error(throwable.toString());
                abortLoop.cancel();
                unhandled(message);
            }
        }, ctx);
        //getSender().tell(runJob(message));
    } else if (message instanceof Master.FileJob) {
        Master.FileJob fileJob = (Master.FileJob) message;
        try {
            if (fileJob.content != null) {
                FileUtils.touch(
                        new File(agentConfig.getJob().getPath(), fileJob.uploadFileRequest.getFileName()));
                FileUtils.writeStringToFile(
                        new File(agentConfig.getJob().getPath(), fileJob.uploadFileRequest.getFileName()),
                        fileJob.content);
                getSender().tell(new Worker.FileUploadComplete(fileJob.uploadFileRequest, HostUtils.lookupIp()),
                        getSelf());
            } else if (fileJob.remotePath != null) {
                FileUtils.touch(
                        new File(agentConfig.getJob().getPath(), fileJob.uploadFileRequest.getFileName()));
                FileUtils.copyURLToFile(new URL(fileJob.remotePath),
                        new File(agentConfig.getJob().getPath(), fileJob.uploadFileRequest.getFileName()));
                getSender().tell(new Worker.FileUploadComplete(fileJob.uploadFileRequest, HostUtils.lookupIp()),
                        getSelf());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

From source file:hoot.services.controllers.ingest.BasemapResourceTest.java

@Test
@Category(UnitTest.class)
public void TestDeleteBasemap() throws Exception {
    String testMapName = "testmap";

    BasemapResource mapRes = new BasemapResource();
    File dir = new File(mapRes._tileServerPath + "/BASEMAP/" + testMapName);
    FileUtils.forceMkdir(dir);/*w  w  w.j  ava2s.  c o  m*/

    org.junit.Assert.assertTrue(dir.exists());

    File controlFile = new File(mapRes._ingestStagingPath + "/BASEMAP/" + testMapName + ".enabled");
    FileUtils.touch(controlFile);
    org.junit.Assert.assertTrue(controlFile.exists());

    mapRes._deleteBaseMap(testMapName);

    org.junit.Assert.assertFalse(dir.exists());

    org.junit.Assert.assertFalse(controlFile.exists());
}

From source file:com.orange.mmp.dao.flf.ServiceDaoFlfImpl.java

public Service createOrUdpdate(Service service) throws MMPDaoException {
    if (service == null || service.getId() == null) {
        throw new MMPDaoException("missing or bad data access object");
    }/*from   w  ww  .  ja v a  2  s.  c o  m*/
    this.lock.lock();
    // Find default service
    Service defaultService = new Service();
    defaultService.setIsDefault(true);
    Service[] tmpServices = this.find(defaultService);
    if (tmpServices.length > 0)
        defaultService = tmpServices[0];
    else
        defaultService = null;

    Service aService = new Service();
    Service[] allServices = this.find(aService);
    if (!service.getIsDefault()) {
        if (allServices.length == 0
                || (allServices.length == 1 && allServices[0].getId().equals(service.getId()))) {
            // This is the only service: change isDefault to true
            service.setIsDefault(true);
        } else {
            if (defaultService == null) {
                // If no default service, take the first in the list and make it default
                for (int i = 0; i < allServices.length; i++) {
                    Service tmpService = allServices[i];
                    if (!tmpService.getId().equals(service.getId())) {
                        tmpService.setIsDefault(true);
                        this.createOrUdpdate(tmpService);
                        break;
                    }
                }
            }
        }
    }

    OutputStream out = null;
    try {
        // Build dedicated service XML file
        File serviceFile = new File(
                this.path.concat("/").concat(filenameFormat.format(new String[] { service.getId() })));

        out = new FileOutputStream(serviceFile);

        new XMLBinding().write(this.fromServicePOJOToServiceXML(service), out, SERVICE_XML_BINDING_PACKAGE,
                null);

        FileUtils.touch(new File(this.path));

        if (service.getIsDefault()) {
            if (defaultService != null && !defaultService.getId().equals(service.getId())) {
                // Change defaultService.isDefault to false
                defaultService.setIsDefault(false);
                this.createOrUdpdate(defaultService);
            }
        } else {
            if (defaultService != null && defaultService.getId().equals(service.getId())) {
                for (int i = 0; i < allServices.length; i++) {
                    Service tmpService = allServices[i];
                    if (!tmpService.getId().equals(service.getId())) {
                        tmpService.setIsDefault(true);
                        this.createOrUdpdate(tmpService);
                        break;
                    }
                }
            }
        }

        return service;
    } catch (IOException ioe) {
        throw new MMPDaoException("unable to add/update service [" + ioe.getMessage() + "]");
    } catch (BindingException be) {
        throw new MMPDaoException("unable to add/update service [" + be.getMessage() + "]");
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ioe) {
                //NOP
            }
        }
        this.lock.unlock();
    }
}

From source file:com.p6spy.engine.spy.option.P6TestOptionsReload.java

@Test
public void testSetPropertyDiscartedOnAutoReload() throws Exception {
    // precondition
    assertFalse(P6SpyOptions.getActiveInstance().getStackTrace());

    // value modification
    P6SpyOptions.getActiveInstance().setStackTrace(true);
    assertTrue(P6SpyOptions.getActiveInstance().getStackTrace());

    // no explicit props reload, just modify timestamp and wait till autoreload happens
    FileUtils.touch(new File(System.getProperty(SpyDotProperties.OPTIONS_FILE_PROPERTY)));
    Thread.sleep(2000);//  w w w .  ja v a2  s  .c o  m

    // jmx value modification discarted
    assertFalse(P6SpyOptions.getActiveInstance().getStackTrace());
}

From source file:com.thoughtworks.go.server.service.ConsoleService.java

public void moveConsoleArtifacts(LocatableEntity locatableEntity) {
    try {//from w w  w  .j  a  v  a 2 s . c  om
        File from = chooser.temporaryConsoleFile(locatableEntity);

        // Job cancellation skips temporary file creation. Force create one if it does not exist.
        FileUtils.touch(from);

        File to = consoleLogArtifact(locatableEntity);
        FileUtils.moveFile(from, to);
    } catch (IOException | IllegalArtifactLocationException e) {
        throw new RuntimeException(e);
    }
}

From source file:atg.tools.dynunit.test.util.FileUtil.java

private static void persistConfigCache() throws IOException {
    FileUtils.touch(configFilesLastModifiedCache);
    final OutputStream out = new BufferedOutputStream(new FileOutputStream(configFilesLastModifiedCache));
    SerializationUtils.serialize(configFilesLastModified, out);
}

From source file:com.qcadoo.plugin.internal.filemanager.PluginFileManagerTest.java

@Test
public void shouldUploadPluginFile() throws Exception {
    // given//from   w  w w.ja v a2 s .  com
    File newPluginFile = new File(source, "newpluginname.jar");
    FileUtils.touch(newPluginFile);

    PluginArtifact pluginArtifact = mock(PluginArtifact.class);
    given(pluginArtifact.getInputStream()).willReturn(new FileInputStream(newPluginFile));
    given(pluginArtifact.getName()).willReturn("uploadpluginname.jar");

    // when
    File pluginFile = defaultPluginFileManager.uploadPlugin(pluginArtifact);

    // then
    assertTrue(pluginFile.exists());
}