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.ebayopensource.turmeric.eclipse.test.util.TLArtifactValidator.java

@Override
public boolean visit(IResource resource) throws CoreException {

    if (!matches)
        return false;

    IPath path = resource.getProjectRelativePath();
    if (StringUtils.isEmpty(path.toString()))
        return true;

    if (path.toString().startsWith("bin"))
        return true;

    if (path.toString().startsWith("build"))
        return true;

    // Verify Builder and Nature in .project
    if (path.toString().equalsIgnoreCase(".project"))
        return true;

    // Skipping validaton of ObjectFactory.java as it is generated in a
    // different way each time.
    if (path.toString().endsWith("ObjectFactory.java"))
        return true;

    if (path.toString().startsWith(".settings"))
        return true;

    // Skipping validaton of TypeMapping.xml as it is generated in a
    // different way each time.
    if (path.toString().endsWith("TypeInformation.xml"))
        return true;

    if (path.toString().endsWith(".episode"))
        return true;

    if (path.toString().endsWith("pom.xml"))
        return true;

    if (path.toString().endsWith(".classpath"))
        return true;

    // now compare with the files in the gold copy
    IPath rsrcPath = resource.getProject().getLocation().append(path);
    System.out.println(rsrcPath.toOSString());
    if (rsrcPath.toFile().isFile()) {
        if (rsrcPath.toString().endsWith("properties")) {
            Properties srcProp = new Properties();
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(rsrcPath.toFile());
                srcProp.load(fis);/*from www . j  a v a2  s .co  m*/
            } catch (Exception e) {
                e.printStackTrace();
                matches = false;
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                } catch (IOException ex) {

                }
            }
            Properties goldCopyProp = new Properties();
            FileInputStream fileStream = null;
            try {
                fileStream = new FileInputStream(new File(goldCopyDir + "/" + path.toString()));
                goldCopyProp.load(fileStream);
            } catch (Exception e) {
                e.printStackTrace();
                matches = false;
            } finally {
                if (fileStream != null) {
                    try {
                        fileStream.close();
                    } catch (IOException e) {

                    }
                }
            }
            if (matches) {
                matches = PropertiesFileUtil.isEqual(srcProp, goldCopyProp);
            }
        } else {
            try {
                if (path.toString().startsWith("gen-src")) {
                    if (path.toString().endsWith(resource.getProject().getName() + ".java")) {
                        // Assert the location
                        if (FileUtils.contentEquals(rsrcPath.toFile(),
                                new File(goldCopyDir + "/" + path.toString())) == false) {
                            System.out.println("the following did not match: " + goldCopyDir + "/" + path);
                            matches = false;
                        }
                    } else {
                        matches = true;
                    }
                } else if (path.toString().startsWith("gen-meta-src")) {
                    if (FileUtils.contentEquals(rsrcPath.toFile(),
                            new File(goldCopyDir + "/" + path.toString())) == false) {
                        System.out.println("the following did not match: " + goldCopyDir + "/" + path);
                        matches = false;
                    }

                } else {
                    if (FileUtils.contentEquals(rsrcPath.toFile(),
                            new File(goldCopyDir + "/" + path.toString())) == false) {
                        System.out.println("the following did not match: " + goldCopyDir + "/" + path);
                        matches = false;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("the following did not match: " + goldCopyDir + "/" + path);
                matches = false;
            }
        }
    } else {
        files.remove(new File(goldCopyDir + "/" + path.toString()));
    }
    return true;

}

From source file:org.ebayopensource.turmeric.eclipse.test.utils.TLArtifactValidator.java

/**
 * {@inheritDoc}//from   ww  w  .  j av  a 2  s . co  m
 */

@Override
public boolean visit(IResource resource) throws CoreException {

    if (!matches)
        return false;

    IPath path = resource.getProjectRelativePath();
    if (StringUtils.isEmpty(path.toString()))
        return true;

    if (path.toString().startsWith("bin"))
        return true;

    if (path.toString().startsWith("build"))
        return true;

    // Verify Builder and Nature in .project 
    if (path.toString().equalsIgnoreCase(".project"))
        return true;

    // Skipping validaton of ObjectFactory.java as it is generated in a different way each time.
    if (path.toString().endsWith("ObjectFactory.java"))
        return true;

    if (path.toString().startsWith(".settings"))
        return true;

    // Skipping validaton of TypeMapping.xml as it is generated in a different way each time.
    if (path.toString().endsWith("TypeInformation.xml"))
        return true;

    if (path.toString().endsWith(".episode"))
        return true;

    // now compare with the files in the gold copy
    IPath rsrcPath = resource.getProject().getLocation().append(path);
    System.out.println(rsrcPath.toOSString());
    if (rsrcPath.toFile().isFile()) {
        if (rsrcPath.toString().endsWith("properties")) {
            Properties srcProp = new Properties();
            FileInputStream srcIs = null;
            try {
                srcIs = new FileInputStream(rsrcPath.toFile());
                srcProp.load(srcIs);
            } catch (Exception e) {
                e.printStackTrace();
                matches = false;
            } finally {
                closeInputStream(srcIs);
            }
            Properties goldCopyProp = new Properties();
            FileInputStream is = null;
            try {
                is = new FileInputStream(new File(goldCopyDir + "/" + path.toString()));
                goldCopyProp.load(is);
            } catch (Exception e) {
                e.printStackTrace();
                matches = false;
            } finally {
                closeInputStream(is);
            }
            if (matches) {
                matches = PropertiesFileUtil.isEqual(srcProp, goldCopyProp);
            }
        } else {
            try {
                if (path.toString().startsWith("gen-src")) {
                    if (path.toString().endsWith(resource.getProject().getName() + ".java")) {
                        //                  Assert the location
                        if (FileUtils.contentEquals(rsrcPath.toFile(),
                                new File(goldCopyDir + "/" + path.toString())) == false) {
                            System.out.println("the following did not match: " + goldCopyDir + "/" + path);
                            matches = false;
                        }
                    } else {
                        matches = true;
                    }
                } else if (path.toString().startsWith("gen-meta-src")) {
                    if (FileUtils.contentEquals(rsrcPath.toFile(),
                            new File(goldCopyDir + "/" + path.toString())) == false) {
                        System.out.println("the following did not match: " + goldCopyDir + "/" + path);
                        matches = false;
                    }

                } else {
                    if (FileUtils.contentEquals(rsrcPath.toFile(),
                            new File(goldCopyDir + "/" + path.toString())) == false) {
                        System.out.println("the following did not match: " + goldCopyDir + "/" + path);
                        matches = false;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("the following did not match: " + goldCopyDir + "/" + path);
                matches = false;
            }
        }
    } else {
        files.remove(new File(goldCopyDir + "/" + path.toString()));
    }
    return true;

}

From source file:org.eclipse.jdt.ls.core.internal.handlers.InitHandlerTest.java

@Test
public void testWatchers() throws Exception {
    ClientPreferences mockCapabilies = mock(ClientPreferences.class);
    when(mockCapabilies.isWorkspaceChangeWatchedFilesDynamicRegistered()).thenReturn(Boolean.TRUE);
    when(preferenceManager.getClientPreferences()).thenReturn(mockCapabilies);

    importProjects(Arrays.asList("maven/salut", "gradle/simple-gradle"));
    newEmptyProject();//from w ww . j  a v a  2  s. co m
    List<FileSystemWatcher> watchers = projectsManager.registerWatchers();
    Collections.sort(watchers, new Comparator<FileSystemWatcher>() {

        @Override
        public int compare(FileSystemWatcher o1, FileSystemWatcher o2) {
            return o1.getGlobPattern().compareTo(o2.getGlobPattern());
        }
    });
    assertEquals("Unexpected watchers:\n" + toString(watchers), 8, watchers.size());
    assertEquals("**/*.gradle", watchers.get(0).getGlobPattern());
    assertEquals("**/*.java", watchers.get(1).getGlobPattern());
    assertEquals("**/.classpath", watchers.get(2).getGlobPattern());
    assertEquals("**/.project", watchers.get(3).getGlobPattern());
    assertEquals("**/.settings/*.prefs", watchers.get(4).getGlobPattern());
    assertEquals("**/gradle.properties", watchers.get(5).getGlobPattern());
    assertEquals("**/pom.xml", watchers.get(6).getGlobPattern());
    assertEquals("**/src/**", watchers.get(7).getGlobPattern());
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("salut");
    String location = project.getLocation().toString();
    IJavaProject javaProject = JavaCore.create(project);
    // for test purposes only
    removeExclusionPattern(javaProject);
    File outputDir = new File(new File(location),
            javaProject.getOutputLocation().removeFirstSegments(1).toOSString());
    File outputFile = new File(outputDir, "test.properties");
    String resourceName = location + "/src/main/resources/test.properties";
    String uri = "file://" + resourceName;
    File sourceFile = new Path(resourceName).toFile();
    assertTrue(FileUtils.contentEquals(sourceFile, outputFile));
    FileUtils.writeStringToFile(sourceFile, TEST_CONTENT);
    FileEvent fileEvent = new FileEvent(uri, FileChangeType.Changed);
    DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams();
    params.getChanges().add(fileEvent);
    server.didChangeWatchedFiles(params);
    JobHelpers.waitForJobsToComplete();
    assertTrue(FileUtils.contentEquals(sourceFile, outputFile));
    verify(client, times(1)).registerCapability(any());
    List<FileSystemWatcher> newWatchers = projectsManager.registerWatchers();
    verify(client, times(1)).registerCapability(any());
    Collections.sort(newWatchers, new Comparator<FileSystemWatcher>() {

        @Override
        public int compare(FileSystemWatcher o1, FileSystemWatcher o2) {
            return o1.getGlobPattern().compareTo(o2.getGlobPattern());
        }
    });
    assertEquals(newWatchers, watchers);
}

From source file:org.eclipse.kura.linux.net.iptables.LinuxFirewall.java

private boolean writeFile() throws KuraException {
    s_logger.trace("writing to file:  " + FIREWALL_TMP_SCRIPT_NAME);
    PrintWriter pw = null;/*from  w  w w  . j  a v  a 2s .  c  o m*/
    try {
        pw = new PrintWriter(new FileOutputStream(FIREWALL_TMP_SCRIPT_NAME));
        for (String line : HEADER) {
            pw.println(line);
        }
        for (String line : CLEAR_ALL_CHAINS) {
            pw.println(line);
        }
        for (String line : BLOCK_POLICY) {
            pw.println(line);
        }

        if (m_allowIcmp) {
            for (String line : ALLOW_ICMP) {
                pw.println(line);
            }
        } else {
            for (String line : DO_NOT_ALLOW_ICMP) {
                pw.println(line);
            }
        }

        pw.println("#custom local service rules");
        Iterator<LocalRule> itLocalRules = m_localRules.iterator();
        while (itLocalRules.hasNext()) {
            pw.println(itLocalRules.next());
        }
        pw.println();
        pw.println("#custom port forward service rules");
        Iterator<PortForwardRule> itPortForwardRules = m_portForwardRules.iterator();
        while (itPortForwardRules.hasNext()) {
            pw.println(itPortForwardRules.next());
        }
        pw.println();
        pw.println("#custom automatic NAT service rules (if NAT option is enabled for LAN interface)");
        Iterator<NATRule> itAutoNatRules = m_autoNatRules.iterator();
        while (itAutoNatRules.hasNext()) {
            pw.println(itAutoNatRules.next());
        }
        pw.println();
        pw.println("#custom NAT service rules");
        Iterator<NATRule> itNatRules = m_natRules.iterator();
        while (itNatRules.hasNext()) {
            pw.println(itNatRules.next());
        }
        pw.println();
        pw.println("#custom rules");
        Iterator<String> itCustomRules = m_customRules.iterator();
        while (itCustomRules.hasNext()) {
            pw.println(itCustomRules.next());
        }
        pw.println();
        if (m_allowForwarding) {
            for (String line : ALLOW_FORWARDING) {
                pw.println(line);
            }
        } else {
            for (String line : DO_NOT_ALLOW_FORWARDING) {
                pw.println(line);
            }
        }

        pw.println();
        for (String line : FOOTER) {
            pw.println(line);
        }
        pw.close();

        SafeProcess proc = null;
        try {
            proc = ProcessUtil.exec("chmod 755 " + FIREWALL_TMP_SCRIPT_NAME);
            proc.waitFor();
        } finally {
            if (proc != null)
                ProcessUtil.destroy(proc);
        }

        //move the file if we made it this far
        File tmpFirewallFile = new File(FIREWALL_TMP_SCRIPT_NAME);
        File firewallFile = new File(FIREWALL_SCRIPT_NAME);
        if (!FileUtils.contentEquals(tmpFirewallFile, firewallFile)) {
            if (tmpFirewallFile.renameTo(firewallFile)) {
                s_logger.info("writeFile() :: Successfully wrote firewall file");
                return true;
            } else {
                s_logger.error("writeFile() :: Failed to write firewall file");
                throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR,
                        "error while building up new configuration file for firewall");
            }
        } else {
            s_logger.info("writeFile() :: Not rewriting firewall file because it is the same");
            return false;
        }
    } catch (Exception e) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
    } finally {
        if (pw != null) {
            pw.close();
        }
    }
}

From source file:org.eclipse.kura.linux.net.iptables.LinuxFirewall.java

public void disable() throws KuraException {
    this.iptablesSave();

    s_logger.trace("writing to file:  " + FIREWALL_TMP_SCRIPT_NAME);
    try {/*from ww  w  .  java 2 s .  c  o  m*/
        PrintWriter pw = new PrintWriter(new FileOutputStream(FIREWALL_TMP_SCRIPT_NAME));
        for (String line : HEADER) {
            pw.println(line);
        }
        for (String line : CLEAR_ALL_CHAINS) {
            pw.println(line);
        }
        pw.flush();
        pw.close();

        //move the file if we made it this far
        File tmpFirewallFile = new File(FIREWALL_TMP_SCRIPT_NAME);
        File firewallFile = new File(FIREWALL_SCRIPT_NAME);
        if (!FileUtils.contentEquals(tmpFirewallFile, firewallFile)) {
            if (tmpFirewallFile.renameTo(firewallFile)) {
                s_logger.info("disable() :: Successfully wrote firewall file");
                runScript();
            } else {
                s_logger.error("disable() :: Failed to write firewall file");
                throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR,
                        "error while building up new configuration file for firewall");
            }
        } else {
            s_logger.info("disable() :: Not rewriting firewall file because it is the same");
        }
    } catch (Exception e) {
        throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
    }
}

From source file:org.eclipse.kura.net.admin.visitor.linux.DhcpConfigWriter.java

private void writeConfig(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig)
        throws KuraException {
    String interfaceName = netInterfaceConfig.getName();

    /*//  ww w  . j ava  2 s . c o m
     * String dhcpConfigFileName = new
     * StringBuffer().append(FILE_DIR).append("dhcpd-").append(interfaceName).append(".conf").toString();
     * String tmpDhcpConfigFileName = new
     * StringBuffer().append(FILE_DIR).append("dhcpd-").append(interfaceName).append(".conf").append(".tmp").
     * toString();
     */
    String dhcpConfigFileName = DhcpServerManager.getConfigFilename(interfaceName);
    String tmpDhcpConfigFileName = new StringBuilder(dhcpConfigFileName).append(".tmp").toString();

    s_logger.debug("Writing DHCP config for {}", interfaceName);

    List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = netInterfaceConfig
            .getNetInterfaceAddresses();

    if (netInterfaceAddressConfigs != null && netInterfaceAddressConfigs.size() > 0) {
        for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) {
            List<NetConfig> netConfigs = netInterfaceAddressConfig.getConfigs();

            if (netConfigs != null) {
                for (NetConfig netConfig : netConfigs) {
                    if (netConfig instanceof DhcpServerConfig4) {
                        DhcpServerConfig4 dhcpServerConfig = (DhcpServerConfig4) netConfig;
                        writeConfigFile(tmpDhcpConfigFileName, interfaceName, dhcpServerConfig);
                        // move the file if we made it this far and they are different
                        File tmpDhcpConfigFile = new File(tmpDhcpConfigFileName);
                        File dhcpConfigFile = new File(dhcpConfigFileName);
                        try {
                            if (!FileUtils.contentEquals(tmpDhcpConfigFile, dhcpConfigFile)) {
                                if (tmpDhcpConfigFile.renameTo(dhcpConfigFile)) {
                                    s_logger.trace("Successfully wrote DHCP config file");
                                } else {
                                    s_logger.error("Failed to write DHCP config file for " + interfaceName);
                                    throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR,
                                            "error while building up new configuration files for dhcp server: "
                                                    + interfaceName);
                                }
                            } else {
                                s_logger.info("Not rewriting DHCP config file for " + interfaceName
                                        + " because it is the same");
                            }
                        } catch (IOException e) {
                            throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR,
                                    "error while building up new configuration files for dhcp servers", e);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.kura.net.admin.visitor.linux.HostapdConfigWriter.java

private void moveFile(String ifaceName) throws Exception {
    File tmpFile = new File(HOSTAPD_TMP_CONFIG_FILE);
    File file = new File(HostapdManager.getHostapdConfigFileName(ifaceName));
    if (!FileUtils.contentEquals(tmpFile, file)) {
        if (tmpFile.renameTo(file)) {
            s_logger.trace("Successfully wrote hostapd.conf file");
        } else {//from  ww w .  ja  va2 s.co  m
            s_logger.error("Failed to write hostapd.conf file");
            throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR,
                    "error while building up new configuration file for hostapd");
        }
    } else {
        s_logger.info("Not rewriting hostapd.conf file because it is the same");
    }
}

From source file:org.eclipse.kura.net.admin.visitor.linux.IfcfgConfigWriter.java

private void writeRedhatConfig(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig)
        throws KuraException {
    String interfaceName = netInterfaceConfig.getName();
    String outputFileName = new StringBuffer().append(REDHAT_NET_CONFIGURATION_DIRECTORY).append("ifcfg-")
            .append(interfaceName).toString();
    String tmpOutputFileName = new StringBuffer().append(REDHAT_NET_CONFIGURATION_DIRECTORY).append("ifcfg-")
            .append(interfaceName).append(".tmp").toString();
    s_logger.debug("Writing config for {}", interfaceName);

    NetInterfaceType type = netInterfaceConfig.getType();
    if (type == NetInterfaceType.ETHERNET || type == NetInterfaceType.WIFI
            || type == NetInterfaceType.LOOPBACK) {
        StringBuffer sb = new StringBuffer();
        sb.append("# Networking Interface\n");

        // DEVICE
        sb.append("DEVICE=").append(netInterfaceConfig.getName()).append("\n");

        // NAME//from w  ww. j a  va2  s.c  om
        sb.append("NAME=").append(netInterfaceConfig.getName()).append("\n");

        // TYPE
        sb.append("TYPE=").append(netInterfaceConfig.getType()).append("\n");

        List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = netInterfaceConfig
                .getNetInterfaceAddresses();
        s_logger.debug("There are " + netInterfaceAddressConfigs.size()
                + " NetInterfaceConfigs in this configuration");

        boolean allowWrite = false;
        for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) {
            List<NetConfig> netConfigs = netInterfaceAddressConfig.getConfigs();

            if (netConfigs != null) {
                for (NetConfig netConfig : netConfigs) {
                    if (netConfig instanceof NetConfigIP4) {
                        // ONBOOT
                        sb.append("ONBOOT=");
                        if (((NetConfigIP4) netConfig).isAutoConnect()) {
                            sb.append("yes");
                        } else {
                            sb.append("no");
                        }
                        sb.append("\n");

                        if (((NetConfigIP4) netConfig).isDhcp()) {
                            // BOOTPROTO
                            sb.append("BOOTPROTO=");
                            s_logger.debug("new config is DHCP");
                            sb.append("dhcp");
                            sb.append("\n");
                        } else {
                            // BOOTPROTO
                            sb.append("BOOTPROTO=");
                            s_logger.debug("new config is STATIC");
                            sb.append("static");
                            sb.append("\n");

                            // IPADDR
                            sb.append("IPADDR=")
                                    .append(((NetConfigIP4) netConfig).getAddress().getHostAddress())
                                    .append("\n");

                            // PREFIX
                            sb.append("PREFIX=").append(((NetConfigIP4) netConfig).getNetworkPrefixLength())
                                    .append("\n");

                            // Gateway
                            if (((NetConfigIP4) netConfig).getGateway() != null) {
                                sb.append("GATEWAY=")
                                        .append(((NetConfigIP4) netConfig).getGateway().getHostAddress())
                                        .append("\n");
                            }
                        }

                        // DEFROUTE
                        if (((NetConfigIP4) netConfig)
                                .getStatus() == NetInterfaceStatus.netIPv4StatusEnabledWAN) {
                            sb.append("DEFROUTE=yes\n");
                        } else {
                            sb.append("DEFROUTE=no\n");
                        }

                        // DNS
                        List<? extends IPAddress> dnsAddresses = ((NetConfigIP4) netConfig).getDnsServers();
                        if (dnsAddresses != null && dnsAddresses.size() > 0) {
                            for (int i = 0; i < dnsAddresses.size(); i++) {
                                IPAddress ipAddr = dnsAddresses.get(i);
                                if (!(ipAddr.isLoopbackAddress() || ipAddr.isLinkLocalAddress()
                                        || ipAddr.isMulticastAddress())) {
                                    sb.append("DNS").append(i + 1).append("=").append(ipAddr.getHostAddress())
                                            .append("\n");
                                }
                            }
                        } else {
                            s_logger.debug("no DNS entries");
                        }

                        allowWrite = true;
                    }
                }
            } else {
                s_logger.debug("netConfigs is null");
            }

            // WIFI
            if (netInterfaceAddressConfig instanceof WifiInterfaceAddressConfig) {
                s_logger.debug("new config is a WifiInterfaceAddressConfig");
                sb.append("\n#Wireless configuration\n");

                // MODE
                String mode = null;
                WifiMode wifiMode = ((WifiInterfaceAddressConfig) netInterfaceAddressConfig).getMode();
                if (wifiMode == WifiMode.INFRA) {
                    mode = "Managed";
                } else if (wifiMode == WifiMode.MASTER) {
                    mode = "Master";
                } else if (wifiMode == WifiMode.ADHOC) {
                    mode = "Ad-Hoc";
                } else if (wifiMode == null) {
                    s_logger.error("WifiMode is null");
                    mode = "null";
                } else {
                    mode = wifiMode.toString();
                }
                sb.append("MODE=").append(mode).append("\n");
            }
        }

        if (allowWrite) {
            FileOutputStream fos = null;
            PrintWriter pw = null;
            try {
                fos = new FileOutputStream(tmpOutputFileName);
                pw = new PrintWriter(fos);
                pw.write(sb.toString());
                pw.flush();
                fos.getFD().sync();
            } catch (Exception e) {
                throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException ex) {
                        s_logger.error("I/O Exception while closing BufferedReader!");
                    }
                }
                if (pw != null) {
                    pw.close();
                }
            }

            // move the file if we made it this far
            File tmpFile = new File(tmpOutputFileName);
            File outputFile = new File(outputFileName);
            try {
                if (!FileUtils.contentEquals(tmpFile, outputFile)) {
                    if (tmpFile.renameTo(outputFile)) {
                        s_logger.trace("Successfully wrote network interface file for {}", interfaceName);
                    } else {
                        s_logger.error("Failed to write network interface file");
                        throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR,
                                "error while building up new configuration file for network interface "
                                        + interfaceName);
                    }
                } else {
                    s_logger.info("Not rewriting network interfaces file for " + interfaceName
                            + " because it is the same");
                }
            } catch (IOException e) {
                throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
            }
        } else {
            s_logger.warn("writeNewConfig :: operation is not allowed");
        }
    }
}

From source file:org.eclipse.kura.net.admin.visitor.linux.IfcfgConfigWriter.java

private void writeDebianConfig(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig)
        throws KuraException {
    StringBuffer sb = new StringBuffer();
    File kuraFile = new File(DEBIAN_NET_CONFIGURATION_FILE);
    String iName = netInterfaceConfig.getName();
    boolean appendConfig = true;

    if (kuraFile.exists()) {
        // found our match so load the properties
        Scanner scanner = null;/*from   w w  w .j av  a 2s.  c  o m*/
        try {
            scanner = new Scanner(new FileInputStream(kuraFile));

            // need to loop through the existing file and replace only the desired interface
            while (scanner.hasNextLine()) {
                String noTrimLine = scanner.nextLine();
                String line = noTrimLine.trim();
                // ignore comments and blank lines
                if (!line.isEmpty()) {
                    if (line.startsWith("#!kura!")) {
                        line = line.substring("#!kura!".length());
                    }

                    if (!line.startsWith("#")) {
                        String[] args = line.split("\\s+");
                        // must be a line stating that interface starts on boot
                        if (args.length > 1) {
                            if (args[1].equals(iName)) {
                                s_logger.debug("Found entry in interface file...");
                                appendConfig = false;
                                sb.append(debianWriteUtility(netInterfaceConfig, iName));

                                // remove old config lines from the scanner
                                while (scanner.hasNextLine() && !(line = scanner.nextLine()).isEmpty()) {
                                }
                                sb.append("\n");
                            } else {
                                sb.append(noTrimLine + "\n");
                            }
                        }
                    } else {
                        sb.append(noTrimLine + "\n");
                    }
                } else {
                    sb.append(noTrimLine + "\n");
                }
            }
        } catch (FileNotFoundException e1) {
            throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e1);
        } finally {
            scanner.close();
            scanner = null;
        }

        // If config not present in file, append to end
        if (appendConfig) {
            s_logger.debug("Appending entry to interface file...");
            // append an empty line if not there
            String s = sb.toString();
            if (!"\\n".equals(s.substring(s.length() - 1))) {
                sb.append("\n");
            }
            sb.append(debianWriteUtility(netInterfaceConfig, iName));
            sb.append("\n");
        }

        FileOutputStream fos = null;
        PrintWriter pw = null;
        try {
            fos = new FileOutputStream(DEBIAN_TMP_NET_CONFIGURATION_FILE);
            pw = new PrintWriter(fos);
            pw.write(sb.toString());
            pw.flush();
            fos.getFD().sync();
        } catch (Exception e) {
            throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    s_logger.error("I/O Exception while closing BufferedReader!");
                }
            }
            if (pw != null) {
                pw.close();
            }
        }

        // move the file if we made it this far
        File tmpFile = new File(DEBIAN_TMP_NET_CONFIGURATION_FILE);
        File file = new File(DEBIAN_NET_CONFIGURATION_FILE);
        try {
            if (!FileUtils.contentEquals(tmpFile, file)) {
                if (tmpFile.renameTo(file)) {
                    s_logger.trace("Successfully wrote network interfaces file");
                } else {
                    s_logger.error("Failed to write network interfaces file");
                    throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR,
                            "error while building up new configuration file for network interfaces");
                }
            } else {
                s_logger.info("Not rewriting network interfaces file because it is the same");
            }
        } catch (IOException e) {
            throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e);
        }
    }
}

From source file:org.eclipse.kura.net.admin.visitor.linux.util.KuranetConfig.java

public static void storeProperties(Properties props) throws IOException, KuraException {
    Properties oldProperties = KuranetConfig.getProperties();

    if (oldProperties == null || !oldProperties.equals(props)) {
        FileOutputStream fos = null;
        try {//from   w w w.j ava2s . c o  m
            fos = new FileOutputStream(KURANET_TMP_FILENAME);
            props.store(fos, null);
            fos.flush();
            fos.getFD().sync();

            // move the file if we made it this far
            File tmpFile = new File(KURANET_TMP_FILENAME);
            File file = new File(KURANET_FILENAME);
            if (!FileUtils.contentEquals(tmpFile, file)) {
                if (tmpFile.renameTo(file)) {
                    s_logger.trace("Successfully wrote kuranet props file");
                } else {
                    s_logger.error("Failed to write kuranet props file");
                    throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR,
                            "error while building up new configuration file for kuranet props");
                }
            } else {
                s_logger.info("Not rewriting kuranet props file because it is the same");
            }
        } finally {
            fos.close();
        }
    }
}