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.pentaho.di.ui.trans.step.BaseStreamingDialog.java

protected Optional<String> selectFile(TextVar fileWidget, String[] fileFilters) {
    String curFile = transMeta.environmentSubstitute(fileWidget.getText());

    FileObject root = null;

    try {/*w ww .  ja va 2s  .  co  m*/
        root = KettleVFS.getFileObject(curFile != null ? curFile : Const.getUserHomeDirectory());

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

        String filePath = getRelativePath(file.getName().toString());
        fileWidget.setText(filePath);

        return Optional.ofNullable(filePath);
    } catch (IOException | KettleException e) {
        new ErrorDialog(shell,
                BaseMessages.getString(PKG, "TransExecutorDialog.ErrorLoadingTransformation.DialogTitle"),
                BaseMessages.getString(PKG, "TransExecutorDialog.ErrorLoadingTransformation.DialogMessage"), e);
    }
    return Optional.empty();
}

From source file:org.pentaho.hadoop.shim.common.DistributedCacheUtilImpl.java

/**
 * Extract a zip archive to a directory.
 *
 * @param archive Zip archive to extract
 * @param dest    Destination directory. This must not exist!
 * @return Directory the zip was extracted into
 * @throws IllegalArgumentException when the archive file does not exist or the destination directory already exists
 * @throws IOException/*from   w  w  w.j a  va2s.c  om*/
 * @throws KettleFileException
 */
public FileObject extract(FileObject archive, FileObject dest) throws IOException, KettleFileException {
    if (!archive.exists()) {
        throw new IllegalArgumentException("archive does not exist: " + archive.getURL().getPath());
    }

    if (dest.exists()) {
        throw new IllegalArgumentException("destination already exists");
    }
    dest.createFolder();

    try {
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int len = 0;
        ZipInputStream zis = new ZipInputStream(archive.getContent().getInputStream());
        try {
            ZipEntry ze;
            while ((ze = zis.getNextEntry()) != null) {
                FileObject entry = KettleVFS.getFileObject(dest + Const.FILE_SEPARATOR + ze.getName());
                FileObject parent = entry.getParent();
                if (parent != null) {
                    parent.createFolder();
                }
                if (ze.isDirectory()) {
                    entry.createFolder();
                    continue;
                }

                OutputStream os = KettleVFS.getOutputStream(entry, false);
                try {
                    while ((len = zis.read(buffer)) > 0) {
                        os.write(buffer, 0, len);
                    }
                } finally {
                    if (os != null) {
                        os.close();
                    }
                }
            }
        } finally {
            if (zis != null) {
                zis.close();
            }
        }
    } catch (Exception ex) {
        // Try to clean up the temp directory and all files
        if (!deleteDirectory(dest)) {
            throw new KettleFileException("Could not clean up temp dir after error extracting", ex);
        }
        throw new KettleFileException("error extracting archive", ex);
    }

    return dest;
}

From source file:org.pentaho.platform.repository.solution.filebased.FileObjectTestHelper.java

public static FileObject mockFile(final String contents, final boolean exists) throws FileSystemException {
    FileObject fileObject = mock(FileObject.class);
    when(fileObject.exists()).thenReturn(exists);
    FileContent fileContent = mock(FileContent.class);
    when(fileObject.getContent()).thenReturn(fileContent);
    when(fileContent.getInputStream()).thenReturn(IOUtils.toInputStream(contents));
    final FileObject parent = mock(FileObject.class);
    when(fileObject.getParent()).thenReturn(parent);
    final FileName fileName = mock(FileName.class);
    when(parent.getName()).thenReturn(fileName);
    when(fileName.getURI()).thenReturn("mondrian:/catalog");
    return fileObject;
}

From source file:org.pentaho.reporting.designer.extensions.pentaho.repository.dialogs.RepositoryOpenDialog.java

private ComboBoxModel createLocationModel(final FileObject selectedFolder) {
    if (fileSystemRoot == null) {
        return new DefaultComboBoxModel();
    }/*w  w  w .j a  v  a  2s.com*/

    try {
        final ArrayList<FileObject> list = new ArrayList<FileObject>();
        FileObject folder = selectedFolder;
        while (folder != null) {
            if (fileSystemRoot.equals(folder)) {
                break;
            }

            if (folder.getType() != FileType.FILE) {
                list.add(folder);
            }

            final FileObject parent = folder.getParent();
            if (folder.equals(parent)) {
                // protect yourself against infinite loops ..
                break;
            }
            folder = parent;
        }
        list.add(fileSystemRoot);
        final DefaultComboBoxModel model = new DefaultComboBoxModel(list.toArray());
        model.setSelectedItem(list.get(0));
        return model;
    } catch (FileSystemException e) {
        return new DefaultComboBoxModel();
    }
}

From source file:org.pentaho.reporting.designer.extensions.pentaho.repository.dialogs.RepositoryOpenDialog.java

public String performOpen(final AuthenticationData loginData, final String previousSelection)
        throws FileSystemException, UnsupportedEncodingException {
    fileSystemRoot = PublishUtil.createVFSConnection(VFS.getManager(), loginData);
    if (previousSelection == null) {
        setSelectedView(fileSystemRoot);
    } else {/*ww w.j  ava 2  s .c  om*/
        final FileObject view = fileSystemRoot.resolveFile(previousSelection);
        if (view == null) {
            setSelectedView(fileSystemRoot);
        } else {
            if (view.exists() == false) {
                setSelectedView(fileSystemRoot);
            } else if (view.getType() == FileType.FOLDER) {
                setSelectedView(view);
            } else {
                setSelectedView(view.getParent());
            }
        }
    }

    if (StringUtils.isEmpty(fileNameTextField.getText(), true) && previousSelection != null) {
        final String fileName = IOUtils.getInstance().getFileName(previousSelection);
        DebugLog.log("Setting filename to " + fileName);
        fileNameTextField.setText(fileName);
    }

    getConfirmAction().setEnabled(validateInputs(false));
    if (super.performEdit() == false || selectedView == null) {
        return null;
    }

    return getSelectedFile();
}

From source file:org.pentaho.reporting.designer.extensions.pentaho.repository.model.RepositoryTreeModel.java

public TreePath getTreePathForSelection(FileObject selectedFolder, final String selection)
        throws FileSystemException {
    if (root.getRoot() == null) {
        return null;
    }/*from   ww  w . j  a v  a 2  s .  co  m*/
    if (root.getRoot().equals(selectedFolder)) {
        return new TreePath(root);
    }

    final LinkedList<Object> list = new LinkedList<Object>();
    while (selectedFolder != null) {
        list.add(0, selectedFolder);
        final FileObject parent = selectedFolder.getParent();
        if (selectedFolder.equals(parent)) {
            break;
        }
        if (root.getRoot().equals(parent)) {
            break;
        }
        selectedFolder = parent;
    }
    list.add(0, root);
    return new TreePath(list.toArray());
}

From source file:org.pentaho.vfs.ui.VfsBrowser.java

public boolean renameItem(TreeItem ti, String newName) throws FileSystemException {
    FileObject file = (FileObject) ti.getData();
    FileObject newFileObject = file.getParent().resolveFile(newName);

    if (file.canRenameTo(newFileObject)) {
        if (!newFileObject.exists()) {
            newFileObject.createFile();//from  w w  w  .j  ava  2  s  .  c o m
        } else {
            return false;
        }
        file.moveTo(newFileObject);
        ti.setText(newName);
        ti.setData(newFileObject);
        return true;
    } else {
        return false;
    }

}

From source file:org.pentaho.vfs.ui.VfsBrowser.java

public boolean moveItem(TreeItem source, TreeItem destination) throws FileSystemException {
    FileObject file = (FileObject) source.getData();
    FileObject destFile = (FileObject) destination.getData();
    if (!file.exists() && !destFile.exists()) {
        return false;
    }/*w w w . jav a  2 s .  c  o  m*/
    try {
        if (destFile.getChildren() != null) {
            destFile = destFile.resolveFile(source.getText());
        }
    } catch (Exception e) {
        destFile = destFile.getParent().resolveFile(source.getText());
        destination = destination.getParentItem();
    }
    if (!file.getParent().equals(destFile.getParent())) {
        file.moveTo(destFile);
        TreeItem destTreeItem = new TreeItem(destination, SWT.NONE);
        destTreeItem.setImage(getFileImage(source.getDisplay()));
        destTreeItem.setData(destFile);
        destTreeItem.setData("isLoaded", Boolean.FALSE); //$NON-NLS-1$
        populateTreeItemText(destTreeItem, destFile);
        source.dispose();
    }
    return true;
}

From source file:org.pentaho.vfs.ui.VfsBrowser.java

public void selectTreeItemByFileObject(FileObject selectedFileObject, boolean expandSelection)
        throws FileSystemException {
    // note that this method WILL cause the tree to load files from VFS
    // go through selectedFileObject's parent elements until we hit the root
    if (selectedFileObject == null) {
        return;//from w w  w . j  ava2s .c  o  m
    }
    List selectedFileObjectParentList = new ArrayList();
    selectedFileObjectParentList.add(selectedFileObject);
    FileObject parent = selectedFileObject.getParent();
    while (parent != null && !parent.equals(rootFileObject)) {
        selectedFileObjectParentList.add(parent);
        parent = parent.getParent();
    }

    if (fileSystemTree.getSelection().length > 0) {
        TreeItem treeItem = fileSystemTree.getSelection()[0];
        treeItem.setExpanded(true);
        fileSystemTree.setSelection(treeItem);
        setSelectedFileObject(selectedFileObject);
        for (int i = selectedFileObjectParentList.size() - 1; i >= 0; i--) {
            FileObject obj = (FileObject) selectedFileObjectParentList.get(i);
            treeItem = findTreeItemByName(treeItem, obj.getName().getBaseName());
            if (treeItem != null && !treeItem.isDisposed()) {
                if (treeItem.getData() == null || treeItem.getData("isLoaded") == null //$NON-NLS-1$
                        || !((Boolean) treeItem.getData("isLoaded")).booleanValue()) { //$NON-NLS-1$
                    treeItem.removeAll();
                    populateFileSystemTree(obj, fileSystemTree, treeItem);
                }
            }
            if (treeItem != null && !treeItem.isDisposed()) {
                fileSystemTree.setSelection(treeItem);
                treeItem.setExpanded(expandSelection);
            }
        }
    }
}

From source file:org.pentaho.vfs.ui.VfsFileChooserDialog.java

public FileObject open(Shell applicationShell, String[] schemeRestrictions, String initialScheme,
        boolean showFileScheme, String fileName, String[] fileFilters, String[] fileFilterNames,
        boolean returnUserAuthenticatedFile, int fileDialogMode, boolean showLocation, boolean showCustomUI) {

    this.fileDialogMode = fileDialogMode;
    this.fileFilters = fileFilters;
    this.fileFilterNames = fileFilterNames;
    this.applicationShell = applicationShell;
    this.showFileScheme = showFileScheme;
    this.initialScheme = initialScheme;
    this.schemeRestrictions = schemeRestrictions;
    this.showLocation = showLocation;
    this.showCustomUI = showCustomUI;

    FileObject tmpInitialFile = initialFile;

    if (defaultInitialFile != null && rootFile == null) {
        try {/*  w ww  .ja va 2 s .  co m*/
            rootFile = defaultInitialFile.getFileSystem().getRoot();
            initialFile = defaultInitialFile;
        } catch (FileSystemException ignored) {
            // well we tried
        }
    }

    createDialog(applicationShell);

    if (!showLocation) {
        comboPanel.setParent(fakeShell);
    } else {
        comboPanel.setParent(customUIPanel);
    }

    if (!showCustomUI) {
        customUIPanel.setParent(fakeShell);
    } else {
        customUIPanel.setParent(dialog);
    }

    // create our file chooser tool bar, contains parent folder combo and various controls
    createToolbarPanel(dialog);
    // create our vfs browser component
    createVfsBrowser(dialog);
    populateCustomUIPanel(dialog);
    if (fileDialogMode == VFS_DIALOG_SAVEAS) {
        createFileNamePanel(dialog, fileName);
    } else {
        // create file filter panel
        createFileFilterPanel(dialog);
    }
    // create our ok/cancel buttons
    createButtonPanel(dialog);

    initialFile = tmpInitialFile;
    // set the initial file selection
    try {
        if (initialFile != null || rootFile != null) {
            vfsBrowser.selectTreeItemByFileObject(initialFile != null ? initialFile : rootFile, true);
            updateParentFileCombo(initialFile != null ? initialFile : rootFile);
            setSelectedFile(initialFile != null ? initialFile : rootFile);
            openFileCombo.setText(
                    initialFile != null ? initialFile.getName().getURI() : rootFile.getName().getURI());
        }
    } catch (FileSystemException e) {
        MessageBox box = new MessageBox(dialog.getShell());
        box.setText(Messages.getString("VfsFileChooserDialog.error")); //$NON-NLS-1$
        box.setMessage(e.getMessage());
        box.open();
    }

    // set the size and show the dialog
    int height = 550;
    int width = 800;
    dialog.setSize(width, height);
    Rectangle bounds = dialog.getDisplay().getPrimaryMonitor().getClientArea();
    int x = (bounds.width - width) / 2;
    int y = (bounds.height - height) / 2;
    dialog.setLocation(x, y);
    dialog.open();

    if (rootFile != null && fileDialogMode == VFS_DIALOG_SAVEAS) {
        if (!rootFile.getFileSystem().hasCapability(Capability.WRITE_CONTENT)) {
            MessageBox messageDialog = new MessageBox(dialog.getShell(), SWT.OK);
            messageDialog.setText(Messages.getString("VfsFileChooserDialog.warning")); //$NON-NLS-1$
            messageDialog.setMessage(Messages.getString("VfsFileChooserDialog.noWriteSupport")); //$NON-NLS-1$
            messageDialog.open();
        }
    }

    vfsBrowser.fileSystemTree.forceFocus();
    while (!dialog.isDisposed()) {
        if (!dialog.getDisplay().readAndDispatch())
            dialog.getDisplay().sleep();
    }

    // we just woke up, we are probably disposed already..
    if (!dialog.isDisposed()) {
        hideCustomPanelChildren();
        dialog.dispose();
    }
    if (okPressed) {
        FileObject returnFile = vfsBrowser.getSelectedFileObject();
        if (returnFile != null && fileDialogMode == VFS_DIALOG_SAVEAS) {
            try {
                if (returnFile.getType().equals(FileType.FILE)) {
                    returnFile = returnFile.getParent();
                }
                returnFile = returnFile.resolveFile(enteredFileName);
            } catch (FileSystemException e) {
                e.printStackTrace();
            }
        }

        // put user/pass on the filename so it comes out in the getUri call.
        if (!returnUserAuthenticatedFile) {
            // make sure to put the user/pass on the url if it's not there
            if (returnFile != null && returnFile.getName() instanceof URLFileName) {
                URLFileName urlFileName = (URLFileName) returnFile.getName();
                if (urlFileName.getUserName() == null || urlFileName.getPassword() == null) {
                    // set it
                    String user = "";
                    String pass = "";

                    UserAuthenticator userAuthenticator = DefaultFileSystemConfigBuilder.getInstance()
                            .getUserAuthenticator(returnFile.getFileSystem().getFileSystemOptions());

                    if (userAuthenticator != null) {
                        UserAuthenticationData data = userAuthenticator
                                .requestAuthentication(AUTHENTICATOR_TYPES);
                        user = String.valueOf(data.getData(UserAuthenticationData.USERNAME));
                        pass = String.valueOf(data.getData(UserAuthenticationData.PASSWORD));
                        try {
                            user = URLEncoder.encode(user, "UTF-8");
                            pass = URLEncoder.encode(pass, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            // ignore, just use the un encoded values
                        }
                    }

                    // build up the url with user/pass on it
                    int port = urlFileName.getPort();
                    String portString = (port < 1) ? "" : (":" + port);
                    String urlWithUserPass = urlFileName.getScheme() + "://" + user + ":" + pass + "@"
                            + urlFileName.getHostName() + portString + urlFileName.getPath();

                    try {
                        returnFile = currentPanel.resolveFile(urlWithUserPass);
                    } catch (FileSystemException e) {
                        // couldn't resolve with user/pass on url??? interesting
                        e.printStackTrace();
                    }

                }
            }
        }
        return returnFile;
    } else {
        return null;
    }
}