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

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

Introduction

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

Prototype

FileName getName();

Source Link

Document

Returns the name of this file.

Usage

From source file:org.pentaho.di.resource.NameResourceIT.java

/**
 * This tests ResourceNamingInterface.nameResouce(), comparing the directory maps generated by the legacy and new
 * method.//from   www . java2  s. co  m
 *
 * @param fileName
 * @param pathOnly
 *          Resolve the path - leave out the file name
 * @throws Exception
 *
 *           Legacy: namingResource(String, String, String, FileNamingType) New: namingResource(FileObject, TransMeta)
 */
private void testNamingResourceLegacyAndNew(String fileName, String extension, String fileMask)
        throws Exception {

    // Create a new transformation.
    TransMeta transMeta = new TransMeta();

    FileObject fileObject = KettleVFS.getFileObject(fileName, transMeta);

    // This code is modeled after the legacy code in legacy step meta classes
    // that have an exportResources method that deal with file masks
    // e.g., ExcelInputMeta
    //
    // There is a big exception: where the legacy code does a "getName()"
    // this code does a "getURL()". This is because of the JIRA case
    // that resulted in the refactoring of ResourceNamingInterface.
    //
    // The UNC and VFS protocols where being dropped.
    // The code you see here would be the fix for that without adding
    // the new nameResource() to ResourceNamingInterface.
    //

    String path = null;
    String prefix = null;
    if (Utils.isEmpty(fileMask)) {
        prefix = fileObject.getName().getBaseName();
        path = fileObject.getParent().getURL().toString();
    } else {
        prefix = "";
        path = fileObject.getURL().toString();
    }

    // Create a resource naming interface to use the legacy method call
    ResourceNamingInterface resourceNamingInterface_LEGACY = new SequenceResourceNaming();

    // Create two resource naming interfaces, one for legacy call, the other for new method call
    ResourceNamingInterface resourceNamingInterface_NEW = new SequenceResourceNaming();

    // The old and new interfaces to get the file name.
    String resolvedFileName_LEGACY = resourceNamingInterface_LEGACY.nameResource(prefix, path, extension,
            FileNamingType.DATA_FILE);
    String resolvedFileName_NEW = resourceNamingInterface_NEW.nameResource(fileObject, transMeta,
            Utils.isEmpty(fileMask));

    // get the variable name from both naming interfaces directory maps
    String pathFromMap_LEGACY = resourceNamingInterface_LEGACY.getDirectoryMap().get(path);
    String pathFromMap_NEW = resourceNamingInterface_NEW.getDirectoryMap().get(path);

    // The paths in both directories should be the same
    assertEquals(pathFromMap_LEGACY, pathFromMap_NEW);

    // The file names should be the same
    assertEquals(resolvedFileName_LEGACY, resolvedFileName_NEW);
}

From source file:org.pentaho.di.resource.ResourceDefinitionHelper.java

public static boolean containsResource(Repository repository, Map<String, ResourceDefinition> definitions,
        VariableSpace space, ResourceNamingInterface namingInterface, AbstractMeta meta)
        throws KettleException {
    if (definitions == null || space == null || namingInterface == null || meta == null) {
        return false;
    }/*from  www .  j a  va2s  . c  o  m*/

    String extension = meta instanceof TransMeta ? Const.STRING_TRANS_DEFAULT_EXT
            : Const.STRING_JOB_DEFAULT_EXT;
    String fullname;
    try {
        RepositoryDirectoryInterface directory = meta.getRepositoryDirectory();
        if (Utils.isEmpty(meta.getFilename())) {
            // Assume repository...
            //
            fullname = directory.getPath()
                    + (directory.getPath().endsWith(RepositoryDirectory.DIRECTORY_SEPARATOR) ? ""
                            : RepositoryDirectory.DIRECTORY_SEPARATOR)
                    + meta.getName() + "." + extension; //
        } else {
            // Assume file
            //
            FileObject fileObject = KettleVFS.getFileObject(space.environmentSubstitute(meta.getFilename()),
                    space);
            fullname = fileObject.getName().getPath();
        }
    } catch (KettleFileException e) {
        throw new KettleException(
                BaseMessages.getString(PKG, "JobMeta.Exception.AnErrorOccuredReadingJob", meta.getFilename()),
                e);
    }

    // if (repository != null) {
    //    repository.getLog().logError("=====> Checking [" + fullname + "] in " + definitions + " result=" + definitions.containsKey(fullname));
    // }
    return definitions.containsKey(fullname) || meta.equals(space);
}

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);/* w  w w. java  2s  . co m*/
        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.jav a2  s .  c  om
 *
 * @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;/*from  w w  w  .  java2  s . c  o  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.file.BaseFileInputStep.java

/**
 * Prepare file-dependent data for fill additional fields.
 *///ww w .  j a  va 2 s.com
protected void fillFileAdditionalFields(D data, FileObject file) throws FileSystemException {
    data.shortFilename = file.getName().getBaseName();
    data.path = KettleVFS.getFilename(file.getParent());
    data.hidden = file.isHidden();
    data.extension = file.getName().getExtension();
    data.uriName = file.getName().getURI();
    data.rootUriName = file.getName().getRootURI();
    if (file.getType().hasContent()) {
        data.lastModificationDateTime = new Date(file.getContent().getLastModifiedTime());
        data.size = file.getContent().getSize();
    } else {
        data.lastModificationDateTime = null;
        data.size = null;
    }
}

From source file:org.pentaho.di.trans.steps.propertyinput.PropertyInputMetaTest.java

@Test
public void testOpenNextFile() throws Exception {

    PropertyInputMeta propertyInputMeta = Mockito.mock(PropertyInputMeta.class);
    PropertyInputData propertyInputData = new PropertyInputData();
    FileInputList fileInputList = new FileInputList();
    FileObject fileObject = Mockito.mock(FileObject.class);
    FileName fileName = Mockito.mock(FileName.class);
    Mockito.when(fileName.getRootURI()).thenReturn("testFolder");
    Mockito.when(fileName.getURI()).thenReturn("testFileName.ini");

    String header = "test ini data with umlauts";
    String key = "key";
    String testValue = "value-with-";
    String testData = "[" + header + "]\r\n" + key + "=" + testValue;
    String charsetEncode = "Windows-1252";

    InputStream inputStream = new ByteArrayInputStream(testData.getBytes(Charset.forName(charsetEncode)));
    FileContent fileContent = Mockito.mock(FileContent.class);
    Mockito.when(fileObject.getContent()).thenReturn(fileContent);
    Mockito.when(fileContent.getInputStream()).thenReturn(inputStream);
    Mockito.when(fileObject.getName()).thenReturn(fileName);
    fileInputList.addFile(fileObject);/*from   ww  w  .j  a v a2  s. co m*/

    propertyInputData.files = fileInputList;
    propertyInputData.propfiles = false;
    propertyInputData.realEncoding = charsetEncode;

    PropertyInput propertyInput = Mockito.mock(PropertyInput.class);

    Field logField = BaseStep.class.getDeclaredField("log");
    logField.setAccessible(true);
    logField.set(propertyInput, Mockito.mock(LogChannelInterface.class));

    Mockito.doCallRealMethod().when(propertyInput).dispose(propertyInputMeta, propertyInputData);

    propertyInput.dispose(propertyInputMeta, propertyInputData);

    Method method = PropertyInput.class.getDeclaredMethod("openNextFile");
    method.setAccessible(true);
    method.invoke(propertyInput);

    Assert.assertEquals(testValue, propertyInputData.wini.get(header).get(key));
}

From source file:org.pentaho.di.trans.steps.textfileoutput.TextFileOutputSplittingIT.java

private static void assertSplitFileIsCorrect(FileObject file, String expectedName, String... expectedLines)
        throws Exception {
    List<String> content = readContentOf(file);
    assertEquals(expectedName, file.getName().getBaseName());
    assertEquals(expectedLines.length, content.size());
    for (int i = 0; i < content.size(); i++) {
        assertEquals(expectedLines[i], content.get(i));
    }/*from w ww  .  jav a 2  s. c om*/
}

From source file:org.pentaho.di.trans.steps.xbaseinput.BaseXBaseParsingTest.java

/**
 * Initialize for processing specified file.
 *//*from  ww w. ja v a 2  s.  c  o m*/
protected void init(String file) throws Exception {
    FileObject fo = getFile(file);
    meta.setDbfFileName(fo.getName().getPath());

    step = new XBaseInput(stepMeta, null, 1, transMeta, trans);
    step.init(meta, data);
    step.addRowListener(rowListener);
}

From source file:org.pentaho.di.ui.core.widget.VFSFileSelection.java

private Optional<String> promptForFile() {
    String curFile = abstractMeta.environmentSubstitute(wFileName.getText());
    FileObject root;/*from   ww  w  .j  a  v a 2 s.  c om*/

    try {
        root = KettleVFS.getFileObject(curFile != null ? curFile : Const.getUserHomeDirectory());
        VfsFileChooserDialog vfsFileChooser = Spoon.getInstance().getVfsFileChooserDialog(root.getParent(),
                root);
        if (StringUtil.isEmpty(initialScheme)) {
            initialScheme = "file";
        }
        FileObject file = vfsFileChooser.open(getShell(), null, initialScheme, true, curFile, fileFilters,
                fileFilterNames, false, fileDialogMode, showLocation, true);
        if (file == null) {
            return Optional.empty();
        }

        String filePath = getRelativePath(file.getName().toString());
        return Optional.ofNullable(filePath);
    } catch (IOException | KettleException e) {
        new ErrorDialog(getShell(),
                BaseMessages.getString(PKG, "VFSFileSelection.ErrorLoadingFile.DialogTitle"),
                BaseMessages.getString(PKG, "VFSFileSelection.ErrorLoadingFile.DialogMessage"), e);
    }
    return Optional.empty();
}