List of usage examples for java.io File equals
public boolean equals(Object obj)
From source file:org.collectionspace.services.common.imaging.nuxeo.NuxeoBlobUtils.java
/** * Creates the picture./*from w w w .j a v a2s .c o m*/ * * @param ctx * the ctx * @param repoSession * the repo session * @param filePath * the file path * @return the string * @throws Exception */ public static BlobsCommon createBlobInRepository(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, CoreSessionInterface repoSession, BlobInput blobInput, boolean purgeOriginal, boolean useNuxeoAdaptors) throws Exception { BlobsCommon result = null; File originalFile = blobInput.getBlobFile(); File targetFile = originalFile; try { // We'll store the blob inside the workspace directory of the calling service String nuxeoWspaceId = ctx.getRepositoryWorkspaceId(); DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId); DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace); // // If the original file's name contains "illegal" characters, then we create a copy of the file to give Nuxeo. // String sanitizedName = NuxeoBlobUtils.getSanizitedFilename(originalFile); if (sanitizedName.equals(originalFile.getName()) == false) { targetFile = FileUtilities.createTmpFile(originalFile, sanitizedName); if (logger.isDebugEnabled() == true) { logger.debug(String.format( "The file '%s''s name has characters that Nuxeo can't deal with. Rather than renaming the file, we created a new temp file at '%s'", originalFile.getName(), targetFile.getAbsolutePath())); } } result = createBlobInRepository(repoSession, wspaceDoc, purgeOriginal, targetFile, null, // MIME type useNuxeoAdaptors); // // Make sure we're using the original file name in our BlobsCommon instance. If the original file's name // contained illegal characters, then we created and handed a copy of the file to Nuxeo. We don't want the // copy's file name stored in the BlobsCommon instance, we want the original file name instead. // if (targetFile.equals(originalFile) == false) { result.setName(originalFile.getName()); } } catch (Exception e) { logger.error("Could not create image blob.", e); throw e; } finally { // // If we created a temp file then we should delete it. // if (targetFile.equals(originalFile) == false) { if (targetFile.delete() == false) { logger.warn(String.format("Attempt to delete temporary file '%s' failed.", targetFile.getAbsolutePath())); } } } return result; }
From source file:org.opennms.upgrade.implementations.JmxRrdMigratorOffline.java
/** * Process group files./*from w ww. ja va 2 s.c o m*/ * * @param resourceDir the resource directory * @param isRrdtool the is RRDtool enabled * @throws Exception the exception */ private void processGroupFiles(File resourceDir, boolean isRrdtool) throws Exception { // DS File dsFile = new File(resourceDir, "ds.properties"); log("Processing DS %s\n", dsFile); if (dsFile.exists()) { Properties dsProperties = new Properties(); Properties newDsProperties = new Properties(); try (FileReader fr = new FileReader(dsFile);) { dsProperties.load(fr); for (Object key : dsProperties.keySet()) { String oldName = (String) key; String newName = getFixedDsName(oldName); String oldFile = dsProperties.getProperty(oldName); String newFile = getFixedFileName(oldFile); newDsProperties.put(newName, newFile); } try (FileWriter fw = new FileWriter(dsFile);) { newDsProperties.store(new FileWriter(dsFile), null); } } } // META final String metaExt = ".meta"; File[] metaFiles = getFiles(resourceDir, metaExt); if (metaFiles == null) { log("Warning: there are no %s files on %s\n", metaExt, resourceDir); } else { for (final File metaFile : metaFiles) { log("Processing META %s\n", metaFile); Properties meta = new Properties(); Properties newMeta = new Properties(); try (FileReader fr = new FileReader(metaFile);) { meta.load(fr); for (Object k : meta.keySet()) { String key = (String) k; String dsName = meta.getProperty(key); String newName = getFixedDsName(dsName); String newKey = key.replaceAll(dsName, newName); newMeta.put(newKey, newName); } File newFile = new File(metaFile.getParentFile(), getFixedFileName(metaFile.getName().replaceFirst(metaExt, "")) + metaExt); log("Recreating META into %s\n", newFile); try (FileWriter fw = new FileWriter(newFile);) { newMeta.store(fw, null); } if (!metaFile.equals(newFile)) { if (!metaFile.delete()) { LOG.warn("Could not delete file: {}", metaFile.getPath()); } } } } } // JRBs final String rrdExt = getRrdExtension(); File[] jrbFiles = getFiles(resourceDir, rrdExt); if (jrbFiles == null) { log("Warning: there are no %s files on %s\n", rrdExt, resourceDir); } else { for (final File jrbFile : jrbFiles) { log("Processing %s %s\n", rrdExt.toUpperCase(), jrbFile); File newFile = new File(jrbFile.getParentFile(), getFixedFileName(jrbFile.getName().replaceFirst(rrdExt, "")) + rrdExt); if (!jrbFile.equals(newFile)) { try { log("Renaming %s to %s\n", rrdExt.toUpperCase(), newFile); FileUtils.moveFile(jrbFile, newFile); } catch (Exception e) { log("Warning: Can't move file because: %s", e.getMessage()); continue; } } if (!isRrdtool) { // Only the JRBs may contain invalid DS inside updateJrb(newFile); } } } }
From source file:org.commonjava.maven.ext.io.PomIO.java
/** * Read {@link Model} instances by parsing the POM directly. This is useful to escape some post-processing that happens when the * {@link MavenProject#getOriginalModel()} instance is set. * * @param executionRoot the top level pom file. * @param peeked a collection of poms resolved from the top level file. * @return a collection of Projects//from www. j av a2 s . co m * @throws ManipulationException if an error occurs. */ private List<Project> readModelsForManipulation(File executionRoot, final List<PomPeek> peeked) throws ManipulationException { final List<Project> projects = new ArrayList<>(); final HashMap<Project, ProjectVersionRef> projectToParent = new HashMap<>(); for (final PomPeek peek : peeked) { final File pom = peek.getPom(); // Sucks, but we have to brute-force reading in the raw model. // The effective-model building, below, has a tantalizing getRawModel() // method on the result, BUT this seems to return models that have // the plugin versions set inside profiles...so they're not entirely // raw. Model raw = null; InputStream in = null; try { in = new FileInputStream(pom); raw = new MavenXpp3Reader().read(in); } catch (final IOException | XmlPullParserException e) { throw new ManipulationException("Failed to build model for POM: %s.\n--> %s", e, pom, e.getMessage()); } finally { closeQuietly(in); } if (raw == null) { continue; } final Project project = new Project(pom, raw); projectToParent.put(project, peek.getParentKey()); project.setInheritanceRoot(peek.isInheritanceRoot()); if (executionRoot.equals(pom)) { logger.debug( "Setting execution root to {} with file {}" + (project.isInheritanceRoot() ? " and is the inheritance root. " : ""), project, pom); project.setExecutionRoot(); try { if (FileUtils.readFileToString(pom).contains(MODIFIED_BY)) { project.setIncrementalPME(true); } } catch (final IOException e) { throw new ManipulationException("Failed to read POM: %s", e, pom); } } projects.add(project); } // Fill out inheritance info for every project we have created. for (Project p : projects) { ProjectVersionRef pvr = projectToParent.get(p); p.setProjectParent(getParent(projects, pvr)); } return projects; }
From source file:com.izforge.izpack.panels.shortcut.ShortcutPanelLogic.java
/** * Creates all shortcuts based on the information in shortcuts. *//*from www . jav a2 s . c o m*/ private void createShortcuts(List<ShortcutData> shortcuts) { if (!createShortcuts) { return; } String groupName; List<String> startMenuShortcuts = new ArrayList<String>(); for (ShortcutData data : shortcuts) { try { groupName = this.groupName + data.subgroup; shortcut.setUserType(userType); shortcut.setLinkName(data.name); shortcut.setLinkType(data.type); shortcut.setArguments(data.commandLine); shortcut.setDescription(data.description); shortcut.setIconLocation(data.iconFile, data.iconIndex); shortcut.setShowCommand(data.initialState); shortcut.setTargetPath(data.target); shortcut.setWorkingDirectory(data.workingDirectory); shortcut.setEncoding(data.deskTopEntryLinux_Encoding); shortcut.setMimetype(data.deskTopEntryLinux_MimeType); shortcut.setRunAsAdministrator(data.runAsAdministrator); shortcut.setTerminal(data.deskTopEntryLinux_Terminal); shortcut.setTerminalOptions(data.deskTopEntryLinux_TerminalOptions); shortcut.setType(data.deskTopEntryLinux_Type); shortcut.setKdeSubstUID(data.deskTopEntryLinux_X_KDE_SubstituteUID); shortcut.setKdeUserName(data.deskTopEntryLinux_X_KDE_UserName); shortcut.setURL(data.deskTopEntryLinux_URL); shortcut.setTryExec(data.TryExec); shortcut.setCategories(data.Categories); shortcut.setCreateForAll(data.createForAll); shortcut.setUninstaller(uninstallData); if (data.addToGroup) { shortcut.setProgramGroup(groupName); } else { shortcut.setProgramGroup(""); } shortcut.save(); if (data.type == Shortcut.APPLICATIONS || data.addToGroup) { if (shortcut instanceof com.izforge.izpack.util.os.Unix_Shortcut) { com.izforge.izpack.util.os.Unix_Shortcut unixcut = (com.izforge.izpack.util.os.Unix_Shortcut) shortcut; String f = unixcut.getWrittenFileName(); if (f != null) { startMenuShortcuts.add(f); } } } // add the file and directory name to the file list String fileName = shortcut.getFileName(); files.add(0, fileName); File file = new File(fileName); File base = new File(shortcut.getBasePath()); Vector<File> intermediates = new Vector<File>(); execFiles.add(new ExecutableFile(fileName, ExecutableFile.UNINSTALL, ExecutableFile.IGNORE, new ArrayList<OsModel>(), false)); files.add(fileName); while ((file = file.getParentFile()) != null) { if (file.equals(base)) { break; } intermediates.add(file); } if (file != null) { Enumeration<File> filesEnum = intermediates.elements(); while (filesEnum.hasMoreElements()) { files.add(0, filesEnum.nextElement().toString()); } } } catch (Exception ignored) { } } if (OsVersion.IS_UNIX) { writeXDGMenuFile(startMenuShortcuts, this.groupName, programGroupIconFile, programGroupComment); } shortcut.execPostAction(); try { if (execFiles != null) { // // TODO: Hi Guys, // TODO The following commented lines sometimes produces an uncatchable // nullpointer Exception! // TODO evaluate for what reason the files should exec. // TODO if there is a serious explanation, why to do that, // TODO the code must be more robust //FileExecutor executor = new FileExecutor(execFiles); // evaluate executor.executeFiles( ExecutableFile.NEVER, null ); } } catch (NullPointerException nep) { nep.printStackTrace(); } catch (RuntimeException cannot) { cannot.printStackTrace(); } shortcut.cleanUp(); }
From source file:org.opennms.upgrade.implementations.JmxRrdMigratorOffline.java
/** * Process single files./* w w w .j a va2 s . co m*/ * * @param resourceDir the resource directory * @param isRrdtool the is RRDtool enabled * @throws Exception the exception */ private void processSingleFiles(File resourceDir, boolean isRrdtool) throws Exception { // META final String metaExt = ".meta"; File[] metaFiles = getFiles(resourceDir, metaExt); if (metaFiles == null) { log("Warning: there are no %s files on %s\n", metaExt, resourceDir); } else { for (final File metaFile : metaFiles) { log("Processing META %s\n", metaFile); String dsName = metaFile.getName().replaceFirst(metaExt, ""); String newName = getFixedDsName(dsName); if (!dsName.equals(newName)) { Properties meta = new Properties(); Properties newMeta = new Properties(); try (FileReader fr = new FileReader(metaFile);) { meta.load(fr); for (Object k : meta.keySet()) { String key = (String) k; String newKey = key.replaceAll(dsName, newName); newMeta.put(newKey, newName); } File newFile = new File(metaFile.getParentFile(), newName + metaExt); log("Re-creating META into %s\n", newFile); try (FileWriter fw = new FileWriter(newFile);) { newMeta.store(fw, null); } if (!metaFile.equals(newFile)) { if (!metaFile.delete()) { LOG.warn("Could not delete file {}", metaFile.getPath()); } } } } } } // JRBs final String rrdExt = getRrdExtension(); File[] jrbFiles = getFiles(resourceDir, rrdExt); if (jrbFiles == null) { log("Warning: there are no %s files on %s\n", rrdExt, resourceDir); } else { for (final File jrbFile : jrbFiles) { log("Processing %s %s\n", rrdExt.toUpperCase(), jrbFile); String dsName = jrbFile.getName().replaceFirst(rrdExt, ""); String newName = getFixedDsName(dsName); File newFile = new File(jrbFile.getParentFile(), newName + rrdExt); if (!dsName.equals(newName)) { try { log("Renaming %s to %s\n", rrdExt.toUpperCase(), newFile); FileUtils.moveFile(jrbFile, newFile); } catch (Exception e) { log("Warning: Can't move file because: %s", e.getMessage()); continue; } } if (!isRrdtool) { // Only the JRBs may contain invalid DS inside updateJrb(newFile); } } } }
From source file:com.sap.prd.mobile.ios.mios.XCodeCopySourcesMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { final File baseDirectory = getCanonicalFile(project.getBasedir()); final File checkoutDirectory = getCanonicalFile(getCheckoutDirectory()); final String buildDirPath = getProjectBuildDirectory(); getLog().info("Base directory: " + baseDirectory); getLog().info("Checkout directory: " + checkoutDirectory); getLog().info("BuildDirPath: " + buildDirPath); final File originalLibDir = getCanonicalFile( new File(project.getBuild().getDirectory(), FolderLayout.LIBS_DIR_NAME)); final File copyOfLibDir = getCanonicalFile( new File(checkoutDirectory, buildDirPath + "/" + FolderLayout.LIBS_DIR_NAME)); final File originalHeadersDir = getCanonicalFile( new File(project.getBuild().getDirectory(), FolderLayout.HEADERS_DIR_NAME)); final File copyOfHeadersDir = getCanonicalFile( new File(checkoutDirectory, buildDirPath + "/" + FolderLayout.HEADERS_DIR_NAME)); final File originalXcodeDepsDir = getCanonicalFile( new File(project.getBuild().getDirectory(), FolderLayout.XCODE_DEPS_TARGET_FOLDER)); final File copyOfXcodeDepsDir = getCanonicalFile( new File(checkoutDirectory, buildDirPath + "/" + FolderLayout.XCODE_DEPS_TARGET_FOLDER)); try {//from ww w . j a va 2s .co m if (checkoutDirectory.exists()) com.sap.prd.mobile.ios.mios.FileUtils.deleteDirectory(checkoutDirectory); copy(baseDirectory, checkoutDirectory, new FileFilter() { @Override public boolean accept(final File pathname) { final File canonicalPathName = getCanonicalFile(pathname); return !(checkoutDirectory.equals(canonicalPathName) || originalLibDir.equals(canonicalPathName) || originalHeadersDir.equals(canonicalPathName) || originalXcodeDepsDir.equals(canonicalPathName)); } }); if (originalLibDir.exists()) { if (useSymbolicLinks()) { com.sap.prd.mobile.ios.mios.FileUtils.createSymbolicLink(originalLibDir, copyOfLibDir); } else { FileUtils.copyDirectory(originalLibDir, copyOfLibDir); } } if (originalHeadersDir.exists()) { if (useSymbolicLinks) { com.sap.prd.mobile.ios.mios.FileUtils.createSymbolicLink(originalHeadersDir, copyOfHeadersDir); } else { FileUtils.copyDirectory(originalHeadersDir, copyOfHeadersDir); } } if (originalXcodeDepsDir.exists()) { if (useSymbolicLinks) { com.sap.prd.mobile.ios.mios.FileUtils.createSymbolicLink(originalXcodeDepsDir, copyOfXcodeDepsDir); } else { FileUtils.copyDirectory(originalXcodeDepsDir, copyOfXcodeDepsDir); } } } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:org.apache.nifi.processors.standard.TailFile.java
/** * Returns a list of all Files that match the following criteria: * * <ul>/*from ww w. j a v a 2 s . c om*/ * <li>Filename matches the Rolling Filename Pattern</li> * <li>Filename does not match the actual file being tailed</li> * <li>The Last Modified Time on the file is equal to or later than the * given minimum timestamp</li> * </ul> * * <p> * The List that is returned will be ordered by file timestamp, providing * the oldest file first. * </p> * * @param context the ProcessContext to use in order to determine Processor * configuration * @param minTimestamp any file with a Last Modified Time before this * timestamp will not be returned * @return a list of all Files that have rolled over * @throws IOException if unable to perform the listing of files */ private List<File> getRolledOffFiles(final ProcessContext context, final long minTimestamp, final String tailFilePath) throws IOException { final File tailFile = new File(tailFilePath); File directory = tailFile.getParentFile(); if (directory == null) { directory = new File("."); } String rollingPattern = context.getProperty(ROLLING_FILENAME_PATTERN).getValue(); if (rollingPattern == null) { return Collections.emptyList(); } else { rollingPattern = rollingPattern.replace("${filename}", StringUtils.substringBeforeLast(tailFile.getName(), ".")); } final List<File> rolledOffFiles = new ArrayList<>(); try (final DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory.toPath(), rollingPattern)) { for (final Path path : dirStream) { final File file = path.toFile(); final long lastMod = file.lastModified(); if (file.lastModified() < minTimestamp) { getLogger().debug( "Found rolled off file {} but its last modified timestamp is before the cutoff (Last Mod = {}, Cutoff = {}) so will not consume it", new Object[] { file, lastMod, minTimestamp }); continue; } else if (file.equals(tailFile)) { continue; } rolledOffFiles.add(file); } } // Sort files based on last modified timestamp. If same timestamp, use filename as a secondary sort, as often // files that are rolled over are given a naming scheme that is lexicographically sort in the same order as the // timestamp, such as yyyy-MM-dd-HH-mm-ss Collections.sort(rolledOffFiles, new Comparator<File>() { @Override public int compare(final File o1, final File o2) { final int lastModifiedComp = Long.compare(o1.lastModified(), o2.lastModified()); if (lastModifiedComp != 0) { return lastModifiedComp; } return o1.getName().compareTo(o2.getName()); } }); return rolledOffFiles; }
From source file:mondrian.gui.Workbench.java
private boolean checkFileOpen(File file) { Iterator<JInternalFrame> it = schemaWindowMap.keySet().iterator(); // keys=schemaframes while (it.hasNext()) { JInternalFrame elem = it.next(); File f = ((SchemaExplorer) elem.getContentPane().getComponent(0)).getSchemaFile(); if (f.equals(file)) { try { // make the schema file active elem.setSelected(true);//from ww w .j a v a 2s . c o m return true; } catch (Exception ex) { // remove file from map as schema frame does not exist schemaWindowMap.remove(elem); break; } } } return false; }
From source file:com.gitblit.utils.JGitUtils.java
/** * Recursive function to find git repositories. * * @param basePath//from w ww. j ava 2 s .c o m * basePath is stripped from the repository name as repositories * are relative to this path * @param searchFolder * @param onlyBare * if true only bare repositories will be listed. if false all * repositories are included. * @param searchSubfolders * recurse into subfolders to find grouped repositories * @param depth * recursion depth, -1 = infinite recursion * @param patterns * list of regex patterns for matching to folder names * @return */ private static List<String> getRepositoryList(String basePath, File searchFolder, boolean onlyBare, boolean searchSubfolders, int depth, List<Pattern> patterns) { File baseFile = new File(basePath); List<String> list = new ArrayList<String>(); if (depth == 0) { return list; } int nextDepth = (depth == -1) ? -1 : depth - 1; for (File file : searchFolder.listFiles()) { if (file.isDirectory()) { boolean exclude = false; for (Pattern pattern : patterns) { String path = FileUtils.getRelativePath(baseFile, file).replace('\\', '/'); if (pattern.matcher(path).matches()) { LOGGER.debug( MessageFormat.format("excluding {0} because of rule {1}", path, pattern.pattern())); exclude = true; break; } } if (exclude) { // skip to next file continue; } File gitDir = FileKey.resolve(new File(searchFolder, file.getName()), FS.DETECTED); if (gitDir != null) { if (onlyBare && gitDir.getName().equals(".git")) { continue; } if (gitDir.equals(file) || gitDir.getParentFile().equals(file)) { // determine repository name relative to base path String repository = FileUtils.getRelativePath(baseFile, file); list.add(repository); } else if (searchSubfolders && file.canRead()) { // look for repositories in subfolders list.addAll( getRepositoryList(basePath, file, onlyBare, searchSubfolders, nextDepth, patterns)); } } else if (searchSubfolders && file.canRead()) { // look for repositories in subfolders list.addAll(getRepositoryList(basePath, file, onlyBare, searchSubfolders, nextDepth, patterns)); } } } return list; }
From source file:SWTFileViewerDemo.java
/** * Handles deferred Refresh notifications (due to Drag & Drop) *//* www.j a v a 2 s. co m*/ void handleDeferredRefresh() { if (isDragging || isDropping || !deferredRefreshRequested) return; if (progressDialog != null) { progressDialog.close(); progressDialog = null; } deferredRefreshRequested = false; File[] files = deferredRefreshFiles; deferredRefreshFiles = null; shell.setCursor(iconCache.stockCursors[iconCache.cursorWait]); /* * Table view: Refreshes information about any files in the list and * their children. */ boolean refreshTable = false; if (files != null) { for (int i = 0; i < files.length; ++i) { final File file = files[i]; if (file.equals(currentDirectory)) { refreshTable = true; break; } File parentFile = file.getParentFile(); if ((parentFile != null) && (parentFile.equals(currentDirectory))) { refreshTable = true; break; } } } else refreshTable = true; if (refreshTable) workerUpdate(currentDirectory, true); /* * Combo view: Refreshes the list of roots */ final File[] roots = getRoots(); if (files == null) { boolean refreshCombo = false; final File[] comboRoots = (File[]) combo.getData(COMBODATA_ROOTS); if ((comboRoots != null) && (comboRoots.length == roots.length)) { for (int i = 0; i < roots.length; ++i) { if (!roots[i].equals(comboRoots[i])) { refreshCombo = true; break; } } } else refreshCombo = true; if (refreshCombo) { combo.removeAll(); combo.setData(COMBODATA_ROOTS, roots); for (int i = 0; i < roots.length; ++i) { final File file = roots[i]; combo.add(file.getPath()); } } } /* * Tree view: Refreshes information about any files in the list and * their children. */ treeRefresh(roots); // Remind everyone where we are in the filesystem final File dir = currentDirectory; currentDirectory = null; notifySelectedDirectory(dir); shell.setCursor(iconCache.stockCursors[iconCache.cursorDefault]); }