List of usage examples for java.io File equals
public boolean equals(Object obj)
From source file:com.ning.maven.plugins.duplicatefinder.DuplicateFinderMojo.java
/** * Calculates the SHA256 Hash of a class in a file. * /* w w w. ja va 2 s. com*/ * @param file the archive contains the class * @param resourcePath the name of the class * @return the MD% Hash as Hex-Value * @throws IOException if any error occurs on reading class in archive */ private String getSHA256HexOfElement(final File file, final String resourcePath) throws IOException { class Sha256CacheKey { final File file; final String resourcePath; Sha256CacheKey(File file, String resourcePath) { this.file = file; this.resourcePath = resourcePath; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Sha256CacheKey key = (Sha256CacheKey) o; return file.equals(key.file) && resourcePath.equals(key.resourcePath); } public int hashCode() { return 31 * file.hashCode() + resourcePath.hashCode(); } } final Sha256CacheKey key = new Sha256CacheKey(file, resourcePath); if (CACHED_SHA256.containsKey(key)) { return (String) CACHED_SHA256.get(key); } ZipFile zip = new ZipFile(file); ZipEntry zipEntry = zip.getEntry(resourcePath); if (zipEntry == null) { throw new IOException("Could not found Zip-Entry for " + resourcePath + " in file " + file); } String sha256; InputStream in = zip.getInputStream(zipEntry); try { sha256 = DigestUtils.sha256Hex(in); } finally { IOUtils.closeQuietly(in); } CACHED_SHA256.put(key, sha256); return sha256; }
From source file:org.apache.hadoop.hdfs.server.namenode.FileJournalManager.java
@Override synchronized public void finalizeLogSegment(long firstTxId, long lastTxId) throws IOException { File inprogressFile = NNStorage.getInProgressEditsFile(sd, firstTxId); File dstFile = NNStorage.getFinalizedEditsFile(sd, firstTxId, lastTxId); LOG.info("Finalizing edits file " + inprogressFile + " -> " + dstFile); Preconditions.checkState(!dstFile.exists(), "Can't finalize edits file " + inprogressFile + " since finalized file " + "already exists"); try {/*from ww w.j a v a 2s. c om*/ NativeIO.renameTo(inprogressFile, dstFile); } catch (IOException e) { errorReporter.reportErrorOnFile(dstFile); throw new IllegalStateException("Unable to finalize edits file " + inprogressFile, e); } if (inprogressFile.equals(currentInProgress)) { currentInProgress = null; } }
From source file:org.orbisgis.mapeditor.map.MapEditor.java
/** * The DefaultMapContext property of {@link MapEditorPersistence} has been updated, load this map */// ww w .j a v a 2 s . c om public void onSerialisationMapChange() { String fileName = mapEditorPersistence.getDefaultMapContext(); File mapFilePath = new File(viewWorkspace.getMapContextPath(), fileName); if (!mapFilePath.exists()) { return; } if (mapElement != null && mapFilePath.equals(mapElement.getMapContextFile())) { return; } MapElement mapElement = new MapElement(mapFilePath, dataManager); execute(new ReadMapContextJob(mapElement, editorManager)); }
From source file:adalid.util.meta.sql.MetaFolderSql.java
private void updateFolders(FileWrapper fileWrapper, File folder) { File parent = folder.getParentFile(); if (parent != null) { FolderWrapper parentWrapper;// ww w.j a v a 2s. c o m Path parentPath = getRelativeToBasePath(parent); if (folders.containsKey(parentPath)) { parentWrapper = folders.get(parentPath); } else { parentWrapper = new FolderWrapper(parent); folders.put(parentPath, parentWrapper); } parentWrapper.getBytesSizes().get(fileWrapper.getBytesSize()).next(); parentWrapper.getLinesSizes().get(fileWrapper.getLinesSize()).next(); parentWrapper.setTotalFiles(parentWrapper.getTotalFiles() + 1); parentWrapper.setTotalBytes(parentWrapper.getTotalBytes() + fileWrapper.getBytes()); parentWrapper.setTotalLines(parentWrapper.getTotalLines() + fileWrapper.getLines()); if (parent.equals(metaFolder)) { } else { updateFolders(fileWrapper, parent); } } }
From source file:com.heliosapm.script.AbstractDeployedScript.java
/** * Builds the path segments for this file * @return the path segments for this file *///www .j ava 2 s. com protected String[] calcPathSegments() { final File rootFile = new File(rootDir); if (rootFile.equals(sourceFile.getParentFile())) { return new String[] { rootFile.getName() }; } final List<String> segments = new ArrayList<String>(); segments.add(rootFile.getName()); Collections.addAll(segments, rootFile.toPath().relativize(sourceFile.getParentFile().toPath()).toString() .replace("\\", "/").split("/")); return segments.toArray(new String[segments.size()]); }
From source file:com.hivewallet.androidclient.wallet.ui.WalletActivity.java
private Dialog createImportKeysDialog() { final View view = getLayoutInflater().inflate(R.layout.import_keys_from_storage_dialog, null); final Spinner fileView = (Spinner) view.findViewById(R.id.import_keys_from_storage_file); final EditText passwordView = (EditText) view.findViewById(R.id.import_keys_from_storage_password); final DialogBuilder dialog = new DialogBuilder(this); dialog.setTitle(R.string.import_keys_dialog_title); dialog.setView(view);/*w w w .j a v a2 s. c o m*/ dialog.setPositiveButton(R.string.import_keys_dialog_button_import, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { final File file = (File) fileView.getSelectedItem(); final String password = passwordView.getText().toString().trim(); passwordView.setText(null); // get rid of it asap final boolean isProtobuf = file.getName() .startsWith(Constants.Files.WALLET_KEY_BACKUP_PROTOBUF + '.') || file.getName().startsWith(Constants.Files.EXTERNAL_WALLET_BACKUP + '-') || file.getName().startsWith(Constants.Files.EXTERNAL_WALLET_TMP_FILE); if (isProtobuf) restoreWalletFromProtobuf(file, password); else importPrivateKeysFromBase58(file, password); } }); dialog.setNegativeButton(R.string.button_cancel, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { passwordView.setText(null); // get rid of it asap } }); dialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(final DialogInterface dialog) { passwordView.setText(null); // get rid of it asap } }); final FileAdapter adapter = new FileAdapter(this) { @Override public View getDropDownView(final int position, View row, final ViewGroup parent) { final File file = getItem(position); File externalWalletBackupDir = new File(getFilesDir(), Constants.Files.EXTERNAL_WALLET_BACKUP_DIR); File selectedExternalWalletBackup = new File(getFilesDir(), Constants.Files.EXTERNAL_WALLET_TMP_FILE); final boolean isExternal = selectedExternalWalletBackup.equals(file); final boolean isManual = externalWalletBackupDir.equals(file.getParentFile()); final boolean isEncrypted = Crypto.OPENSSL_FILE_FILTER.accept(file); if (row == null) row = inflater.inflate(R.layout.wallet_import_keys_file_row, null); final TextView filenameView = (TextView) row .findViewById(R.id.wallet_import_keys_file_row_filename); filenameView.setText(file.getName()); final TextView securityView = (TextView) row .findViewById(R.id.wallet_import_keys_file_row_security); final String encryptedStr = context .getString(isEncrypted ? R.string.import_keys_dialog_file_security_encrypted : R.string.import_keys_dialog_file_security_unencrypted); final String storageStr = isExternal ? "" : ", " + context.getString(R.string.import_keys_dialog_file_security_internal); securityView.setText(encryptedStr + storageStr); final TextView createdView = (TextView) row.findViewById(R.id.wallet_import_keys_file_row_created); if (isExternal) { createdView.setText(context.getString(R.string.import_keys_dialog_file_just_selected)); } else if (isManual) { createdView.setText(context.getString(R.string.import_keys_dialog_file_created_manual, DateUtils.getRelativeTimeSpanString(context, file.lastModified(), true))); } else { createdView.setText(context.getString(R.string.import_keys_dialog_file_created_automatic, DateUtils.getRelativeTimeSpanString(context, file.lastModified(), true))); } return row; } }; fileView.setAdapter(adapter); return dialog.create(); }
From source file:com.frostwire.gui.player.MediaPlayer.java
public boolean isThisBeingPlayed(File file) { if (isPlayerStoppedClosedFailed()) { return false; }// w w w . ja v a 2 s. c om MediaSource currentMedia = getCurrentMedia(); if (currentMedia == null) { return false; } File currentMediaFile = currentMedia.getFile(); if (currentMediaFile != null && file.equals(currentMediaFile)) return true; PlaylistItem playlistItem = currentMedia.getPlaylistItem(); if (playlistItem != null && new File(playlistItem.getFilePath()).equals(file)) { return true; } return false; }
From source file:com.android.tools.idea.sdk.remote.internal.archives.ArchiveInstaller.java
/** * Install the given archive in the given folder. *//* ww w .j a va2 s . c o m*/ private boolean unarchive(ArchiveReplacement archiveInfo, String osSdkRoot, File archiveFile, SdkManager sdkManager, ITaskMonitor monitor) { boolean success = false; Archive newArchive = archiveInfo.getNewArchive(); RemotePkgInfo pkg = newArchive.getParentPackage(); String pkgName = pkg.getShortDescription(); monitor.setDescription("Installing %1$s", pkgName); monitor.log("Installing %1$s", pkgName); // Ideally we want to always unzip in a temp folder which name depends on the package // type (e.g. addon, tools, etc.) and then move the folder to the destination folder. // If the destination folder exists, it will be renamed and deleted at the very // end if everything succeeded. This provides a nice atomic swap and should leave the // original folder untouched in case something wrong (e.g. program crash) in the // middle of the unzip operation. // // However that doesn't work on Windows, we always end up not being able to move the // new folder. There are actually 2 cases: // A- A process such as a the explorer is locking the *old* folder or a file inside // (e.g. adb.exe) // In this case we really shouldn't be tried to work around it and we need to let // the user know and let it close apps that access that folder. // B- A process is locking the *new* folder. Very often this turns to be a file indexer // or an anti-virus that is busy scanning the new folder that we just unzipped. // // So we're going to change the strategy: // 1- Try to move the old folder to a temp/old folder. This might fail in case of issue A. // Note: for platform-tools, we can try killing adb first. // If it still fails, we do nothing and ask the user to terminate apps that can be // locking that folder. // 2- Once the old folder is out of the way, we unzip the archive directly into the // optimal new location. We no longer unzip it in a temp folder and move it since we // know that's what fails in most of the cases. // 3- If the unzip fails, remove everything and try to restore the old folder by doing // a *copy* in place and not a folder move (which will likely fail too). String pkgKind = pkg.getClass().getSimpleName(); File destFolder = null; File oldDestFolder = null; try { // -0- Compute destination directory and check install pre-conditions destFolder = pkg.getInstallFolder(osSdkRoot, sdkManager); if (destFolder == null) { // this should not seriously happen. monitor.log("Failed to compute installation directory for %1$s.", pkgName); return false; } if (!pkg.preInstallHook(newArchive, monitor, osSdkRoot, destFolder)) { monitor.log("Skipping archive: %1$s", pkgName); return false; } // -1- move old folder. if (mFileOp.exists(destFolder)) { // Create a new temp/old dir if (oldDestFolder == null) { oldDestFolder = getNewTempFolder(osSdkRoot, pkgKind, "old"); //$NON-NLS-1$ } if (oldDestFolder == null) { // this should not seriously happen. monitor.logError("Failed to find a temp directory in %1$s.", osSdkRoot); return false; } // Try to move the current dest dir to the temp/old one. Tell the user if it failed. while (true) { if (!moveFolder(destFolder, oldDestFolder)) { monitor.logError("Failed to rename directory %1$s to %2$s.", destFolder.getPath(), oldDestFolder.getPath()); if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_WINDOWS) { boolean tryAgain = true; tryAgain = windowsDestDirLocked(osSdkRoot, destFolder, monitor); if (tryAgain) { // loop, trying to rename the temp dir into the destination continue; } else { return false; } } } break; } } assert !mFileOp.exists(destFolder); // -2- Unzip new content directly in place. if (!mFileOp.mkdirs(destFolder)) { monitor.logError("Failed to create directory %1$s", destFolder.getPath()); return false; } if (!unzipFolder(archiveInfo, archiveFile, destFolder, monitor)) { return false; } if (!generateSourceProperties(newArchive, destFolder)) { monitor.logError("Failed to generate source.properties in directory %1$s", destFolder.getPath()); return false; } // In case of success, if we were replacing an archive // and the older one had a different path, remove it now. LocalPkgInfo oldArchive = archiveInfo.getReplaced(); if (oldArchive != null) { File oldFolder = oldArchive.getLocalDir(); if (mFileOp.exists(oldFolder) && !oldFolder.equals(destFolder)) { monitor.logVerbose("Removing old archive at %1$s", oldFolder.getAbsolutePath()); mFileOp.deleteFileOrFolder(oldFolder); } } success = true; pkg.postInstallHook(newArchive, monitor, destFolder); return true; } finally { if (!success) { // In case of failure, we try to restore the old folder content. if (oldDestFolder != null) { restoreFolder(oldDestFolder, destFolder); } // We also call the postInstallHool with a null directory to give a chance // to the archive to cleanup after preInstallHook. pkg.postInstallHook(newArchive, monitor, null /*installDir*/); } // Cleanup if the unzip folder is still set. mFileOp.deleteFileOrFolder(oldDestFolder); } }
From source file:org.openbel.framework.tools.DocumentConverter.java
private void run() { verbose = hasOption(SHORT_OPT_VERBOSE); debug = hasOption(LONG_OPT_DEBUG);/*from w w w .j a v a 2 s.c o m*/ final List<String> extraArgs = getExtraneousArguments(); // Determine the input document file path if (extraArgs.size() == 0) { reportable.error("No documents specified."); end(); } else if (extraArgs.size() > 1) { fatal("Only a single document can be specified."); } final String inputFileName = extraArgs.get(0); // Check that the input file exists final File inputFile = new File(inputFileName); if (!inputFile.exists()) { fatal("Input file does not exist - " + inputFile.getAbsolutePath()); } // Determine the format of the input document final DocumentFormat format = determineType(inputFile); if (format == null) { fatal("Could not determine the format of the input file '" + inputFileName + "'. " + "Please specify '-t BEL' or '-t XBEL'."); } OutputStream output = null; if (hasOption("o")) { final String outputFilename = getOptionValue("o"); final boolean noPreserve = (hasOption("f") || hasOption(LONG_OPT_NO_PRESERVE)); final File outputFile = new File(outputFilename); if (!noPreserve && outputFile.exists()) { fatal("File '" + outputFilename + "' exists, specify --" + LONG_OPT_NO_PRESERVE + " to override."); } else if (inputFile.equals(outputFile)) { fatal("The input file cannot be the same as the output file."); } else { // Create a file to write the output document try { outputFile.createNewFile(); output = new FileOutputStream(outputFile); } catch (IOException ex) { bailOnException(ex); } } } else { output = System.out; } if (format == DocumentFormat.BEL) { convertBelToXbel(inputFile, output); } else if (format == DocumentFormat.XBEL) { convertXbelToBel(inputFile, output); } }
From source file:org.cytoscape.app.internal.manager.App.java
/** * Moves an app file to the given directory, copying the app if it is outside one of the local app storage directories * and moving if it is not. Also assigns filename that does not colliide with any from the local app storage directories. * //from www. j a v a 2 s .co m * Will also add postfix to filename if desired filename already exists in target directory when * moving app to a directory other than the 3 local app storage directories. * * @param appManager A reference to the app manager * @param targetDirectory The local storage directory to move to, such as the local sotrage directory * containing installed apps obtained via the app manager * @throws IOException If there was an error while moving/copying the file */ public void moveAppFile(AppManager appManager, File targetDirectory) throws IOException { File parentPath = this.getAppFile().getParentFile(); File installDirectoryPath = new File(appManager.getInstalledAppsPath()); File disabledDirectoryPath = new File(appManager.getDisabledAppsPath()); File uninstallDirectoryPath = new File(appManager.getUninstalledAppsPath()); // Want to make sure the app file's name does not collide with another name in these directories LinkedList<String> uniqueNameDirectories = new LinkedList<String>(); if (!parentPath.equals(installDirectoryPath)) uniqueNameDirectories.add(installDirectoryPath.getCanonicalPath()); if (!parentPath.equals(disabledDirectoryPath)) uniqueNameDirectories.add(disabledDirectoryPath.getCanonicalPath()); if (!parentPath.equals(uninstallDirectoryPath)) uniqueNameDirectories.add(uninstallDirectoryPath.getCanonicalPath()); if (!parentPath.equals(targetDirectory) && !installDirectoryPath.equals(targetDirectory) && !disabledDirectoryPath.equals(targetDirectory) && !uninstallDirectoryPath.equals(targetDirectory)) uniqueNameDirectories.add(targetDirectory.getCanonicalPath()); // If the app file is in one of these directories, do a move instead of a copy LinkedList<File> moveDirectories = new LinkedList<File>(); moveDirectories.add(installDirectoryPath); moveDirectories.add(disabledDirectoryPath); moveDirectories.add(uninstallDirectoryPath); File targetFile = new File(targetDirectory.getCanonicalPath() + File.separator + suggestFileName(uniqueNameDirectories, this.getAppFile().getName())); if (!targetDirectory.equals(parentPath)) { if (moveDirectories.contains(parentPath)) { FileUtils.moveFile(this.getAppFile(), targetFile); //System.out.println("Moving: " + this.getAppFile() + " -> " + targetFile); // ** Disabled to let directory observers assign file reference // this.setAppFile(targetFile); } else { FileUtils.copyFile(this.getAppFile(), targetFile); //System.out.println("Copying: " + this.getAppFile() + " -> " + targetFile); // ** Disabled to let directory observers assign file reference // this.setAppFile(targetFile); } } }