List of usage examples for org.apache.commons.vfs2 FileObject getFileSystem
FileSystem getFileSystem();
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. * //from w w w .java 2 s . c o m * @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.eobjects.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-/*from ww w . j av a2 s . c om*/ * * @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 FileObject dataCleanerHome = DataCleanerHome.get(); if (userRequestedFilename == null) { return dataCleanerHome.resolveFile(localFilename); } 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(); @SuppressWarnings("resource") MonitorHttpClient httpClient = new SimpleWebServiceHttpClient(); 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(); httpClient = monitorConnection.getHttpClient(); } } } try { 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) dataCleanerHome.getFileSystem(); return new DelegateFileObject(fileName, fileSystem, ramFile); } finally { httpClient.close(); userPreferences.setMonitorConnection(monitorConnection); } } } return VFSUtils.getFileSystemManager().resolveFile(userRequestedFilename); } }
From source file:org.geoserver.backuprestore.utils.BackupUtils.java
/** * Extracts the archive file {@code archiveFile} to {@code targetFolder}; both shall previously exist. * * @param archiveFile//from w w w . j av a 2 s .c o m * @param targetFolder * @throws IOException */ public static void extractTo(Resource archiveFile, Resource targetFolder) throws IOException { FileSystemManager manager = VFS.getManager(); String sourceURI = resolveArchiveURI(archiveFile); FileObject source = manager.resolveFile(sourceURI); if (manager.canCreateFileSystem(source)) { source = manager.createFileSystem(source); } FileObject target = manager .createVirtualFileSystem(manager.resolveFile(targetFolder.dir().getAbsolutePath())); FileSelector selector = new AllFileSelector() { @Override public boolean includeFile(FileSelectInfo fileInfo) { LOGGER.fine("Uncompressing " + fileInfo.getFile().getName().getFriendlyURI()); return true; } }; target.copyFrom(source, selector); source.close(); target.close(); manager.closeFileSystem(source.getFileSystem()); }
From source file:org.geoserver.backuprestore.utils.BackupUtils.java
/** * Compress {@code sourceFolder} to the archive file {@code archiveFile}; both shall previously exist. * //from w w w .j a v a2 s .co m * @param sourceFolder * @param archiveFile * @throws IOException */ public static void compressTo(Resource sourceFolder, Resource archiveFile) throws IOException { // See https://commons.apache.org/proper/commons-vfs/filesystems.html // for the supported filesystems FileSystemManager manager = VFS.getManager(); FileObject sourceDir = manager .createVirtualFileSystem(manager.resolveFile(sourceFolder.dir().getAbsolutePath())); try { if ("zip".equalsIgnoreCase(FileUtils.getExtension(archiveFile.path()))) { // apache VFS does not support ZIP as writable FileSystem OutputStream fos = archiveFile.out(); // Create access to zip. ZipOutputStream zos = new ZipOutputStream(fos); // add entry/-ies. for (FileObject sourceFile : sourceDir.getChildren()) { writeEntry(zos, sourceFile, null); } // Close streams zos.flush(); zos.close(); fos.close(); } else { // Create access to archive. FileObject zipFile = manager.resolveFile(resolveArchiveURI(archiveFile)); zipFile.createFile(); ZipOutputStream zos = new ZipOutputStream(zipFile.getContent().getOutputStream()); // add entry/-ies. for (FileObject sourceFile : sourceDir.getChildren()) { writeEntry(zos, sourceFile, null); } // Close streams zos.flush(); zos.close(); zipFile.close(); manager.closeFileSystem(zipFile.getFileSystem()); } } finally { manager.closeFileSystem(sourceDir.getFileSystem()); } }
From source file:org.geoserver.importer.RemoteData.java
public ImportData resolve(Importer importer) throws IOException { // prepare the target Directory target = Directory.createNew(importer.getUploadRoot()); FileSystemManager manager = null;/* w w w .j a va 2 s .c om*/ FileObject fo = null; try { manager = VFS.getManager(); if (username != null) { StaticUserAuthenticator auth = new StaticUserAuthenticator(domain, username, password); FileSystemOptions opts = new FileSystemOptions(); DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth); fo = manager.resolveFile(location, opts); } else { fo = manager.resolveFile(location); } target.accept(fo); } finally { if (fo != null) { FileSystem fs = fo.getFileSystem(); fo.close(); manager.closeFileSystem(fs); } } return target; }
From source file:org.helios.ember.sftp.FileObjectWrapperCollection.java
/** * Creates a new FileObjectWrapperCollection /* w w w .ja v a 2 s . co m*/ * @param parent The parent folder * @param fileObjects The wrapped file objects to aggregate */ public FileObjectWrapperCollection(FileObject parent, FileObjectWrapper... fileObjects) { this.parentFolder = parent.getName().getPath(); this.root = parent.getFileSystem().getRootName().equals(parent.getName()); this.urlPrefix = parent.getFileSystem().getRootURI(); if (fileObjects != null) { for (FileObjectWrapper fileObject : fileObjects) { if (fileObject == null) continue; try { if (FileType.FILE.getName().equals(fileObject.getType())) { files.add(fileObject); totalSize += fileObject.getSize(); } else if (FileType.FOLDER.getName().equals(fileObject.getType())) { folders.add(fileObject); } } catch (Exception ex) { ex.printStackTrace(System.err); } } } }
From source file:org.kalypso.commons.io.VFSUtilities.java
/** * This function closes the file object. It does not throw any exceptions. It calls {@link FileObject#close()} of the * given file objects.//from w w w . ja v a 2s.c o m * * @param files * The file objects which should be closed. May be null or already closed. */ public static void closeQuietly(final FileObject... files) { for (final FileObject file : files) { try { if (Objects.isNotNull(file)) { /* Close the file object. */ file.close(); /* Close the connection of the file system (e.g. a FTP connection). */ final FileSystem fileSystem = file.getFileSystem(); if (fileSystem instanceof AbstractFileSystem) ((AbstractFileSystem) fileSystem).closeCommunicationLink(); } } catch (final FileSystemException ignore) { /* If a file system exception is thrown, it was probably already closed. */ } catch (final Exception ex) { /* On other exceptions, do tell the developer on the console. */ ex.printStackTrace(); } } }
From source file:org.metaborg.intellij.idea.projects.ArtifactProjectService.java
/** * Gets the root file of the specified layer. * * @param layer The layer; or <code>null</code>. * @return The root file; or <code>null</code>. *//*from w w w .j a v a 2 s . c om*/ @Nullable private FileObject getRoot(@Nullable final FileObject layer) { if (layer == null) return null; try { return layer.getFileSystem().getRoot(); } catch (final FileSystemException e) { this.logger.error("Ignored exception.", e); return null; } }
From source file:org.metaborg.intellij.idea.projects.ArtifactProjectService.java
/** * Gets the parent root of the specified file. * * @param file The file./* ww w. ja va 2 s . com*/ * @return The parent root; or <code>null</code>. */ @Nullable private FileObject getParentRoot(final FileObject file) { try { return getRoot(file.getFileSystem().getParentLayer()); } catch (final FileSystemException e) { this.logger.error("Ignored exception.", e); return null; } }
From source file:org.mycore.backend.filesystem.MCRCStoreVFS.java
@Override public File getLocalFile(String storageId) throws IOException { FileObject fileObject = fsManager.resolveFile(getBase(), storageId); return fileObject.getFileSystem().replicateFile(fileObject, Selectors.SELECT_SELF); }