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.pentaho.di.trans.steps.enhanced.jsoninput.JsonInput.java

public boolean onNewFile(FileObject file) throws FileSystemException {
    if (file == null) {
        String errMsg = BaseMessages.getString(PKG, "JsonInput.Log.IsNotAFile", "null");
        logError(errMsg);/*from  w  w w. j  av a2  s . c om*/
        inputError(errMsg);
        return false;
    } else if (!file.exists()) {
        String errMsg = BaseMessages.getString(PKG, "JsonInput.Log.IsNotAFile",
                file.getName().getFriendlyURI());
        logError(errMsg);
        inputError(errMsg);
        return false;
    }
    if (hasAdditionalFileFields()) {
        fillFileAdditionalFields(data, file);
    }
    if (file.getContent().getSize() == 0) {
        // log only basic as a warning (was before logError)
        if (meta.isIgnoreEmptyFile()) {
            logBasic(BaseMessages.getString(PKG, "JsonInput.Error.FileSizeZero", "" + file.getName()));
        } else {
            logError(BaseMessages.getString(PKG, "JsonInput.Error.FileSizeZero", "" + file.getName()));
            incrementErrors();
            return false;
        }
    }
    return true;
}

From source file:org.pentaho.di.trans.steps.enhanced.jsoninput.JsonInputMeta.java

/**
 * Since the exported transformation that runs this will reside in a ZIP file, we can't reference files relatively. So
 * what this does is turn the name of files into absolute paths OR it simply includes the resource in the ZIP file.
 * For now, we'll simply turn it into an absolute path and pray that the file is on a shared drive or something like
 * that.//from  www.j a  va2 s  .co m
 *
 * @param space
 *          the variable space to use
 * @param definitions
 * @param resourceNamingInterface
 * @param repository
 *          The repository to optionally load other resources from (to be converted to XML)
 * @param metaStore
 *          the metaStore in which non-kettle metadata could reside.
 *
 * @return the filename of the exported resource
 */
public String exportResources(VariableSpace space, Map<String, ResourceDefinition> definitions,
        ResourceNamingInterface resourceNamingInterface, Repository repository, IMetaStore metaStore)
        throws KettleException {
    try {
        // The object that we're modifying here is a copy of the original!
        // So let's change the filename from relative to absolute by grabbing the file object...
        // In case the name of the file comes from previous steps, forget about this!
        //
        List<String> newFilenames = new ArrayList<String>();

        if (!isInFields()) {
            FileInputList fileList = getFiles(space);
            if (fileList.getFiles().size() > 0) {
                for (FileObject fileObject : fileList.getFiles()) {
                    // From : ${Internal.Transformation.Filename.Directory}/../foo/bar.xml
                    // To : /home/matt/test/files/foo/bar.xml
                    //
                    // If the file doesn't exist, forget about this effort too!
                    //
                    if (fileObject.exists()) {
                        // Convert to an absolute path and add it to the list.
                        //
                        newFilenames.add(fileObject.getName().getPath());
                    }
                }

                // Still here: set a new list of absolute filenames!
                //
                setFileName(newFilenames.toArray(new String[newFilenames.size()]));
                setFileMask(new String[newFilenames.size()]); // all null since converted to absolute path.
                setFileRequired(new String[newFilenames.size()]); // all null, turn to "Y" :
                Arrays.fill(getFileRequired(), YES);
            }
        }
        return null;
    } catch (Exception e) {
        throw new KettleException(e);
    }
}

From source file:org.pentaho.di.trans.steps.enhanced.jsonoutput.JsonOutput.java

private void createParentFolder(String filename) throws KettleStepException {
    if (!meta.isCreateParentFolder()) {
        return;// w  w  w. j a v  a2s.co m
    }
    // Check for parent folder
    FileObject parentfolder = null;
    try {
        // Get parent folder
        parentfolder = KettleVFS.getFileObject(filename, getTransMeta()).getParent();
        if (!parentfolder.exists()) {
            if (log.isDebug()) {
                logDebug(BaseMessages.getString(PKG, "JsonOutput.Error.ParentFolderNotExist",
                        parentfolder.getName()));
            }
            parentfolder.createFolder();
            if (log.isDebug()) {
                logDebug(BaseMessages.getString(PKG, "JsonOutput.Log.ParentFolderCreated"));
            }
        }
    } catch (Exception e) {
        throw new KettleStepException(BaseMessages.getString(PKG, "JsonOutput.Error.ErrorCreatingParentFolder",
                parentfolder.getName()));
    } finally {
        if (parentfolder != null) {
            try {
                parentfolder.close();
            } catch (Exception ex) { /* Ignore */
            }
        }
    }
}

From source file:org.pentaho.di.trans.steps.pentahoreporting.urlrepository.FileObjectContentLocation.java

/**
 * Creates a new location for the given parent and directory.
 *
 * @param parent  the parent location.//www  .  j a v a 2s  . c  o m
 * @param backend the backend.
 * @throws ContentIOException if an error occured or the file did not point to a directory.
 */
public FileObjectContentLocation(final ContentLocation parent, final FileObject backend)
        throws ContentIOException {
    super(parent, backend);
    boolean error;
    try {
        error = backend.exists() == false || backend.isFolder() == false;
    } catch (FileSystemException e) {
        throw new RuntimeException(e);
    }
    if (error) {
        throw new ContentIOException("The given backend-file is not a directory.");
    }
}

From source file:org.pentaho.di.trans.steps.pentahoreporting.urlrepository.FileObjectContentLocation.java

/**
 * Creates a new root-location for the given repository and directory.
 *
 * @param repository the repository for which a location should be created.
 * @param backend    the backend.//w  w w  . j a v a 2s.  c om
 * @throws ContentIOException if an error occured or the file did not point to a directory.
 */
public FileObjectContentLocation(final Repository repository, final FileObject backend)
        throws ContentIOException {
    super(repository, backend);
    boolean error;
    try {
        error = backend.exists() == false || backend.isFolder() == false;
    } catch (FileSystemException e) {
        throw new RuntimeException(e);
    }
    if (error) {
        throw new ContentIOException("The given backend-file is not a directory.");
    }
}

From source file:org.pentaho.di.trans.steps.pentahoreporting.urlrepository.FileObjectContentLocation.java

/**
 * Returns the content entity with the given name. If the entity does not exist, an Exception will be raised.
 *
 * @param name the name of the entity to be retrieved.
 * @return the content entity for this name, never null.
 * @throws ContentIOException if an repository error occured.
 *//*  ww  w . j a v a2  s. co m*/
public ContentEntity getEntry(final String name) throws ContentIOException {
    try {
        if (RepositoryUtilities.isInvalidPathName(name)) {
            throw new IllegalArgumentException("The name given is not valid.");
        }

        final FileObject file = getBackend();
        final FileObject child = file.resolveFile(name);
        if (child.exists() == false) {
            throw new ContentIOException("Not found:" + child);
        }

        if (child.isFolder()) {
            return new FileObjectContentLocation(this, child);
        } else if (child.isFile()) {
            return new FileObjectContentItem(this, child);
        } else {
            throw new ContentIOException("Not File nor directory.");
        }
    } catch (FileSystemException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.pentaho.di.trans.steps.pentahoreporting.urlrepository.FileObjectContentLocation.java

/**
 * Creates a new data item in the current location. This method must never return null. This method will fail if an
 * entity with the same name exists in this location.
 *
 * @param name the name of the new entity.
 * @return the newly created entity, never null.
 * @throws ContentCreationException if the item could not be created.
 */// w ww .  ja v  a  2  s  .c om
public ContentItem createItem(final String name) throws ContentCreationException {
    if (RepositoryUtilities.isInvalidPathName(name)) {
        throw new IllegalArgumentException("The name given is not valid.");
    }
    try {
        final FileObject file = getBackend();
        final FileObject child = file.resolveFile(name);
        if (child.exists()) {
            if (child.getContent().getSize() == 0) {
                // probably one of the temp files created by the pentaho-system
                return new FileObjectContentItem(this, child);
            }
            throw new ContentCreationException("File already exists: " + child);
        }
        try {
            child.createFile();
            return new FileObjectContentItem(this, child);
        } catch (IOException e) {
            throw new ContentCreationException("IOError while create", e);
        }
    } catch (FileSystemException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.pentaho.di.trans.steps.pentahoreporting.urlrepository.FileObjectContentLocation.java

/**
 * Creates a new content location in the current location. This method must never return null. This method will fail
 * if an entity with the same name exists in this location.
 *
 * @param name the name of the new entity.
 * @return the newly created entity, never null.
 * @throws ContentCreationException if the item could not be created.
 *//* w w w  .j a  v a2 s. c o m*/
public ContentLocation createLocation(final String name) throws ContentCreationException {
    if (RepositoryUtilities.isInvalidPathName(name)) {
        throw new IllegalArgumentException("The name given is not valid.");
    }
    try {
        final FileObject file = getBackend();
        final FileObject child = file.resolveFile(name);
        if (child.exists()) {
            throw new ContentCreationException("File already exists.");
        }
        child.createFile();
        try {
            return new FileObjectContentLocation(this, child);
        } catch (ContentIOException e) {
            throw new ContentCreationException("Failed to create the content-location", e);
        }
    } catch (FileSystemException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.pentaho.di.trans.steps.pentahoreporting.urlrepository.FileObjectContentLocation.java

/**
 * Checks, whether an content entity with the given name exists in this content location. This method will report
 * invalid filenames as non-existent./*from   ww  w . ja  v  a2s .  com*/
 *
 * @param name the name of the new entity.
 * @return true, if an entity exists with this name, false otherwise.
 */
public boolean exists(final String name) {
    if (RepositoryUtilities.isInvalidPathName(name)) {
        return false;
    }
    try {
        final FileObject file = getBackend();
        final FileObject child = file.resolveFile(name);
        return child.exists();
    } catch (FileSystemException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.pentaho.di.trans.steps.ssh.SSHData.java

public static Connection OpenConnection(String serveur, int port, String username, String password,
        boolean useKey, String keyFilename, String passPhrase, int timeOut, VariableSpace space,
        String proxyhost, int proxyport, String proxyusername, String proxypassword) throws KettleException {
    Connection conn = null;/*from   w  w  w .  jav  a  2s .c  o  m*/
    char[] content = null;
    boolean isAuthenticated = false;
    try {
        // perform some checks
        if (useKey) {
            if (Utils.isEmpty(keyFilename)) {
                throw new KettleException(
                        BaseMessages.getString(SSHMeta.PKG, "SSH.Error.PrivateKeyFileMissing"));
            }
            FileObject keyFileObject = KettleVFS.getFileObject(keyFilename);

            if (!keyFileObject.exists()) {
                throw new KettleException(
                        BaseMessages.getString(SSHMeta.PKG, "SSH.Error.PrivateKeyNotExist", keyFilename));
            }

            FileContent keyFileContent = keyFileObject.getContent();

            CharArrayWriter charArrayWriter = new CharArrayWriter((int) keyFileContent.getSize());

            try (InputStream in = keyFileContent.getInputStream()) {
                IOUtils.copy(in, charArrayWriter);
            }

            content = charArrayWriter.toCharArray();
        }
        // Create a new connection
        conn = createConnection(serveur, port);

        /* We want to connect through a HTTP proxy */
        if (!Utils.isEmpty(proxyhost)) {
            /* Now connect */
            // if the proxy requires basic authentication:
            if (!Utils.isEmpty(proxyusername)) {
                conn.setProxyData(new HTTPProxyData(proxyhost, proxyport, proxyusername, proxypassword));
            } else {
                conn.setProxyData(new HTTPProxyData(proxyhost, proxyport));
            }
        }

        // and connect
        if (timeOut == 0) {
            conn.connect();
        } else {
            conn.connect(null, 0, timeOut * 1000);
        }
        // authenticate
        if (useKey) {
            isAuthenticated = conn.authenticateWithPublicKey(username, content,
                    space.environmentSubstitute(passPhrase));
        } else {
            isAuthenticated = conn.authenticateWithPassword(username, password);
        }
        if (isAuthenticated == false) {
            throw new KettleException(
                    BaseMessages.getString(SSHMeta.PKG, "SSH.Error.AuthenticationFailed", username));
        }
    } catch (Exception e) {
        // Something wrong happened
        // do not forget to disconnect if connected
        if (conn != null) {
            conn.close();
        }
        throw new KettleException(
                BaseMessages.getString(SSHMeta.PKG, "SSH.Error.ErrorConnecting", serveur, username), e);
    }
    return conn;
}