List of usage examples for org.apache.commons.vfs2 FileObject exists
boolean exists() throws FileSystemException;
From source file:org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.byon.CleanGSFilesByonTest.java
/** * Checks whether the files or folders exist on a remote host. * The returned value depends on the last parameter - "allMustExist". * If allMustExist is True the returned value is True only if all listed objects exist. * If allMustExist is False, the returned value is True if at least one object exists. * //w ww .j av a2 s . c om * @param host The host to connect to * @param username The name of the user that deletes the file/folder * @param password The password of the above user * @param keyFile The key file, if used * @param fileSystemObjects The files or folders to delete * @param fileTransferMode SCP for secure copy in Linux, or CIFS for windows file sharing * @param allMustExist If set to True the function will return True only if all listed objects exist. * If set to False, the function will return True if at least one object exists. * @return depends on allMustExist * @throws IOException Indicates the deletion failed */ public static boolean fileSystemObjectsExist(final String host, final String username, final String password, final String keyFile, final List<String> fileSystemObjects, final FileTransferModes fileTransferMode, final boolean allMustExist) throws IOException { boolean objectsExist; if (allMustExist) { objectsExist = true; } else { objectsExist = false; } if (!fileTransferMode.equals(FileTransferModes.SCP)) { //TODO Support get with CIFS as well throw new IOException("File resolving is currently not supported for this file transfer protocol (" + fileTransferMode + ")"); } final FileSystemOptions opts = new FileSystemOptions(); SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no"); SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false); if (keyFile != null && !keyFile.isEmpty()) { final File temp = new File(keyFile); if (!temp.isFile()) { throw new FileNotFoundException("Could not find key file: " + temp); } SftpFileSystemConfigBuilder.getInstance().setIdentities(opts, new File[] { temp }); } SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, SFTP_DISCONNECT_DETECTION_TIMEOUT_MILLIS); final FileSystemManager mng = VFS.getManager(); String scpTargetBase, scpTarget; if (password != null && !password.isEmpty()) { scpTargetBase = "sftp://" + username + ':' + password + '@' + host; } else { scpTargetBase = "sftp://" + username + '@' + host; } FileObject remoteDir = null; try { for (final String fileSystemObject : fileSystemObjects) { scpTarget = scpTargetBase + fileSystemObject; remoteDir = mng.resolveFile(scpTarget, opts); if (remoteDir.exists()) { if (!allMustExist) { objectsExist = true; break; } } else { if (allMustExist) { objectsExist = false; break; } } } } finally { if (remoteDir != null) { mng.closeFileSystem(remoteDir.getFileSystem()); } } return objectsExist; }
From source file:org.codehaus.mojo.vfs.internal.DefaultVfsFileSetManager.java
private void copyFile(FileObject fromFile, FileObject toFile, boolean overwrite) throws FileSystemException { if (overwrite || !toFile.exists() || fromFile.getContent().getLastModifiedTime() > toFile.getContent().getLastModifiedTime()) { toFile.copyFrom(fromFile, Selectors.SELECT_ALL); }/* w ww . ja va 2 s . c o m*/ }
From source file:org.datacleaner.actions.DownloadFilesActionListener.java
@Override protected FileObject[] doInBackground() throws Exception { for (int i = 0; i < _urls.length; i++) { final String url = _urls[i]; final FileObject file = _files[i]; InputStream inputStream = null; OutputStream outputStream = null; try {/*from w w w. jav a 2 s . co m*/ byte[] buffer = new byte[1024]; final HttpGet method = new HttpGet(url); if (!_cancelled) { final HttpResponse response = _httpClient.execute(method); if (response.getStatusLine().getStatusCode() != 200) { throw new InvalidHttpResponseException(url, response); } final HttpEntity responseEntity = response.getEntity(); final long expectedSize = responseEntity.getContentLength(); if (expectedSize > 0) { publish(new Task() { @Override public void execute() throws Exception { _downloadProgressWindow.setExpectedSize(file.getName().getBaseName(), expectedSize); } }); } inputStream = responseEntity.getContent(); if (!file.exists()) { file.createFile(); } outputStream = file.getContent().getOutputStream(); long bytes = 0; for (int numBytes = inputStream.read(buffer); numBytes != -1; numBytes = inputStream .read(buffer)) { if (_cancelled) { break; } outputStream.write(buffer, 0, numBytes); bytes += numBytes; final long totalBytes = bytes; publish(new Task() { @Override public void execute() throws Exception { _downloadProgressWindow.setProgress(file.getName().getBaseName(), totalBytes); } }); } if (!_cancelled) { publish(new Task() { @Override public void execute() throws Exception { _downloadProgressWindow.setFinished(file.getName().getBaseName()); } }); } } } catch (IOException e) { logger.debug("IOException occurred while downloading files", e); throw e; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { logger.warn("Could not close input stream: " + e.getMessage(), e); } } if (outputStream != null) { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { logger.warn("Could not flush & close output stream: " + e.getMessage(), e); } } _httpClient.close(); } if (_cancelled) { logger.info("Deleting non-finished download-file '{}'", file); file.delete(); } } return _files; }
From source file:org.datacleaner.actions.SaveAnalysisJobActionListener.java
@Override public void actionPerformed(ActionEvent event) { final String actionCommand = event.getActionCommand(); _window.setStatusLabelNotice();/*w w w . j av a 2 s. com*/ _window.setStatusLabelText(LABEL_TEXT_SAVING_JOB); AnalysisJob analysisJob = null; try { _window.applyPropertyValues(); analysisJob = _analysisJobBuilder.toAnalysisJob(); } catch (Exception e) { if (e instanceof NoResultProducingComponentsException) { int result = JOptionPane.showConfirmDialog(_window.toComponent(), "You job does not have any result-producing components in it, and is thus 'incomplete'. Do you want to save it anyway?", "No result producing components in job", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (result == JOptionPane.YES_OPTION) { analysisJob = _analysisJobBuilder.toAnalysisJob(false); } else { return; } } else { String detail = _window.getStatusLabelText(); if (LABEL_TEXT_SAVING_JOB.equals(detail)) { detail = e.getMessage(); } WidgetUtils.showErrorMessage("Errors in job", "Please fix the errors that exist in the job before saving it:\n\n" + detail, e); return; } } final FileObject existingFile = _window.getJobFile(); final FileObject file; if (existingFile == null || ACTION_COMMAND_SAVE_AS.equals(actionCommand)) { // ask the user to select a file to save to ("Save as" scenario) final DCFileChooser fileChooser = new DCFileChooser(_userPreferences.getAnalysisJobDirectory()); fileChooser.setFileFilter(FileFilters.ANALYSIS_XML); final int result = fileChooser.showSaveDialog(_window.toComponent()); if (result != JFileChooser.APPROVE_OPTION) { return; } final FileObject candidate = fileChooser.getSelectedFileObject(); final boolean exists; try { final String baseName = candidate.getName().getBaseName(); if (!baseName.endsWith(".xml")) { final FileObject parent = candidate.getParent(); file = parent.resolveFile(baseName + FileFilters.ANALYSIS_XML.getExtension()); } else { file = candidate; } exists = file.exists(); } catch (FileSystemException e) { throw new IllegalStateException("Failed to prepare file for saving", e); } if (exists) { int overwrite = JOptionPane.showConfirmDialog(_window.toComponent(), "Are you sure you want to overwrite the file '" + file.getName() + "'?", "Overwrite existing file?", JOptionPane.YES_NO_OPTION); if (overwrite != JOptionPane.YES_OPTION) { return; } } } else { // overwrite existing file ("Save" scenario). file = existingFile; } try { final FileObject parent = file.getParent(); final File parentFile = VFSUtils.toFile(parent); if (parentFile != null) { _userPreferences.setAnalysisJobDirectory(parentFile); } } catch (FileSystemException e) { logger.warn("Failed to determine parent of {}: {}", file, e.getMessage()); } final AnalysisJobMetadata existingMetadata = analysisJob.getMetadata(); final String jobName = existingMetadata.getJobName(); final String jobVersion = existingMetadata.getJobVersion(); final String author; if (Strings.isNullOrEmpty(existingMetadata.getAuthor())) { author = System.getProperty("user.name"); } else { author = existingMetadata.getAuthor(); } final String jobDescription; if (Strings.isNullOrEmpty(existingMetadata.getJobDescription())) { jobDescription = "Created with DataCleaner " + Version.getEdition() + " " + Version.getVersion(); } else { jobDescription = existingMetadata.getJobDescription(); } final JaxbJobWriter writer = new JaxbJobWriter(_configuration, new JaxbJobMetadataFactoryImpl(author, jobName, jobDescription, jobVersion)); OutputStream outputStream = null; try { outputStream = file.getContent().getOutputStream(); writer.write(analysisJob, outputStream); } catch (IOException e1) { throw new IllegalStateException(e1); } finally { FileHelper.safeClose(outputStream); } if (file instanceof DelegateFileObject) { // this "file" is probably a HTTP URL resource (often provided by DC // monitor) final DelegateFileObject delegateFileObject = (DelegateFileObject) file; final String scheme = file.getName().getScheme(); if ("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme)) { final String uri = delegateFileObject.getName().getURI(); final MonitorConnection monitorConnection = _userPreferences.getMonitorConnection(); if (monitorConnection.matchesURI(uri) && monitorConnection.isAuthenticationEnabled() && monitorConnection.getEncodedPassword() == null) { // password is not configured, ask for it. final MonitorConnectionDialog dialog = new MonitorConnectionDialog(_window.getWindowContext(), _userPreferences); dialog.openBlocking(); } final PublishJobToMonitorActionListener publisher = new PublishJobToMonitorActionListener( delegateFileObject, _window.getWindowContext(), _userPreferences); publisher.actionPerformed(event); } else { throw new UnsupportedOperationException("Unexpected delegate file object: " + delegateFileObject + " (delegate: " + delegateFileObject.getDelegateFile() + ")"); } } else { _userPreferences.addRecentJobFile(file); } _window.setJobFile(file); _window.setStatusLabelNotice(); _window.setStatusLabelText("Saved job to file " + file.getName().getBaseName()); }
From source file:org.datacleaner.bootstrap.Bootstrap.java
/** * Looks up a file, either based on a user requested filename (typically a * CLI parameter, may be a URL) or by a relative filename defined in the * system-/*w ww. j av a 2s . co m*/ * * @param userRequestedFilename * the user requested filename, may be null * @param localFilename * the relative filename defined by the system * @param userPreferences * @return * @throws FileSystemException */ private FileObject resolveFile(final String userRequestedFilename, final String localFilename, UserPreferences userPreferences) throws FileSystemException { final File dataCleanerHome = DataCleanerHome.getAsFile(); if (userRequestedFilename == null) { File file = new File(dataCleanerHome, localFilename); return VFSUtils.toFileObject(file); } else { String lowerCaseFilename = userRequestedFilename.toLowerCase(); if (lowerCaseFilename.startsWith("http://") || lowerCaseFilename.startsWith("https://")) { if (!GraphicsEnvironment.isHeadless()) { // download to a RAM file. final FileObject targetDirectory = VFSUtils.getFileSystemManager() .resolveFile("ram:///datacleaner/temp"); if (!targetDirectory.exists()) { targetDirectory.createFolder(); } final URI uri; try { uri = new URI(userRequestedFilename); } catch (URISyntaxException e) { throw new IllegalArgumentException("Illegal URI: " + userRequestedFilename, e); } final WindowContext windowContext = new SimpleWindowContext(); MonitorConnection monitorConnection = null; // check if URI points to DC monitor. If so, make sure // credentials are entered. if (userPreferences != null && userPreferences.getMonitorConnection() != null) { monitorConnection = userPreferences.getMonitorConnection(); if (monitorConnection.matchesURI(uri)) { if (monitorConnection.isAuthenticationEnabled()) { if (monitorConnection.getEncodedPassword() == null) { final MonitorConnectionDialog dialog = new MonitorConnectionDialog( windowContext, userPreferences); dialog.openBlocking(); } monitorConnection = userPreferences.getMonitorConnection(); } } } try (MonitorHttpClient httpClient = getHttpClient(monitorConnection)) { final String[] urls = new String[] { userRequestedFilename }; final String[] targetFilenames = DownloadFilesActionListener.createTargetFilenames(urls); final FileObject[] files = downloadFiles(urls, targetDirectory, targetFilenames, windowContext, httpClient, monitorConnection); assert files.length == 1; final FileObject ramFile = files[0]; if (logger.isInfoEnabled()) { final InputStream in = ramFile.getContent().getInputStream(); try { final String str = FileHelper .readInputStreamAsString(ramFile.getContent().getInputStream(), "UTF8"); logger.info("Downloaded file contents: {}\n{}", userRequestedFilename, str); } finally { FileHelper.safeClose(in); } } final String scheme = uri.getScheme(); final int defaultPort; if ("http".equals(scheme)) { defaultPort = 80; } else { defaultPort = 443; } final UrlFileName fileName = new UrlFileName(scheme, uri.getHost(), uri.getPort(), defaultPort, null, null, uri.getPath(), FileType.FILE, uri.getQuery()); AbstractFileSystem fileSystem = (AbstractFileSystem) VFSUtils.getBaseFileSystem(); return new DelegateFileObject(fileName, fileSystem, ramFile); } finally { userPreferences.setMonitorConnection(monitorConnection); } } } return VFSUtils.getFileSystemManager().resolveFile(userRequestedFilename); } }
From source file:org.datacleaner.guice.DCModuleImpl.java
private final Ref<UserPreferences> createUserPreferencesRef(final FileObject dataCleanerHome) { try {/*ww w . j a v a 2 s. co m*/ if ("true".equalsIgnoreCase(System.getProperty(SystemProperties.SANDBOX))) { return new ImmutableRef<UserPreferences>(new UserPreferencesImpl(null)); } if (dataCleanerHome == null || !dataCleanerHome.exists()) { logger.info( "DataCleaner home was not set or does not exist. Non-persistent user preferences will be applied."); return new ImmutableRef<UserPreferences>(new UserPreferencesImpl(null)); } final FileObject userPreferencesFile = dataCleanerHome .resolveFile(UserPreferencesImpl.DEFAULT_FILENAME); return new LazyRef<UserPreferences>() { @Override protected UserPreferences fetch() { return UserPreferencesImpl.load(userPreferencesFile, true); } }; } catch (FileSystemException e) { throw new IllegalStateException("Not able to resolve files in DataCleaner home: " + dataCleanerHome, e); } }
From source file:org.datacleaner.panels.WelcomePanel.java
private List<FileObject> getRecentJobFiles() { final List<FileObject> recentJobFiles = _userPreferences.getRecentJobFiles(); final List<FileObject> result = new ArrayList<>(); for (FileObject fileObject : recentJobFiles) { try {/*from ww w.ja va2 s .c o m*/ if (fileObject.exists()) { result.add(fileObject); if (result.size() == 10) { break; } } } catch (FileSystemException ex) { logger.debug("Skipping file {} because of unexpected error", ex); } } return result; }
From source file:org.datacleaner.test.scenario.OpenAnalysisJobTest.java
/** * A very broad integration test which opens a job with (more or less) all * built-in analyzers.//www. j a v a2 s .co m * * @throws Exception */ public void testOpenJobWithManyAnalyzers() throws Exception { if (GraphicsEnvironment.isHeadless()) { System.out.println("!!! Skipping test because environment is headless: " + getName()); return; } DCModule module = new DCModuleImpl(); Injector injector = Guice.createInjector(module); DataCleanerConfiguration configuration = injector.getInstance(DataCleanerConfiguration.class); FileObject file = VFSUtils.getFileSystemManager() .resolveFile("src/test/resources/all_analyzers.analysis.xml"); assertTrue(file.exists()); injector = OpenAnalysisJobActionListener.open(file, configuration, injector); AnalysisJobBuilderWindow window = injector.getInstance(AnalysisJobBuilderWindow.class); assertNotNull(window); assertEquals("all_analyzers.analysis.xml", window.getJobFile().getName().getBaseName()); ((AnalysisJobBuilderWindowImpl) window).updateStatusLabel(); assertEquals("Job is correctly configured", window.getStatusLabelText()); }
From source file:org.datacleaner.user.DataCleanerHome.java
private static FileObject initializeDataCleanerHome(FileObject candidate) throws FileSystemException { final FileSystemManager manager = VFSUtils.getFileSystemManager(); if (ClassLoaderUtils.IS_WEB_START) { // in web start, the default folder will be in user.home final String path = getUserHomeCandidatePath(); candidate = manager.resolveFile(path); logger.info("Running in WebStart mode. Attempting to build DATACLEANER_HOME in user.home: {} -> {}", path, candidate);// ww w. j a v a 2 s . c o m } else { // in normal mode try to use specified directory first logger.info("Running in standard mode."); if (isWriteable(candidate)) { logger.info("Attempting to build DATACLEANER_HOME in {}", candidate); } else { // Workaround: isWritable is not reliable for a non-existent // directory. Trying to create it, if it does not exist. if ((candidate != null) && (!candidate.exists())) { logger.info("Folder {} does not exist. Trying to create it.", candidate); try { candidate.createFolder(); logger.info("Folder {} created successfully. Attempting to build DATACLEANER_HOME here.", candidate); } catch (FileSystemException e) { logger.info("Unable to create folder {}. No write permission in that location.", candidate); candidate = initializeDataCleanerHomeFallback(); } } else { candidate = initializeDataCleanerHomeFallback(); } } } if ("true".equalsIgnoreCase(System.getProperty(SystemProperties.SANDBOX))) { logger.info("Running in sandbox mode ({}), setting {} as DATACLEANER_HOME", SystemProperties.SANDBOX, candidate); if (!candidate.exists()) { candidate.createFolder(); } return candidate; } if (!isUsable(candidate)) { DataCleanerHomeUpgrader upgrader = new DataCleanerHomeUpgrader(); boolean upgraded = upgrader.upgrade(candidate); if (!upgraded) { logger.debug("Copying default configuration and examples to DATACLEANER_HOME directory: {}", candidate); copyIfNonExisting(candidate, manager, "conf.xml"); final List<String> allFilePaths = DemoConfiguration.getAllFilePaths(); for (String filePath : allFilePaths) { copyIfNonExisting(candidate, manager, filePath); } } } return candidate; }
From source file:org.datacleaner.user.DataCleanerHome.java
private static FileObject initializeDataCleanerHomeFallback() throws FileSystemException { final FileSystemManager manager = VFSUtils.getFileSystemManager(); FileObject candidate; // Fallback to user home directory final String path = getUserHomeCandidatePath(); candidate = manager.resolveFile(path); logger.info("Attempting to build DATACLEANER_HOME in user.home: {} -> {}", path, candidate); if (!isWriteable(candidate)) { // Workaround: isWritable is not reliable for a non-existent // directory. Trying to create it, if it does not exist. if ((candidate != null) && (!candidate.exists())) { logger.info("Folder {} does not exist. Trying to create it.", candidate); try { candidate.createFolder(); logger.info("Folder {} created successfully. Attempting to build DATACLEANER_HOME here.", candidate);/*from w ww . jav a 2s .com*/ } catch (FileSystemException e) { logger.info("Unable to create folder {}. No write permission in that location.", candidate); throw new IllegalStateException("User home directory (" + candidate + ") is not writable. DataCleaner requires write access to its home directory."); } } } return candidate; }