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

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

Introduction

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

Prototype

FileObject getParent() throws FileSystemException;

Source Link

Document

Returns the folder that contains this file.

Usage

From source file:org.obiba.opal.web.FilesResourceTest.java

@Test
public void testCreateFolder_FolderCreatedSuccessfully() throws FileSystemException, URISyntaxException {
    expect(fileObjectMock.getType()).andReturn(FileType.FOLDER).atLeastOnce();
    expect(fileObjectMock.exists()).andReturn(true).atLeastOnce();

    FileObject childFolderMock = createMock(FileObject.class);

    FileName fileNameMock = createMock(FileName.class);
    expect(fileNameMock.getBaseName()).andReturn("folder").atLeastOnce();
    expect(fileNameMock.getPath()).andReturn("folder1/folder").atLeastOnce();

    expect(childFolderMock.getName()).andReturn(fileNameMock).atLeastOnce();
    expect(childFolderMock.exists()).andReturn(false).atLeastOnce();

    FileContent mockContent = createMock(FileContent.class);
    expect(childFolderMock.getContent()).andReturn(mockContent).atLeastOnce();
    expect(mockContent.getLastModifiedTime()).andReturn((long) 1).atLeastOnce();

    childFolderMock.createFolder();/*from  w  w w  . j a va2s.c o m*/
    FileObject parentFolderMock = createMock(FileObject.class);
    expect(childFolderMock.getParent()).andReturn(parentFolderMock).atLeastOnce();
    expect(childFolderMock.isReadable()).andReturn(true).atLeastOnce();
    expect(childFolderMock.isWriteable()).andReturn(true).atLeastOnce();
    expect(parentFolderMock.isWriteable()).andReturn(true).atLeastOnce();
    expect(fileObjectMock.resolveFile("folder")).andReturn(childFolderMock).atLeastOnce();
    expect(uriInfoMock.getBaseUriBuilder()).andReturn(UriBuilder.fromPath("/"));

    replay(fileObjectMock, uriInfoMock, parentFolderMock, childFolderMock, fileNameMock, mockContent);

    Response response = getFileResource().createFolder("folder1", "folder", uriInfoMock);
    assertThat(response.getStatus()).isEqualTo(Status.CREATED.getStatusCode());
    verify(fileObjectMock, uriInfoMock, parentFolderMock, childFolderMock, fileNameMock, mockContent);
}

From source file:org.ow2.proactive.scheduler.smartproxy.JobTrackerImpl.java

/**
 * Removes from the proxy knowledge all info related with the given job.
 * This will also delete every folder created by the job in the shared input and output spaces
 *
 * @param id jobID//from   w w w . j  a  va2 s  .c  om
 */
public void removeAwaitedJob(String id) {
    AwaitedJob aj = jobDatabase.getAwaitedJob(id);

    if (aj == null) {
        logger.warn("Job " + id + " not in the awaited list");
        return;
    }
    logger.debug("Removing knowledge of job " + id);

    String pullUrl = aj.getPullURL();
    String pushUrl = aj.getPushURL();

    FileObject remotePullFolder = null;
    FileObject remotePushFolder = null;

    try {
        remotePullFolder = resolveFile(pullUrl);
        remotePushFolder = resolveFile(pushUrl);
    } catch (Exception e) {
        logger.error("Could not remove data for job " + id, e);
        return;
    }
    if (aj.isIsolateTaskOutputs()) {
        try {
            remotePullFolder = remotePullFolder.getParent();
        } catch (FileSystemException e) {
            logger.error("Could not get the parent of folder " + remotePullFolder, e);
        }
    }

    Set<FileObject> foldersToDelete = new HashSet<>();
    try {
        foldersToDelete.add(remotePullFolder.getParent());
        if (!remotePullFolder.getParent().equals(remotePushFolder.getParent()))
            foldersToDelete.add(remotePushFolder.getParent());
    } catch (FileSystemException e) {
        logger.warn("Data in folders " + pullUrl + " and " + pushUrl
                + " cannot be deleted due to an unexpected error ", e);
    }

    String url = "NOT YET DEFINED";
    for (FileObject fo : foldersToDelete) {
        try {
            url = fo.getURL().toString();

            if (!logger.isTraceEnabled()) {
                logger.debug("Deleting directory " + url);
                fo.delete(Selectors.SELECT_ALL);
                fo.delete();
            }
        } catch (FileSystemException e) {
            logger.warn("Could not delete temporary files at location " + url + " .", e);
        }
    }

    jobDatabase.removeAwaitedJob(id);

    try {
        jobDatabase.commit();
    } catch (IOException e) {
        logger.error("Could not save status file after removing job " + id, e);
    }
}

From source file:org.pentaho.big.data.kettle.plugins.kafka.KafkaConsumerInputDialog.java

private void selectFileTrans() {
    String curFile = transMeta.environmentSubstitute(wTransPath.getText());

    FileObject root = null;

    String parentFolder = null;//from  w  w w. ja  va 2s . c o  m
    try {
        parentFolder = KettleVFS.getFileObject(transMeta.environmentSubstitute(transMeta.getFilename()))
                .getParent().toString();
    } catch (Exception e) {
        // Take no action
    }

    try {
        root = KettleVFS.getFileObject(curFile != null ? curFile : Const.getUserHomeDirectory());

        VfsFileChooserDialog vfsFileChooser = Spoon.getInstance().getVfsFileChooserDialog(root.getParent(),
                root);
        FileObject file = vfsFileChooser.open(shell, null, Const.STRING_TRANS_FILTER_EXT,
                Const.getTransformationFilterNames(), VfsFileChooserDialog.VFS_DIALOG_OPEN_FILE);
        if (file == null) {
            return;
        }
        String fileName = file.getName().toString();
        if (fileName != null) {
            loadFileTrans(fileName);
            if (parentFolder != null && fileName.startsWith(parentFolder)) {
                fileName = fileName.replace(parentFolder,
                        "${" + Const.INTERNAL_VARIABLE_ENTRY_CURRENT_DIRECTORY + "}");
            }
            wTransPath.setText(fileName);
            specificationMethod = ObjectLocationSpecificationMethod.FILENAME;
        }
    } catch (IOException | KettleException e) {
        new ErrorDialog(shell,
                BaseMessages.getString(PKG, "TransExecutorDialog.ErrorLoadingTransformation.DialogTitle"),
                BaseMessages.getString(PKG, "TransExecutorDialog.ErrorLoadingTransformation.DialogMessage"), e);
    }
}

From source file:org.pentaho.di.plugins.fileopensave.providers.vfs.VFSFileProvider.java

/**
 * @param file//  w  ww  . j  a  v  a 2s .c  o  m
 * @param newPath
 * @param overwrite
 * @return
 */
private VFSFile doMove(VFSFile file, String newPath, Boolean overwrite) {
    try {
        FileObject fileObject = KettleVFS.getFileObject(file.getPath(), new Variables(),
                VFSHelper.getOpts(file.getPath(), file.getConnection()));
        FileObject renameObject = KettleVFS.getFileObject(newPath, new Variables(),
                VFSHelper.getOpts(file.getPath(), file.getConnection()));
        if (overwrite) {
            if (renameObject.exists()) {
                renameObject.delete();
            }
        }
        fileObject.moveTo(renameObject);
        if (file instanceof VFSDirectory) {
            return VFSDirectory.create(renameObject.getParent().getPublicURIString(), renameObject,
                    file.getConnection());
        } else {
            return VFSFile.create(renameObject.getParent().getPublicURIString(), renameObject,
                    file.getConnection());
        }
    } catch (KettleFileException | FileSystemException e) {
        return null;
    }
}

From source file:org.pentaho.di.plugins.fileopensave.providers.vfs.VFSFileProvider.java

/**
 * @param file//  ww w .ja va  2  s .  c o m
 * @param toPath
 * @param overwrite
 * @return
 * @throws FileException
 */
@Override
public VFSFile copy(VFSFile file, String toPath, boolean overwrite) throws FileException {
    try {
        FileObject fileObject = KettleVFS.getFileObject(file.getPath(), new Variables(),
                VFSHelper.getOpts(file.getPath(), file.getConnection()));
        FileObject copyObject = KettleVFS.getFileObject(toPath, new Variables(),
                VFSHelper.getOpts(file.getPath(), file.getConnection()));
        copyObject.copyFrom(fileObject, Selectors.SELECT_SELF);
        if (file instanceof VFSDirectory) {
            return VFSDirectory.create(copyObject.getParent().getPublicURIString(), fileObject,
                    file.getConnection());
        } else {
            return VFSFile.create(copyObject.getParent().getPublicURIString(), fileObject,
                    file.getConnection());
        }
    } catch (KettleFileException | FileSystemException e) {
        throw new FileException();
    }
}

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 ww  w  .  j a va2  s  .c om*/
 *
 * @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.sdk.samples.steps.mymapping.MyMappingDialog.java

private void selectFileTrans() {
    String curFile = wFilename.getText();
    FileObject root;

    try {//from   w w w  .  j  a  va 2s. c  om
        root = KettleVFS.getFileObject(curFile != null ? curFile : Const.getUserHomeDirectory());

        VfsFileChooserDialog vfsFileChooser = Spoon.getInstance().getVfsFileChooserDialog(root.getParent(),
                root);
        FileObject file = vfsFileChooser.open(shell, null, Const.STRING_TRANS_FILTER_EXT,
                Const.getTransformationFilterNames(), VfsFileChooserDialog.VFS_DIALOG_OPEN_FILE);
        if (file == null) {
            return;
        }
        String fname;

        fname = file.getURL().getFile();

        if (fname != null) {

            loadFileTrans(fname);
            wFilename.setText(mappingTransMeta.getFilename());
            wTransname.setText(Const.NVL(mappingTransMeta.getName(), ""));
            wDirectory.setText("");
            setSpecificationMethod(ObjectLocationSpecificationMethod.FILENAME);
            setRadioButtons();
        }
    } catch (IOException e) {
        new ErrorDialog(shell,
                BaseMessages.getString(PKG, "MappingDialog.ErrorLoadingTransformation.DialogTitle"),
                BaseMessages.getString(PKG, "MappingDialog.ErrorLoadingTransformation.DialogMessage"), e);
    } catch (KettleException e) {
        new ErrorDialog(shell,
                BaseMessages.getString(PKG, "MappingDialog.ErrorLoadingTransformation.DialogTitle"),
                BaseMessages.getString(PKG, "MappingDialog.ErrorLoadingTransformation.DialogMessage"), e);
    }
}

From source file:org.pentaho.di.trans.steps.file.BaseFileInputStep.java

/**
 * Prepare file-dependent data for fill additional fields.
 *///from ww  w.  j av  a2 s.  c o  m
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.metainject.RepositoryExporterExtension.java

private String calcRepositoryDirectory(KettleFileRepository fileRep, FileObject fileObject)
        throws FileSystemException {
    String path = fileObject.getParent().getName().getPath();
    String baseDirectory = fileRep.getRepositoryMeta().getBaseDirectory();
    // Double check!
    ///*  w w  w . ja  va2  s. c  om*/
    if (path.startsWith(baseDirectory)) {
        return path.substring(baseDirectory.length());
    } else {
        return path;
    }
}

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

private Optional<String> promptForFile() {
    String curFile = abstractMeta.environmentSubstitute(wFileName.getText());
    FileObject root;

    try {/*from ww w. ja v a  2 s  .co m*/
        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();
}