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

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

Introduction

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

Prototype

public static boolean contentEquals(File file1, File file2) throws IOException 

Source Link

Document

Compares the contents of two files to determine if they are equal or not.

Usage

From source file:org.apache.drill.fmpp.mojo.FMPPMojo.java

private Report moveIfChanged(File root, String tmpPath) throws MojoFailureException, IOException {
    Report report = new Report();
    for (File file : root.listFiles()) {
        if (file.isDirectory()) {
            report.add(moveIfChanged(file, tmpPath));
            if (!file.delete()) {
                throw new MojoFailureException(format("can not delete %s", file));
            }/* www  .  j av a2s.  c  o m*/
        } else {
            String absPath = file.getAbsolutePath();
            if (!absPath.startsWith(tmpPath)) {
                throw new MojoFailureException(format("%s should start with %s", absPath, tmpPath));
            }
            String relPath = absPath.substring(tmpPath.length());
            File outputFile = new File(output, relPath);
            if (!outputFile.exists()) {
                report.addNew();
            } else if (!FileUtils.contentEquals(file, outputFile)) {
                getLog().info(format("%s has changed", relPath));
                if (!outputFile.delete()) {
                    throw new MojoFailureException(format("can not delete %s", outputFile));
                }
                report.addChanged();
            } else {
                report.addUnchanged();
            }
            if (!outputFile.exists()) {
                File parentDir = outputFile.getParentFile();
                if (parentDir.exists() && !parentDir.isDirectory()) {
                    throw new MojoFailureException(
                            format("can not move %s to %s as %s is not a dir", file, outputFile, parentDir));
                }
                if (!parentDir.exists() && !parentDir.mkdirs()) {
                    throw new MojoFailureException(format("can not move %s to %s as dir %s can not be created",
                            file, outputFile, parentDir));
                }
                FileUtils.moveFile(file, outputFile);
            } else {
                if (!file.delete()) {
                    throw new MojoFailureException(format("can not delete %s", file));
                }
            }
        }
    }
    return report;
}

From source file:org.apache.drill.parsers.DrqlParserAstTest.java

@Test
public void testQueryList() throws IOException {
    Joiner withNewline = Joiner.on("\n");
    //tests parsing all SQL that are encountered in the documentation
    for (int i = 1; i <= 15; i++) {

        File tempFile = getFile("q" + i + "_temp.drql.sm");
        File expectedFile = getFile("q" + i + ".drql.ast");
        File queryFile = getFile("q" + i + ".drql");

        String query = FileUtils.readFileToString(queryFile);
        String ast = AntlrParser.parseToAst(query).toStringTree();
        Formatter f = new Formatter();
        formatAst(AntlrParser.parseToAst(query), f, 0);

        query = withNewline.join(Resources.readLines(Resources.getResource("q" + i + ".drql"), Charsets.UTF_8));
        assertEquals(query, f.toString());

        FileUtils.writeStringToFile(tempFile, ast);

        assertEquals(withNewline.join(Files.readLines(expectedFile, Charsets.UTF_8)),
                withNewline.join(Files.readLines(expectedFile, Charsets.UTF_8)));
        assertEquals(String.format("sm files differs %s versus %s", expectedFile, tempFile),
                withNewline.join(Files.readLines(expectedFile, Charsets.UTF_8)),
                withNewline.join(Files.readLines(tempFile, Charsets.UTF_8)));
        assertTrue(String.format("sm files differs %s versus %s", expectedFile, tempFile),
                FileUtils.contentEquals(expectedFile, tempFile));

        FileUtils.forceDelete(tempFile);
    }//from   ww w .  j a  va2s  .  c  o  m
}

From source file:org.apache.hive.beeline.util.QFileClient.java

public boolean compareResults() throws IOException {
    if (!expectedFile.exists()) {
        LOG.error("Expected results file does not exist: " + expectedFile);
        return false;
    }/*  w ww  .  j  a  v  a 2s .c o  m*/
    return FileUtils.contentEquals(expectedFile, outputFile);
}

From source file:org.apache.lens.cli.TestLensLogResourceCommands.java

@Test
public void testLogsCommand() throws IOException {
    String request = "testId";
    File file = createFileWithContent(request, "test log resource");

    // create output directory to store the resulted log file
    String outputDirName = "target/sample-logs/";
    File dir = new File(outputDirName);
    dir.mkdirs();/*  w  ww .  j a v  a  2  s.  c  o  m*/

    String response = commands.getLogs(request, outputDirName);
    File outputFile = new File(outputDirName + request);
    Assert.assertTrue(FileUtils.contentEquals(file, outputFile));
    Assert.assertTrue(response.contains("Saved to"));

    response = commands.getLogs(request, null);
    Assert.assertTrue(response.contains("printed complete log content"));

    // check 404 response
    response = commands.getLogs("random", null);
    Assert.assertTrue(response.contains("404"));
}

From source file:org.apache.oodt.cas.filemgr.datatransfer.TestLocalDataTransferer.java

public void testTransferAndRetrieve() throws DataTransferException, IOException {
    Product testProduct = createDummyProduct();

    // Test transfer.
    transfer.transferProduct(testProduct);

    // Check that file was successfully transfered.
    assertTrue("Repo file does not exist", repoFile.exists());
    assertTrue("Repo file does not have the same contents as orig file",
            FileUtils.contentEquals(origFile, repoFile));

    // Test retrieve
    transfer.retrieveProduct(testProduct, destDir);

    // Check that file was successfully transfered.
    assertTrue("Destination file does not exist", destFile.exists());
    assertTrue("Destination file does not have the same contents as orig file",
            FileUtils.contentEquals(origFile, destFile));
}

From source file:org.apache.oodt.cas.protocol.sftp.TestJschSftpProtocol.java

public void testGET() throws ProtocolException, IOException {
    int port = context.getPort();
    File pubKeyFile = createPubKeyForPort(port);
    //JschSftpProtocol sftpProtocol = new JschSftpProtocol(port);
    JschSftpProtocol mockc = mock(JschSftpProtocol.class);

    Mockito.doAnswer(new Answer() {
        public Object answer(InvocationOnMock invocation) {
            return null;
        }//from   w  ww  .  ja v a2 s  . c o m
    }).when(mockc).connect("localhost",
            new HostKeyAuthentication("bfoster", "", pubKeyFile.getAbsoluteFile().getAbsolutePath()));
    mockc.connect("localhost",
            new HostKeyAuthentication("bfoster", "", pubKeyFile.getAbsoluteFile().getAbsolutePath()));

    File bogusFile = File.createTempFile("bogus", "bogus");
    final File tmpFile = new File(bogusFile.getParentFile(), "TestJschSftpProtocol");
    bogusFile.delete();
    tmpFile.mkdirs();
    mockc.cd(new ProtocolFile("sshTestDir", true));
    File testDownloadFile = new File(tmpFile, "testDownloadFile");

    Mockito.doAnswer(new Answer() {
        public Object answer(InvocationOnMock invocationOnMock) throws IOException {

            PrintWriter writer = new PrintWriter(tmpFile + "/testDownloadFile", "UTF-8");
            writer.print(readFile("src/test/resources/sshTestDir/sshTestFile"));
            writer.close();

            return null;
        }
    }).when(mockc).get(new ProtocolFile("sshTestFile", false), testDownloadFile);

    mockc.get(new ProtocolFile("sshTestFile", false), testDownloadFile);

    assertTrue(
            FileUtils.contentEquals(new File("src/test/resources/sshTestDir/sshTestFile"), testDownloadFile));

    FileUtils.forceDelete(tmpFile);
}

From source file:org.apache.solr.cloud.ZkCLITest.java

@Test
public void testUpConfigLinkConfigClearZk() throws Exception {
    File tmpDir = createTempDir().toFile();

    // test upconfig
    String confsetname = "confsetone";
    final String[] upconfigArgs;
    if (random().nextBoolean()) {
        upconfigArgs = new String[] { "-zkhost", zkServer.getZkAddress(), "-cmd", ZkCLI.UPCONFIG, "-confdir",
                ExternalPaths.TECHPRODUCTS_CONFIGSET, "-confname", confsetname };
    } else {//from   w ww .j  a v  a 2  s  .c  om
        final String excluderegexOption = (random().nextBoolean() ? "--" + ZkCLI.EXCLUDE_REGEX
                : "-" + ZkCLI.EXCLUDE_REGEX_SHORT);
        upconfigArgs = new String[] { "-zkhost", zkServer.getZkAddress(), "-cmd", ZkCLI.UPCONFIG,
                excluderegexOption, ZkCLI.EXCLUDE_REGEX_DEFAULT, "-confdir",
                ExternalPaths.TECHPRODUCTS_CONFIGSET, "-confname", confsetname };
    }
    ZkCLI.main(upconfigArgs);

    assertTrue(zkClient.exists(ZkConfigManager.CONFIGS_ZKNODE + "/" + confsetname, true));

    // print help
    // ZkCLI.main(new String[0]);

    // test linkconfig
    String[] args = new String[] { "-zkhost", zkServer.getZkAddress(), "-cmd", "linkconfig", "-collection",
            "collection1", "-confname", confsetname };
    ZkCLI.main(args);

    ZkNodeProps collectionProps = ZkNodeProps
            .load(zkClient.getData(ZkStateReader.COLLECTIONS_ZKNODE + "/collection1", null, null, true));
    assertTrue(collectionProps.containsKey("configName"));
    assertEquals(confsetname, collectionProps.getStr("configName"));

    // test down config
    File confDir = new File(tmpDir,
            "solrtest-confdropspot-" + this.getClass().getName() + "-" + System.nanoTime());
    assertFalse(confDir.exists());

    args = new String[] { "-zkhost", zkServer.getZkAddress(), "-cmd", "downconfig", "-confdir",
            confDir.getAbsolutePath(), "-confname", confsetname };
    ZkCLI.main(args);

    File[] files = confDir.listFiles();
    List<String> zkFiles = zkClient.getChildren(ZkConfigManager.CONFIGS_ZKNODE + "/" + confsetname, null, true);
    assertEquals(files.length, zkFiles.size());

    File sourceConfDir = new File(ExternalPaths.TECHPRODUCTS_CONFIGSET);
    // filter out all directories starting with . (e.g. .svn)
    Collection<File> sourceFiles = FileUtils.listFiles(sourceConfDir, TrueFileFilter.INSTANCE,
            new RegexFileFilter("[^\\.].*"));
    for (File sourceFile : sourceFiles) {
        int indexOfRelativePath = sourceFile.getAbsolutePath()
                .lastIndexOf("sample_techproducts_configs" + File.separator + "conf");
        String relativePathofFile = sourceFile.getAbsolutePath().substring(indexOfRelativePath + 33,
                sourceFile.getAbsolutePath().length());
        File downloadedFile = new File(confDir, relativePathofFile);
        if (ZkConfigManager.UPLOAD_FILENAME_EXCLUDE_PATTERN.matcher(relativePathofFile).matches()) {
            assertFalse(sourceFile.getAbsolutePath() + " exists in ZK, downloaded:"
                    + downloadedFile.getAbsolutePath(), downloadedFile.exists());
        } else {
            assertTrue(
                    downloadedFile.getAbsolutePath() + " does not exist source:" + sourceFile.getAbsolutePath(),
                    downloadedFile.exists());
            assertTrue(relativePathofFile + " content changed",
                    FileUtils.contentEquals(sourceFile, downloadedFile));
        }
    }

    // test reset zk
    args = new String[] { "-zkhost", zkServer.getZkAddress(), "-cmd", "clear", "/" };
    ZkCLI.main(args);

    assertEquals(0, zkClient.getChildren("/", null, true).size());
}

From source file:org.apache.zeppelin.dep.DependencyResolver.java

public List<File> load(String artifact, Collection<String> excludes, File destPath)
        throws RepositoryException, IOException {
    List<File> libs = new LinkedList<>();

    if (StringUtils.isNotBlank(artifact)) {
        libs = load(artifact, excludes);

        for (File srcFile : libs) {
            File destFile = new File(destPath, srcFile.getName());
            if (!destFile.exists() || !FileUtils.contentEquals(srcFile, destFile)) {
                FileUtils.copyFile(srcFile, destFile);
                logger.debug("copy {} to {}", srcFile.getAbsolutePath(), destPath);
            }//from ww w  .  j ava  2s  . c om
        }
    }
    return libs;
}

From source file:org.apache.zeppelin.dep.DependencyResolver.java

public synchronized void copyLocalDependency(String srcPath, File destPath) throws IOException {
    if (StringUtils.isBlank(srcPath)) {
        return;//  w  ww .ja va  2s .c  o m
    }

    File srcFile = new File(srcPath);
    File destFile = new File(destPath, srcFile.getName());

    if (!destFile.exists() || !FileUtils.contentEquals(srcFile, destFile)) {
        FileUtils.copyFile(srcFile, destFile);
        logger.debug("copy {} to {}", srcFile.getAbsolutePath(), destPath);
    }
}

From source file:org.berkholz.configurationframework.ConfigurationTest.java

/**
 * Test of save method, of class Configuration.
 *///www . ja v  a2s .c  o m
@Test
public void testSave_3args() {
    Boolean result = null;
    TestXMLAnnotatedClass testConfig = new TestXMLAnnotatedClass();

    // creating instance of configuration
    Configuration instance = new Configuration();

    try {
        // this file is initialized
        targetSaveFile = File.createTempFile("pabamo_targetSaveFile-", ".xml");
        //            targetSaveFile = new File(File.createTempFile("pabamo_targetSaveFile-", ".xml").getParent() + File.separator + "pabamo_targetSaveFile.xml");
        targetSaveFile.deleteOnExit();

    } catch (IOException ex) {
        LOG.error(ex);
    }

    if (targetSaveFile.exists()) {
        // initialize our testfile(here: targetInitFile)
        LOG.trace("Saving file: " + targetSaveFile.getAbsolutePath());
        Configuration.save(testConfig, targetSaveFile, true);
    } else {
        LOG.error("targetSaveFile: \"" + targetSaveFile + "\" does not exist.");
    }

    try {
        LOG.trace("Starting comparation of saved files.");
        result = FileUtils.contentEquals(templateSaveFile, targetSaveFile);
        LOG.trace("Result of file comparation: " + result);
    } catch (IOException ex) {
        LOG.error(ex);
    }
    assertEquals(true, result);
    //        fail("The test case is not implemented, yet.");
}