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:calliope.db.CouchConnection.java

/**
 * Delete a file from the file system//from w w w .  j  av  a2 s. c o m
 * @param db the database name
 * @param docID the document ID of the resource
 * @throws AeseException 
 */
@Override
public void removeImageFromDb(String db, String docID) throws AeseException {
    try {
        docID = deconvertDocID(docID);
        File wd = new File(CouchConnection.webRoot);
        File f = new File(wd, db + "/" + docID);
        if (f.exists()) {
            f.delete();
            File parent = f.getParentFile();
            do {
                File[] children = parent.listFiles();
                if (children.length > 0)
                    break;
                else {
                    parent.delete();
                    parent = parent.getParentFile();
                    if (parent.equals(wd))
                        break;
                }
            } while (parent != null);
        } else
            throw new AeseException("File not found " + db + "/" + docID);
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:psiprobe.beans.LogResolverBean.java

/**
 * Gets the log sources./* ww w  .j  av a  2 s . c  om*/
 *
 * @param logFile the log file
 * @return the log sources
 */
public List<LogDestination> getLogSources(File logFile) {
    List<LogDestination> filtered = new LinkedList<>();
    List<LogDestination> sources = getLogSources();
    for (LogDestination dest : sources) {
        if (logFile.equals(dest.getFile())) {
            filtered.add(dest);
        }
    }
    return filtered;
}

From source file:org.nuxeo.launcher.config.ServerConfigurator.java

/**
 * Check server paths; warn if existing deprecated paths. Override this method to perform server specific checks.
 *
 * @throws ConfigurationException If deprecated paths have been detected
 * @since 5.4.2/*from   w  ww.j av  a 2s .  c  o  m*/
 */
public void checkPaths() throws ConfigurationException {
    File badInstanceClid = new File(generator.getNuxeoHome(),
            getDefaultDataDir() + File.separator + "instance.clid");
    if (badInstanceClid.exists() && !getDataDir().equals(badInstanceClid.getParentFile())) {
        log.warn(String.format("Moving %s to %s.", badInstanceClid, getDataDir()));
        try {
            FileUtils.moveFileToDirectory(badInstanceClid, getDataDir(), true);
        } catch (IOException e) {
            throw new ConfigurationException("NXP-6722 move failed: " + e.getMessage(), e);
        }
    }

    File oldPackagesPath = new File(getDataDir(), getDefaultPackagesDir());
    if (oldPackagesPath.exists() && !oldPackagesPath.equals(getPackagesDir())) {
        log.warn(String.format(
                "NXP-8014 Packages cache location changed. You can safely delete %s or move its content to %s",
                oldPackagesPath, getPackagesDir()));
    }

}

From source file:de.jcup.egradle.eclipse.ide.launch.EGradleLaunchShortCut.java

private String createGradleProjectName(IResource resource) {
    if (resource == null) {
        throw new IllegalArgumentException("Resource may not be null!");
    }/*from  ww  w .  j av a2  s  .  com*/
    IProject project = resource.getProject();
    if (project == null) {
        throw new IllegalStateException("Cannot determine project for resource:" + resource.getName());
    }
    if (hasVirtualRootProjectNature(project)) {
        return "";
    }
    /* when the project itself is the root - leave project name empty! */
    if (isRootProject(project)) {
        return "";
    }

    try {
        File projectRealFolder = getResourceHelper().toFile(project);
        if (projectRealFolder == null) {
            throw new IllegalStateException("Cannot determine real project folder for" + project.getName());
        }
        File rootFolder = rootProjectFinder.findRootProjectFolder(projectRealFolder);
        if (projectRealFolder.equals(rootFolder)) {
            // is a root folder!
            return "";
        }

        return projectRealFolder.getName();
    } catch (CoreException e) {
        throw new IllegalStateException(e);
    }
}

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

/**
 * Copies src file to dst file. If the dst file does not exist, it is
 * created//from  w  ww  . java  2  s.c  o  m
 */
private void copyFile(File src, File dst) throws IOException {
    // see if source and destination are the same
    if (src.equals(dst)) {
        // do not copy
        return;
    }

    //System.out.println("copying " + src + " to " + dst);

    FileChannel srcChannel = new FileInputStream(src).getChannel();
    FileChannel dstChannel = new FileOutputStream(dst).getChannel();
    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
    srcChannel.close();
    dstChannel.close();

    /* hacking for non-windows */
    // set the permission of the target file the same as the source file
    if (_commandArr[0] == "/bin/sh") {

        String osName = StringUtilities.getProperty("os.name");
        if (osName.startsWith("Mac OS X")) {

            // chmod --reference does not exist on mac, so do the best
            // we can using the java file api
            // WARNING: this relies on the umask to set the group, world
            // permissions.
            dst.setExecutable(src.canExecute());
            dst.setWritable(src.canWrite());

        } else {

            String cmd = "chmod --reference=" + src.getAbsolutePath() + " " + dst.getAbsolutePath();
            try {
                ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
                ByteArrayOutputStream streamErr = new ByteArrayOutputStream();
                executeCmd(cmd, streamOut, streamErr);
            } catch (ExecException e) {
                log.warn("Tried to set the target file permissions the same as "
                        + "the source but the command failed: " + cmd + "\n" + e);
            }
        }
    }
}

From source file:org.dcm4che.tool.dcmdir.DcmDir.java

public int addReferenceTo(File f) throws IOException {
    checkOut();// w w  w . ja v a 2s  . c o  m
    checkRecordFactory();
    int n = 0;
    if (f.isDirectory()) {
        for (String s : f.list())
            n += addReferenceTo(new File(f, s));
        return n;
    }
    // do not add reference to DICOMDIR
    if (f.equals(file))
        return 0;

    Attributes fmi;
    Attributes dataset;
    DicomInputStream din = null;
    try {
        din = new DicomInputStream(f);
        din.setIncludeBulkData(IncludeBulkData.NO);
        fmi = din.readFileMetaInformation();
        dataset = din.readDataset(-1, Tag.PixelData);
    } catch (IOException e) {
        System.out.println();
        System.out.println(MessageFormat.format(rb.getString("failed-to-parse"), f, e.getMessage()));
        return 0;
    } finally {
        if (din != null)
            try {
                din.close();
            } catch (Exception ignore) {
            }
    }
    char prompt = '.';
    if (fmi == null) {
        fmi = dataset.createFileMetaInformation(UID.ImplicitVRLittleEndian);
        prompt = 'F';
    }
    String iuid = fmi.getString(Tag.MediaStorageSOPInstanceUID, null);
    if (iuid == null) {
        System.out.println();
        System.out.println(MessageFormat.format(rb.getString("skip-file"), f));
        return 0;
    }
    String pid = dataset.getString(Tag.PatientID, null);
    String styuid = dataset.getString(Tag.StudyInstanceUID, null);
    String seruid = dataset.getString(Tag.SeriesInstanceUID, null);
    if (styuid != null && seruid != null) {
        if (pid == null) {
            dataset.setString(Tag.PatientID, VR.LO, pid = styuid);
            prompt = prompt == 'F' ? 'P' : 'p';
        }
        Attributes patRec = in.findPatientRecord(pid);
        if (patRec == null) {
            patRec = recFact.createRecord(RecordType.PATIENT, null, dataset, null, null);
            out.addRootDirectoryRecord(patRec);
            n++;
        }
        Attributes studyRec = in.findStudyRecord(patRec, styuid);
        if (studyRec == null) {
            studyRec = recFact.createRecord(RecordType.STUDY, null, dataset, null, null);
            out.addLowerDirectoryRecord(patRec, studyRec);
            n++;
        }
        Attributes seriesRec = in.findSeriesRecord(studyRec, seruid);
        if (seriesRec == null) {
            seriesRec = recFact.createRecord(RecordType.SERIES, null, dataset, null, null);
            out.addLowerDirectoryRecord(studyRec, seriesRec);
            n++;
        }
        Attributes instRec;
        if (checkDuplicate) {
            instRec = in.findLowerInstanceRecord(seriesRec, false, iuid);
            if (instRec != null) {
                System.out.print('-');
                return 0;
            }
        }
        instRec = recFact.createRecord(dataset, fmi, out.toFileIDs(f));
        out.addLowerDirectoryRecord(seriesRec, instRec);
    } else {
        if (checkDuplicate) {
            if (in.findRootInstanceRecord(false, iuid) != null) {
                System.out.print('-');
                return 0;
            }
        }
        Attributes instRec = recFact.createRecord(dataset, fmi, out.toFileIDs(f));
        out.addRootDirectoryRecord(instRec);
        prompt = prompt == 'F' ? 'R' : 'r';
    }
    System.out.print(prompt);
    return n + 1;
}

From source file:com.cyberway.issue.crawler.settings.XMLSettingsHandler.java

/** Delete a settings object from persistent storage.
 *
 * Deletes the file represented by the submitted settings object. All empty
 * directories that are parents to the files path are also deleted.
 *
 * @param settings the settings object to delete.
 *//*from   w w w  . j  a  va  2 s  .co m*/
public void deleteSettingsObject(CrawlerSettings settings) {
    super.deleteSettingsObject(settings);
    File settingsDirectory = getSettingsDirectory();
    File settingsFile = settingsToFilename(settings);

    if (!settingsFile.delete()) {
        throw new RuntimeException("Could not delete: " + settingsFile);
    }
    settingsFile = settingsFile.getParentFile();
    while (settingsFile.isDirectory() && settingsFile.list().length == 0
            && !settingsFile.equals(settingsDirectory)) {
        if (!settingsFile.delete()) {
            logger.warning("Could not delete: " + settingsFile);
        }
        settingsFile = settingsFile.getParentFile();
    }
}

From source file:org.apache.jackrabbit.core.data.LocalCache.java

/**
 * This method tries to delete a file. If it is not able to delete file due
 * to any reason, it add it toBeDeleted list.
 * /*w w w.jav  a  2 s  .c  o m*/
 * @param fileName name of the file which will be deleted.
 * @return true if this method deletes file successfuly else return false.
 */
boolean tryDelete(final String fileName) {
    LOG.debug("try deleting file [{}]", fileName);
    File f = getFile(fileName);
    if (f.exists() && f.delete()) {
        LOG.debug("File [{}]  deleted successfully", fileName);
        toBeDeleted.remove(fileName);
        while (true) {
            f = f.getParentFile();
            if (f.equals(directory) || f.list().length > 0) {
                break;
            }
            // delete empty parent folders (except the main directory)
            f.delete();
        }
        return true;
    } else if (f.exists()) {
        LOG.info("not able to delete file [{}]", f.getAbsolutePath());
        toBeDeleted.add(fileName);
        return false;
    }
    return true;
}

From source file:hudson.lifecycle.WindowsInstallerLink.java

public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
    if (installationDir == null) {
        // if the user reloads the page after Hudson has restarted,
        // it comes back here. In such a case, don't let this restart Hudson.
        // so just send them back to the top page
        rsp.sendRedirect(req.getContextPath() + "/");
        return;//from ww w .  ja  v  a  2  s  .c om
    }
    Hudson.getInstance().checkPermission(Hudson.ADMINISTER);

    rsp.forward(this, "_restart", req);
    final File oldRoot = Hudson.getInstance().getRootDir();

    // initiate an orderly shutdown after we finished serving this request
    new Thread("terminator") {
        public void run() {
            try {
                Thread.sleep(1000);

                // let the service start after we close our sockets, to avoid conflicts
                Runtime.getRuntime().addShutdownHook(new Thread("service starter") {
                    public void run() {
                        try {
                            if (!oldRoot.equals(installationDir)) {
                                LOGGER.info("Moving data");
                                Move mv = new Move();
                                Project p = new Project();
                                p.addBuildListener(createLogger());
                                mv.setProject(p);
                                FileSet fs = new FileSet();
                                fs.setDir(oldRoot);
                                fs.setExcludes("war/**"); // we can't really move the exploded war. 
                                mv.addFileset(fs);
                                mv.setTodir(installationDir);
                                mv.setFailOnError(false); // plugins can also fail to move
                                mv.execute();
                            }
                            LOGGER.info("Starting a Windows service");
                            StreamTaskListener task = new StreamTaskListener(System.out);
                            int r = new LocalLauncher(task).launch()
                                    .cmds(new File(installationDir, "hudson.exe"), "start").stdout(task)
                                    .pwd(installationDir).join();
                            task.getLogger().println(
                                    r == 0 ? "Successfully started" : "start service failed. Exit code=" + r);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    private DefaultLogger createLogger() {
                        DefaultLogger logger = new DefaultLogger();
                        logger.setOutputPrintStream(System.out);
                        logger.setErrorPrintStream(System.err);
                        return logger;
                    }
                });

                System.exit(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }.start();
}

From source file:org.apache.sshd.server.filesystem.NativeSshFile.java

@Override
public boolean equals(Object obj) {
    if (obj != null && obj instanceof NativeSshFile) {
        File thisCanonicalFile;
        File otherCanonicalFile;/*from   w  w  w  . jav a2 s .  c  o m*/
        try {
            thisCanonicalFile = this.file.getCanonicalFile();
            otherCanonicalFile = ((NativeSshFile) obj).file.getCanonicalFile();
        } catch (IOException e) {
            throw new RuntimeException("Failed to get the canonical path", e);
        }

        return thisCanonicalFile.equals(otherCanonicalFile);
    }
    return false;
}