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.opendatakit.common.android.provider.impl.FormsProviderImpl.java

@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 1 || segments.size() > 2) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri);
    }//from w  w  w.  j  a v a 2  s .  c om

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    String uriFormId = ((segments.size() == 2) ? segments.get(1) : null);
    boolean isNumericId = StringUtils.isNumeric(uriFormId);

    // Modify the where clause to account for the presence of
    // a form id. Accept either:
    // (1) numeric _ID value
    // (2) string FORM_ID value.
    String whereId;
    String[] whereIdArgs;

    if (uriFormId == null) {
        whereId = where;
        whereIdArgs = whereArgs;
    } else {
        if (TextUtils.isEmpty(where)) {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?";
            whereIdArgs = new String[1];
            whereIdArgs[0] = uriFormId;
        } else {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")";
            whereIdArgs = new String[whereArgs.length + 1];
            whereIdArgs[0] = uriFormId;
            for (int i = 0; i < whereArgs.length; ++i) {
                whereIdArgs[i + 1] = whereArgs[i];
            }
        }
    }

    /*
     * First, find out what records match this query, and if they refer to two
     * or more (formId,formVersion) tuples, then be sure to remove all
     * FORM_MEDIA_PATH references. Otherwise, if they are all for the same
     * tuple, and the update specifies a FORM_MEDIA_PATH, move all the
     * non-matching directories elsewhere.
     */
    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>();
    boolean multiset = false;
    Cursor c = null;
    try {
        c = this.query(uri, null, whereId, whereIdArgs, null);
        if (c == null) {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row did not return a cursor");
        }
        if (c.getCount() >= 1) {
            FormIdVersion ref = null;
            c.moveToPosition(-1);
            while (c.moveToNext()) {
                idValue = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class,
                        c.getColumnIndex(FormsColumns._ID));
                tableIdValue = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.TABLE_ID));
                formIdValue = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_ID));
                String tableId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.TABLE_ID));
                String formId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_ID));
                String formVersion = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_VERSION));
                FormIdVersion cur = new FormIdVersion(tableId, formId, formVersion);

                int appRelativeMediaPathIdx = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
                String mediaPath = ODKDatabaseUtils.get().getIndexAsString(c, appRelativeMediaPathIdx);
                if (mediaPath != null) {
                    mediaDirs.put(ODKFileUtils.asAppFile(appName, mediaPath),
                            (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS);
                }

                if (ref != null && !ref.equals(cur)) {
                    multiset = true;
                    break;
                } else {
                    ref = cur;
                }
            }
        }
    } catch (Exception e) {
        log.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }

    if (multiset) {
        // don't let users manually update media path
        // we are referring to two or more (formId,formVersion) tuples.
        if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
            values.remove(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
        }
    } else if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
        // we are not a multiset and we are setting the media path
        // try to move all the existing non-matching media paths to
        // somewhere else...
        File mediaPath = ODKFileUtils.asAppFile(appName,
                values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH));
        for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) {
            File altPath = entry.getKey();
            if (!altPath.equals(mediaPath)) {
                try {
                    moveDirectory(appName, entry.getValue(), altPath);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.e(t, "Attempt to move " + altPath.getAbsolutePath() + " failed: " + e.toString());
                }
            }
        }
        // OK. we have moved the existing form definitions elsewhere. We can
        // proceed with update...
    }

    // ensure that all values are correct and ignore some user-supplied
    // values...
    patchUpValues(appName, values);

    // Make sure that the necessary fields are all set
    if (values.containsKey(FormsColumns.DATE) == true) {
        Date today = new Date();
        String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time),
                Locale.getDefault()).format(today);
        values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
    }

    SQLiteDatabase db = null;
    int count;
    try {
        // OK Finally, now do the update...
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        count = db.update(DatabaseConstants.FORMS_TABLE_NAME, values, whereId, whereIdArgs);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
        log.w(t, "Unable to perform update " + uri);
        return 0;
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    if (count == 1) {
        Uri formUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue);
        getContext().getContentResolver().notifyChange(formUri, null);
        Uri idUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                Long.toString(idValue));
        getContext().getContentResolver().notifyChange(idUri, null);
    } else {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return count;
}

From source file:org.dita.dost.module.CleanPreprocessModule.java

@Override
public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException {
    final URI base = job.getInputDir();

    final Collection<FileInfo> fis = job.getFileInfo().stream().collect(Collectors.toList());

    final LinkFilter filter = new LinkFilter();
    filter.setJob(job);/* w  ww.j  a  v a 2  s .c  om*/
    filter.setLogger(logger);
    final Collection<FileInfo> res = new ArrayList<>(fis.size());
    for (final FileInfo fi : fis) {
        try {
            final FileInfo.Builder builder = new FileInfo.Builder(fi);
            final File srcFile = new File(job.tempDirURI.resolve(fi.uri));
            if (srcFile.exists()) {
                final URI rel = base.relativize(fi.result);
                final File destFile = new File(job.tempDirURI.resolve(rel));
                if (fi.format == null || fi.format.equals(ATTR_FORMAT_VALUE_DITA)
                        || fi.format.equals(ATTR_FORMAT_VALUE_DITAMAP)) {
                    logger.info("Processing " + srcFile.toURI() + " to " + destFile.toURI());
                    filter.setCurrentFile(srcFile.toURI());
                    filter.setDestFile(destFile.toURI());
                    transform(srcFile.toURI(), destFile.toURI(), Collections.singletonList(filter));
                    if (!srcFile.equals(destFile)) {
                        logger.debug("Deleting " + srcFile.toURI());
                        FileUtils.deleteQuietly(srcFile);
                    }
                } else if (fi.format.equals("coderef")) {
                    // SKIP
                } else if (!srcFile.equals(destFile)) {
                    logger.info("Copying " + srcFile.toURI() + " to " + destFile.toURI());
                    FileUtils.moveFile(srcFile, destFile);
                }
                builder.uri(rel);

                // start map
                if (fi.src.equals(job.getInputFile())) {
                    job.setProperty(INPUT_DITAMAP_URI, rel.toString());
                    job.setProperty(INPUT_DITAMAP, toFile(rel).getPath());
                }
            }
            res.add(builder.build());
        } catch (final IOException e) {
            logger.error("Failed to clean " + job.tempDirURI.resolve(fi.uri) + ": " + e.getMessage(), e);
        }
    }

    fis.stream().forEach(fi -> job.remove(fi));
    res.stream().forEach(fi -> job.add(fi));

    try {
        job.write();
    } catch (IOException e) {
        throw new DITAOTException();
    }

    return null;
}

From source file:org.gradle.api.internal.project.AbstractProject.java

public File findRelativePath(Object path) {
    File file = new File(path.toString());
    if (!file.isAbsolute()) {
        return file;
    }/*ww w.j a  v  a 2 s.c  om*/
    File loopFile = file;
    String relativePath = "";
    while (loopFile != null) {
        if (loopFile.equals(getProjectDir())) {
            break;
        }
        relativePath = loopFile.getName() + "/" + relativePath;
        loopFile = loopFile.getParentFile();
    }
    return loopFile == null ? null : new File(relativePath);
}

From source file:edu.stolaf.cs.wmrserver.TransformProcessor.java

/**
 * Internal implementation of #prepareMapperPackage() and
 * #prepareReducerPackage() that works for either, determined by the
 * transformType argument./*from www.j a v  a 2 s  .c  om*/
 */
protected File prepareTransformPackage(TransformType transformType, String transformSource, String language)
        throws IOException, ValidationException, CompilationException {
    // Get the given language's configuration, checking whether the language
    // exists in the configuration in the first place
    SubnodeConfiguration languageConf;
    try {
        languageConf = m_wmrConfig.configurationAt(language);
    } catch (IllegalArgumentException ex) {
        throw new ValidationException("Specified source code language is not recognized.", language);
    }

    // Get the transform type in string form ("mapper" or "reducer") for use
    // in messages, etc.
    String transformTypeString = transformType.toString().toLowerCase();

    // Wrap source in library code as appropriate
    transformSource = wrap(languageConf, transformTypeString, transformSource);

    // Create temp directory to store transform package
    File jobTempDir = getJobTempDir();
    File jobTransformDir = new File(jobTempDir, transformTypeString);
    if (!jobTransformDir.mkdir()) {
        throw new IOException("Could not create " + transformTypeString + " temporary directory:\n"
                + jobTransformDir.toString());
    }

    // Write processed transform source to disk
    String scriptExtension = languageConf.getString("extension", "");
    if (!scriptExtension.isEmpty())
        scriptExtension = "." + scriptExtension;
    File transformFile = writeTransformSource(transformTypeString, jobTransformDir, scriptExtension,
            transformSource);

    // Copy extra library files unless otherwise specified
    boolean copyLibraryFiles = languageConf.getBoolean("copyLibraryFiles", true);
    if (copyLibraryFiles) {
        copyLibraryFiles(languageConf, jobTransformDir);
    }

    // Compile if specified
    File srcTransformFile = transformFile;
    transformFile = compile(languageConf, transformTypeString, transformFile, jobTransformDir);
    if (!transformFile.equals(srcTransformFile))
        srcTransformFile.delete();

    // Return the path to the final transform file, relativized to the temp dir
    return relativizeFile(transformFile, getJobTempDir());
}

From source file:forge.gui.ImportSourceAnalyzer.java

private void analyzeListedDir(final File root, final String targetDir, final ListedAnalyzer listedAnalyzer) {
    analyzeDir(root, new Analyzer() {
        @Override//from w  w  w .  j av  a  2  s.co m
        void onFile(final File file) {
            final String filename = listedAnalyzer.map(file.getName());
            if (null != filename) {
                final File targetFile = new File(targetDir, filename);
                if (!file.equals(targetFile)) {
                    cb.addOp(listedAnalyzer.getOpType(filename), file, targetFile);
                }
            }
        }

        @Override
        boolean onDir(final File dir) {
            return listedAnalyzer.onDir(dir);
        }
    });
}

From source file:com.intellij.diagnostic.SubmitPerformanceReportAction.java

@Override
public void actionPerformed(final AnActionEvent e) {
    String reportFileName = "perf_" + ApplicationInfo.getInstance().getBuild().asString() + "_"
            + SystemProperties.getUserName() + "_" + myDateFormat.format(new Date()) + ".zip";
    final File reportPath = new File(SystemProperties.getUserHome(), reportFileName);
    final File logDir = new File(PathManager.getLogPath());
    final Project project = e.getData(CommonDataKeys.PROJECT);

    final boolean[] archiveCreated = new boolean[1];
    final boolean completed = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
        @Override/*from  w  w  w.  java  2s  .c  o m*/
        public void run() {
            try {
                ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(reportPath));
                ZipUtil.addDirToZipRecursively(zip, reportPath, logDir, "", new FileFilter() {
                    @Override
                    public boolean accept(final File pathname) {
                        ProgressManager.checkCanceled();

                        if (logDir.equals(pathname.getParentFile())) {
                            return pathname.getPath().contains("threadDumps");
                        }
                        return true;
                    }
                }, null);
                zip.close();
                archiveCreated[0] = true;
            } catch (final IOException ex) {
                ApplicationManager.getApplication().invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        Messages.showErrorDialog(project,
                                "Failed to create performance report archive: " + ex.getMessage(),
                                MESSAGE_TITLE);
                    }
                });
            }
        }
    }, "Collecting Performance Report data", true, project);

    if (!completed || !archiveCreated[0]) {
        return;
    }

    int rc = Messages.showYesNoDialog(project,
            "The performance report has been saved to\n" + reportPath
                    + "\n\nWould you like to submit it to JetBrains?",
            MESSAGE_TITLE, Messages.getQuestionIcon());
    if (rc == Messages.YES) {
        ProgressManager.getInstance().run(new Task.Backgroundable(project, "Uploading Performance Report") {
            @Override
            public void run(@NotNull final ProgressIndicator indicator) {
                final String error = uploadFileToFTP(reportPath, "ftp.intellij.net", ".uploads", indicator);
                if (error != null) {
                    ApplicationManager.getApplication().invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            Messages.showErrorDialog(error, MESSAGE_TITLE);
                        }
                    });
                }
            }
        });
    }
}

From source file:org.qipki.site.plugin.WebsiteMojo.java

public void copyDirectoryStructureFiltering(File sourceDirectory, File destinationDirectory,
        File rootDestinationDirectory, boolean filtering, MavenProject mavenProject, List filters,
        boolean escapedBackslashesInFilePath, String encoding, MavenSession mavenSession)
        throws IOException, MavenFilteringException {
    if (sourceDirectory == null) {
        throw new IOException("source directory can't be null.");
    }//from   w  w  w.  j  ava  2s.com
    if (destinationDirectory == null) {
        throw new IOException("destination directory can't be null.");
    }
    if (sourceDirectory.equals(destinationDirectory)) {
        throw new IOException("source and destination are the same directory.");
    }
    if (!sourceDirectory.exists()) {
        throw new IOException("Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ").");
    }

    File[] files = sourceDirectory.listFiles();
    String sourcePath = sourceDirectory.getAbsolutePath();

    for (int i = 0; i < files.length; i++) {
        File file = files[i];

        if (file.equals(rootDestinationDirectory)) {
            // We don't copy the destination directory in itself
            continue;
        }

        String dest = file.getAbsolutePath();
        dest = dest.substring(sourcePath.length() + 1);
        File destination = new File(destinationDirectory, dest);

        if (file.isFile()) {

            destination = destination.getParentFile();
            if ("html".equals(FileUtils.getExtension(file.getName()))) {
                mavenFileFilter.copyFile(file, new File(destination, file.getName()), filtering, mavenProject,
                        filters, escapedBackslashesInFilePath, encoding, mavenSession);
            } else {
                FileUtils.copyFile(file, new File(destination, file.getName()));
            }

        } else if (file.isDirectory()) {

            if (!destination.exists() && !destination.mkdirs()) {
                throw new IOException(
                        "Could not create destination directory '" + destination.getAbsolutePath() + "'.");
            }
            copyDirectoryStructureFiltering(file, destination, filtering, mavenProject, filters,
                    escapedBackslashesInFilePath, encoding, mavenSession);

        } else {
            throw new IOException("Unknown file type: " + file.getAbsolutePath());
        }
    }
}

From source file:org.apache.velocity.tools.view.WebappResourceLoader.java

/**
 * Checks to see if a resource has been deleted, moved or modified.
 *
 * @param resource Resource  The resource to check for modification
 * @return boolean  True if the resource has been modified
 *///from  w  w w . ja  v a 2  s.c  o m
public boolean isSourceModified(Resource resource) {
    String rootPath = servletContext.getRealPath("/");
    if (rootPath == null) {
        // rootPath is null if the servlet container cannot translate the
        // virtual path to a real path for any reason (such as when the
        // content is being made available from a .war archive)
        return false;
    }

    // first, try getting the previously found file
    String fileName = resource.getName();
    File cachedFile = getCachedFile(rootPath, fileName);
    if (!cachedFile.exists()) {
        /* then the source has been moved and/or deleted */
        return true;
    }

    /* check to see if the file can now be found elsewhere
     * before it is found in the previously saved path */
    File currentFile = null;
    for (int i = 0; i < paths.length; i++) {
        currentFile = new File(rootPath + paths[i], fileName);
        if (currentFile.canRead()) {
            /* stop at the first resource found
             * (just like in getResourceStream()) */
            break;
        }
    }

    /* if the current is the cached and it is readable */
    if (cachedFile.equals(currentFile) && cachedFile.canRead()) {
        /* then (and only then) do we compare the last modified values */
        return (cachedFile.lastModified() != resource.getLastModified());
    } else {
        /* we found a new file for the resource
         * or the resource is no longer readable. */
        return true;
    }
}

From source file:org.apache.velocity.tools.view.servlet.WebappLoader.java

/**
 * Checks to see if a resource has been deleted, moved or modified.
 *
 * @param resource Resource  The resource to check for modification
 * @return boolean  True if the resource has been modified
 *///from   www.  ja  v a  2s  .c o m
public boolean isSourceModified(Resource resource) {
    String rootPath = servletContext.getRealPath("/");
    if (rootPath == null) {
        /*
         * rootPath is null if the servlet container cannot translate the
         * virtual path to a real path for any reason (such as when the
         * content is being made available from a .war archive)
         */
        return false;
    }

    /* first, try getting the previously found file */
    String fileName = resource.getName();
    String savedPath = (String) templatePaths.get(fileName);
    File cachedFile = new File(rootPath + savedPath, fileName);
    if (!cachedFile.exists()) {
        /* then the source has been moved and/or deleted */
        return true;
    }

    /* check to see if the file can now be found elsewhere
     * before it is found in the previously saved path */
    File currentFile = null;
    for (int i = 0; i < paths.length; i++) {
        currentFile = new File(rootPath + paths[i], fileName);
        if (currentFile.canRead()) {
            /* stop at the first resource found
             * (just like in getResourceStream()) */
            break;
        }
    }

    /* if the current is the cached and it is readable */
    if (cachedFile.equals(currentFile) && cachedFile.canRead()) {
        /* then (and only then) do we compare the last modified values */
        return (cachedFile.lastModified() != resource.getLastModified());
    } else {
        /* we found a new file for the resource
         * or the resource is no longer readable. */
        return true;
    }
}

From source file:forge.gui.ImportSourceAnalyzer.java

private void analyzeKnownDeckDir(final File root, final String targetDir, final OpType opType) {
    analyzeDir(root, new Analyzer() {
        @Override//w w  w .  j a v  a  2s.  co  m
        void onFile(final File file) {
            final String filename = file.getName();
            if (StringUtils.endsWithIgnoreCase(filename, ".dck")) {
                final File targetFile = new File(targetDir, lcaseExt(filename));
                if (!file.equals(targetFile)) {
                    cb.addOp(opType, file, targetFile);
                }
            }
        }

        @Override
        boolean onDir(final File dir) {
            // if there's a dir beneath a known directory, assume the same kind of decks are in there
            analyzeKnownDeckDir(dir, targetDir, opType);
            return true;
        }
    });
}