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.eclipse.kura.net.admin.visitor.linux.WpaSupplicantConfigWriter.java

private void moveWpaSupplicantConf(String ifaceName, String configFile) throws KuraException {

    File outputFile = new File(configFile);
    File wpaConfigFile = new File(WpaSupplicantManager.getWpaSupplicantConfigFilename(ifaceName));
    try {/* w w  w  .  ja  v a  2  s. co m*/
        if (!FileUtils.contentEquals(outputFile, wpaConfigFile)) {
            if (outputFile.renameTo(wpaConfigFile)) {
                s_logger.trace("Successfully wrote wpa_supplicant config file");
            } else {
                s_logger.error("Failed to write wpa_supplicant config file");
                throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR,
                        "error while building up new configuration file for wpa_supplicant config");
            }
        } else {
            s_logger.info("Not rewriting wpa_supplicant.conf file because it is the same");
        }
    } catch (IOException e) {
        throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR,
                "error while building up new configuration file for wpa_supplicant config");
    }
}

From source file:org.fuin.srcgen4j.core.base.GeneratedFile.java

/**
 * Compares the content of the temporary file with the possibly existing
 * target file. If both are equal the temporary file is deleted. Otherwise
 * the old target file is deleted and the new generated file is renamed.
 * This prevents time stamp changes for the target file if nothing changed
 * since the last generation.//  w  ww  .  j  a  v  a  2 s . c o m
 */
public final void persist() {

    if (persisted) {
        // Do nothing if already done
        return;
    }

    try {

        // Compare new and old file
        if (FileUtils.contentEquals(tmpFile, file)) {
            LOG.debug("Omitted: " + getPath() + logInfo);
            tmpFile.delete();
        } else {
            file.delete();
            tmpFile.renameTo(file);
            LOG.info("Generated: " + getPath() + logInfo);
        }

        persisted = true;

    } catch (final IOException ex) {
        throw new RuntimeException("Error comparing content: tmp=" + tmpFile + ", target=" + file + logInfo,
                ex);
    }

}

From source file:org.fuin.srcgen4j.core.velocity.ParameterizedTemplateGeneratorTest.java

@Test
public void testIntegration() throws Exception {

    // PREPARE/*  ww  w. j a v a  2  s.c  o m*/
    final File expectedA = new File(TEST_RES_DIR + "/A.java");
    final File expectedB = new File(TEST_RES_DIR + "/B.java");
    final File expectedA2 = new File(TEST_RES_DIR + "/A2.java");
    final File expectedB2 = new File(TEST_RES_DIR + "/B2.java");

    final File configFile = new File(TEST_RES_DIR + "/velocity-test-config.xml");
    final SrcGen4JConfig config = PTGenHelper.createAndInit(new DefaultContext(), configFile);
    final SrcGen4J testee = new SrcGen4J(config, new DefaultContext());

    // EXECUTE
    testee.execute();

    // VERIFY

    // Generated using a list
    final File fileA = new File(TARGET_DIR, "a/A.java");
    final File fileB = new File(TARGET_DIR, "b/B.java");
    assertThat(fileA).exists();
    assertThat(fileB).exists();
    assertThat(FileUtils.contentEquals(fileA, expectedA)).isTrue();
    assertThat(FileUtils.contentEquals(fileB, expectedB)).isTrue();

    // Generated using a generator
    final File fileA2 = new File(TARGET_DIR, "a/A2.java");
    final File fileB2 = new File(TARGET_DIR, "b/B2.java");
    assertThat(fileA2).exists();
    assertThat(fileB2).exists();
    assertThat(FileUtils.contentEquals(fileA2, expectedA2)).isTrue();
    assertThat(FileUtils.contentEquals(fileB2, expectedB2)).isTrue();

}

From source file:org.fuin.utils4j.RandomAccessFileOutputStreamTest.java

/**
 * @testng.test/*  w  ww. j  a  va  2s  .  com*/
 */
public final void testWriteByte() throws IOException {
    outputStream = createOutputStream();
    for (int i = 0; i < 256; i++) {
        outputStream.write(i);
    }
    outputStream.truncate();
    outputStream.close();
    Assert.assertTrue(FileUtils.contentEquals(inputFile, file));
}

From source file:org.fuin.utils4j.RandomAccessFileOutputStreamTest.java

/**
 * @testng.test/*from   w w w  .ja  v a2  s  .com*/
 */
public final void testWriteByteArray() throws IOException {
    outputStream = createOutputStream();
    outputStream.write(create256bytes());
    outputStream.truncate();
    outputStream.close();
    Assert.assertTrue(FileUtils.contentEquals(inputFile, file));
}

From source file:org.gluu.oxtrust.action.ManageCertificateAction.java

/**
 * Updates certificates from temporary working directory to production and
 * restarts services./*from ww w. jav  a 2s.c o m*/
 * 
 * @return true if update was successful. false if update was aborted due to
 *         some error (perhaps permissions issue.)
 */
private boolean updateCertificates() {
    if (!compare(tomcatCertFN) || !compare(idpCertFN)) {
        facesMessages.add(Severity.ERROR,
                "Certificates and private keys should match. Certificate update aborted.");
        return false;
    }

    String tempDirFN = applicationConfiguration.getTempCertDir();
    String dirFN = applicationConfiguration.getCertDir();
    File certDir = new File(dirFN);
    File tempDir = new File(tempDirFN);
    if (tempDirFN == null || dirFN == null || !certDir.isDirectory() || !tempDir.isDirectory()) {
        facesMessages.add(Severity.ERROR, "Certificate update aborted due to filesystem error");
        return false;
    } else {
        File[] files = tempDir.listFiles();
        for (File file : files) {
            try {
                if (file.isFile()
                        && !FileUtils.contentEquals(file, new File(dirFN + File.separator + file.getName()))) {
                    FileHelper.copy(file, new File(dirFN + File.separator + file.getName()));
                    this.wereAnyChanges = true;
                }
            } catch (IOException e) {
                facesMessages.add(Severity.FATAL,
                        "Certificate update failed. Certificates may have been corrupted. Please contact a Gluu administrator for help.");
                log.fatal("Error occured on certificates update:", e);
            }
        }
    }

    return true;
}

From source file:org.jahia.configuration.configurators.JBossConfiguratorTest.java

@Override
public void testUpdateConfiguration() throws Exception {
    FileSystemManager fsManager = VFS.getManager();
    AbstractLogger logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);

    URL cfgFileUrl = this.getClass().getClassLoader().getResource("configurators/jboss/standalone.xml");
    File sourceCfgFile = new File(cfgFileUrl.getFile());

    JBossConfigurator configurator = new JBossConfigurator(oracleDBProperties, websphereOracleConfigBean, null,
            logger);// w  ww.ja  va2 s.co  m
    String destFileName = sourceCfgFile.getParent() + "/standalone-modified.xml";
    configurator.updateConfiguration(new VFSConfigFile(fsManager, cfgFileUrl.toExternalForm()), destFileName);

    String content = FileUtils.readFileToString(new File(destFileName));

    assertTrue(content.contains("<driver name=\"jahia.oracle\" module=\"org.jahia.jdbc.oracle\">"));
    assertTrue(content.contains("<driver-class>oracle.jdbc.OracleDriver</driver-class>"));
    assertTrue(content.contains("<datasource jndi-name=\"java:/jahiaDS\""));
    assertTrue(content.contains("<connection-url>jdbc:oracle"));

    assertTrue(content.contains("enable-welcome-root=\"false\""));

    String unchangedDestFileName = sourceCfgFile.getParent() + "/standalone-modified-unchanged.xml";
    configurator.updateConfiguration(new VFSConfigFile(fsManager, destFileName), unchangedDestFileName);

    assertTrue(FileUtils.contentEquals(new File(destFileName), new File(unchangedDestFileName)));

    configurator = new JBossConfigurator(mysqlDBProperties, tomcatMySQLConfigBean, null, logger);
    String updatedDestFileName = sourceCfgFile.getParent() + "/standalone-modified-updated.xml";
    configurator.updateConfiguration(new VFSConfigFile(fsManager, unchangedDestFileName), updatedDestFileName);

    assertFalse(FileUtils.contentEquals(new File(unchangedDestFileName), new File(updatedDestFileName)));

    content = FileUtils.readFileToString(new File(updatedDestFileName));
    assertTrue(content.contains("<driver name=\"jahia.mysql\" module=\"org.jahia.jdbc.mysql\">"));
    assertTrue(content.contains("<driver-class>com.mysql.jdbc.Driver</driver-class>"));
    assertTrue(content.contains("<connection-url>jdbc:mysql"));
    assertFalse(content.contains("<connection-url>jdbc:oracle"));
    assertTrue(content.contains(
            "<connector name=\"http\" protocol=\"org.apache.coyote.http11.Http11NioProtocol\" scheme=\"http\" socket-binding=\"http\" />"));
}

From source file:org.jbb.lib.properties.UpdateFilePropertyChangeListenerTest.java

@Test
public void shouldUpdateFileContent_whenPropertyChange() throws Exception {
    // given/*from ww w  .ja v  a2 s  .  c om*/
    // see setUp method

    // when
    listener.propertyChange(new PropertyChangeEvent(testPropertyFile, "foo", "test1", "new"));

    // then
    assertThat(FileUtils.contentEquals(testPropertyFile,
            new ClassPathResource("test1-after-change-event.properties").getFile())).isTrue();
}

From source file:org.jboss.tools.tycho.sitegenerator.CompareWithBaselineMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {//from  w  w w  .jav a 2  s. c  o m
        getLog().info("Skipped");
        return;
    }
    ReactorProject reactorProject = DefaultReactorProject.adapt(project);
    Set<?> dependencyMetadata = reactorProject.getDependencyMetadata(true);
    if (dependencyMetadata == null || dependencyMetadata.isEmpty()) {
        getLog().debug("Skipping baseline version comparison, no p2 artifacts created in build.");
        return;
    }

    P2ResolverFactory resolverFactory = this.equinox.getService(P2ResolverFactory.class);
    P2Resolver resolver = resolverFactory.createResolver(new MavenLoggerAdapter(this.plexusLogger, true));

    TargetPlatformConfigurationStub baselineTPStub = new TargetPlatformConfigurationStub();
    baselineTPStub.setForceIgnoreLocalArtifacts(true);
    baselineTPStub.setEnvironments(Collections.singletonList(TargetEnvironment.getRunningEnvironment()));
    for (String baselineRepo : this.baselines) {
        baselineTPStub.addP2Repository(toRepoURI(baselineRepo));
    }
    TargetPlatform baselineTP = resolverFactory.getTargetPlatformFactory().createTargetPlatform(baselineTPStub,
            TychoProjectUtils.getExecutionEnvironmentConfiguration(this.project), null, null);

    for (Object item : dependencyMetadata) {
        try {
            Method getIdMethod = item.getClass().getMethod("getId");
            Method getVersionMethod = item.getClass().getMethod("getVersion");
            String id = (String) getIdMethod.invoke(item);
            Version version = new Version(getVersionMethod.invoke(item).toString());
            P2ResolutionResult res = resolver.resolveInstallableUnit(baselineTP, id, "0.0.0");

            for (Entry foundInBaseline : res.getArtifacts()) {
                Version baselineVersion = new Version(foundInBaseline.getVersion());
                String delta = "" + (version.getMajor() - baselineVersion.getMajor()) + "."
                        + (version.getMinor() - baselineVersion.getMinor()) + "."
                        + (version.getMicro() - baselineVersion.getMicro());

                getLog().debug("Found " + foundInBaseline.getId() + "/" + foundInBaseline.getVersion()
                        + " with delta: " + delta);
                if (version.compareTo(baselineVersion) <= 0) {
                    String message = "Version have moved backwards for (" + id + "/" + version
                            + "). Baseline has " + baselineVersion + ") with delta: " + delta;
                    if (this.onIllegalVersion == ReportBehavior.warn) {
                        getLog().warn(message);
                        return;
                    } else {
                        throw new MojoFailureException(message);
                    }
                } else if (version.equals(baselineVersion)) {
                    File baselineFile = foundInBaseline.getLocation();
                    File currentFile = null;
                    // TODO: currently, there are only 2 kinds of (known) artifacts, but we could have more
                    // and unknown ones. Need to find something smarter to map artifact with actual file.
                    if (id.endsWith("source")) {
                        currentFile = reactorProject.getArtifact("sources");
                    } else {
                        currentFile = reactorProject.getArtifact();
                    }
                    if (!FileUtils.contentEquals(currentFile, baselineFile)) {
                        String message = "Duplicate version but different content found for (" + id + "/"
                                + version + "). Also exists in baseline, but its content is different.";
                        if (this.onIllegalVersion == ReportBehavior.warn) {
                            getLog().warn(message);
                            return;
                        } else {
                            throw new MojoFailureException(message);
                        }
                    }
                } else if (version.getMajor() == baselineVersion.getMajor()
                        && version.getMinor() == baselineVersion.getMinor()
                        && version.getMicro() == baselineVersion.getMicro()) {
                    String message = "Only qualifier changed for (" + id + "/" + version
                            + "). Expected to have bigger x.y.z than what is available in baseline ("
                            + baselineVersion + ")";
                    if (this.onIllegalVersion == ReportBehavior.warn) {
                        getLog().warn(message);
                        return;
                    } else {
                        throw new MojoFailureException(message);
                    }
                }
            }

        } catch (Exception ex) {
            throw new MojoFailureException(ex.getMessage(), ex);
        }
    }
}

From source file:org.jvnet.hudson.plugins.backup.utils.compress.ArchiverTestUtil.java

/**
 * Compare the content of 2 dufferents directory
 * @param directory1//from  ww  w .  j  a v a  2 s.  co m
 * @param directory2
 * @return
 * @throws IOException
 */
public static boolean compareDirectoryContent(File directory1, File directory2) throws IOException {
    if (!directory1.isDirectory() || !directory2.isDirectory()) {
        return false;
    }

    File list1[] = directory1.listFiles();
    File list2[] = directory2.listFiles();

    if (list1.length != list2.length) {
        return false;
    }

    for (int i = 0; i < list1.length; i++) {
        File file1 = list1[i];
        File file2 = list2[i];

        if (!file1.getName().equals(file2.getName())) {
            return false;
        }

        if (file1.isDirectory()) {
            return compareDirectoryContent(file1, file2);
        } else {
            return FileUtils.contentEquals(file1, file2);
        }
    }
    return true;
}