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.ambraproject.admin.service.impl.DocumentManagementServiceImpl.java

/**
 * Revert the data out of the ingested queue
 *
 * @param uri the article uri//from   www  .j a  v a  2s  .c om
 * @throws java.io.IOException on an error
 */
@Override
public void revertIngestedQueue(String uri) throws IOException {
    // delete any crossref submission file
    File queueDir = new File(documentDirectory);
    File ingestedDir = new File(ingestedDocumentDirectory);
    File ingestedXmlFile = new File(ingestedDir, uri.replaceAll("[:/.]", "_") + ".xml");

    if (log.isDebugEnabled())
        log.debug("Deleting '" + ingestedXmlFile + "'");

    try {
        FileUtils.forceDelete(ingestedXmlFile);
    } catch (FileNotFoundException fnfe) {
        log.info("'" + ingestedXmlFile + "' does not exist - cannot delete: ", fnfe);
    }

    // move zip back to ingestion queue
    if (!queueDir.equals(ingestedDir)) {
        // strip 'info:doi/10.1371/journal.'
        String fname = uri.substring(documentPrefix.length()) + ".zip";
        File fromFile = new File(ingestedDir, fname);
        File toFile = new File(queueDir, fname);

        try {
            if (log.isDebugEnabled())
                log.debug("Moving '" + fromFile + "' to '" + toFile + "'");
            FileUtils.moveFile(fromFile, toFile);
        } catch (FileNotFoundException fnfe) {
            log.info("Could not move '" + fromFile + "' to '" + toFile + "': ", fnfe);
        }
    }
}

From source file:org.jenkinsci.maven.plugins.hpi.AbstractHpiMojo.java

/**
 * Copies webapp webResources from the specified directory.
 * <p>//from  www  . j a  v  a2 s. c  o m
 * Note that the {@code webXml} parameter could be null and may
 * specify a file which is not named {@code web.xml}. If the file
 * exists, it will be copied to the {@code META-INF} directory and
 * renamed accordingly.
 *
 * @param sourceDirectory the source directory
 * @param webappDirectory the target directory
 * @throws java.io.IOException if an error occurred while copying webResources
 */
public void copyResources(File sourceDirectory, File webappDirectory) throws IOException {
    if (!sourceDirectory.equals(webappDirectory)) {
        getLog().info("Copy webapp webResources to " + webappDirectory.getAbsolutePath());
        if (warSourceDirectory.exists()) {
            String[] fileNames = getWarFiles(sourceDirectory);
            for (String fileName : fileNames) {
                copyFileIfModified(new File(sourceDirectory, fileName), new File(webappDirectory, fileName));
            }
        }
    }
}

From source file:DragDropTreeExample.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;
        }//from  ww w .j  ava  2  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();
    }
}

From source file:org.openanzo.binarystore.server.BinaryStoreServlet.java

private File getLock(File target) {
    File parent = target.getParentFile();
    File lockfile = new File(parent, nodelockid);
    boolean exists = true;
    try {//from  w w  w . j  a  v a 2  s .  c o m
        exists = lockfile.createNewFile();
    } catch (IOException e) {
        return null;
    }
    if (!exists) {
        return null;
    }
    File[] files = parent.listFiles();
    for (File f : files) {
        if (!f.equals(lockfile)) {
            if (f.getName().startsWith(LOCKFILE_PREFIX)) {
                String lock = f.getName().substring(LOCKFILE_PREFIX.length());
                String[] nodeid = lock.split(LOCKFILE_DELIMETER);
                if (nodeid.length != 2)
                    continue;
                boolean validLock = isLockValid(nodeid[0], nodeid[1]);
                if (!validLock) {
                    //its an invalid lockfile - presumably created by a crashed or shutdown server so lets clean it up.
                    f.delete();
                } else {
                    lockfile.delete();
                    return null;
                }
            }
        }
    }

    return lockfile;
}

From source file:org.madsonic.ajax.CoverArtService.java

private void saveCoverArt(String path, String url, boolean isArtist) throws Exception {
    InputStream input = null;/*from  w w  w .j av  a 2  s . c  om*/
    OutputStream output = null;
    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";
        }

        String coverName = "cover.";

        if (isArtist == true) {
            coverName = "artist.";
        }

        // Check permissions.         
        File newCoverFile = new File(path, coverName + 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, "cover.backup." + suffix));

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

        MediaFile dir = mediaFileService.getMediaFile(path);

        // Refresh database.
        mediaFileService.refreshMediaFile(dir);
        dir = mediaFileService.getMediaFile(dir.getId());

        // Rename existing cover file if new cover file is not the preferred.
        try {
            File coverFile = mediaFileService.getCoverArt(dir);
            if (coverFile != null && !isMediaFile(coverFile)) {
                if (!newCoverFile.equals(coverFile)) {
                    coverFile.renameTo(new File(coverFile.getCanonicalPath() + ".old"));
                    LOG.info("Renamed old image file " + coverFile);

                    // Must refresh again.
                    mediaFileService.refreshMediaFile(dir);
                }
            }
        } catch (Exception x) {
            LOG.warn("Failed to rename existing cover file.", x);
        }

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

From source file:com.mtgi.analytics.XmlBehaviorEventPersisterTest.java

/** 
 * if the persister was not shut down cleanly, we might have an old log file without a timestamp laying around.
 * make sure log rotation doesn't clobber it.
 *//*  w  w w. j ava 2s  .c o m*/
@Test
public void testOfflineConfigurationChange() throws Exception {

    //generate an old log file with some data, *not* the one currently referenced by our persister.
    File staleFile = new File(persister.getFile() + ".gz");
    staleFile.deleteOnExit();
    assertFalse("sanity check: " + staleFile.getAbsolutePath() + " does not exist", staleFile.exists());

    byte[] data = { 0xC, 0xA, 0xF, 0xE, 0xB, 0xA, 0xB, 0xE };
    FileOutputStream fos = new FileOutputStream(staleFile);
    try {
        fos.write(data);
        fos.flush();
        fos.getFD().sync();
    } finally {
        IOUtils.closeQuietly(fos);
    }
    assertEquals("sanity check: stale log file has content", 8, staleFile.length());
    assertFalse("sanity check: persister currently points to different location",
            staleFile.equals(new File(persister.getFile())));

    //change logging config, such that the next log rotation would cause us to clobber the
    //pre-existing file 'staleFile'.  staleFile should be preserved in a new location with a timestamp
    //suffix.
    persister.setCompress(true);
    persister.rotateLog();
    File newPath = new File(persister.getFile());
    assertEquals("persister now points to stale log file location after rotate", staleFile, newPath);

    //we should be able to locate a backup file in the parent dir somewhere.
    final String backupPrefix = staleFile.getName();
    class BackupLocator implements FilenameFilter {
        File backup = null;
        int matchCount = 0;

        public boolean accept(File dir, String name) {
            if (name.length() > backupPrefix.length() && name.startsWith(backupPrefix)) {
                ++matchCount;
                backup = new File(dir, name);
            }
            return false;
        }
    }
    ;
    BackupLocator locator = new BackupLocator();
    File dir = staleFile.getParentFile();
    dir.listFiles(locator);

    assertEquals("exactly one backup log file found", 1, locator.matchCount);
    //verify backup contents
    FileInputStream fis = new FileInputStream(locator.backup);
    try {
        for (int i = 0; i < data.length; ++i)
            assertEquals("@" + i + " matches", data[i], (byte) fis.read());
        assertEquals("no data remains", -1, fis.read());
    } finally {
        IOUtils.closeQuietly(fis);
        locator.backup.delete();
    }
}

From source file:bboss.org.apache.velocity.runtime.resource.loader.FileResourceLoader.java

/**
 * How to keep track of all the modified times
 * across the paths.  Note that a file might have
 * appeared in a directory which is earlier in the
 * path; so we should search the path and see if
 * the file we find that way is the same as the one
 * that we have cached./*from   w  ww.  j  ava2 s . co m*/
 * @param resource
 * @return True if the source has been modified.
 */
public boolean isSourceModified(Resource resource) {
    /*
     * we assume that the file needs to be reloaded;
     * if we find the original file and it's unchanged,
     * then we'll flip this.
     */
    boolean modified = true;

    String fileName = resource.getName();
    String path = (String) templatePaths.get(fileName);
    File currentFile = null;

    for (int i = 0; currentFile == null && i < paths.size(); i++) {
        String testPath = (String) paths.get(i);
        File testFile = getFile(testPath, fileName);
        if (testFile.canRead()) {
            currentFile = testFile;
        }
    }
    File file = getFile(path, fileName);
    if (currentFile == null || !file.exists()) {
        /*
         * noop: if the file is missing now (either the cached
         * file is gone, or the file can no longer be found)
         * then we leave modified alone (it's set to true); a
         * reload attempt will be done, which will either use
         * a new template or fail with an appropriate message
         * about how the file couldn't be found.
         */
    } else if (currentFile.equals(file) && file.canRead()) {
        /*
         * if only if currentFile is the same as file and
         * file.lastModified() is the same as
         * resource.getLastModified(), then we should use the
         * cached version.
         */
        modified = (file.lastModified() != resource.getLastModified());
    }

    /*
     * rsvc.debug("isSourceModified for " + fileName + ": " + modified);
     */
    return modified;
}

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

/**
 * Creates a HashMap containing the details of the SAML assertion
 * @param usrId String//www .j a  v a 2 s .  co  m
 * @param sf File
 * @return HashMap
 * @throws Exception
 */
private HashMap getSAMLDetail(String usrId, File sf) throws Exception {
    HashMap ch = new HashMap();

    File samlf = getSAML(usrId);
    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()) {
            //List<TrustDelegation> tdList = new ArrayList<TrustDelegation>();

            id = td.getAssertion().getID();
            issuer = td.getAssertion().getIssuer().getStringValue();
            endTime = td.getAssertion().getConditions().getNotOnOrAfter().getTimeInMillis();
            subject = td.getAssertion().getSubject().toString();

        } else {
            System.out.println("MyPorxyPortlet::getSamlDetail:trust delegation is null");
        }
        ch.put("id", id);
        ch.put("issuer", issuer);
        ch.put("tleft", timeConvert(endTime));
        ch.put("subject", subject);
        ch.put("ptype", "SAML");

        return ch;
    }

    return ch;
}

From source file:DragDropTreeExample.java

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

    // Create a File entry for the target
    String name = srcFile.getName();
    File newFile = new File(targetDirectory, name);
    if (newFile.exists()) {
        // Already exists - is it the same file?
        if (newFile.equals(srcFile)) {
            // Exactly the same file - ignore
            return;
        }//w  ww  .  j av  a  2  s .c o  m
        // File of this name exists in this directory
        if (copyOverExistingFiles == false) {
            int res = JOptionPane.showOptionDialog(tree,
                    "A file called\n   " + name + "\nalready exists in the directory\n   "
                            + targetDirectory.getAbsolutePath() + "\nOverwrite it?",
                    "File Exists", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                    new String[] { "Yes", "Yes to All", "No", "Cancel" }, "No");
            switch (res) {
            case 1: // Yes to all
                copyOverExistingFiles = true;
            case 0: // Yes
                break;
            case 2: // No
                return;
            default: // Cancel
                throw new IllegalStateException("Cancelled");
            }
        }
    } else {
        // New file - create it
        try {
            newFile.createNewFile();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(tree, "Failed to create new file\n  " + newFile.getAbsolutePath(),
                    "File Creation Failed", JOptionPane.ERROR_MESSAGE);
            return;
        }
    }

    // Copy the data and close file.
    BufferedInputStream is = null;
    BufferedOutputStream os = null;

    try {
        is = new BufferedInputStream(new FileInputStream(srcFile));
        os = new BufferedOutputStream(new FileOutputStream(newFile));
        int size = 4096;
        byte[] buffer = new byte[size];
        int len;
        while ((len = is.read(buffer, 0, size)) > 0) {
            os.write(buffer, 0, len);
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(tree,
                "Failed to copy file\n  " + name + "\nto directory\n  " + targetDirectory.getAbsolutePath(),
                "File Copy Failed", JOptionPane.ERROR_MESSAGE);
        return;
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
        }
    }

    // Remove the source if this is a move operation.
    if (action == DnDConstants.ACTION_MOVE && System.getProperty("DnDExamples.allowRemove") != null) {
        srcFile.delete();
    }

    // Update the tree display
    if (targetNode != null) {
        tree.addNode(targetNode, name);
    }
}

From source file:com.igormaznitsa.sciareto.ui.editors.MMDEditor.java

private void addFileToElement(@Nonnull final File theFile, @Nullable final AbstractElement element) {
    if (element != null) {
        final Topic topic = element.getModel();
        final MMapURI theURI;

        if (PreferencesManager.getInstance().getPreferences().getBoolean("makeRelativePathToProject", true)) { //NOI18N
            final File projectFolder = getProjectFolder();
            if (theFile.equals(projectFolder)) {
                theURI = new MMapURI(projectFolder, new File("."), null);
            } else {
                theURI = new MMapURI(projectFolder, theFile, null);
            }/*from   www.ja v  a 2s. co m*/
        } else {
            theURI = new MMapURI(null, theFile, null);
        }

        if (topic.getExtras().containsKey(Extra.ExtraType.FILE)) {
            if (!DialogProviderManager.getInstance().getDialogProvider().msgConfirmOkCancel(
                    BUNDLE.getString("MMDGraphEditor.addDataObjectToElement.confirmTitle"),
                    BUNDLE.getString("MMDGraphEditor.addDataObjectToElement.confirmMsg"))) {
                return;
            }
        }

        topic.setExtra(new ExtraFile(theURI));
        this.mindMapPanel.invalidate();
        this.mindMapPanel.repaint();
        onMindMapModelChanged(this.mindMapPanel);
    }
}