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

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

Introduction

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

Prototype

public boolean exists() throws FileSystemException;

Source Link

Document

Determines if this file exists.

Usage

From source file:org.pentaho.di.ui.repository.dialog.RepositoryExportProgressDialog.java

/**
 * Check if file is empty, writable, and return message dialogue box if file not empty, null otherwise.
 * //from  ww w . j av a 2s .  c o  m
 * @param shell
 * @param log
 * @param filename
 * @return
 */
public static MessageBox checkIsFileIsAcceptable(Shell shell, LogChannelInterface log, String filename) {
    MessageBox box = null;

    // check if file is exists
    try {
        // check if file is not empty
        FileObject output = KettleVFS.getFileObject(filename);
        if (output.exists()) {
            if (!output.isWriteable()) {
                box = new MessageBox(shell,
                        SWT.ICON_QUESTION | SWT.APPLICATION_MODAL | SWT.SHEET | SWT.OK | SWT.CANCEL);
                box.setText(BaseMessages.getString(PKG,
                        "RepositoryExportProgressDialog.ExportFileDialog.AreadyExists"));
                box.setMessage(BaseMessages.getString(PKG,
                        "RepositoryExportProgressDialog.ExportFileDialog.NoWritePermissions"));
                return box;
            }

            box = new MessageBox(shell,
                    SWT.ICON_QUESTION | SWT.APPLICATION_MODAL | SWT.SHEET | SWT.OK | SWT.CANCEL);
            box.setText(BaseMessages.getString(PKG,
                    "RepositoryExportProgressDialog.ExportFileDialog.AreadyExists"));
            box.setMessage(
                    BaseMessages.getString(PKG, "RepositoryExportProgressDialog.ExportFileDialog.Overwrite"));
        }
        // in case of exception - anyway we will not be able to write into this file.
    } catch (KettleFileException e) {
        log.logError("Can't access file: " + filename);
    } catch (FileSystemException e) {
        log.logError("Can't check if file exists/file permissions: " + filename);
    }
    return box;
}

From source file:org.pentaho.di.ui.spoon.Spoon.java

public void showWelcomePage() {
    try {/* w  w  w .ja va  2s  .  c om*/
        LocationListener listener = new LocationListener() {
            public void changing(LocationEvent event) {
                if (event.location.endsWith(".pdf")) {
                    Program.launch(event.location);
                    event.doit = false;
                } else if (event.location.contains("samples/transformations")
                        || event.location.contains("samples/jobs")
                        || event.location.contains("samples/mapping")) {
                    try {
                        FileObject fileObject = KettleVFS.getFileObject(event.location);
                        if (fileObject.exists()) {
                            if (event.location.endsWith(".ktr") || event.location.endsWith(".kjb")) {
                                openFile(event.location, false);
                            } else {
                                lastDirOpened = KettleVFS.getFilename(fileObject);
                                openFile(true);
                            }
                            event.doit = false;
                        }
                    } catch (Exception e) {
                        log.logError("Error handling samples location: " + event.location, e);
                    }
                }
            }

            public void changed(LocationEvent event) {
                // System.out.println("Changed to: " + event.location);
            }
        };

        // see if we are in webstart mode
        String webstartRoot = System.getProperty("spoon.webstartroot");
        if (webstartRoot != null) {
            URL url = new URL(webstartRoot + '/' + FILE_WELCOME_PAGE);
            addSpoonBrowser(STRING_WELCOME_TAB_NAME, url.toString(), listener); // ./docs/English/tips/index.htm
        } else {
            // see if we can find the welcome file on the file system
            File file = new File(FILE_WELCOME_PAGE);
            if (file.exists()) {
                // ./docs/English/tips/index.htm
                addSpoonBrowser(STRING_WELCOME_TAB_NAME, file.toURI().toURL().toString(), listener);
            }
        }
    } catch (MalformedURLException e1) {
        log.logError(Const.getStackTracker(e1));
    }
}

From source file:org.pentaho.di.ui.spoon.Spoon.java

public void createCmdLineFile() {
    String cmdFile = getCmdLine();

    if (Const.isEmpty(cmdFile)) {
        MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
        mb.setMessage(BaseMessages.getString(PKG, "ExportCmdLine.JobOrTransformationMissing.Message"));
        mb.setText(BaseMessages.getString(PKG, "ExportCmdLine.JobOrTransformationMissing.Title"));
        mb.open();/*from  w w w.j ava  2  s  . com*/
    } else {
        boolean export = true;

        FileDialog dialog = new FileDialog(shell, SWT.SAVE);
        dialog.setFilterExtensions(new String[] { "*.bat", ".sh", "*.*" });
        dialog.setFilterNames(new String[] { BaseMessages.getString(PKG, "ExportCmdLine.BatFiles"),
                BaseMessages.getString(PKG, "ExportCmdLineShFiles"),
                BaseMessages.getString(PKG, "ExportCmdLine.AllFiles") });
        String filename = dialog.open();

        if (filename != null) {
            // See if the file already exists...
            int id = SWT.YES;
            try {
                FileObject f = KettleVFS.getFileObject(filename);
                if (f.exists()) {
                    MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING);
                    mb.setMessage(
                            BaseMessages.getString(PKG, "ExportCmdLineShFiles.FileExistsReplace", filename));
                    mb.setText(BaseMessages.getString(PKG, "ExportCmdLineShFiles.ConfirmOverwrite"));
                    id = mb.open();
                }
            } catch (Exception e) {
                // Ignore errors
            }
            if (id == SWT.NO) {
                export = false;
            }

            if (export) {
                java.io.FileWriter out = null;
                try {
                    out = new java.io.FileWriter(filename);
                    out.write(cmdFile);
                    out.flush();
                } catch (Exception e) {
                    new ErrorDialog(shell,
                            BaseMessages.getString(PKG, "ExportCmdLineShFiles.ErrorWritingFile.Title"),
                            BaseMessages.getString(PKG, "ExportCmdLineShFiles.ErrorWritingFile.Message",
                                    filename),
                            e);
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (Exception e) {
                            // Ignore errors
                        }
                    }
                }

                MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
                mb.setMessage(
                        BaseMessages.getString(PKG, "ExportCmdLineShFiles.CmdExported.Message", filename));
                mb.setText(BaseMessages.getString(PKG, "ExportCmdLineShFiles.CmdExported.Title"));
                mb.open();
            }
        }
    }
}

From source file:org.pentaho.di.ui.spoon.Spoon.java

/**
 * Export this job or transformation including all depending resources to a single zip file.
 *///from w  w  w . j  a v a  2s. co  m
public void exportAllXMLFile() {

    ResourceExportInterface resourceExportInterface = getActiveTransformation();
    if (resourceExportInterface == null) {
        resourceExportInterface = getActiveJob();
    }
    if (resourceExportInterface == null) {
        return; // nothing to do here, prevent an NPE
    }

    // ((VariableSpace)resourceExportInterface).getVariable("Internal.Transformation.Filename.Directory");

    // Ask the user for a zip file to export to:
    //
    try {
        String zipFilename = null;
        while (Const.isEmpty(zipFilename)) {
            FileDialog dialog = new FileDialog(shell, SWT.SAVE);
            dialog.setText(BaseMessages.getString(PKG, "Spoon.ExportResourceSelectZipFile"));
            dialog.setFilterExtensions(new String[] { "*.zip;*.ZIP", "*" });
            dialog.setFilterNames(new String[] { BaseMessages.getString(PKG, "System.FileType.ZIPFiles"),
                    BaseMessages.getString(PKG, "System.FileType.AllFiles"), });
            setFilterPath(dialog);
            if (dialog.open() != null) {
                lastDirOpened = dialog.getFilterPath();
                zipFilename = dialog.getFilterPath() + Const.FILE_SEPARATOR + dialog.getFileName();
                FileObject zipFileObject = KettleVFS.getFileObject(zipFilename);
                if (zipFileObject.exists()) {
                    MessageBox box = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL);
                    box.setMessage(BaseMessages.getString(PKG, "Spoon.ExportResourceZipFileExists.Message",
                            zipFilename));
                    box.setText(BaseMessages.getString(PKG, "Spoon.ExportResourceZipFileExists.Title"));
                    int answer = box.open();
                    if (answer == SWT.CANCEL) {
                        return;
                    }
                    if (answer == SWT.NO) {
                        zipFilename = null;
                    }
                }
            } else {
                return;
            }
        }

        // Export the resources linked to the currently loaded file...
        //
        TopLevelResource topLevelResource = ResourceUtil.serializeResourceExportInterface(zipFilename,
                resourceExportInterface, (VariableSpace) resourceExportInterface, rep, metaStore);
        String message = ResourceUtil.getExplanation(zipFilename, topLevelResource.getResourceName(),
                resourceExportInterface);

        /*
         * // Add the ZIP file as a repository to the repository list... // RepositoriesMeta repositoriesMeta = new
         * RepositoriesMeta(); repositoriesMeta.readData();
         *
         * KettleFileRepositoryMeta fileRepositoryMeta = new KettleFileRepositoryMeta(
         * KettleFileRepositoryMeta.REPOSITORY_TYPE_ID, "Export " + baseFileName, "Export to file : " + zipFilename,
         * "zip://" + zipFilename + "!"); fileRepositoryMeta.setReadOnly(true); // A ZIP file is read-only int nr = 2;
         * String baseName = fileRepositoryMeta.getName(); while
         * (repositoriesMeta.findRepository(fileRepositoryMeta.getName()) != null) { fileRepositoryMeta.setName(baseName +
         * " " + nr); nr++; }
         *
         * repositoriesMeta.addRepository(fileRepositoryMeta); repositoriesMeta.writeData();
         */

        // Show some information concerning all this work...

        EnterTextDialog enterTextDialog = new EnterTextDialog(shell,
                BaseMessages.getString(PKG, "Spoon.Dialog.ResourceSerialized"),
                BaseMessages.getString(PKG, "Spoon.Dialog.ResourceSerializedSuccesfully"), message);
        enterTextDialog.setReadOnly();
        enterTextDialog.open();
    } catch (Exception e) {
        new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Error"),
                BaseMessages.getString(PKG, "Spoon.ErrorExportingFile"), e);
    }
}

From source file:org.pentaho.di.ui.spoon.Spoon.java

/**
 * Export this job or transformation including all depending resources to a single ZIP file containing a file
 * repository.//from   w w  w .  java2 s.  co  m
 */
public void exportAllFileRepository() {

    ResourceExportInterface resourceExportInterface = getActiveTransformation();
    if (resourceExportInterface == null) {
        resourceExportInterface = getActiveJob();
    }
    if (resourceExportInterface == null) {
        return; // nothing to do here, prevent an NPE
    }

    // Ask the user for a zip file to export to:
    //
    try {
        String zipFilename = null;
        while (Const.isEmpty(zipFilename)) {
            FileDialog dialog = new FileDialog(shell, SWT.SAVE);
            dialog.setText(BaseMessages.getString(PKG, "Spoon.ExportResourceSelectZipFile"));
            dialog.setFilterExtensions(new String[] { "*.zip;*.ZIP", "*" });
            dialog.setFilterNames(new String[] { BaseMessages.getString(PKG, "System.FileType.ZIPFiles"),
                    BaseMessages.getString(PKG, "System.FileType.AllFiles"), });
            setFilterPath(dialog);
            if (dialog.open() != null) {
                lastDirOpened = dialog.getFilterPath();
                zipFilename = dialog.getFilterPath() + Const.FILE_SEPARATOR + dialog.getFileName();
                FileObject zipFileObject = KettleVFS.getFileObject(zipFilename);
                if (zipFileObject.exists()) {
                    MessageBox box = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL);
                    box.setMessage(BaseMessages.getString(PKG, "Spoon.ExportResourceZipFileExists.Message",
                            zipFilename));
                    box.setText(BaseMessages.getString(PKG, "Spoon.ExportResourceZipFileExists.Title"));
                    int answer = box.open();
                    if (answer == SWT.CANCEL) {
                        return;
                    }
                    if (answer == SWT.NO) {
                        zipFilename = null;
                    }
                }
            } else {
                return;
            }
        }

        // Export the resources linked to the currently loaded file...
        //
        TopLevelResource topLevelResource = ResourceUtil.serializeResourceExportInterface(zipFilename,
                resourceExportInterface, (VariableSpace) resourceExportInterface, rep, metaStore);
        String message = ResourceUtil.getExplanation(zipFilename, topLevelResource.getResourceName(),
                resourceExportInterface);

        /*
         * // Add the ZIP file as a repository to the repository list... // RepositoriesMeta repositoriesMeta = new
         * RepositoriesMeta(); repositoriesMeta.readData();
         *
         * KettleFileRepositoryMeta fileRepositoryMeta = new KettleFileRepositoryMeta(
         * KettleFileRepositoryMeta.REPOSITORY_TYPE_ID, "Export " + baseFileName, "Export to file : " + zipFilename,
         * "zip://" + zipFilename + "!"); fileRepositoryMeta.setReadOnly(true); // A ZIP file is read-only int nr = 2;
         * String baseName = fileRepositoryMeta.getName(); while
         * (repositoriesMeta.findRepository(fileRepositoryMeta.getName()) != null) { fileRepositoryMeta.setName(baseName +
         * " " + nr); nr++; }
         *
         * repositoriesMeta.addRepository(fileRepositoryMeta); repositoriesMeta.writeData();
         */

        // Show some information concerning all this work...
        //
        EnterTextDialog enterTextDialog = new EnterTextDialog(shell,
                BaseMessages.getString(PKG, "Spoon.Dialog.ResourceSerialized"),
                BaseMessages.getString(PKG, "Spoon.Dialog.ResourceSerializedSuccesfully"), message);
        enterTextDialog.setReadOnly();
        enterTextDialog.open();
    } catch (Exception e) {
        new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Error"),
                BaseMessages.getString(PKG, "Spoon.ErrorExportingFile"), e);
    }
}

From source file:org.pentaho.di.ui.spoon.Spoon.java

public boolean saveXMLFile(EngineMetaInterface meta, boolean export) {
    if (log.isBasic()) {
        log.logBasic("Save file as...");
    }//from  ww w  .j av a2s  . co  m
    boolean saved = false;
    String beforeFilename = meta.getFilename();
    String beforeName = meta.getName();

    FileDialog dialog = new FileDialog(shell, SWT.SAVE);
    String[] extensions = meta.getFilterExtensions();
    dialog.setFilterExtensions(extensions);
    dialog.setFilterNames(meta.getFilterNames());
    setFilterPath(dialog);
    String filename = dialog.open();
    if (filename != null) {
        lastDirOpened = dialog.getFilterPath();

        // Is the filename ending on .ktr, .xml?
        boolean ending = false;
        for (int i = 0; i < extensions.length - 1; i++) {
            String[] parts = extensions[i].split(";");
            for (String part : parts) {
                if (filename.toLowerCase().endsWith(part.substring(1).toLowerCase())) {
                    ending = true;
                }
            }
        }
        if (filename.endsWith(meta.getDefaultExtension())) {
            ending = true;
        }
        if (!ending) {
            if (!meta.getDefaultExtension().startsWith(".") && !filename.endsWith(".")) {
                filename += ".";
            }
            filename += meta.getDefaultExtension();
        }
        // See if the file already exists...
        int id = SWT.YES;
        try {
            FileObject f = KettleVFS.getFileObject(filename);
            if (f.exists()) {
                MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING);
                // "This file already exists.  Do you want to overwrite it?"
                mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.PromptOverwriteFile.Message"));
                // "This file already exists!"
                mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.PromptOverwriteFile.Title"));
                id = mb.open();
            }
        } catch (Exception e) {
            // TODO do we want to show an error dialog here? My first guess
            // is not, but we might.
        }
        if (id == SWT.YES) {
            if (!export && !Const.isEmpty(beforeFilename) && !beforeFilename.equals(filename)) {
                meta.setName(Const.createName(filename));
                meta.setFilename(filename);
                // If the user hits cancel here, don't save anything
                //
                if (!editProperties()) {
                    // Revert the changes!
                    //
                    meta.setFilename(beforeFilename);
                    meta.setName(beforeName);
                    return saved;
                }
            }

            saved = save(meta, filename, export);
            if (!saved) {
                meta.setFilename(beforeFilename);
                meta.setName(beforeName);
            }
        }
    }
    return saved;
}

From source file:org.pentaho.di.ui.spoon.Spoon.java

public boolean saveXMLFileToVfs(EngineMetaInterface meta) {
    if (log.isBasic()) {
        log.logBasic("Save file as...");
    }/*from  w  ww .ja  v a  2 s  .c om*/

    FileObject rootFile;
    FileObject initialFile;
    try {
        initialFile = KettleVFS.getFileObject(getLastFileOpened());
        rootFile = KettleVFS.getFileObject(getLastFileOpened()).getFileSystem().getRoot();
    } catch (Exception e) {
        MessageBox messageDialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
        messageDialog.setText("Error");
        messageDialog.setMessage(e.getMessage());
        messageDialog.open();
        return false;
    }

    String filename = null;
    FileObject selectedFile = getVfsFileChooserDialog(rootFile, initialFile).open(shell, "Untitled",
            Const.STRING_TRANS_AND_JOB_FILTER_EXT, Const.getTransformationAndJobFilterNames(),
            VfsFileChooserDialog.VFS_DIALOG_SAVEAS);
    if (selectedFile != null) {
        filename = selectedFile.getName().getFriendlyURI();
    }

    String[] extensions = meta.getFilterExtensions();
    if (filename != null) {
        // Is the filename ending on .ktr, .xml?
        boolean ending = false;
        for (int i = 0; i < extensions.length - 1; i++) {
            if (filename.endsWith(extensions[i].substring(1))) {
                ending = true;
            }
        }
        if (filename.endsWith(meta.getDefaultExtension())) {
            ending = true;
        }
        if (!ending) {
            filename += '.' + meta.getDefaultExtension();
        }
        // See if the file already exists...
        int id = SWT.YES;
        try {
            FileObject f = KettleVFS.getFileObject(filename);
            if (f.exists()) {
                MessageBox mb = new MessageBox(shell, SWT.NO | SWT.YES | SWT.ICON_WARNING);
                // "This file already exists.  Do you want to overwrite it?"
                mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.PromptOverwriteFile.Message"));
                mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.PromptOverwriteFile.Title"));
                id = mb.open();
            }
        } catch (Exception e) {
            // TODO do we want to show an error dialog here? My first guess
            // is not, but we might.
        }
        if (id == SWT.YES) {
            save(meta, filename, false);
        }
    }
    return false;
}

From source file:org.pentaho.reporting.libraries.pensol.VfsTest.java

public void testInitialLoading() throws FileSystemException {
    final FileObject nonExistent = VFS.getManager().resolveFile("test-solution://localhost/non-existent");
    assertFalse(nonExistent.exists());
    assertEquals(FileType.IMAGINARY, nonExistent.getType());
    assertEquals("non-existent", nonExistent.getName().getBaseName());
    final FileObject directory = VFS.getManager().resolveFile("test-solution://localhost/bi-developers");
    assertTrue(directory.exists());//from   ww  w  .java  2s. c o m
    assertEquals(FileType.FOLDER, directory.getType());
    assertEquals("bi-developers", directory.getName().getBaseName());
    final FileObject file = VFS.getManager()
            .resolveFile("test-solution://localhost/bi-developers/analysis/query1.xaction");
    assertTrue(file.exists());
    assertEquals(FileType.FILE, file.getType());
    assertEquals("query1.xaction", file.getName().getBaseName());
}

From source file:org.pentaho.s3.S3Test.java

@Test
public void readFile() throws Exception {
    assertNotNull("FileSystemManager is null", fsManager);

    FileObject bucket = fsManager.resolveFile(buildS3URL("/mdamour_read_file_bucket_test"));
    bucket.createFolder();//w  w w  .  j a  v a  2 s .c  o  m

    FileObject s3FileOut = fsManager.resolveFile(buildS3URL("/mdamour_read_file_bucket_test/writeFileTest"));
    OutputStream out = s3FileOut.getContent().getOutputStream();
    out.write(HELLO_S3_STR.getBytes("UTF-8"));
    out.close();

    ByteArrayOutputStream testOut = new ByteArrayOutputStream();
    IOUtils.copy(s3FileOut.getContent().getInputStream(), testOut);
    assertEquals(HELLO_S3_STR.getBytes().length, testOut.toByteArray().length);
    assertEquals(new String(HELLO_S3_STR.getBytes("UTF-8"), "UTF-8"),
            new String(testOut.toByteArray(), "UTF-8"));

    bucket.delete(deleteFileSelector);
    assertEquals(false, bucket.exists());
}

From source file:org.pentaho.s3.S3Test.java

@Test
public void writeFile() throws Exception {
    assertNotNull("FileSystemManager is null", fsManager);

    FileObject bucket = fsManager.resolveFile(buildS3URL("/mdamour_write_file_bucket_test"));
    bucket.createFolder();/*  w w w  .j  av a2 s  .co  m*/

    FileObject s3FileOut = fsManager.resolveFile(buildS3URL("/mdamour_write_file_bucket_test/writeFileTest"));
    OutputStream out = s3FileOut.getContent().getOutputStream();
    out.write(HELLO_S3_STR.getBytes());
    out.close();

    IOUtils.copy(s3FileOut.getContent().getInputStream(), System.out);

    bucket.delete(deleteFileSelector);
    assertEquals(false, bucket.exists());
}