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

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

Introduction

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

Prototype

public void createFile() throws FileSystemException;

Source Link

Document

Creates this file, if it does not exist.

Usage

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 {/* w  w  w . j ava 2 s.  c  om*/

            //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.FileMenu.java

public void createInFileSystem(FileObject file) throws FileSystemException {
    FileObject parent = file.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);/*w  w  w .jav a2 s .c o m*/
    }

    file.createFile();
}

From source file:org.eclim.plugin.core.command.archive.ArchiveReadCommand.java

/**
 * {@inheritDoc}//  w  w  w.j a  va  2s . c  o  m
 */
public String execute(CommandLine commandLine) throws Exception {
    InputStream in = null;
    OutputStream out = null;
    FileSystemManager fsManager = null;
    try {
        String file = commandLine.getValue(Options.FILE_OPTION);

        fsManager = VFS.getManager();
        FileObject fileObject = fsManager.resolveFile(file);
        FileObject tempFile = fsManager
                .resolveFile(SystemUtils.JAVA_IO_TMPDIR + "/eclim/" + fileObject.getName().getPath());

        // the vfs file cache isn't very intelligent, so clear it.
        fsManager.getFilesCache().clear(fileObject.getFileSystem());
        fsManager.getFilesCache().clear(tempFile.getFileSystem());

        // NOTE: FileObject.getName().getPath() does not include the drive
        // information.
        String path = tempFile.getName().getURI().substring(URI_PREFIX.length());
        // account for windows uri which has an extra '/' in front of the drive
        // letter (file:///C:/blah/blah/blah).
        if (WIN_PATH.matcher(path).matches()) {
            path = path.substring(1);
        }

        //if(!tempFile.exists()){
        tempFile.createFile();

        in = fileObject.getContent().getInputStream();
        out = tempFile.getContent().getOutputStream();
        IOUtils.copy(in, out);

        new File(path).deleteOnExit();
        //}

        return path;
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

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

public GatherArchive save(GatherArchive envelopeToSave) {
    try {//  w ww . ja  v  a 2 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.jahia.services.content.impl.vfs.VFSNodeImpl.java

public Node addNode(String name, String type)
        throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException,
        VersionException, ConstraintViolationException, RepositoryException {
    try {//from   w  ww .  ja v a2 s.  co m
        if (type.equals(Constants.NT_FOLDER) || type.equals(Constants.JAHIANT_FOLDER)
                || type.equals(Constants.JAHIANT_CONTENTLIST)) {
            FileObject obj = fileObject.resolveFile(name);
            obj.createFolder();
            return new VFSNodeImpl(obj, session);
        } else if (type.equals(Constants.NT_FILE) || type.equals(Constants.JAHIANT_FILE)) {
            FileObject obj = fileObject.resolveFile(name);
            obj.createFile();
            return new VFSNodeImpl(obj, session);
        } else if (type.equals(Constants.NT_RESOURCE)) {
            // 
        }
    } catch (FileSystemException e) {
        throw new RepositoryException("Cannot add node", e);
    }
    return null;
}

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

public CommandResponse actionUploadFile(CommandRequest request) throws IOException {
    if (uploadFileAllowed || getUserStatus().isRootUser()) {
        FileObject currentDir = getCurrentDir();
        if (currentDir != null && currentDir.isWriteable()) {
            File file = (File) request.getFilesByParamName().get("file");
            if (file != null) {
                String fileName = file.getName();
                FileObject fileObject = currentDir.resolveFile(fileName);
                if (!fileObject.exists()) {
                    fileObject.createFile();
                    OutputStream os = fileObject.getContent().getOutputStream(true);
                    InputStream is = new BufferedInputStream(new FileInputStream(file));
                    IOUtils.copy(is, os);
                    is.close();//from   w ww .  ja va  2  s.c  o  m
                    os.close();
                    currentFilePath = fileObject.getName().getPath();
                    return getCommonResponse(request);
                } else {
                    //TODO: Deal with errors
                }
            }
        }
    }
    //TODO: Deal with permission error
    return getCommonResponse(request);
}

From source file:org.jclouds.vfs.tools.blobstore.BlobStoreShell.java

/**
 * Does a 'touch' command.//w w w .j a v  a2  s  .  com
 */
private void touch(final String[] cmd) throws Exception {
    if (cmd.length < 2) {
        throw new Exception("USAGE: touch <path>");
    }
    final FileObject file = remoteMgr.resolveFile(remoteCwd, cmd[1]);
    if (!file.exists()) {
        file.createFile();
    }
    file.getContent().setLastModifiedTime(System.currentTimeMillis());
}

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();
        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());//w  w w.  j a va2 s  .com
        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.openbi.kettle.plugins.refreshtableauextract.RefreshTableauExtract.java

private FileObject createTemporaryShellFile(FileObject tempFile, String fileContent) throws Exception {
    // Create a unique new temporary filename in the working directory, put the script in there
    // Set the permissions to execute and then run it...
    ////from   ww w .  java 2 s . com
    if (tempFile != null && fileContent != null) {
        try {
            tempFile.createFile();
            OutputStream outputStream = tempFile.getContent().getOutputStream();
            outputStream.write(fileContent.getBytes());
            outputStream.close();
            if (!Const.getOS().startsWith("Windows")) {
                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(log, proc.getErrorStream(),
                        toString() + " (stderr)");
                StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(),
                        toString() + " (stdout)");
                new Thread(errorLogger).start();
                new Thread(outputLogger).start();
                proc.waitFor();
            }

        } catch (Exception e) {
            throw new Exception("Unable to create temporary file to execute script", e);
        }
    }
    return tempFile;
}

From source file:org.ow2.proactive.scripting.helper.filetransfer.driver.SFTP_VFS_Driver.java

public void putFile(String localPathFile, String remoteFolder) throws Exception {
    if (remoteFolder == "")
        remoteFolder = ".";

    debug("Putting file " + localPathFile + " to " + remoteFolder);

    //--Setup the SCP connection
    connect();/*from w w  w .  j a va2 s.co m*/

    //--Define paths
    //      String localFolder = FileTransfertUtils.getFolderFromPathfile(localPathFile);
    String fileName = new File(localPathFile).getName();

    // we first set strict key checking off
    FileSystemOptions fsOptions = new FileSystemOptions();
    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, "no");
    // now we create a new filesystem manager

    // the url is of form sftp://user:pass@host/remotepath/
    String uri = "sftp://" + _user + ":" + _pass + "@" + _host + "/" + remoteFolder + "/" + fileName;
    // get file object representing the local file
    FileObject fo = fsManager.resolveFile(uri, fsOptions);
    fo.createFile();
    OutputStream os = fo.getContent().getOutputStream();
    BufferedInputStream is = new BufferedInputStream(new FileInputStream(new File(localPathFile)));

    int c;
    // do copying
    while ((c = is.read()) != -1) {
        os.write(c);
    }
    os.close();
    is.close();
    fo.close();

    debug("File copied :" + localPathFile + " to " + remoteFolder);

    //--Logout and disconnect
    disconnect();

}