List of usage examples for org.apache.commons.vfs2 FileObject getType
FileType getType() throws FileSystemException;
From source file:org.wso2.carbon.transport.remotefilesystem.client.connector.contractimpl.VFSClientConnectorImpl.java
@Override public void send(RemoteFileSystemMessage message) { FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true); String fileURI = connectorConfig.get(Constants.URI); String action = connectorConfig.get(Constants.ACTION); FileType fileType;/*from ww w. j a va2 s .co m*/ ByteBuffer byteBuffer; InputStream inputStream = null; OutputStream outputStream = null; FileObject path = null; try { FileSystemManager fsManager = VFS.getManager(); path = fsManager.resolveFile(fileURI, opts); fileType = path.getType(); switch (action) { case Constants.CREATE: boolean isFolder = Boolean .parseBoolean(connectorConfig.getOrDefault(Constants.CREATE_FOLDER, "false")); if (path.exists()) { throw new RemoteFileSystemConnectorException("File already exists: " + path.getName().getURI()); } if (isFolder) { path.createFolder(); } else { path.createFile(); } break; case Constants.WRITE: if (!path.exists()) { path.createFile(); path.refresh(); fileType = path.getType(); } if (fileType == FileType.FILE) { byteBuffer = message.getBytes(); byte[] bytes = byteBuffer.array(); if (connectorConfig.get(Constants.APPEND) != null) { outputStream = path.getContent() .getOutputStream(Boolean.parseBoolean(connectorConfig.get(Constants.APPEND))); } else { outputStream = path.getContent().getOutputStream(); } outputStream.write(bytes); outputStream.flush(); } break; case Constants.DELETE: if (path.exists()) { int filesDeleted = path.delete(Selectors.SELECT_ALL); if (logger.isDebugEnabled()) { logger.debug(filesDeleted + " files successfully deleted"); } } else { throw new RemoteFileSystemConnectorException( "Failed to delete file: " + path.getName().getURI() + " not found"); } break; case Constants.COPY: if (path.exists()) { String destination = connectorConfig.get(Constants.DESTINATION); FileObject dest = fsManager.resolveFile(destination, opts); dest.copyFrom(path, Selectors.SELECT_ALL); } else { throw new RemoteFileSystemConnectorException( "Failed to copy file: " + path.getName().getURI() + " not found"); } break; case Constants.MOVE: if (path.exists()) { //TODO: Improve this to fix issue #331 String destination = connectorConfig.get(Constants.DESTINATION); FileObject newPath = fsManager.resolveFile(destination, opts); FileObject parent = newPath.getParent(); if (parent != null && !parent.exists()) { parent.createFolder(); } if (!newPath.exists()) { path.moveTo(newPath); } else { throw new RemoteFileSystemConnectorException("The file at " + newPath.getURL().toString() + " already exists or it is a directory"); } } else { throw new RemoteFileSystemConnectorException( "Failed to move file: " + path.getName().getURI() + " not found"); } break; case Constants.READ: if (path.exists()) { //TODO: Do not assume 'path' always refers to a file inputStream = path.getContent().getInputStream(); byte[] bytes = toByteArray(inputStream); RemoteFileSystemMessage fileContent = new RemoteFileSystemMessage(ByteBuffer.wrap(bytes)); remoteFileSystemListener.onMessage(fileContent); } else { throw new RemoteFileSystemConnectorException( "Failed to read file: " + path.getName().getURI() + " not found"); } break; case Constants.EXISTS: RemoteFileSystemMessage fileContent = new RemoteFileSystemMessage(Boolean.toString(path.exists())); remoteFileSystemListener.onMessage(fileContent); break; default: break; } remoteFileSystemListener.done(); } catch (RemoteFileSystemConnectorException | IOException e) { remoteFileSystemListener.onError(e); } finally { if (path != null) { try { path.close(); } catch (FileSystemException e) { //Do nothing. } } closeQuietly(inputStream); closeQuietly(outputStream); } }
From source file:org.wso2.carbon.transport.remotefilesystem.server.RemoteFileSystemConsumer.java
/** * Determine whether file object is a file or a folder. * * @param fileObject File to get the type of * @return FileType of given file *///from ww w .ja v a 2s .co m private FileType getFileType(FileObject fileObject) throws RemoteFileSystemConnectorException { try { return fileObject.getType(); } catch (FileSystemException e) { remoteFileSystemListener.onError(new RemoteFileSystemConnectorException("[" + serviceName + "] Error occurred when determining whether file: " + FileTransportUtils.maskURLPassword(fileObject.getName().getURI()) + " is a file or a folder", e)); } return FileType.IMAGINARY; }
From source file:pl.otros.logview.api.io.Utils.java
public static LoadingInfo openFileObject(FileObject fileObject, boolean tailing) throws Exception { LoadingInfo loadingInfo = new LoadingInfo(); loadingInfo.setFileObject(fileObject); loadingInfo.setFriendlyUrl(fileObject.getName().getFriendlyURI()); final FileContent content = fileObject.getContent(); InputStream httpInputStream = content.getInputStream(); byte[] buff = Utils.loadProbe(httpInputStream, 10000); loadingInfo.setGziped(checkIfIsGzipped(buff, buff.length)); ByteArrayInputStream bin = new ByteArrayInputStream(buff); SequenceInputStream sequenceInputStream = new SequenceInputStream(bin, httpInputStream); ObservableInputStreamImpl observableInputStreamImpl = new ObservableInputStreamImpl(sequenceInputStream); if (loadingInfo.isGziped()) { loadingInfo.setContentInputStream(new GZIPInputStream(observableInputStreamImpl)); loadingInfo.setInputStreamBufferedStart(ungzip(buff)); } else {/*from w w w . j a va 2 s .c om*/ loadingInfo.setContentInputStream(observableInputStreamImpl); loadingInfo.setInputStreamBufferedStart(buff); } loadingInfo.setObserableInputStreamImpl(observableInputStreamImpl); loadingInfo.setTailing(tailing); if (fileObject.getType().hasContent()) { loadingInfo.setLastFileSize(content.getSize()); } return loadingInfo; }
From source file:pl.otros.vfs.browser.JOtrosVfsBrowserDialog.java
public static void main(String[] args) throws FileSystemException { if (args.length > 1) throw new IllegalArgumentException( "SYNTAX: java... " + JOtrosVfsBrowserDialog.class.getName() + " [initialPath]"); JOtrosVfsBrowserDialog jOtrosVfsBrowserDialog = new JOtrosVfsBrowserDialog( (args.length < 1) ? null : args[0]); jOtrosVfsBrowserDialog.setMultiSelectionEnabled(true); jOtrosVfsBrowserDialog.vfsBrowser.setSelectionMode(SelectionMode.DIRS_AND_FILES); ReturnValue rv = jOtrosVfsBrowserDialog.showOpenDialog(null, "title"); System.out.println(rv);// ww w . ja va2s. c o m FileObject[] selectedFiles = jOtrosVfsBrowserDialog.getSelectedFiles(); System.out.println("Selected files count " + selectedFiles.length); for (FileObject selectedFile : selectedFiles) { System.out.println(selectedFile.getType().toString() + ": " + selectedFile.getURL()); } System.exit(0); }
From source file:pl.otros.vfs.browser.preview.PreviewListener.java
@Override public void valueChanged(ListSelectionEvent listSelectionEvent) { if (listSelectionEvent.getValueIsAdjusting()) { return;// w w w. j a va 2 s. c o m } boolean previewEnabled = previewComponent.isPreviewEnabled(); if (!previewEnabled) { return; } FileObject fileObjectToPreview = null; for (FileObject fileObject : vfsBrowser.getSelectedFiles()) { try { if (fileObject.getType().equals(FileType.FILE)) { fileObjectToPreview = fileObject; break; } } catch (FileSystemException e) { LOGGER.error("Can't resolve file", e); } } if (fileObjectToPreview != null) { makePreview(fileObjectToPreview); } else { clearPreview(); } }
From source file:pl.otros.vfs.browser.table.FileObjectComparator.java
@Override public int compare(FileObject o1, FileObject o2) { if (o1 != null && o2 != null) { try {//from w ww .j a va2 s. co m return fileNameWithTypeComparator.compare(new FileNameWithType(o1.getName(), o1.getType()), new FileNameWithType(o2.getName(), o2.getType())); } catch (FileSystemException e) { return 0; } } return 0; }
From source file:pl.otros.vfs.browser.table.VfsTableModel.java
@Override public Object getValueAt(int rowIndex, int columnIndex) { FileObject fileObject = fileObjects[rowIndex]; boolean isFile = false; try {/*from w w w. j a v a 2 s .co m*/ isFile = FileType.FILE.equals(fileObject.getType()); } catch (FileSystemException e1) { LOGGER.warn("Can't check file type " + fileObject.getName().getBaseName(), e1); } if (columnIndex == COLUMN_NAME) { try { return new FileNameWithType(fileObject.getName(), fileObject.getType()); } catch (FileSystemException e) { return new FileNameWithType(fileObject.getName(), null); } } else if (columnIndex == COLUMN_TYPE) { try { return fileObject.getType().getName(); } catch (FileSystemException e) { LOGGER.warn("Can't get file type " + fileObject.getName().getBaseName(), e); return "?"; } } else if (columnIndex == COLUMN_SIZE) { try { long size = -1; if (isFile) { size = fileObject.getContent().getSize(); } return new FileSize(size); } catch (FileSystemException e) { LOGGER.warn("Can't get size " + fileObject.getName().getBaseName(), e); return new FileSize(-1); } } else if (columnIndex == COLUMN_LAST_MOD_DATE) { try { long lastModifiedTime = 0; if (!VFSUtils.isHttpProtocol(fileObject)) { lastModifiedTime = fileObject.getContent().getLastModifiedTime(); } return new Date(lastModifiedTime); } catch (FileSystemException e) { LOGGER.warn("Can't get last mod date " + fileObject.getName().getBaseName(), e); return null; } } return "?"; }
From source file:pl.otros.vfs.browser.util.VFSUtils.java
/** * Returns a file representation//from www .j av a2 s. c o m * * @param filePath The file path * @param options The filesystem options * @return a file representation * @throws FileSystemException */ public static FileObject resolveFileObject(String filePath, FileSystemOptions options, OtrosUserAuthenticator authenticator, AuthStore persistentAuthStore, AuthStore sessionAuthStore) throws FileSystemException { if (filePath.startsWith("sftp://")) { SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance(); builder.setStrictHostKeyChecking(opts, "no"); builder.setUserDirIsRoot(opts, false); builder.setCompression(opts, "zlib,none"); } DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(options, authenticator); FileObject resolveFile; VFSURIParser parser = new VFSURIParser(filePath); //Get file type to force authentication try { resolveFile = getFileSystemManager().resolveFile(filePath, options); resolveFile.getType(); } catch (FileSystemException e) { LOGGER.error("Error resolving file " + filePath, e); Throwable rootCause = Throwables.getRootCause(e); boolean authorizationFailed = false; authorizationFailed = checkForWrongCredentials(rootCause); if (authorizationFailed) { LOGGER.error("Wrong user name or password for " + filePath); //clear last data //authenticator can be null if user/password was entered in URL if (authenticator != null) { UserAuthenticationDataWrapper lastUserAuthenticationData = authenticator .getLastUserAuthenticationData(); lastUserAuthenticationData.remove(UserAuthenticationDataWrapper.PASSWORD); String user = new String(lastUserAuthenticationData.getData(UserAuthenticationData.USERNAME)); UserAuthenticationInfo auInfo = new UserAuthenticationInfo(parser.getProtocol().getName(), parser.getHostname(), user); sessionAuthStore.remove(auInfo); sessionAuthStore.add(auInfo, lastUserAuthenticationData); LOGGER.info("Removing password for {} on {}", new Object[] { new String(lastUserAuthenticationData.getData(UserAuthenticationData.USERNAME)), filePath }); } } throw e; } if (resolveFile != null && authenticator != null && authenticator.getLastUserAuthenticationData() != null) { UserAuthenticationDataWrapper lastUserAuthenticationData = authenticator .getLastUserAuthenticationData(); Map<Type, char[]> addedTypes = lastUserAuthenticationData.getAddedTypes(); String user = new String(addedTypes.get(UserAuthenticationData.USERNAME)); UserAuthenticationInfo auInfo = new UserAuthenticationInfo(parser.getProtocol().getName(), parser.getHostname(), user); sessionAuthStore.add(auInfo, lastUserAuthenticationData.copy()); if (authenticator.isPasswordSave()) { LOGGER.info("Saving password for {}://{}@{}", new Object[] { parser.getProtocol().getName(), user, parser.getHostname() }); persistentAuthStore.add(auInfo, lastUserAuthenticationData); saveAuthStore(); } } return resolveFile; }
From source file:pl.otros.vfs.browser.util.VFSUtils.java
/** * y/*from w w w. ja v a2 s. com*/ * * @param fileObject A file object representation * @return whether a file object is a directory */ public static boolean isDirectory(FileObject fileObject) { try { return fileObject.getType().equals(FileType.FOLDER); } catch (FileSystemException ex) { LOGGER.info("Exception when checking if fileobject is folder", ex); return false; } }
From source file:pl.otros.vfs.browser.util.VFSUtils.java
/** * Returns whether a file object is a local file * * @param fileObject//from ww w .ja va 2 s . com * @return true of {@link FileObject} is a local file */ public static boolean isLocalFile(FileObject fileObject) { try { return fileObject.getURL().getProtocol().equalsIgnoreCase("file") && FileType.FILE.equals(fileObject.getType()); } catch (FileSystemException e) { LOGGER.info("Exception when checking if fileobject is local file", e); return false; } }