Java Code Examples for org.apache.commons.vfs2.FileSystemException

The following are top voted examples for showing how to use org.apache.commons.vfs2.FileSystemException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: yajsw   File: StandardFileSystemManager.java   Source Code and License 6 votes vote down vote up
/**
 * Scans the classpath to find any droped plugin.<br />
 * The plugin-description has to be in /META-INF/vfs-providers.xml
 * 
 * @throws FileSystemException
 *             if an error occurs.
 */
protected void configurePlugins() throws FileSystemException
{
	ClassLoader cl = findClassLoader();

	Enumeration<URL> enumResources;
	try
	{
		enumResources = cl.getResources(PLUGIN_CONFIG_RESOURCE);
	}
	catch (IOException e)
	{
		throw new FileSystemException(e);
	}

	while (enumResources.hasMoreElements())
	{
		URL url = enumResources.nextElement();
		configure(url);
	}
}
 
Example 2
Project: yajsw   File: StandardFileSystemManager.java   Source Code and License 6 votes vote down vote up
/**
 * Configures this manager from an XML configuration file.
 * 
 * @param configUri
 *            The URI of the configuration.
 * @param configStream
 *            An InputStream containing the configuration.
 * @throws FileSystemException
 *             if an error occurs.
 */
@SuppressWarnings("unused")
private void configure(final String configUri,
		final InputStream configStream) throws FileSystemException
{
	try
	{
		// Load up the config
		// TODO - validate
		final DocumentBuilder builder = createDocumentBuilder();
		final Element config = builder.parse(configStream)
				.getDocumentElement();

		configure(config);

	}
	catch (final Exception e)
	{
		throw new FileSystemException("vfs.impl/load-config.error",
				configUri, e);
	}
}
 
Example 3
Project: yajsw   File: StandardFileSystemManager.java   Source Code and License 6 votes vote down vote up
/**
 * Adds a operationProvider from a operationProvider definition.
 */
private void addOperationProvider(final Element providerDef)
		throws FileSystemException
{
	final String classname = providerDef.getAttribute("class-name");

	// Attach only to available schemas
	final String[] schemas = getSchemas(providerDef);
	for (int i = 0; i < schemas.length; i++)
	{
		final String schema = schemas[i];
		if (hasProvider(schema))
		{
			final FileOperationProvider operationProvider = (FileOperationProvider) createInstance(classname);
			addOperationProvider(schema, operationProvider);
		}
	}
}
 
Example 4
Project: yajsw   File: ScriptCounter.java   Source Code and License 6 votes vote down vote up
private void checkScript()
{
	long lastModified;
	try
	{
		lastModified = VFSUtils.resolveFile(".", _scriptFile).getContent()
				.getLastModifiedTime();
	}
	catch (FileSystemException e)
	{
		throw new IllegalArgumentException("Cannot find script "
				+ _scriptFile + " ex=" + e.getMessage());
	}
	if (_lastModified == lastModified)
		return;
	else
	{
		_lastModified = lastModified;
		_script = ScriptFactory.createScript(_scriptFile, _counterString,
				null, _args, _log, 0, null, false, 0, 1);
		if (_script == null)
			throw new IllegalArgumentException("Cannot find script "
					+ _scriptFile);
	}
}
 
Example 5
Project: yajsw   File: AbstractWrappedProcess.java   Source Code and License 6 votes vote down vote up
public Configuration getConfiguration()
{
	if (_config == null)
	{
		Map utils = new HashMap();
		utils.put("util", new Utils(this));
		try
		{
			VFSUtils.init();
		}
		catch (FileSystemException e)
		{
			e.printStackTrace();
		}

		_config = new YajswConfigurationImpl(_localConfiguration,
				_useSystemProperties, utils);
	}
	return _config;
}
 
Example 6
Project: yajsw   File: YajswConfigurationImpl.java   Source Code and License 6 votes vote down vote up
private boolean fileExists(String file)
{
	try
	{
		// this hack is no longer required, changed VFS to init without
		// providers.xm.
		// String current =
		// System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
		// System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
		// "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
		DefaultFileSystemManager fsManager = (DefaultFileSystemManager) VFS
				.getManager();
		// if (current != null)
		// System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
		// current);
		// else
		// System.clearProperty("javax.xml.parsers.DocumentBuilderFactory");
		FileObject f = VFSUtils.resolveFile(".", file);
		return f.exists();
	}
	catch (FileSystemException e)
	{
		e.printStackTrace();
		return false;
	}
}
 
Example 7
Project: mycore   File: MCRStore.java   Source Code and License 6 votes vote down vote up
/**
 * Recursively searches for the highest ID, which is the greatest slot file
 * name currently used in the store.
 * 
 * @param dir
 *            the directory to search
 * @param depth
 *            the subdirectory depth level of the dir
 * @return the highest slot file name / ID currently stored
 */
private String findMaxID(final FileObject dir, final int depth) throws FileSystemException {
    final FileObject[] children = dir.getChildren();

    if (children.length == 0) {
        return null;
    }

    Arrays.sort(children, new MCRFileObjectComparator());

    if (depth == slotLength.length) {
        return children[children.length - 1].getName().getBaseName();
    }

    for (int i = children.length - 1; i >= 0; i--) {
        final FileObject child = children[i];
        if (!child.getType().hasChildren()) {
            continue;
        }
        final String found = findMaxID(child, depth + 1);
        if (found != null) {
            return found;
        }
    }
    return null;
}
 
Example 8
Project: Rapture   File: WatchFTPRunner.java   Source Code and License 6 votes vote down vote up
public WatchFTPRunner(FTPConfig config) {
    this.config = config;
    try { 
        fsManager = VFS.getManager();
       
        UserAuthenticator auth = new StaticUserAuthenticator("", config.getConnection().getUsername(), config.getConnection().getPassword()); 
        DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth); 
        FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts,true);
        FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
       
        resolvedAbsPath = fsManager.resolveFile(config.getFolder() + config.getConnection().getPathtomonitor() , opts);
        
        log.info("Connection successfully established to " +  resolvedAbsPath.getPublicURIString());        
        log.debug("Exists: " + resolvedAbsPath.exists());
        log.debug("Type  : " + resolvedAbsPath.getType());       
    } catch (FileSystemException e) {
        log.error("File system exception for " + config.getFolder(), e);
        //throw here?
    }
}
 
Example 9
Project: cloudturbine   File: FilePumpWorker.java   Source Code and License 6 votes vote down vote up
protected FileSystemOptions createDefaultFileSystemOptions() throws FileSystemException {
	
    FileSystemOptions opts = new FileSystemOptions();
    
    // SSH Key checking
    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
    
    // VFS file system root:
    // setting this parameter false = cause VFS to choose File System's Root as VFS's root
    // setting this parameter true = cause VFS to choose user's home directory as VFS's root
    SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
    
    // Timeout is count by Milliseconds
    SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 20000);
    
    return opts;
}
 
Example 10
Project: common-vfs2-nfs   File: NfsFileName.java   Source Code and License 6 votes vote down vote up
/**
 * Construct the path suitable for NfsFile when used with NtlmPasswordAuthentication.
 *
 * @return caches and return URI with no username/password, never null
 * @throws FileSystemException if any of the invoked methods throw
 */
public String getUriWithoutAuth() throws FileSystemException
{
    if (uriWithoutAuth != null)
    {
        return uriWithoutAuth;
    }

    final StringBuilder sb = new StringBuilder(120);
    sb.append(getScheme());
    sb.append("://");
    sb.append(getHostName());
    if (getPort() != DEFAULT_PORT)
    {
        sb.append(":");
        sb.append(getPort());
    }
    sb.append(getPathDecoded());
    uriWithoutAuth = sb.toString();
    return uriWithoutAuth;
}
 
Example 11
Project: common-vfs2-nfs   File: NfsFileObject.java   Source Code and License 6 votes vote down vote up
/**
 * Determines the type of the file, returns null if the file does not
 * exist.
 */
@Override
protected FileType doGetType() throws Exception
{
    if (!file.exists())
    {
        return FileType.IMAGINARY;
    }
    else if (file.isDirectory())
    {
        return FileType.FOLDER;
    }
    else if (file.isFile())
    {
        return FileType.FILE;
    }

    throw new FileSystemException("vfs.provider.Nfs/get-type.error", getName());
}
 
Example 12
Project: motu   File: GridFTPClientWrapper.java   Source Code and License 6 votes vote down vote up
/**
 * Creates the client.
 * 
 * @return the grid ftp client
 * 
 * @throws FileSystemException the file system exception
 */
protected GridFTPClient createClient() throws FileSystemException {
    final GenericFileName rootName = getRoot();

    UserAuthenticationData authData = null;
    try {
        authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, GsiFtpFileProvider.AUTHENTICATOR_TYPES);

        String username = UserAuthenticatorUtils
                .getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())).toString();
        String password = UserAuthenticatorUtils
                .getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())).toString();
        return GsiFtpClientFactory.createConnection(rootName.getHostName(), rootName.getPort(), username, password, getFileSystemOptions());
    } finally {
        UserAuthenticatorUtils.cleanup(authData);
    }
}
 
Example 13
Project: motu   File: GsiFtpFileObject.java   Source Code and License 6 votes vote down vote up
/**
 * Determines the type of the file, returns null if the file does not exist.
 * 
 * @return the file type
 * 
 * @throws Exception the exception
 */
@Override
protected FileType doGetType() throws Exception {
    // log.debug("relative path:" + relPath);

    if (this.fileInfo == null) {
        return FileType.IMAGINARY;
    } else if (this.fileInfo.isDirectory()) {
        return FileType.FOLDER;
    } else if (this.fileInfo.isFile()) {
        return FileType.FILE;
    } else if (this.fileInfo.isSoftLink()) {
        return FileType.FILE; // getLinkDestination().getType();
    }

    throw new FileSystemException("vfs.provider.gsiftp/get-type.error", getName());
}
 
Example 14
Project: motu   File: GsiFtpFileObject.java   Source Code and License 6 votes vote down vote up
/**
 * Renames the file.
 * 
 * @param newfile the newfile
 * 
 * @throws Exception the exception
 */
@Override
protected void doRename(FileObject newfile) throws Exception {
    boolean ok = true;
    final GridFTPClient ftpClient = ftpFs.getClient();
    try {
        String oldName = getName().getPath();
        String newName = newfile.getName().getPath();
        ftpClient.rename(oldName, newName);
    } catch (IOException ioe) {
        ok = false;
    } catch (ServerException e) {
        ok = false;
    } finally {
        ftpFs.putClient(ftpClient);
    }

    if (!ok) {
        throw new FileSystemException("vfs.provider.gsiftp/rename-file.error", new Object[] { getName().toString(), newfile });
    }
    this.fileInfo = null;
    children = EMPTY_FTP_FILE_MAP;
}
 
Example 15
Project: motu   File: GsiFtpFileObject.java   Source Code and License 6 votes vote down vote up
/**
 * Creates this file as a folder.
 * 
 * @throws Exception the exception
 */
@Override
protected void doCreateFolder() throws Exception {
    boolean ok = true;
    final GridFTPClient client = ftpFs.getClient();
    try {
        client.makeDir(getName().getPath());
    } catch (IOException ioe) {
        ok = false;
    } catch (ServerException se) {
        ok = false;
    } finally {
        ftpFs.putClient(client);
    }

    if (!ok) {
        throw new FileSystemException("vfs.provider.gsiftp/create-folder.error", getName());
    }
}
 
Example 16
Project: motu   File: GsiFtpFileSystem.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an FTP client to use.
 * 
 * @return the client
 * 
 * @throws FileSystemException the file system exception
 */
public GridFTPClient getClient() throws FileSystemException {
    synchronized (idleClientSync) {
        if (idleClient == null) {
            final GenericFileName rootName = (GenericFileName) getRoot().getName();

            LOG.debug("Creating connection to GSIFTP Host: " + rootName.getHostName() + " Port:" + rootName.getPort() + " User:"
                    + rootName.getUserName() + " Path: " + rootName.getPath());

            return GsiFtpClientFactory.createConnection(rootName.getHostName(),
                                                        rootName.getPort(),
                                                        rootName.getUserName(),
                                                        rootName.getPassword(),
                                                        // rootName.getPath(),
                                                        getFileSystemOptions());
        } else {
            final GridFTPClient client = idleClient;
            idleClient = null;
            return client;
        }
    }
}
 
Example 17
Project: motu   File: VFSManager.java   Source Code and License 6 votes vote down vote up
/**
 * Delete all descendents of this file that match a selector.
 * 
 * @param file the file
 * @param selector the selector
 * 
 * @return true, if successful
 * @throws MotuException
 */
public boolean delete(FileObject file, FileSelector selector) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("delete(FileObject, FileSelector) - entering");
    }

    int deleted = 0;
    try {
        if (file.exists()) {
            deleted = file.delete(selector);
        }
    } catch (FileSystemException e) {
        LOG.error("delete(FileObject, FileSelector)", e);

        // throw new MotuException(String.format("Unable to copy file '%s' to '%s'",
        // foSrc.getURL().toString(), foDest.getURL().toString()), e);
        throw new MotuException(ErrorType.NETCDF_LOADING, String.format("Unable to delete '%s'", file.getName().toString()), e);
    }
    boolean returnboolean = (deleted > 0);
    if (LOG.isDebugEnabled()) {
        LOG.debug("delete(FileObject, FileSelector) - exiting");
    }
    return returnboolean;
}
 
Example 18
Project: motu   File: VFSManager.java   Source Code and License 6 votes vote down vote up
/**
 * Refresh ftp cache.
 * 
 * @param fileObject the file object
 * @throws FileSystemException
 */
public void refreshFtpCache(FileObject fileObject) throws FileSystemException {

    if (fileObject == null) {
        return;
    }

    if (!(fileObject.getFileSystem() instanceof FtpFileSystem)) {
        return;
    }
    if (fileObject.exists()) {
        return;
    }
    FileObject fileObjectParent = fileObject.getParent();
    if (fileObjectParent == null) {
        return;
    }

    fileObjectParent.getType(); // force to attach : needed for force refresh
    fileObjectParent.refresh();

}
 
Example 19
Project: vfs-azure   File: SimpleShell.java   Source Code and License 6 votes vote down vote up
/**
 * Lists the children of a folder.
 */
public void listChildren(final FileObject dir,
                          final boolean recursive,
                          final String prefix)
    throws FileSystemException
{
    final FileObject[] children = dir.getChildren();
    for (int i = 0; i < children.length; i++)
    {
        final FileObject child = children[i];
        System.out.print(prefix);
        System.out.print(child.getName().getBaseName());
        if (child.getType() == FileType.FOLDER)
        {
            System.out.println("/");
            if (recursive)
            {
                listChildren(child, recursive, prefix + "    ");
            }
        }
        else
        {
            System.out.println();
        }
    }
}
 
Example 20
Project: vfs-azure   File: AzTestUtils.java   Source Code and License 6 votes vote down vote up
public static void uploadFile(String accntName, String accntHost, String accntKey, String containerName,
                                   Path localFile, Path remotePath) throws FileSystemException
{
    DefaultFileSystemManager currMan = new DefaultFileSystemManager();
    currMan.addProvider(AzConstants.AZSBSCHEME, new AzFileProvider());
    currMan.addProvider("file", new DefaultLocalFileProvider());
    currMan.init(); 
    
    StaticUserAuthenticator auth = new StaticUserAuthenticator("", accntName, accntKey);
    FileSystemOptions opts = new FileSystemOptions(); 
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth); 
    
    String currUriStr = String.format("%s://%s/%s/%s", 
                       AzConstants.AZSBSCHEME, accntHost, containerName, remotePath);
    FileObject currFile = currMan.resolveFile(currUriStr, opts);
    FileObject currFile2 = currMan.resolveFile(
            String.format("file://%s", localFile));
    
    currFile.copyFrom(currFile2, Selectors.SELECT_SELF);
    
    currFile.close();
    currMan.close();
}
 
Example 21
Project: vfs-azure   File: AzTestUtils.java   Source Code and License 6 votes vote down vote up
public static void deleteFile(String accntName, String accntHost, String accntKey, String containerName,
                                   Path remotePath) throws FileSystemException
{
    DefaultFileSystemManager currMan = new DefaultFileSystemManager();
    currMan.addProvider(AzConstants.AZSBSCHEME, new AzFileProvider());
    currMan.init(); 
    
    StaticUserAuthenticator auth = new StaticUserAuthenticator("", accntName, accntKey);
    FileSystemOptions opts = new FileSystemOptions(); 
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth); 
    
    String currUriStr = String.format("%s://%s/%s/%s", 
                       AzConstants.AZSBSCHEME, accntHost, containerName, remotePath);
    FileObject currFile = currMan.resolveFile(currUriStr, opts);
    
    Boolean delRes = currFile.delete();
    Assert.assertTrue(delRes);
}
 
Example 22
Project: Gobblin   File: SimpleJsonExtractor.java   Source Code and License 6 votes vote down vote up
public SimpleJsonExtractor(WorkUnitState workUnitState) throws FileSystemException {
  this.workUnitState = workUnitState;

  // Resolve the file to pull
  if (workUnitState.getPropAsBoolean(ConfigurationKeys.SOURCE_CONN_USE_AUTHENTICATION, false)) {
    // Add authentication credential if authentication is needed
    UserAuthenticator auth =
        new StaticUserAuthenticator(workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_DOMAIN, ""),
            workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USERNAME), PasswordManager.getInstance(workUnitState)
                .readPassword(workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_PASSWORD)));
    FileSystemOptions opts = new FileSystemOptions();
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
    this.fileObject = VFS.getManager().resolveFile(workUnitState.getProp(SOURCE_FILE_KEY), opts);
  } else {
    this.fileObject = VFS.getManager().resolveFile(workUnitState.getProp(SOURCE_FILE_KEY));
  }

  // Open the file for reading
  LOGGER.info("Opening file " + this.fileObject.getURL().toString());
  this.bufferedReader =
      this.closer.register(new BufferedReader(new InputStreamReader(this.fileObject.getContent().getInputStream(),
          ConfigurationKeys.DEFAULT_CHARSET_ENCODING)));
}
 
Example 23
Project: embulk-output-sftp   File: SftpUtils.java   Source Code and License 6 votes vote down vote up
private StandardFileSystemManager initializeStandardFileSystemManager()
{
    if (!logger.isDebugEnabled()) {
        // TODO: change logging format: org.apache.commons.logging.Log
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
    }
    StandardFileSystemManager manager = new StandardFileSystemManager();
    manager.setClassLoader(SftpUtils.class.getClassLoader());
    try {
        manager.init();
    }
    catch (FileSystemException e) {
        logger.error(e.getMessage());
        throw new ConfigException(e);
    }

    return manager;
}
 
Example 24
Project: blaze-storage   File: FtpStorageProvider.java   Source Code and License 6 votes vote down vote up
private FileObject createTempFile(String tempFolder) {
	int retries = CREATE_RETRIES;
	Exception retryException = null;
	while (retries-- != 0) {
		try {
			String externalKey = UUID.randomUUID().toString();
			FileObject tempFolderObject = tempFolder == null ? root : root.resolveFile(tempFolder);
			FileObject fileObject = tempFolderObject.resolveFile(externalKey);
			
			if (fileObject.exists()) {
				continue;
			}
			
			fileObject.createFile();
			return fileObject;
		} catch (FileSystemException ex) {
			retryException = ex;
		}
	}
	
	throw new StorageException("Could not create object. Tried " + CREATE_RETRIES + " times!", retryException);
}
 
Example 25
Project: scheduling   File: RestDataspaceImpl.java   Source Code and License 6 votes vote down vote up
private Response gzipComponentResponse(final String pathname, final FileObject fo) throws FileSystemException {
    return Response.ok(new StreamingOutput() {
        @Override
        public void write(OutputStream os) throws IOException, WebApplicationException {
            try {
                VFSZipper.GZIP.zip(fo, os);
            } catch (IOException ioe) {
                throw new WebApplicationException(ioe, Response.Status.INTERNAL_SERVER_ERROR);
            }
        }
    })
                   .header(HttpHeaders.CONTENT_TYPE, mediaType(fo))
                   .header(HttpHeaders.CONTENT_ENCODING, "gzip")
                   .header("x-pds-pathname", pathname)
                   .build();
}
 
Example 26
Project: scheduling   File: RestDataspaceImpl.java   Source Code and License 6 votes vote down vote up
private Response deleteDir(FileObject fo, List<String> includes, List<String> excludes) throws FileSystemException {
    if ((includes == null || includes.isEmpty()) && (excludes == null || excludes.isEmpty())) {
        fo.delete(SELECT_ALL);
        fo.delete();
        return noContentRes();
    } else {
        List<FileObject> children = FileSystem.findFiles(fo, includes, excludes);
        for (FileObject child : children) {
            if (!child.delete()) {
                child.delete(SELECT_ALL);
                child.delete();
            }
        }
        return noContentRes();
    }
}
 
Example 27
Project: hopsworks   File: ZeppelinResource.java   Source Code and License 6 votes vote down vote up
public void forceKillInterpreter(InterpreterSetting interpreter,
        Project project) {
  FileObject[] pidFiles;
  try {
    pidFiles = getPidFiles(project);
  } catch (URISyntaxException | FileSystemException ex) {
    logger.log(Level.SEVERE, "Could not read pid files ", ex);
    return;
  }
  boolean running = false;
  for (FileObject file : pidFiles) {
    if (file.getName().toString().contains("interpreter-" + interpreter.
            getName() + "-")) {
      running = isProccessAlive(readPid(file));
      if (running) {
        forceKillProccess(readPid(file));
        break;
      }
    }
  }
}
 
Example 28
Project: otroslogviewer   File: VfsBrowser.java   Source Code and License 6 votes vote down vote up
public void goToUrl(String url) {
  LOGGER.info("Going to URL: " + url);
  try {
    FileObject resolveFile = VFSUtils.resolveFileObject(url);
    String type = "?";
    if (resolveFile != null) {
      type = resolveFile.getType().toString();
    }
    LOGGER.info("URL: " + url + " is resolved " + type);
    goToUrl(resolveFile);
  } catch (FileSystemException e) {
    LOGGER.error("Can't go to URL " + url, e);
    final String message = ExceptionsUtils.getRootCause(e).getClass().getName() + ": " + ExceptionsUtils.getRootCause(e).getLocalizedMessage();

    Runnable runnable = new Runnable() {
      public void run() {
        JOptionPane.showMessageDialog(VfsBrowser.this, message,
            Messages.getMessage("browser.badlocation"),
            JOptionPane.ERROR_MESSAGE);
      }
    };
    SwingUtils.runInEdt(runnable);
  }
}
 
Example 29
Project: otroslogviewer   File: VFSUtils.java   Source Code and License 6 votes vote down vote up
public static boolean pointToItself(FileObject fileObject) throws FileSystemException {
  if (!fileObject.getURL().getProtocol().equalsIgnoreCase("file") && FileType.FILE.equals(fileObject.getType())) {
    LOGGER.debug("Checking if {} is pointing to itself", fileObject.getName().getFriendlyURI());
    FileObject[] children = VFSUtils.getChildren(fileObject);
    LOGGER.debug("Children number of {} is {}", fileObject.getName().getFriendlyURI(), children.length);
    if (children.length == 1) {
      FileObject child = children[0];
      if (child.getContent().getSize() != child.getContent().getSize()) {
        return false;
      }
      if (child.getName().getBaseName().equals(fileObject.getName().getBaseName())) {
        return true;
      }
    }
  }
  return false;
}
 
Example 30
Project: vfsjfilechooser2   File: VFSUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Tells whether a file exists
 * @param fileObject A file representation
 * @return whether a file exists
 */
public static boolean exists(FileObject fileObject)
{
    if (fileObject == null)
    {
        return false;
    }

    try
    {
        return fileObject.exists();
    }
    catch (FileSystemException ex)
    {
        return false;
    }
}
 
Example 31
Project: otroslogviewer   File: VFSUtils.java   Source Code and License 6 votes vote down vote up
private static FileObject extractHttpFileObject(String link, URL url) throws FileSystemException, URISyntaxException {
  FileObject child;
  LOGGER.info("Extracting {} from URL {}", link, url);
  if (link.startsWith("/")) {

    URI uri = url.toURI();

    String host = uri.getHost();
    int port = uri.getPort();
    if (port != -1) {
      child = resolveFileObject(String.format("%s://%s:%s%s", url.getProtocol(), host, port, link));
    } else {
      child = resolveFileObject(String.format("%s://%s%s", url.getProtocol(), host, link));
    }
  } else if (link.matches("(http|https|smb|ftp|sftp)://.*")) {
    child = resolveFileObject(link);
  } else {
    child = resolveFileObject(url + "/" + link);
  }
  return child;
}
 
Example 32
Project: otroslogviewer   File: VFSUtils.java   Source Code and License 6 votes vote down vote up
public static boolean canGoUrl(FileObject fileObject) {
  //http files
  try {
    if (!fileObject.getURL().getProtocol().startsWith("http") && VFSUtils.pointToItself(fileObject)) {
      return false;
    }
  } catch (FileSystemException e1) {
    LOGGER.error("Can't check if file is link", e1);
  }

  //Local files
  if (VFSUtils.isLocalFile(fileObject)) {
    return false;
  }
  return true;

}
 
Example 33
Project: spoofax-intellij   File: DefaultIntelliJResourceService.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public final VirtualFile unresolve(final FileObject resource) {
    if (resource instanceof IntelliJFileObject) {
        final IntelliJFileObject intellijResource = (IntelliJFileObject)resource;
        try {
            return intellijResource.asVirtualFile();
        } catch (final FileSystemException e) {
            throw LoggerUtils2.exception(this.logger, UnhandledException.class,
                    "Unexpected exception while resolving file: {}", e, resource);
        }
    }

    final URI uri = toUri(resource.getName().getURI());
    @Nullable final VirtualFileSystem fileSystem = getFileSystem(uri);
    @Nullable final String path = getPath(uri);
    if (fileSystem == null || path == null) {
        throw LoggerUtils2.exception(this.logger, IllegalStateException.class, "Can't unresolve this URI: {}", uri);
    }
    return fileSystem.refreshAndFindFileByPath(path);
}
 
Example 34
Project: spoofax-intellij   File: IntelliJFileObject.java   Source Code and License 6 votes vote down vote up
private void ensureExists()
        throws FileSystemException {
    if (this.file != null) return;

    try {
        new File(this.getName().getPath()).createNewFile();
    } catch (final IOException e) {
        throw new FileSystemException(e);
    }

    refresh();
    ensureAttached();

    if (this.file == null)
        throw new RuntimeException("No file attached.");
}
 
Example 35
Project: jbake-rtl-jalaali   File: BakeWatcher.java   Source Code and License 5 votes vote down vote up
/**
 * Starts watching the file system for changes to trigger a bake.
 *
 * @param res Commandline options
 * @param config Configuration settings
 */
public void start(final LaunchOptions res, CompositeConfiguration config) {
    try {
        FileSystemManager fsMan = VFS.getManager();
        FileObject listenPath = fsMan.resolveFile(res.getSource(), config.getString( ConfigUtil.Keys.CONTENT_FOLDER));

        System.out.println("Watching for changes in [" + res.getSource() + "]");
        DefaultFileMonitor monitor = new DefaultFileMonitor(new CustomFSChangeListener(res, config));
        monitor.setRecursive(true);
        monitor.addFile(listenPath);
        monitor.start();
    } catch (FileSystemException e) {
        e.printStackTrace();
    }
}
 
Example 36
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
public URI getURI() {
    try {
        // Doing some URL encoding here (e.g. replacing sharp, spaces)
        // TODO want a general way to handle the URL encoding; may need improvements from commons VFS ...
        return new URI(this.getName().getURI()
                .replace("#", "%23")
                .replace(" ", "%20")
                .replace("{", "%7B")
                .replace("}", "%7D")
        );
    } catch (URISyntaxException e) {
        throw new VFSFileSystemException(new FileSystemException(e));
    }
}
 
Example 37
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
public URL getURLDa() {
    try {
        return this.getURI().toURL();
    } catch (MalformedURLException e) {
        throw new VFSFileSystemException(new FileSystemException(e));
    }
}
 
Example 38
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public URL getURL() {
    try {
        return this.fileObject.getURL();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 39
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public boolean exists() {
    try {
        return this.fileObject.exists();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 40
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isHidden() {
    try {
        return this.fileObject.isHidden();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 41
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isReadable() {
    try {
        return this.fileObject.isReadable();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 42
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isWriteable() {
    try {
        return this.fileObject.isWriteable();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 43
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public FileType getType() {
    try {
        return this.fileObject.getType();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 44
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public FileObject getParent() {
    try {
        return FileObject.TO_DA_FILE_OBJECT.valueOf(this.fileObject.getParent());
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 45
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public FileObject[] getChildren() {
    try {
        return Lists.mutable.with(this.fileObject.getChildren()).collect(TO_DA_FILE_OBJECT).toArray(new FileObject[0]);
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 46
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public FileObject getChild(String name) {
    try {
        return FileObject.TO_DA_FILE_OBJECT.valueOf(this.fileObject.getChild(name));
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 47
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public FileObject resolveFile(String name, NameScope scope) {
    try {
        return FileObject.TO_DA_FILE_OBJECT.valueOf(this.fileObject.resolveFile(name, scope));
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 48
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public FileObject resolveFile(String path) {
    try {
        return FileObject.TO_DA_FILE_OBJECT.valueOf(this.fileObject.resolveFile(path));
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 49
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public FileObject[] findFiles(FileSelector selector) {
    try {
        return Lists.mutable.with(this.fileObject.findFiles(selector)).collect(TO_DA_FILE_OBJECT)
                .toArray(new FileObject[0]);
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 50
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public void findFiles(FileSelector selector, boolean depthwise, List<org.apache.commons.vfs2.FileObject> selected) {
    try {
        this.fileObject.findFiles(selector, depthwise, selected);
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 51
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public boolean delete() {
    try {
        return this.fileObject.delete();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 52
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public int delete(FileSelector selector) {
    try {
        return this.fileObject.delete(selector);
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 53
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public void createFolder() {
    try {
        this.fileObject.createFolder();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 54
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public void createFile() {
    try {
        this.fileObject.createFile();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 55
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public void copyFrom(org.apache.commons.vfs2.FileObject srcFile, FileSelector selector) {
    try {
        this.fileObject.copyFrom(srcFile, selector);
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 56
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public void moveTo(org.apache.commons.vfs2.FileObject destFile) {
    try {
        if (destFile instanceof FileObject) {
            destFile = ((FileObject)destFile).fileObject;
        }
        this.fileObject.moveTo(destFile);
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 57
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public FileContent getContent() {
    try {
        return this.fileObject.getContent();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 58
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public void close() {
    try {
        this.fileObject.close();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 59
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public void refresh() {
    try {
        this.fileObject.refresh();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 60
Project: obevo   File: FileObject.java   Source Code and License 5 votes vote down vote up
@Override
public FileOperations getFileOperations() {
    try {
        return this.fileObject.getFileOperations();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}