Example usage for java.io File equals

List of usage examples for java.io File equals

Introduction

In this page you can find the example usage for java.io File equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Tests this abstract pathname for equality with the given object.

Usage

From source file:org.apache.bookkeeper.bookie.LedgerCacheTest.java

/**
 * Test Ledger Cache flush failure//  ww w . j  av  a 2  s  .c  o  m
 */
@Test(timeout = 30000)
public void testLedgerCacheFlushFailureOnDiskFull() throws Exception {
    File ledgerDir1 = createTempDir("bkTest", ".dir");
    File ledgerDir2 = createTempDir("bkTest", ".dir");
    ServerConfiguration conf = TestBKConfiguration.newServerConfiguration();
    conf.setLedgerDirNames(new String[] { ledgerDir1.getAbsolutePath(), ledgerDir2.getAbsolutePath() });

    Bookie bookie = new Bookie(conf);
    InterleavedLedgerStorage ledgerStorage = ((InterleavedLedgerStorage) bookie.ledgerStorage);
    LedgerCacheImpl ledgerCache = (LedgerCacheImpl) ledgerStorage.ledgerCache;
    // Create ledger index file
    ledgerStorage.setMasterKey(1, "key".getBytes());

    FileInfo fileInfo = ledgerCache.getIndexPersistenceManager().getFileInfo(Long.valueOf(1), null);

    // Simulate the flush failure
    FileInfo newFileInfo = new FileInfo(fileInfo.getLf(), fileInfo.getMasterKey());
    ledgerCache.getIndexPersistenceManager().fileInfoCache.put(Long.valueOf(1), newFileInfo);
    // Add entries
    ledgerStorage.addEntry(generateEntry(1, 1));
    ledgerStorage.addEntry(generateEntry(1, 2));
    ledgerStorage.flush();

    ledgerStorage.addEntry(generateEntry(1, 3));
    // add the dir to failed dirs
    bookie.getIndexDirsManager()
            .addToFilledDirs(newFileInfo.getLf().getParentFile().getParentFile().getParentFile());
    File before = newFileInfo.getLf();
    // flush after disk is added as failed.
    ledgerStorage.flush();
    File after = newFileInfo.getLf();

    assertEquals("Reference counting for the file info should be zero.", 0, newFileInfo.getUseCount());

    assertFalse("After flush index file should be changed", before.equals(after));
    // Verify written entries
    Assert.assertArrayEquals(generateEntry(1, 1).array(), ledgerStorage.getEntry(1, 1).array());
    Assert.assertArrayEquals(generateEntry(1, 2).array(), ledgerStorage.getEntry(1, 2).array());
    Assert.assertArrayEquals(generateEntry(1, 3).array(), ledgerStorage.getEntry(1, 3).array());
}

From source file:hu.sztaki.lpds.pgportal.portlets.credential.AssertionPortlet.java

/**
 * Creates a HashMap containing the details of the SAML assertion
 * @param sf File/*  w  ww . j  av  a2s . c o m*/
 * @return HashMap
 * @throws Exception
 */
private HashMap getSAMLDetail(File samlf) throws Exception {
    logger.trace("getSAMLDetail");
    HashMap ch = new HashMap();

    try {
        if (!samlf.equals(null) && samlf.exists() && (samlf.length() > 0)) {
            String id = "";
            String issuer = "";
            String subject = "";
            Long endTime = 0L;
            AssertionDocument td = AssertionDocument.Factory.parse(samlf);

            if (!td.isNil()) {
                id = td.getAssertion().getID();
                issuer = td.getAssertion().getIssuer().getStringValue();
                endTime = td.getAssertion().getConditions().getNotOnOrAfter().getTimeInMillis();
                subject = td.getAssertion().getSubject().getNameID().getStringValue();
            } else {
                logger.info("trust delegation is null");
            }

            ch.put("id", id);
            ch.put("issuer", issuer);
            ch.put("tleft", timeConvert(endTime));
            ch.put("subject", subject);

            return ch;
        }
    } catch (XmlException xmle) {
        logger.info("An XML exception has been caught.", xmle);

        try {
            samlf.delete();
        } catch (Exception e) {
            logger.trace("deleting samlf failed", e);
        }

        throw new Exception("It seems to be not a valid assertion file.");
    }

    return ch;
}

From source file:org.interreg.docexplore.GeneralConfigPanel.java

File browsePlugins() {
    try {/*from  w  w  w  . j a v a2s . c  om*/
        File pluginDir = configFile.getParentFile();
        File file = DocExploreTool.getFileDialogs().openFile(DocExploreTool.getPluginCategory());

        File from = null, dest = null;
        while (from == null) {
            if (file == null)
                break;
            dest = new File(pluginDir, file.getName());
            if (!dest.exists() || file.equals(dest)
                    || JOptionPane.showConfirmDialog(this,
                            XMLResourceBundle.getBundledString("cfgReplacePluginMessage"),
                            XMLResourceBundle.getBundledString("cfgAddPluginLabel"),
                            JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
                from = file;
        }
        if (from == null)
            return null;

        if (!file.equals(dest)) {
            FileUtils.copyFile(from, dest);
            //ByteUtils.copyFile(from, dest);
        }
        return dest;
    } catch (Exception e) {
        ErrorHandler.defaultHandler.submit(e);
    }
    return null;
}

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

public boolean configureVM() throws CoreException {
    String javaHome = preferenceManager.getPreferences().getJavaHome();
    if (javaHome != null) {
        File jvmHome = new File(javaHome);
        if (jvmHome.isDirectory()) {
            IVMInstall defaultVM = JavaRuntime.getDefaultVMInstall();
            File location = defaultVM.getInstallLocation();
            if (!location.equals(jvmHome)) {
                IVMInstall vm = findVM(jvmHome);
                if (vm == null) {
                    IVMInstallType installType = JavaRuntime
                            .getVMInstallType(StandardVMType.ID_STANDARD_VM_TYPE);
                    long unique = System.currentTimeMillis();
                    while (installType.findVMInstall(String.valueOf(unique)) != null) {
                        unique++;/* ww  w . j av  a 2s .  c  o  m*/
                    }
                    String vmId = String.valueOf(unique);
                    VMStandin vmStandin = new VMStandin(installType, vmId);
                    String name = StringUtils.defaultIfBlank(jvmHome.getName(), "JRE");
                    vmStandin.setName(name);
                    vmStandin.setInstallLocation(jvmHome);
                    vm = vmStandin.convertToRealVM();
                }
                JavaRuntime.setDefaultVMInstall(vm, new NullProgressMonitor());
                JDTUtils.setCompatibleVMs(vm.getId());
                return true;
            }
        }
    }
    return false;
}

From source file:org.kepler.ssh.LocalDelete.java

/**
 * Test if a File is a symbolic link. It returns true if the file is a
 * symbolic link, false otherwise. Exception: if the symlink points to
 * itself, it returns false. Sorry. How does it work: it compares the
 * canonical path and the absolute path of the file. The former gives the
 * referred file of a link and thus differs from the absolute path of the
 * link itself./*www. j av a  2s. c  o m*/
 */
private static boolean isSymbolicLink(File f) {

    if (f == null)
        return false;
    if (!f.exists())
        return false;

    // special case: path ends with .., which can never be a symlink, right?
    // Note: symlink/.. refers to the directory containing the symlink and
    // not the link itself
    // special case: path ends with ., it is the same
    // Note: symlink/. refers to the pointed directory and not the link
    // itself
    // They are handled here because they would result in true in later
    // tests.
    if (f.getName().equals("..") || f.getName().equals("."))
        return false;

    // to see if this file is actually a symbolic link to a directory,
    // we want to get its canonical path - that is, we follow the link to
    // the file it's actually linked to
    File canf;
    try {
        canf = f.getCanonicalFile();
    } catch (IOException e) {
        log.error("Cannot get canonical filename of file " + f.getPath());
        return true;
    }

    // we need to get the absolute path
    // Unfortunately File.getAbsolutePath() does not eliminate . and ..
    // thus the equality test fails for paths containing them.
    // Let's do some magic with the parent dir name and get the absolute
    // path this way.

    File absf;
    File parent = f.getParentFile();
    if (parent == null) {
        // no problem, we have a single (relative) file name
        absf = f.getAbsoluteFile();
    } else {
        // eliminate . and .. from the parent path, using getCanonicalFile()
        try {
            parent = parent.getCanonicalFile();
        } catch (IOException e) {
            log.error("Cannot get canonical filename of file " + parent.getPath());
        }
        // recreate the absolute filename
        // Note: if f's name is .., this would not be eliminated here. See
        // pre-test above
        absf = new File(parent, f.getName());
    }

    if (isDebugging)
        log.debug(
                "File " + f.getPath() + "\nCanonical =  " + canf.getPath() + "\nAbsolute = " + absf.getPath());

    // a symbolic link has a different canonical path than its actual path,
    // unless it's a link to itself
    return (!canf.equals(absf));
}

From source file:org.apache.bookkeeper.bookie.EntryLogManagerForEntryLogPerLedger.java

private LedgerDirsListener getLedgerDirsListener() {
    return new LedgerDirsListener() {
        @Override//from   w  ww.  j a  va2 s . co m
        public void diskFull(File disk) {
            Set<BufferedLogChannelWithDirInfo> copyOfCurrentLogsWithDirInfo = getCopyOfCurrentLogs();
            for (BufferedLogChannelWithDirInfo currentLogWithDirInfo : copyOfCurrentLogsWithDirInfo) {
                if (disk.equals(currentLogWithDirInfo.getLogChannel().getLogFile().getParentFile())) {
                    currentLogWithDirInfo.setLedgerDirFull(true);
                }
            }
        }

        @Override
        public void diskWritable(File disk) {
            Set<BufferedLogChannelWithDirInfo> copyOfCurrentLogsWithDirInfo = getCopyOfCurrentLogs();
            for (BufferedLogChannelWithDirInfo currentLogWithDirInfo : copyOfCurrentLogsWithDirInfo) {
                if (disk.equals(currentLogWithDirInfo.getLogChannel().getLogFile().getParentFile())) {
                    currentLogWithDirInfo.setLedgerDirFull(false);
                }
            }
        }
    };
}

From source file:edu.ucsb.eucalyptus.storage.fs.FileSystemStorageManager.java

public void copyObject(String sourceBucket, String sourceObject, String destinationBucket,
        String destinationObject) throws IOException {
    File oldObjectFile = new File(
            rootDirectory + FILE_SEPARATOR + sourceBucket + FILE_SEPARATOR + sourceObject);
    File newObjectFile = new File(
            rootDirectory + FILE_SEPARATOR + destinationBucket + FILE_SEPARATOR + destinationObject);
    if (!oldObjectFile.equals(newObjectFile)) {
        FileInputStream fileInputStream = null;
        FileChannel fileIn = null;
        FileOutputStream fileOutputStream = null;
        FileChannel fileOut = null;
        try {//from w  w  w .  j  ava2  s  . co  m
            fileInputStream = new FileInputStream(oldObjectFile);
            fileIn = fileInputStream.getChannel();
            fileOutputStream = new FileOutputStream(newObjectFile);
            fileOut = fileOutputStream.getChannel();
            fileIn.transferTo(0, fileIn.size(), fileOut);
        } finally {
            if (fileIn != null)
                fileIn.close();
            if (fileInputStream != null)
                fileInputStream.close();
            if (fileOut != null)
                fileOut.close();
            if (fileOutputStream != null)
                fileOutputStream.close();
        }
    }
}

From source file:org.apache.cxf.maven_plugin.AbstractCodegenMoho.java

private void checkResources() {
    File root = project.getBasedir();
    Resource sourceRoot = null;//from  w ww . ja  va  2s  .  c o  m
    Resource testRoot = null;

    File genroot = getGeneratedSourceRoot();
    if (genroot != null) {

        List<Resource> resources = project.getBuild().getResources();
        for (Resource r : resources) {
            File d = new File(root, r.getDirectory());
            if (d.equals(genroot)) {
                sourceRoot = r;
            }
        }
        Resource r2 = scanForResources(genroot, sourceRoot);
        if (r2 != sourceRoot) {
            r2.setDirectory(getGeneratedSourceRoot().getAbsolutePath());
            project.addResource(r2);
        }
    }
    genroot = getGeneratedTestRoot();
    if (genroot != null) {
        List<Resource> resources = project.getBuild().getTestResources();
        for (Resource r : resources) {
            File d = new File(root, r.getDirectory());
            if (d.equals(genroot)) {
                testRoot = r;
            }
        }
        Resource r2 = scanForResources(genroot, testRoot);
        if (r2 != testRoot) {
            r2.setDirectory(getGeneratedTestRoot().getAbsolutePath());
            project.addTestResource(r2);
        }
    }
}

From source file:net.sourceforge.subsonic.ajax.CoverArtService.java

private void saveCoverArt(String path, String url) throws Exception {
    InputStream input = null;/*from  w w  w . j a va  2 s . c  o  m*/
    HttpClient client = new DefaultHttpClient();

    try {
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 20 * 1000); // 20 seconds
        HttpConnectionParams.setSoTimeout(client.getParams(), 20 * 1000); // 20 seconds
        HttpGet method = new HttpGet(url);

        HttpResponse response = client.execute(method);
        input = response.getEntity().getContent();

        // Attempt to resolve proper suffix.
        String suffix = "jpg";
        if (url.toLowerCase().endsWith(".gif")) {
            suffix = "gif";
        } else if (url.toLowerCase().endsWith(".png")) {
            suffix = "png";
        }

        // Check permissions.
        File newCoverFile = new File(path, "folder." + suffix);
        if (!securityService.isWriteAllowed(newCoverFile)) {
            throw new Exception("Permission denied: " + StringUtil.toHtml(newCoverFile.getPath()));
        }

        // If file exists, create a backup.
        backup(newCoverFile, new File(path, "folder.backup." + suffix));

        // Write file.
        IOUtils.copy(input, new FileOutputStream(newCoverFile));

        MediaFile mediaFile = mediaFileService.getMediaFile(path);

        // Rename existing cover file if new cover file is not the preferred.
        try {
            File coverFile = mediaFileService.getCoverArt(mediaFile);
            if (coverFile != null) {
                if (!newCoverFile.equals(coverFile)) {
                    coverFile.renameTo(new File(coverFile.getCanonicalPath() + ".old"));
                    LOG.info("Renamed old image file " + coverFile);
                }
            }
        } catch (Exception x) {
            LOG.warn("Failed to rename existing cover file.", x);
        }

        mediaFileService.refreshMediaFile(mediaFile);

    } finally {
        IOUtils.closeQuietly(input);
        client.getConnectionManager().shutdown();
    }
}

From source file:FileTreeDropTarget.java

protected void transferDirectory(int action, File srcDir, File targetDirectory,
        FileTree.FileTreeNode targetNode) {
    DnDUtils.debugPrintln((action == DnDConstants.ACTION_COPY ? "Copy" : "Move") + " directory "
            + srcDir.getAbsolutePath() + " to " + targetDirectory.getAbsolutePath());

    // Do not copy a directory into itself or 
    // a subdirectory of itself.
    File parentDir = targetDirectory;
    while (parentDir != null) {
        if (parentDir.equals(srcDir)) {
            DnDUtils.debugPrintln("-- SUPPRESSED");
            return;
        }/* w  w  w .j  a  v  a2 s . c o m*/
        parentDir = parentDir.getParentFile();
    }

    // Copy the directory itself, then its contents

    // Create a File entry for the target
    String name = srcDir.getName();
    File newDir = new File(targetDirectory, name);
    if (newDir.exists()) {
        // Already exists - is it the same directory?
        if (newDir.equals(srcDir)) {
            // Exactly the same file - ignore
            return;
        }
    } else {
        // Directory does not exist - create it
        if (newDir.mkdir() == false) {
            // Failed to create - abandon this directory
            JOptionPane.showMessageDialog(tree,
                    "Failed to create target directory\n  " + newDir.getAbsolutePath(),
                    "Directory creation Failed", JOptionPane.ERROR_MESSAGE);
            return;
        }
    }

    // Add a node for the new directory
    if (targetNode != null) {
        targetNode = tree.addNode(targetNode, name);
    }

    // Now copy the directory content.
    File[] files = srcDir.listFiles();
    for (int i = 0; i < files.length; i++) {
        File f = files[i];
        if (f.isFile()) {
            transferFile(action, f, newDir, targetNode);
        } else if (f.isDirectory()) {
            transferDirectory(action, f, newDir, targetNode);
        }
    }

    // Remove the source directory after moving
    if (action == DnDConstants.ACTION_MOVE && System.getProperty("DnDExamples.allowRemove") != null) {
        srcDir.delete();
    }
}