Example usage for org.apache.commons.vfs2 FileObject exists

List of usage examples for org.apache.commons.vfs2 FileObject exists

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileObject exists.

Prototype

boolean exists() throws FileSystemException;

Source Link

Document

Determines if this file exists.

Usage

From source file:org.apache.hadoop.gateway.topology.file.FileTopologyProviderTest.java

private FileObject createFile(FileObject parent, String name, String resource, long timestamp)
        throws IOException {
    FileObject file = parent.resolveFile(name);
    if (!file.exists()) {
        file.createFile();/*from   w  w w  . ja  v  a2 s.  com*/
    }
    InputStream input = ClassLoader.getSystemResourceAsStream(resource);
    OutputStream output = file.getContent().getOutputStream();
    IOUtils.copy(input, output);
    output.flush();
    input.close();
    output.close();
    file.getContent().setLastModifiedTime(timestamp);
    assertTrue("Failed to create test file " + file.getName().getFriendlyURI(), file.exists());
    assertTrue("Failed to populate test file " + file.getName().getFriendlyURI(),
            file.getContent().getSize() > 0);

    //    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    //    IOUtils.copy( file.getContent().getInputStream(), buffer );
    //    System.out.println( new String( buffer.toString( "UTF-8" ) ) );

    return file;
}

From source file:org.apache.metron.common.dsl.functions.resolver.ClasspathFunctionResolver.java

@Override
public void initialize(Context context) {
    super.initialize(context);
    if (context != null) {

        Optional<Object> optional = context.getCapability(STELLAR_CONFIG, false);
        if (optional.isPresent()) {
            Map<String, Object> stellarConfig = (Map<String, Object>) optional.get();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting up classloader using the following config: " + stellarConfig);
            }//  www  .ja  v a 2s.c  o  m

            include(STELLAR_SEARCH_INCLUDES_KEY.get(stellarConfig, String.class).split(STELLAR_SEARCH_DELIMS));
            exclude(STELLAR_SEARCH_EXCLUDES_KEY.get(stellarConfig, String.class).split(STELLAR_SEARCH_DELIMS));
            Optional<ClassLoader> vfsLoader = null;
            try {
                vfsLoader = VFSClassloaderUtil
                        .configureClassloader(STELLAR_VFS_PATHS.get(stellarConfig, String.class));
                if (vfsLoader.isPresent()) {
                    LOG.debug("CLASSLOADER LOADED WITH: " + STELLAR_VFS_PATHS.get(stellarConfig, String.class));
                    if (LOG.isDebugEnabled()) {
                        for (FileObject fo : ((VFSClassLoader) vfsLoader.get()).getFileObjects()) {
                            LOG.error(fo.getURL() + " - " + fo.exists());
                        }
                    }
                    classLoaders(vfsLoader.get());
                }
            } catch (FileSystemException e) {
                LOG.error("Unable to process filesystem: " + e.getMessage(), e);
            }
        } else {
            LOG.info("No stellar config set; I'm reverting to the context classpath with no restrictions.");
            if (LOG.isDebugEnabled()) {
                try {
                    throw new IllegalStateException("No config set, stacktrace follows.");
                } catch (IllegalStateException ise) {
                    LOG.error(ise.getMessage(), ise);
                }
            }
        }
    } else {
        throw new IllegalStateException("CONTEXT IS NULL!");
    }
}

From source file:org.apache.metron.stellar.dsl.functions.resolver.ClasspathFunctionResolver.java

@Override
public void initialize(Context context) {
    super.initialize(context);
    if (context != null) {

        Optional<Object> optional = context.getCapability(STELLAR_CONFIG, false);
        if (optional.isPresent()) {
            Map<String, Object> stellarConfig = (Map<String, Object>) optional.get();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting up classloader using the following config: {}", stellarConfig);
            }/*from   www .  j a  v a  2s  . co  m*/

            include(STELLAR_SEARCH_INCLUDES_KEY.get(stellarConfig, String.class).split(STELLAR_SEARCH_DELIMS));
            exclude(STELLAR_SEARCH_EXCLUDES_KEY.get(stellarConfig, String.class).split(STELLAR_SEARCH_DELIMS));
            Optional<ClassLoader> vfsLoader = Optional.empty();
            try {
                vfsLoader = VFSClassloaderUtil
                        .configureClassloader(STELLAR_VFS_PATHS.get(stellarConfig, String.class));
                if (vfsLoader.isPresent()) {
                    LOG.debug("CLASSLOADER LOADED WITH: {}",
                            STELLAR_VFS_PATHS.get(stellarConfig, String.class));
                    if (LOG.isDebugEnabled()) {
                        for (FileObject fo : ((VFSClassLoader) vfsLoader.get()).getFileObjects()) {
                            LOG.error("{} - {}", fo.getURL(), fo.exists());
                        }
                    }
                    classLoaders(vfsLoader.get());
                }
            } catch (FileSystemException e) {
                LOG.error("Unable to process filesystem: {}", e.getMessage(), e);
            }
        } else {
            LOG.info("No stellar config set; I'm reverting to the context classpath with no restrictions.");
            if (LOG.isDebugEnabled()) {
                try {
                    throw new IllegalStateException("No config set, stacktrace follows.");
                } catch (IllegalStateException ise) {
                    LOG.error(ise.getMessage(), ise);
                }
            }
        }
    } else {
        throw new IllegalStateException("CONTEXT IS NULL!");
    }
}

From source file:org.apache.olingo.fit.utils.FSManager.java

public final FileObject putInMemory(final InputStream is, final String path) throws IOException {
    LOG.info("Write in memory {}", path);
    final FileObject memObject = fsManager.resolveFile(MEM_PREFIX + path);

    if (memObject.exists()) {
        memObject.delete();/*from   w w  w. j  a v  a2s . c o m*/
    }

    // create in-memory file
    memObject.createFile();

    // read in-memory content
    final OutputStream os = memObject.getContent().getOutputStream();
    IOUtils.copy(is, os);
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(os);

    return memObject;
}

From source file:org.apache.olingo.fit.utils.FSManager.java

private InputStream readFile(final String relativePath, final Accept accept, final String fs) {
    final String path = getAbsolutePath(relativePath, accept);
    LOG.info("Read {}{}", fs, path);

    try {//from  www  .java2 s.  c  om
        final FileObject fileObject = fsManager.resolveFile(fs + path);

        if (fileObject.exists()) {
            // return new in-memory content
            return fileObject.getContent().getInputStream();
        } else {
            LOG.warn("In-memory path '{}' not found", path);
            throw new NotFoundException();
        }
    } catch (FileSystemException e) {
        throw new NotFoundException();
    }
}

From source file:org.apache.olingo.fit.utils.FSManager.java

public void deleteFile(final String relativePath) {
    for (Accept accept : Accept.values()) {
        final String path = getAbsolutePath(relativePath, accept);
        LOG.info("Delete {}", path);

        try {/*from ww  w .  ja  v  a  2  s. c  o  m*/
            final FileObject fileObject = fsManager.resolveFile(MEM_PREFIX + path);

            if (fileObject.exists()) {
                fileObject.delete();
            }
        } catch (IOException ignore) {
            // ignore exception
        }
    }
}

From source file:org.apache.olingo.fit.utils.FSManager.java

public void deleteEntity(final String relativePath) {
    final String path = getAbsolutePath(relativePath, null);
    LOG.info("Delete {}", path);

    try {//w  w w  . j a v a  2 s  . c om
        final FileObject fileObject = fsManager.resolveFile(MEM_PREFIX + path);

        if (fileObject.exists()) {
            fileObject.delete(new FileSelector() {
                @Override
                public boolean includeFile(final FileSelectInfo fileInfo) throws Exception {
                    return true;
                }

                @Override
                public boolean traverseDescendents(final FileSelectInfo fileInfo) throws Exception {
                    return true;
                }
            });
        }
    } catch (IOException ignore) {
        // ignore exception
    }
}

From source file:org.apache.olingo.fit.utils.FSManager.java

public FileObject resolve(final String path) throws FileSystemException {
    final FileObject res = fsManager.resolveFile(MEM_PREFIX + path);

    if (!res.exists()) {
        throw new FileSystemException("Unresolved path " + path);
    }//  w w w .  j a v a  2  s . co m

    return res;
}

From source file:org.apache.synapse.commons.vfs.VFSUtils.java

/**
 * Acquires a file item lock before processing the item, guaranteing that
 * the file is not processed while it is being uploaded and/or the item is
 * not processed by two listeners/*ww w . j av a  2 s .  co  m*/
 * 
 * @param fsManager
 *            used to resolve the processing file
 * @param fo
 *            representing the processing file item
 * @param fso
 *            represents file system options used when resolving file from file system manager.
 * @return boolean true if the lock has been acquired or false if not
 */
public synchronized static boolean acquireLock(FileSystemManager fsManager, FileObject fo, VFSParamDTO paramDTO,
        FileSystemOptions fso) {

    // generate a random lock value to ensure that there are no two parties
    // processing the same file
    Random random = new Random();
    // Lock format random:hostname:hostip:time
    String strLockValue = String.valueOf(random.nextLong());
    try {
        strLockValue += STR_SPLITER + InetAddress.getLocalHost().getHostName();
        strLockValue += STR_SPLITER + InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException ue) {
        if (log.isDebugEnabled()) {
            log.debug("Unable to get the Hostname or IP.");
        }
    }
    strLockValue += STR_SPLITER + (new Date()).getTime();
    byte[] lockValue = strLockValue.getBytes();

    try {
        // check whether there is an existing lock for this item, if so it is assumed
        // to be processed by an another listener (downloading) or a sender (uploading)
        // lock file is derived by attaching the ".lock" second extension to the file name
        String fullPath = fo.getName().getURI();
        int pos = fullPath.indexOf("?");
        if (pos != -1) {
            fullPath = fullPath.substring(0, pos);
        }
        FileObject lockObject = fsManager.resolveFile(fullPath + ".lock", fso);
        if (lockObject.exists()) {
            log.debug("There seems to be an external lock, aborting the processing of the file "
                    + maskURLPassword(fo.getName().getURI())
                    + ". This could possibly be due to some other party already "
                    + "processing this file or the file is still being uploaded");
            if (paramDTO != null && paramDTO.isAutoLockRelease()) {
                releaseLock(lockValue, strLockValue, lockObject, paramDTO.isAutoLockReleaseSameNode(),
                        paramDTO.getAutoLockReleaseInterval());
            }
        } else {
            // write a lock file before starting of the processing, to ensure that the
            // item is not processed by any other parties
            lockObject.createFile();
            OutputStream stream = lockObject.getContent().getOutputStream();
            try {
                stream.write(lockValue);
                stream.flush();
                stream.close();
            } catch (IOException e) {
                lockObject.delete();
                log.error(
                        "Couldn't create the lock file before processing the file " + maskURLPassword(fullPath),
                        e);
                return false;
            } finally {
                lockObject.close();
            }

            // check whether the lock is in place and is it me who holds the lock. This is
            // required because it is possible to write the lock file simultaneously by
            // two processing parties. It checks whether the lock file content is the same
            // as the written random lock value.
            // NOTE: this may not be optimal but is sub optimal
            FileObject verifyingLockObject = fsManager.resolveFile(fullPath + ".lock", fso);
            if (verifyingLockObject.exists() && verifyLock(lockValue, verifyingLockObject)) {
                return true;
            }
        }
    } catch (FileSystemException fse) {
        log.error("Cannot get the lock for the file : " + maskURLPassword(fo.getName().getURI())
                + " before processing");
    }
    return false;
}

From source file:org.apache.synapse.commons.vfs.VFSUtils.java

/**
 * Release a file item lock acquired either by the VFS listener or a sender
 *
 * @param fsManager which is used to resolve the processed file
 * @param fo representing the processed file
 * @param fso represents file system options used when resolving file from file system manager.
 */// www .j  a  v  a 2  s.c om
public static void releaseLock(FileSystemManager fsManager, FileObject fo, FileSystemOptions fso) {
    String fullPath = fo.getName().getURI();

    try {
        int pos = fullPath.indexOf("?");
        if (pos > -1) {
            fullPath = fullPath.substring(0, pos);
        }
        FileObject lockObject = fsManager.resolveFile(fullPath + ".lock", fso);
        if (lockObject.exists()) {
            lockObject.delete();
        }
    } catch (FileSystemException e) {
        log.error("Couldn't release the lock for the file : " + maskURLPassword(fo.getName().getURI())
                + " after processing");
    }
}