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:org.opennms.web.rest.GraphRestServiceTest.java

@Before
public void setUp() throws Throwable {
    super.setUp();

    // Add some nodes
    m_dbPopulator.populateDatabase();//w  ww .  j  av  a  2s  .  co m

    // Point to our temporary directory
    m_resourceDao.setRrdDirectory(m_tempFolder.getRoot());

    // Add some blank .jrb files
    File nodeSnmp1 = m_tempFolder.newFolder("snmp", "1");
    FileUtils.touch(new File(nodeSnmp1, "SwapIn.jrb"));
    FileUtils.touch(new File(nodeSnmp1, "SwapOut.jrb"));
}

From source file:org.opennms.web.rest.v1.GraphRestServiceIT.java

@Before
public void setUp() throws Throwable {
    super.setUp();

    // Add some nodes
    m_dbPopulator.populateDatabase();/* www.j  a  v  a 2s.  c o  m*/

    // Point to our temporary directory
    m_resourceStorageDao.setRrdDirectory(m_tempFolder.getRoot());

    // Add some blank RRD files
    final String extension = m_rrdStrategyFactory.getStrategy().getDefaultFileExtension();
    File nodeSnmp1 = m_tempFolder.newFolder("snmp", "1");
    FileUtils.touch(new File(nodeSnmp1, "SwapIn" + extension));
    FileUtils.touch(new File(nodeSnmp1, "SwapOut" + extension));
}

From source file:org.opennms.web.rest.v1.ResourceRestServiceIT.java

@Before
public void setUp() throws Throwable {
    super.setUp();

    // Add some nodes
    m_dbPopulator.populateDatabase();//from  w  w  w  .  java  2  s.c om

    // Point to our temporary directory
    m_resourceStorageDao.setRrdDirectory(m_tempFolder.getRoot());

    // Add some blank RRD files
    m_extension = m_rrdStrategyFactory.getStrategy().getDefaultFileExtension();
    File nodeSnmp1 = m_tempFolder.newFolder("snmp", "1");
    FileUtils.touch(new File(nodeSnmp1, "SwapIn" + m_extension));
    FileUtils.touch(new File(nodeSnmp1, "SwapOut" + m_extension));
}

From source file:org.openremote.beehive.utils.ZipUtil.java

public static boolean unzip(InputStream inputStream, String targetDir, String filterdFileName) {
    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    ZipEntry zipEntry;/*from w w  w . ja  va 2  s  .c o m*/
    FileOutputStream fileOutputStream = null;
    File zippedFile = null;
    try {
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            if (!zipEntry.isDirectory()) {
                if (filterdFileName != null && !zipEntry.getName().equals(filterdFileName)) {
                    continue;
                }
                targetDir = targetDir.endsWith("/") || targetDir.endsWith("\\") ? targetDir : targetDir + "/";
                zippedFile = new File(targetDir, zipEntry.getName());
                FileUtils.deleteQuietly(zippedFile);
                FileUtils.touch(zippedFile);
                fileOutputStream = new FileOutputStream(zippedFile);
                int b;
                while ((b = zipInputStream.read()) != -1) {
                    fileOutputStream.write(b);
                }
                fileOutputStream.close();
            }
        }
    } catch (IOException e) {
        logger.error("Can't unzip file to " + zippedFile.getPath(), e);
        return false;
    } finally {
        try {
            zipInputStream.closeEntry();
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            logger.error("Error while closing stream.", e);
        }

    }
    return true;
}

From source file:org.openremote.controller.utils.ZipUtil.java

/**
 * Unzip a zip.//from ww  w.j  a v  a 2 s  .c  om
 * 
 * @param inputStream the input stream
 * @param targetDir the target dir
 * 
 * @return true, if success
 */
public static boolean unzip(InputStream inputStream, String targetDir) {
    if (targetDir == null || "".equals(targetDir)) {
        throw new ExtractZipFileException("The resources path is null.");
    }
    File checkedTargetDir = new File(targetDir);
    if (!checkedTargetDir.exists()) {
        throw new ExtractZipFileException("The path " + targetDir + " doesn't exist.");
    }

    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    ZipEntry zipEntry;
    FileOutputStream fileOutputStream = null;
    File zippedFile = null;
    try {
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            if (!zipEntry.isDirectory()) {
                targetDir = targetDir.endsWith("/") || targetDir.endsWith("\\") ? targetDir : targetDir + "/";
                zippedFile = new File(targetDir, zipEntry.getName());
                FileUtils.deleteQuietly(zippedFile);
                FileUtils.touch(zippedFile);
                fileOutputStream = new FileOutputStream(zippedFile);
                int b;
                while ((b = zipInputStream.read()) != -1) {
                    fileOutputStream.write(b);
                }
                fileOutputStream.close();
            }
        }
    } catch (IOException e) {
        logger.error("Can't unzip file to " + zippedFile.getPath(), e);
        return false;
    } finally {
        try {
            zipInputStream.closeEntry();
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            logger.error("Error while closing stream.", e);
        }

    }
    return true;
}

From source file:org.openremote.modeler.service.impl.ResourceServiceImpl.java

private File uploadFile(InputStream inputStream, File file) {
    FileOutputStream fileOutputStream = null;

    try {//w ww .j a v  a  2 s .com
        File dir = file.getParentFile();

        if (!dir.exists()) {
            dir.mkdirs(); // TODO : need to check success
        }

        String originalFileName = file.getName();

        // First get rid of "invalid" characters in filename
        String escapedChar = "[ \\+\\-\\*%\\!\\(\\\"')_#;/?:&;=$,#<>]";
        originalFileName = originalFileName.replaceAll(escapedChar, "");
        file = new File(dir.getAbsolutePath() + File.separator + originalFileName);

        // Don't replace an existing file, add "index" if required to not have a name clash
        String extension = FilenameUtils.getExtension(originalFileName);
        String originalNameWithoutExtension = originalFileName.replace("." + extension, "");
        int index = 0;
        while (file.exists()) {
            file = new File(dir.getAbsolutePath() + File.separator + originalNameWithoutExtension + "."
                    + Integer.toString(++index) + "." + extension);
        }

        FileUtils.touch(file);

        fileOutputStream = new FileOutputStream(file);
        IOUtils.copy(inputStream, fileOutputStream);
    }

    catch (IOException e) {
        throw new FileOperationException("Failed to save uploaded image", e);
    }

    finally {
        try {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        }

        catch (IOException e) {
            serviceLog.warn("Failed to close resources on uploaded file", e);
        }
    }

    return file;
}

From source file:org.openremote.modeler.utils.ZipUtils.java

/**
 * Compress.//  w ww  . jav  a 2 s.  c o  m
 * 
 * @param outputFilePath the output file path
 * @param files the files
 * 
 * @return the file
 */
public static File compress(String outputFilePath, List<File> files) {
    final int buffer = 2048;
    BufferedInputStream bufferedInputStream;
    File outputFile = new File(outputFilePath);
    try {
        FileUtils.touch(outputFile);
    } catch (IOException e) {
        LOGGER.error("create zip file fail.", e);
        throw new FileOperationException("create zip file fail.", e);
    }
    FileOutputStream fileOutputStream = null;
    ZipOutputStream zipOutputStream = null;
    FileInputStream fileInputStream;
    try {
        fileOutputStream = new FileOutputStream(outputFilePath);
        zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
        byte[] data = new byte[buffer];
        for (File file : files) {
            if (!file.exists()) {
                continue;
            }
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream, buffer);
            ZipEntry entry = new ZipEntry(file.getName());
            entry.setSize(file.length());
            entry.setTime(file.lastModified());
            zipOutputStream.putNextEntry(entry);

            int count;
            while ((count = bufferedInputStream.read(data, 0, buffer)) != -1) {
                zipOutputStream.write(data, 0, count);
            }
            zipOutputStream.closeEntry();
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (bufferedInputStream != null) {
                bufferedInputStream.close();
            }
        }
    } catch (FileNotFoundException e) {
        LOGGER.error("Can't find the output file.", e);
        throw new FileOperationException("Can't find the output file.", e);
    } catch (IOException e) {
        LOGGER.error("Can't compress file to zip archive, occured IOException", e);
        throw new FileOperationException("Can't compress file to zip archive, occured IOException", e);
    } finally {
        try {
            if (zipOutputStream != null) {
                zipOutputStream.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            LOGGER.error("Close zipOutputStream and fileOutputStream occur IOException", e);
        }
    }
    return outputFile;
}

From source file:org.ourgrid.common.util.SelfSignedCertificateGenerator.java

public static void generateX509Certificate(KeyPair keyPair, String dnData, String certFilePath)
        throws CertificateEncodingException, InvalidKeyException, IllegalStateException,
        NoSuchAlgorithmException, SignatureException, IOException {

    X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();

    certGenerator.setSerialNumber(BigInteger.valueOf(1));
    certGenerator.setPublicKey(keyPair.getPublic());
    certGenerator.setSubjectDN(new X500Principal(dnData));
    certGenerator.setIssuerDN(new X500Principal(dnData));
    certGenerator.setNotBefore(new Date(System.currentTimeMillis() - VALIDITY_INTERVAL));
    certGenerator.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_INTERVAL));
    certGenerator.setSignatureAlgorithm(SignatureConstants.SIGN_ALGORITHM);

    X509Certificate certificate = certGenerator.generate(keyPair.getPrivate());

    File file = new File(certFilePath);
    if (!file.exists()) {
        FileUtils.touch(file);
    }//from w w  w  . j a va 2s .  c o m

    FileOutputStream fosP = new FileOutputStream(file);
    fosP.write(certificate.getEncoded());

    fosP.close();
}

From source file:org.outermedia.solrfusion.SolrFusionServletTest.java

@Test
public void testConfigReload() throws ServletException, IOException, InterruptedException {
    TestSolrFusionServlet servlet = new TestSolrFusionServlet();
    GregorianCalendar currentCal = new GregorianCalendar(2014, 6, 3, 12, 0, 0);
    long startTime = currentCal.getTimeInMillis();
    servlet.currentTime = startTime;//from   w w  w  .j a  va 2 s. c om
    File tmpSchema = File.createTempFile("test-schema-", ".xml", new File("target/test-classes"));
    FileUtils.copyFile(new File("target/test-classes/test-fusion-schema.xml"), tmpSchema);
    FileUtils.touch(tmpSchema);
    servlet.loadSolrFusionConfig(tmpSchema.getName(), false);
    Configuration oldCfg = servlet.getCfg();
    Assert.assertNotNull("Solr Fusion schema not loaded", oldCfg);

    // try to re-load immediately, which should be done after 5 minutes only
    log.info("----1");
    servlet.loadSolrFusionConfig(tmpSchema.getName(), false);
    Assert.assertEquals("Solr Fusion schema re-loaded", oldCfg, servlet.getCfg());

    // 6 minutes in the future, without schema modifications, nothing should happen
    currentCal.add(Calendar.MINUTE, 6);
    servlet.currentTime = currentCal.getTimeInMillis();
    log.info("----2");
    servlet.loadSolrFusionConfig(tmpSchema.getName(), false);
    Assert.assertEquals("Solr Fusion schema re-loaded", oldCfg, servlet.getCfg());

    // 6 minutes in the future with schema modifications
    servlet.setSolrFusionSchemaLoadTime(startTime); // modified after loadSolrFusionConfig() call
    Thread.sleep(1001); // await new time
    FileUtils.touch(tmpSchema);
    log.info("----3");
    servlet.loadSolrFusionConfig(tmpSchema.getName(), false);
    Assert.assertNotSame("Solr Fusion schema not re-loaded", oldCfg, servlet.getCfg());
    oldCfg = servlet.getCfg();

    // force re-load
    currentCal.add(Calendar.MINUTE, 1);
    servlet.currentTime = currentCal.getTimeInMillis();
    log.info("----4");
    servlet.loadSolrFusionConfig(tmpSchema.getName(), false);
    Assert.assertEquals("Solr Fusion schema re-loaded", oldCfg, servlet.getCfg());
    log.info("----5");
    servlet.loadSolrFusionConfig(tmpSchema.getName(), true);
    Assert.assertNotSame("Solr Fusion schema not re-loaded", oldCfg, servlet.getCfg());
}

From source file:org.ow2.clif.jenkins.jobs.FileSystemTest.java

File touch(String p) throws Exception {
    File f = new File(fs.dir() + "/" + p);
    FileUtils.touch(f);
    return f;
}