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

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

Introduction

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

Prototype

public boolean delete() throws FileSystemException;

Source Link

Document

Deletes this file.

Usage

From source file:com.panet.imeta.job.entries.shell.JobEntryShell.java

private void executeShell(Result result, List<RowMetaAndData> cmdRows, String[] args) {
    LogWriter log = LogWriter.getInstance();
    FileObject fileObject = null;
    String realScript = null;//www  . j  a v  a  2  s.c om
    FileObject tempFile = null;

    try {
        // What's the exact command?
        String base[] = null;
        List<String> cmds = new ArrayList<String>();

        if (log.isBasic())
            log.logBasic(toString(), Messages.getString("JobShell.RunningOn", Const.getOS()));

        if (insertScript) {
            realScript = environmentSubstitute(script);
        } else {
            String realFilename = environmentSubstitute(getFilename());
            fileObject = KettleVFS.getFileObject(realFilename);
        }

        if (Const.getOS().equals("Windows 95")) {
            base = new String[] { "command.com", "/C" };
        } else if (Const.getOS().startsWith("Windows")) {
            base = new String[] { "cmd.exe", "/C" };
        } else {
            if (!insertScript) {
                // Just set the command to the script we need to execute...
                //
                base = new String[] { KettleVFS.getFilename(fileObject) };
            } else {
                // Create a unique new temporary filename in the working directory, put the script in there
                // Set the permissions to execute and then run it...
                //
                try {
                    tempFile = KettleVFS.createTempFile("kettle", "shell", workDirectory);
                    tempFile.createFile();
                    OutputStream outputStream = tempFile.getContent().getOutputStream();
                    outputStream.write(realScript.getBytes());
                    outputStream.close();
                    String tempFilename = KettleVFS.getFilename(tempFile);
                    // Now we have to make this file executable...
                    // On Unix-like systems this is done using the command "/bin/chmod +x filename"
                    //
                    ProcessBuilder procBuilder = new ProcessBuilder("chmod", "+x", tempFilename);
                    Process proc = procBuilder.start();
                    // Eat/log stderr/stdout all messages in a different thread...
                    StreamLogger errorLogger = new StreamLogger(proc.getErrorStream(),
                            toString() + " (stderr)");
                    StreamLogger outputLogger = new StreamLogger(proc.getInputStream(),
                            toString() + " (stdout)");
                    new Thread(errorLogger).start();
                    new Thread(outputLogger).start();
                    proc.waitFor();

                    // Now set this filename as the base command...
                    //
                    base = new String[] { tempFilename };
                } catch (Exception e) {
                    throw new Exception("Unable to create temporary file to execute script", e);
                }
            }
        }

        // Construct the arguments...
        if (argFromPrevious && cmdRows != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++)
                cmds.add(base[i]);

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                if (insertScript)
                    cmdline.append(realScript);
                else
                    cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\""));
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) // Normally just
                // one row, but
                // once in a
                // while to
                // remain
                // compatible we
                // have
                // multiple.
                {
                    RowMetaAndData r = (RowMetaAndData) cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmdline.append(' ');
                        cmdline.append(optionallyQuoteField(r.getString(j, null), "\""));
                    }
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) // Normally just
                // one row, but
                // once in a
                // while to
                // remain
                // compatible we
                // have
                // multiple.
                {
                    RowMetaAndData r = (RowMetaAndData) cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmds.add(optionallyQuoteField(r.getString(j, null), "\""));
                    }
                }
            }
        } else if (args != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++)
                cmds.add(base[i]);

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                if (insertScript)
                    cmdline.append(realScript);
                else
                    cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\""));

                for (int i = 0; i < args.length; i++) {
                    cmdline.append(' ');
                    cmdline.append(optionallyQuoteField(args[i], "\""));
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                for (int i = 0; i < args.length; i++) {
                    cmds.add(args[i]);
                }
            }
        }

        StringBuffer command = new StringBuffer();

        Iterator<String> it = cmds.iterator();
        boolean first = true;
        while (it.hasNext()) {
            if (!first)
                command.append(' ');
            else
                first = false;
            command.append((String) it.next());
        }
        if (log.isBasic())
            log.logBasic(toString(), Messages.getString("JobShell.ExecCommand", command.toString()));

        // Build the environment variable list...
        ProcessBuilder procBuilder = new ProcessBuilder(cmds);
        Map<String, String> env = procBuilder.environment();
        String[] variables = listVariables();
        for (int i = 0; i < variables.length; i++) {
            env.put(variables[i], getVariable(variables[i]));
        }

        if (getWorkDirectory() != null && !Const.isEmpty(Const.rtrim(getWorkDirectory()))) {
            String vfsFilename = environmentSubstitute(getWorkDirectory());
            File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename)));
            procBuilder.directory(file);
        }
        Process proc = procBuilder.start();

        // any error message?
        StreamLogger errorLogger = new StreamLogger(proc.getErrorStream(), toString() + " (stderr)");

        // any output?
        StreamLogger outputLogger = new StreamLogger(proc.getInputStream(), toString() + " (stdout)");

        // kick them off
        new Thread(errorLogger).start();
        new Thread(outputLogger).start();

        proc.waitFor();
        if (log.isDetailed())
            log.logDetailed(toString(), Messages.getString("JobShell.CommandFinished", command.toString()));

        // What's the exit status?
        result.setExitStatus(proc.exitValue());
        if (result.getExitStatus() != 0) {
            if (log.isDetailed())
                log.logDetailed(toString(), Messages.getString("JobShell.ExitStatus",
                        environmentSubstitute(getFilename()), "" + result.getExitStatus()));

            result.setNrErrors(1);
        }

        // close the streams
        // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations
        proc.getErrorStream().close();
        proc.getOutputStream().close();

    } catch (IOException ioe) {
        log.logError(toString(), Messages.getString("JobShell.ErrorRunningShell",
                environmentSubstitute(getFilename()), ioe.toString()));
        result.setNrErrors(1);
    } catch (InterruptedException ie) {
        log.logError(toString(), Messages.getString("JobShell.Shellinterupted",
                environmentSubstitute(getFilename()), ie.toString()));
        result.setNrErrors(1);
    } catch (Exception e) {
        log.logError(toString(), Messages.getString("JobShell.UnexpectedError",
                environmentSubstitute(getFilename()), e.toString()));
        result.setNrErrors(1);
    } finally {
        // If we created a temporary file, remove it...
        //
        if (tempFile != null) {
            try {
                tempFile.delete();
            } catch (Exception e) {
                Messages.getString("JobShell.UnexpectedError", tempFile.toString(), e.toString());
            }
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }
}

From source file:org.docx4all.ui.menu.FileMenu.java

private RETURN_TYPE saveAsFile(String callerActionName, ActionEvent actionEvent, String fileType) {
    Preferences prefs = Preferences.userNodeForPackage(getClass());
    WordMLEditor editor = WordMLEditor.getInstance(WordMLEditor.class);
    ResourceMap rm = editor.getContext().getResourceMap(getClass());

    JInternalFrame iframe = editor.getCurrentInternalFrame();
    String oldFilePath = (String) iframe.getClientProperty(WordMLDocument.FILE_PATH_PROPERTY);

    VFSJFileChooser chooser = createFileChooser(rm, callerActionName, iframe, fileType);

    RETURN_TYPE returnVal = chooser.showSaveDialog((Component) actionEvent.getSource());
    if (returnVal == RETURN_TYPE.APPROVE) {
        FileObject selectedFile = getSelectedFile(chooser, fileType);

        boolean error = false;
        boolean newlyCreatedFile = false;

        if (selectedFile == null) {

            // Should never happen, whether the file exists or not

        } else {//from   w w w .  j  av a2s  . c o m

            //Check selectedFile's existence and ask user confirmation when needed.
            try {
                boolean selectedFileExists = selectedFile.exists();
                if (!selectedFileExists) {
                    FileObject parent = selectedFile.getParent();
                    String uri = UriParser.decode(parent.getName().getURI());

                    if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") > -1
                            && parent.getName().getScheme().startsWith("file") && !parent.isWriteable()
                            && (uri.indexOf("/Documents") > -1 || uri.indexOf("/My Documents") > -1)) {
                        //TODO: Check whether we still need this workaround.
                        //See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4939819
                        //Re: File.canWrite() returns false for the "My Documents" directory (win)
                        String localpath = org.docx4j.utils.VFSUtils.getLocalFilePath(parent);
                        File f = new File(localpath);
                        f.setWritable(true, true);
                    }

                    selectedFile.createFile();
                    newlyCreatedFile = true;

                } else if (!selectedFile.getName().getURI().equalsIgnoreCase(oldFilePath)) {
                    String title = rm.getString(callerActionName + ".Action.text");
                    String message = VFSUtils.getFriendlyName(selectedFile.getName().getURI()) + "\n"
                            + rm.getString(callerActionName + ".Action.confirmMessage");
                    int answer = editor.showConfirmDialog(title, message, JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE);
                    if (answer != JOptionPane.YES_OPTION) {
                        selectedFile = null;
                    }
                } // if (!selectedFileExists)

            } catch (FileSystemException exc) {
                exc.printStackTrace();//ignore
                log.error("Couldn't create new file or assure file existence. File = "
                        + selectedFile.getName().getURI());
                selectedFile = null;
                error = true;
            }
        }

        //Check whether there has been an error, cancellation by user
        //or may proceed to saving file.
        if (selectedFile != null) {
            //Proceed to saving file
            String selectedPath = selectedFile.getName().getURI();
            if (log.isDebugEnabled()) {
                log.debug("saveAsFile(): selectedFile = " + VFSUtils.getFriendlyName(selectedPath));
            }

            prefs.put(Constants.LAST_OPENED_FILE, selectedPath);
            if (selectedFile.getName().getScheme().equals("file")) {
                prefs.put(Constants.LAST_OPENED_LOCAL_FILE, selectedPath);
            }
            PreferenceUtil.flush(prefs);

            boolean success = false;
            if (EXPORT_AS_NON_SHARED_DOC_ACTION_NAME.equals(callerActionName)) {
                log.info("saveAsFile(): Exporting as non shared document to "
                        + VFSUtils.getFriendlyName(selectedPath));
                success = export(iframe, selectedPath, callerActionName);
                if (success) {
                    prefs.put(Constants.LAST_OPENED_FILE, selectedPath);
                    if (selectedPath.startsWith("file:")) {
                        prefs.put(Constants.LAST_OPENED_LOCAL_FILE, selectedPath);
                    }
                    PreferenceUtil.flush(prefs);
                    log.info("saveAsFile(): Opening " + VFSUtils.getFriendlyName(selectedPath));
                    editor.createInternalFrame(selectedFile);
                }
            } else {
                success = save(iframe, selectedPath, callerActionName);
                if (success) {
                    if (Constants.DOCX_STRING.equals(fileType) || Constants.FLAT_OPC_STRING.equals(fileType)) {
                        //If saving as .docx then update the document dirty flag 
                        //of toolbar states as well as internal frame title.
                        editor.getToolbarStates().setDocumentDirty(iframe, false);
                        editor.getToolbarStates().setLocalEditsEnabled(iframe, false);
                        FileObject file = null;
                        try {
                            file = VFSUtils.getFileSystemManager().resolveFile(oldFilePath);
                            editor.updateInternalFrame(file, selectedFile);
                        } catch (FileSystemException exc) {
                            ;//ignore
                        }
                    } else {
                        //Because document dirty flag is not cleared
                        //and internal frame title is not changed,
                        //we present a success message.
                        String title = rm.getString(callerActionName + ".Action.text");
                        String message = VFSUtils.getFriendlyName(selectedPath) + "\n"
                                + rm.getString(callerActionName + ".Action.successMessage");
                        editor.showMessageDialog(title, message, JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            }

            if (!success && newlyCreatedFile) {
                try {
                    selectedFile.delete();
                } catch (FileSystemException exc) {
                    log.error("saveAsFile(): Saving failure and cannot remove the newly created file = "
                            + selectedPath);
                    exc.printStackTrace();
                }
            }
        } else if (error) {
            log.error("saveAsFile(): selectedFile = NULL");
            String title = rm.getString(callerActionName + ".Action.text");
            String message = rm.getString(callerActionName + ".Action.errorMessage");
            editor.showMessageDialog(title, message, JOptionPane.ERROR_MESSAGE);
        }

    } //if (returnVal == JFileChooser.APPROVE_OPTION)

    return returnVal;
}

From source file:org.docx4all.ui.menu.HyperlinkMenu.java

private boolean createInFileSystem(FileObject fo, WordprocessingMLPackage source) throws FileSystemException {
    boolean success = false;

    WordprocessingMLPackage newPack = createNewEmptyPackage(source);
    if (newPack != null) {
        String targetPath = fo.getName().getURI();
        FileMenu.getInstance().createInFileSystem(fo);
        success = FileMenu.getInstance().save(newPack, targetPath, OPEN_LINKED_DOCUMENT_ACTION_NAME);
        if (!success) {
            fo.delete();
        }//from w  w w .  ja  va  2 s  . co  m
    }

    return success;
}

From source file:org.gatherdata.archiver.dao.vfs.internal.VfsArchiverDao.java

public void remove(URI uid) {
    try {//from w w w  .  j av a  2  s.  c o m
        FileObject envelopeFile = fsManager.resolveFile(fsBase, uid.toASCIIString());
        if (envelopeFile.exists()) {
            envelopeFile.delete();
        }
    } catch (FileSystemException e) {
        e.printStackTrace();
    }
}

From source file:org.gatherdata.archiver.dao.vfs.internal.VfsArchiverDao.java

public GatherArchive save(GatherArchive envelopeToSave) {
    try {/*from  w w w  .  j a v a2 s  .co m*/
        FileObject envelopeFile = fsManager.resolveFile(fsBase, envelopeToSave.getUid().toASCIIString());
        if (envelopeFile.exists()) {
            envelopeFile.delete();
        }
        envelopeFile.createFile();
        SerializationUtils.serialize(envelopeToSave, envelopeFile.getContent().getOutputStream());
    } catch (FileSystemException e) {
        e.printStackTrace();
    }

    return envelopeToSave;
}

From source file:org.jboss.dashboard.ui.components.FileNavigationHandler.java

public CommandResponse actionDeleteFile(CommandRequest request) throws FileSystemException {
    if (isDeleteFileAllowed() || getUserStatus().isRootUser()) {
        FileObject currentFile = getCurrentFile();
        if (currentFile != null && currentFile.isWriteable()) {
            FileObject parentDir = currentFile.getParent();
            if (parentDir != null && parentDir.isWriteable()) {
                if (currentFile.delete()) {
                    currentFilePath = null;
                }/*  ww  w.j a v a  2s  .  com*/
            }
        }
    }
    return getCommonResponse(request);
}

From source file:org.jboss.dashboard.ui.components.FileNavigationHandler.java

public CommandResponse actionDeleteFolder(CommandRequest request) throws FileSystemException {
    if (isDeleteFolderAllowed() || getUserStatus().isRootUser()) {
        if (!getCurrentPath().equals(getBaseDirPath())) {
            FileObject currentDir = getCurrentDir();
            if (currentDir != null && currentDir.isWriteable()
                    && (currentDir.getChildren() == null || currentDir.getChildren().length == 0)) {
                FileObject parentDir = currentDir.getParent();
                if (parentDir != null && parentDir.isWriteable()) {
                    if (currentDir.delete()) {
                        currentPath = currentPath.substring(0, currentPath.lastIndexOf("/"));
                    }//  ww  w .j  a  va2s  .  c  o  m
                }
            }
        }
    }
    return getCommonResponse(request);
}

From source file:org.josso.tooling.gshell.install.commands.InstallWebGatewayCommand.java

protected void installConfig() throws Exception {

    if (copyConfigFiles) {
        // Generate a key for rememberme auth
        SecretKeySpec key = CipherUtil.generateAESKey();
        byte[] keyBytes = key.getEncoded();
        String keyStr = CipherUtil.encodeBase64(keyBytes);

        FileObject authProperties = tmpDir.resolveFile("josso-auth.properties");

        authProperties.createFile();//from   w  ww  .j  a  v a 2 s.co  m
        OutputStream os = authProperties.getContent().getOutputStream(true);
        java.util.Properties authProps = new java.util.Properties();

        authProps.setProperty("josso.rememberme.authscheme.key", keyStr);
        authProps.store(os, "JOSSO 'Remember Me' authentication schemem properties.");

        printer.printActionOkStatus("Generating", "'Remember Me' AES key",
                "Created " + authProperties.getName().getFriendlyURI());

        getInstaller().installConfiguration(
                createArtifact(tmpDir.getURL().toString(), JOSSOScope.GATEWAY, "josso-auth.properties"),
                isReplaceConfig());
        try {
            authProperties.delete();
        } catch (java.io.IOException e) {
            /* */ }

        String persistenceFileName = "josso-gateway-" + persistence + "-stores.xml";
        printer.printActionOkStatus("Using", "'" + persistence + "' default configuration",
                "Installing " + persistenceFileName + " as " + "josso-gateway-stores.xml");

        // Install all configuration files :
        FileObject[] libs = confDir.getChildren();
        for (int i = 0; i < confDir.getChildren().length; i++) {
            FileObject cfgFile = libs[i];

            if (!cfgFile.getType().getName().equals(FileType.FILE.getName())) {
                // ignore folders
                continue;
            }

            String fileName = cfgFile.getName().getBaseName();
            if (fileName.equals(persistenceFileName)) {
                getInstaller().installConfiguration(
                        createArtifact(confDir.getURL().toString(), JOSSOScope.GATEWAY, fileName),
                        "josso-gateway-stores.xml", isReplaceConfig());
            }

            getInstaller().installConfiguration(
                    createArtifact(confDir.getURL().toString(), JOSSOScope.GATEWAY, fileName),
                    isReplaceConfig());
        }
    } else {
        //TODO backup configuration files, if they exist
        io.out.println("Backup and remove existing configuration files");
        getInstaller().backupGatewayConfigurations(true);
    }

}

From source file:org.josso.tooling.gshell.install.installer.JBossInstaller.java

public void installApplication(JOSSOArtifact artifact, boolean replace) throws InstallException {
    try {/*from   www  .  j a v a2  s .  co  m*/
        // If the war is already expanded, copy it with a new name.
        FileObject srcFile = getFileSystemManager().resolveFile(artifact.getLocation());

        // Is this the josso gateaway ?
        String name = artifact.getBaseName();
        boolean isFolder = srcFile.getType().equals(FileType.FOLDER);

        if (artifact.getType().equals("war") && name.startsWith("josso-gateway-web")) {
            // INSTALL GWY
            String newName = "josso.war";

            // Do we have to explode the war ?
            if (getTargetPlatform().isJOSSOWarExploded() && !isFolder) {
                installJar(srcFile, this.targetDeployDir, newName, true, replace);

                if (getTargetPlatform().getVersion().startsWith("6")) {
                    // Under JBoss 6 remove commons logging JAR files which conflict with slf4j replacement
                    FileObject webInfLibFolder = targetDeployDir.resolveFile(newName + "/WEB-INF/lib");

                    boolean exists = webInfLibFolder.exists();

                    if (exists) {
                        FileObject[] sharedLibs = webInfLibFolder.getChildren();
                        for (int i = 0; i < sharedLibs.length; i++) {
                            FileObject jarFile = sharedLibs[i];

                            if (!jarFile.getType().getName().equals(FileType.FILE.getName())) {
                                // ignore folders
                                continue;
                            }
                            if (jarFile.getName().getBaseName().startsWith("commons-logging")
                                    && jarFile.getName().getBaseName().endsWith(".jar")) {
                                jarFile.delete();
                            }
                        }
                    }
                }
            } else {
                installFile(srcFile, this.targetDeployDir, replace);
            }
            return;
        }

        if ((getTargetPlatform().getVersion().startsWith("5")
                || getTargetPlatform().getVersion().startsWith("6")) && artifact.getType().equals("ear")
                && artifact.getBaseName().startsWith("josso-partner-jboss5")) {
            installFile(srcFile, this.targetDeployDir, replace);
            return;
        } else if (!(getTargetPlatform().getVersion().startsWith("5")
                || getTargetPlatform().getVersion().startsWith("6")) && artifact.getType().equals("ear")
                && artifact.getBaseName().startsWith("josso-partner-jboss-app")) {
            installFile(srcFile, this.targetDeployDir, replace);
            return;
        }

        log.debug("Skipping partner application : " + srcFile.getName().getFriendlyURI());

    } catch (IOException e) {
        throw new InstallException(e.getMessage(), e);
    }
}

From source file:org.josso.tooling.gshell.install.installer.TomcatInstaller.java

@Override
public boolean backupAgentConfigurations(boolean remove) {
    try {/*from   w  ww.  ja  v  a  2  s . c o  m*/
        super.backupAgentConfigurations(remove);
        // backup jaas.conf
        FileObject jaasConfigFile = targetConfDir.resolveFile("jaas.conf");
        if (jaasConfigFile.exists()) {
            // backup file in the same folder it is installed
            backupFile(jaasConfigFile, jaasConfigFile.getParent());
            if (remove) {
                jaasConfigFile.delete();
            }
        }
        // backup setenv.sh and setenv.bat
        FileObject[] libs = targetBinDir.getChildren();
        for (int i = 0; i < libs.length; i++) {
            FileObject cfgFile = libs[i];

            if (!cfgFile.getType().getName().equals(FileType.FILE.getName())) {
                // ignore folders
                continue;
            }
            if (cfgFile.getName().getBaseName().startsWith("setenv")
                    && (cfgFile.getName().getBaseName().endsWith(".sh")
                            || cfgFile.getName().getBaseName().endsWith(".bat"))) {
                // backup files in the same folder they're installed in
                backupFile(cfgFile, cfgFile.getParent());
                if (remove) {
                    cfgFile.delete();
                }
            }
        }
    } catch (Exception e) {
        getPrinter().printErrStatus("BackupAgentConfigurations", e.getMessage());
        return false;
    }
    return true;
}