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

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

Introduction

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

Prototype

void createFolder() throws FileSystemException;

Source Link

Document

Creates this folder, if it does not exist.

Usage

From source file:net.sf.jabb.web.action.VfsTreeAction.java

/**
 * AJAX tree functions//from w  w  w  . j av a  2  s. c  o  m
 */
public String execute() {
    normalizeTreeRequest();
    JsTreeResult result = new JsTreeResult();

    final AllFileSelector ALL_FILES = new AllFileSelector();
    FileSystemManager fsManager = null;
    FileObject rootFile = null;
    FileObject file = null;
    FileObject referenceFile = null;
    try {
        fsManager = VfsUtility.getManager();
        rootFile = fsManager.resolveFile(rootPath, fsOptions);

        if (JsTreeRequest.OP_GET_CHILDREN.equalsIgnoreCase(requestData.getOperation())) {
            String parentPath = requestData.getId();
            List<JsTreeNodeData> nodes = null;
            try {
                nodes = getChildNodes(rootFile, parentPath);
                if (requestData.isRoot() && rootNodeName != null) { // add root node
                    JsTreeNodeData rootNode = new JsTreeNodeData();
                    rootNode.setData(rootNodeName);
                    Map<String, Object> attr = new HashMap<String, Object>();
                    rootNode.setAttr(attr);
                    attr.put("id", ".");
                    attr.put("rel", "root");
                    attr.put("fileType", FileType.FOLDER.toString());
                    rootNode.setChildren(nodes);
                    rootNode.setState(JsTreeNodeData.STATE_OPEN);
                    nodes = new LinkedList<JsTreeNodeData>();
                    nodes.add(rootNode);
                }
            } catch (Exception e) {
                log.error("Cannot get child nodes for: " + parentPath, e);
                nodes = new LinkedList<JsTreeNodeData>();
            }
            responseData = nodes;
        } else if (JsTreeRequest.OP_REMOVE_NODE.equalsIgnoreCase(requestData.getOperation())) {
            String path = requestData.getId();
            try {
                file = rootFile.resolveFile(path, NameScope.DESCENDENT);
                boolean wasDeleted = false;
                if (file.getType() == FileType.FILE) {
                    wasDeleted = file.delete();
                } else {
                    wasDeleted = file.delete(ALL_FILES) > 0;
                }
                result.setStatus(wasDeleted);
            } catch (Exception e) {
                result.setStatus(false);
                log.error("Cannot delete: " + path, e);
            }
            responseData = result;
        } else if (JsTreeRequest.OP_CREATE_NODE.equalsIgnoreCase(requestData.getOperation())) {
            String parentPath = requestData.getReferenceId();
            String name = requestData.getTitle();
            try {
                referenceFile = rootFile.resolveFile(parentPath, NameScope.DESCENDENT_OR_SELF);
                file = referenceFile.resolveFile(name, NameScope.CHILD);
                file.createFolder();
                result.setStatus(true);
                result.setId(rootFile.getName().getRelativeName(file.getName()));
            } catch (Exception e) {
                result.setStatus(false);
                log.error("Cannot create folder '" + name + "' under '" + parentPath + "'", e);
            }
            responseData = result;
        } else if (JsTreeRequest.OP_RENAME_NODE.equalsIgnoreCase(requestData.getOperation())) {
            String path = requestData.getId();
            String name = requestData.getTitle();
            try {
                referenceFile = rootFile.resolveFile(path, NameScope.DESCENDENT);
                file = referenceFile.getParent().resolveFile(name, NameScope.CHILD);
                referenceFile.moveTo(file);
                result.setStatus(true);
            } catch (Exception e) {
                result.setStatus(false);
                log.error("Cannot rename '" + path + "' to '" + name + "'", e);
            }
            responseData = result;
        } else if (JsTreeRequest.OP_MOVE_NODE.equalsIgnoreCase(requestData.getOperation())) {
            String newParentPath = requestData.getReferenceId();
            String originalPath = requestData.getId();
            try {
                referenceFile = rootFile.resolveFile(originalPath, NameScope.DESCENDENT);
                file = rootFile.resolveFile(newParentPath, NameScope.DESCENDENT_OR_SELF)
                        .resolveFile(referenceFile.getName().getBaseName(), NameScope.CHILD);
                if (requestData.isCopy()) {
                    file.copyFrom(referenceFile, ALL_FILES);
                } else {
                    referenceFile.moveTo(file);
                }
                result.setStatus(true);
            } catch (Exception e) {
                result.setStatus(false);
                log.error("Cannot move '" + originalPath + "' to '" + newParentPath + "'", e);
            }
            responseData = result;
        }
    } catch (FileSystemException e) {
        log.error("Cannot perform file operation.", e);
    } finally {
        VfsUtility.close(fsManager, file, referenceFile, rootFile);
    }
    return SUCCESS;
}

From source file:com.sonicle.webtop.mail.Service.java

public void processRequestCloudFile(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    try {//from   w w  w.  jav a 2s .  co  m
        String subject = ServletUtils.getStringParameter(request, "subject", true);
        String path = "/Uploads";
        int sid = vfsmanager.getMyDocumentsStoreId();
        FileObject fo = vfsmanager.getStoreFile(sid, path);
        if (!fo.exists())
            fo.createFolder();

        String dirname = PathUtils
                .sanitizeFolderName(DateTimeUtils.createYmdHmsFormatter(environment.getProfile().getTimeZone())
                        .print(DateTimeUtils.now()) + " - " + subject);

        FileObject dir = fo.resolveFile(dirname);
        if (!dir.exists())
            dir.createFolder();

        JsonResult jsres = new JsonResult();
        jsres.put("storeId", sid);
        jsres.put("filePath", path + "/" + dirname + "/");
        jsres.printTo(out);
    } catch (Exception ex) {
        logger.error("Request cloud file failure", ex);
        new JsonResult(ex).printTo(out);
    }
}

From source file:org.aludratest.service.file.impl.AbstractFileAction.java

protected void getOrCreateDirectory(FileObject directory) {
    FileObject root = configuration.getRootFolder();
    if (!root.equals(directory)) {
        try {//from ww w.  j  av  a2  s.  c om
            getOrCreateDirectory(directory.getParent());
            directory.createFolder();
        } catch (IOException e) {
            throw new TechnicalException("Error creating directory", e);
        }
    }
}

From source file:org.aludratest.service.file.impl.FileActionImpl.java

private void getOrCreateDirectory(FileObject directory) {
    FileObject root = configuration.getRootFolder();
    if (!root.equals(directory)) {
        try {/*from ww  w .jav a2  s.  co  m*/
            getOrCreateDirectory(directory.getParent());
            directory.createFolder();
        } catch (FileSystemException e) {
            throw new TechnicalException("Error creating directory", e);
        }
    }
}

From source file:org.anarres.filechooser.impl.vfs2.VFSJFileChooserTest.java

@Test
public void testFileChooser() throws Exception {
    StandardFileSystemManager manager = new StandardFileSystemManager();
    manager.init();/*from  w w w  . j  a  v  a2  s  .  com*/

    final FileObject root = manager.resolveFile("ram:/");
    FileObject foo = root.resolveFile("foo");
    foo.createFolder();
    foo.resolveFile("foo0").createFile();
    foo.resolveFile("foo1").createFile();
    root.resolveFile("bar").createFile();

    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            try {
                CommonsVfs2JFileChooser chooser = new CommonsVfs2JFileChooser();
                chooser.setMultiSelectionEnabled(true);
                chooser.setCurrentDirectory(root);
                VFSJFileChooser.RETURN_TYPE ret = chooser.showOpenDialog(null);
                LOG.info("RETURN_TYPE = " + ret);
                LOG.info("Selected FO  = " + chooser.getSelectedFile());
                LOG.info("Selected FOs = " + Arrays.toString(chooser.getSelectedFiles()));
                print(chooser.getSelectedFile());
                for (FileObject file : chooser.getSelectedFiles()) {
                    print(file);
                }
            } catch (FileSystemException e) {
                throw new RuntimeException(e);
            }
        }
    });

    Robot robot = BasicRobot.robotWithCurrentAwtHierarchy();
    robot.waitForIdle();

    VFSJFileChooserFixture<FileObject> chooser = VFSJFileChooserFinder.<FileObject>findFileChooser()
            .using(robot);
    // Thread.sleep(2000);
    chooser.setCurrentDirectory(foo);
    // Thread.sleep(2000);
    chooser.approve();
}

From source file:org.apache.hadoop.gateway.topology.file.FileTopologyProviderTest.java

private FileObject createDir(String name) throws FileSystemException {
    FileSystemManager fsm = VFS.getManager();
    FileObject dir = fsm.resolveFile(name);
    dir.createFolder();
    assertTrue("Failed to create test dir " + dir.getName().getFriendlyURI(), dir.exists());
    return dir;/* w  w w.  j a  v  a 2s  .  c o  m*/
}

From source file:org.apache.synapse.transport.vfs.VFSTransportListener.java

/**
 * Take specified action to either move or delete the processed file, depending on the outcome
 * @param entry the PollTableEntry for the file that has been processed
 * @param fileObject the FileObject representing the file to be moved or deleted
 *//*from w w  w  .  j  a v a 2  s . c  o  m*/
private void moveOrDeleteAfterProcessing(final PollTableEntry entry, FileObject fileObject,
        FileSystemOptions fso) throws AxisFault {

    String moveToDirectoryURI = null;
    try {
        switch (entry.getLastPollState()) {
        case PollTableEntry.SUCCSESSFUL:
            if (entry.getActionAfterProcess() == PollTableEntry.MOVE) {
                moveToDirectoryURI = entry.getMoveAfterProcess();
                //Postfix the date given timestamp format
                String strSubfoldertimestamp = entry.getSubfolderTimestamp();
                if (strSubfoldertimestamp != null) {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat(strSubfoldertimestamp);
                        String strDateformat = sdf.format(new Date());
                        int iIndex = moveToDirectoryURI.indexOf("?");
                        if (iIndex > -1) {
                            moveToDirectoryURI = moveToDirectoryURI.substring(0, iIndex) + strDateformat
                                    + moveToDirectoryURI.substring(iIndex, moveToDirectoryURI.length());
                        } else {
                            moveToDirectoryURI += strDateformat;
                        }
                    } catch (Exception e) {
                        log.warn("Error generating subfolder name with date", e);
                    }
                }
            }
            break;

        case PollTableEntry.FAILED:
            if (entry.getActionAfterFailure() == PollTableEntry.MOVE) {
                moveToDirectoryURI = entry.getMoveAfterFailure();
            }
            break;

        default:
            return;
        }

        if (moveToDirectoryURI != null) {
            FileObject moveToDirectory = fsManager.resolveFile(moveToDirectoryURI, fso);
            String prefix;
            if (entry.getMoveTimestampFormat() != null) {
                prefix = entry.getMoveTimestampFormat().format(new Date());
            } else {
                prefix = "";
            }

            //Forcefully create the folder(s) if does not exists
            if (entry.isForceCreateFolder() && !moveToDirectory.exists()) {
                moveToDirectory.createFolder();
            }
            FileObject dest = moveToDirectory.resolveFile(prefix + fileObject.getName().getBaseName());
            if (log.isDebugEnabled()) {
                log.debug("Moving to file :" + VFSUtils.maskURLPassword(dest.getName().getURI()));
            }
            try {
                fileObject.moveTo(dest);
            } catch (FileSystemException e) {
                handleException("Error moving file : " + VFSUtils.maskURLPassword(fileObject.toString())
                        + " to " + VFSUtils.maskURLPassword(moveToDirectoryURI), e);
            } finally {
                try {
                    fileObject.close();
                } catch (FileSystemException ignore) {
                }
            }
        } else {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Deleting file :" + VFSUtils.maskURLPassword(fileObject.toString()));
                }
                fileObject.close();
                if (!fileObject.delete()) {
                    String msg = "Cannot delete file : " + VFSUtils.maskURLPassword(fileObject.toString());
                    log.error(msg);
                    throw new AxisFault(msg);
                }
            } catch (FileSystemException e) {
                log.error("Error deleting file : " + VFSUtils.maskURLPassword(fileObject.toString()), e);
            }
        }

    } catch (FileSystemException e) {
        handleException("Error resolving directory to move after processing : "
                + VFSUtils.maskURLPassword(moveToDirectoryURI), e);
    }
}

From source file:org.apache.synapse.transport.vfs.VFSTransportSender.java

private void writeFile(MessageContext msgCtx, VFSOutTransportInfo vfsOutInfo) throws AxisFault {

    FileSystemOptions fso = null;/*from ww  w .j  a  va2 s. c o  m*/
    try {
        fso = VFSUtils.attachFileSystemOptions(vfsOutInfo.getOutFileSystemOptionsMap(), fsManager);
    } catch (Exception e) {
        log.error("Error while attaching VFS file system properties. " + e.getMessage());
    }

    if (vfsOutInfo != null) {
        FileObject replyFile = null;
        try {

            boolean wasError = true;
            int retryCount = 0;
            int maxRetryCount = vfsOutInfo.getMaxRetryCount();
            long reconnectionTimeout = vfsOutInfo.getReconnectTimeout();
            boolean append = vfsOutInfo.isAppend();

            while (wasError) {

                try {
                    retryCount++;
                    replyFile = fsManager.resolveFile(vfsOutInfo.getOutFileURI(), fso);

                    if (replyFile == null) {
                        log.error("replyFile is null");
                        throw new FileSystemException("replyFile is null");
                    }
                    wasError = false;

                } catch (FileSystemException e) {
                    log.error("cannot resolve replyFile", e);
                    if (maxRetryCount <= retryCount) {
                        handleException("cannot resolve replyFile repeatedly: " + e.getMessage(), e);
                    }
                }

                if (wasError) {
                    try {
                        Thread.sleep(reconnectionTimeout);
                    } catch (InterruptedException e2) {
                        e2.printStackTrace();
                    }
                }
            }

            //If the reply folder does not exists create the folder structure
            if (vfsOutInfo.isForceCreateFolder()) {
                String strPath = vfsOutInfo.getOutFileURI();
                int iIndex = strPath.indexOf("?");
                if (iIndex > -1) {
                    strPath = strPath.substring(0, iIndex);
                }
                //Need to add a slash otherwise vfs consider this as a file
                if (!strPath.endsWith("/") || !strPath.endsWith("\\")) {
                    strPath += "/";
                }
                FileObject replyFolder = fsManager.resolveFile(strPath, fso);
                if (!replyFolder.exists()) {
                    replyFile.createFolder();
                }
            }

            if (replyFile.exists()) {
                if (replyFile.getType() == FileType.FOLDER) {
                    // we need to write a file containing the message to this folder
                    FileObject responseFile = fsManager.resolveFile(replyFile,
                            VFSUtils.getFileName(msgCtx, vfsOutInfo));

                    // if file locking is not disabled acquire the lock
                    // before uploading the file
                    if (vfsOutInfo.isFileLockingEnabled()) {
                        acquireLockForSending(responseFile, vfsOutInfo, fso);
                        if (!responseFile.exists()) {
                            responseFile.createFile();
                        }
                        populateResponseFile(responseFile, msgCtx, append, true, fso);
                        VFSUtils.releaseLock(fsManager, responseFile, fso);
                    } else {
                        if (!responseFile.exists()) {
                            responseFile.createFile();
                        }
                        populateResponseFile(responseFile, msgCtx, append, false, fso);
                    }

                } else if (replyFile.getType() == FileType.FILE) {

                    // if file locking is not disabled acquire the lock
                    // before uploading the file
                    if (vfsOutInfo.isFileLockingEnabled()) {
                        acquireLockForSending(replyFile, vfsOutInfo, fso);
                        populateResponseFile(replyFile, msgCtx, append, true, fso);
                        VFSUtils.releaseLock(fsManager, replyFile, fso);
                    } else {
                        populateResponseFile(replyFile, msgCtx, append, false, fso);
                    }

                } else {
                    handleException("Unsupported reply file type : " + replyFile.getType() + " for file : "
                            + VFSUtils.maskURLPassword(vfsOutInfo.getOutFileURI()));
                }
            } else {
                // if file locking is not disabled acquire the lock before uploading the file
                if (vfsOutInfo.isFileLockingEnabled()) {
                    acquireLockForSending(replyFile, vfsOutInfo, fso);
                    replyFile.createFile();
                    populateResponseFile(replyFile, msgCtx, append, true, fso);
                    VFSUtils.releaseLock(fsManager, replyFile, fso);
                } else {
                    replyFile.createFile();
                    populateResponseFile(replyFile, msgCtx, append, false, fso);
                }
            }
        } catch (FileSystemException e) {
            handleException(
                    "Error resolving reply file : " + VFSUtils.maskURLPassword(vfsOutInfo.getOutFileURI()), e);
        } finally {
            if (replyFile != null) {
                try {/*
                     if (fsManager != null && replyFile.getParent() != null && replyFile.getParent().getFileSystem() != null) {
                     fsManager.closeFileSystem(replyFile.getParent().getFileSystem());
                     }*/
                    replyFile.close();
                } catch (FileSystemException ignore) {
                }
            }
        }
    } else {
        handleException("Unable to determine out transport information to send message");
    }
}

From source file:org.apache.zeppelin.notebook.repo.OldVFSNotebookRepo.java

protected void setNotebookDirectory(String notebookDirPath) throws IOException {
    try {/*from  w w  w  . ja  v a  2s  . c o  m*/
        LOG.info("Using notebookDir: " + notebookDirPath);
        if (conf.isWindowsPath(notebookDirPath)) {
            filesystemRoot = new File(notebookDirPath).toURI();
        } else {
            filesystemRoot = new URI(notebookDirPath);
        }
    } catch (URISyntaxException e1) {
        throw new IOException(e1);
    }

    if (filesystemRoot.getScheme() == null) { // it is local path
        File f = new File(conf.getRelativeDir(filesystemRoot.getPath()));
        this.filesystemRoot = f.toURI();
    }

    fsManager = VFS.getManager();
    FileObject file = fsManager.resolveFile(filesystemRoot.getPath());
    if (!file.exists()) {
        LOG.info("Notebook dir doesn't exist, create on is {}.", file.getName());
        file.createFolder();
    }
}

From source file:org.apache.zeppelin.notebook.repo.OldVFSNotebookRepo.java

@Override
public synchronized void save(Note note, AuthenticationInfo subject) throws IOException {
    LOG.info("Saving note:" + note.getId());
    String json = note.toJson();/*from w  w w  .j  a va2s  . com*/

    FileObject rootDir = getRootDir();

    FileObject noteDir = rootDir.resolveFile(note.getId(), NameScope.CHILD);

    if (!noteDir.exists()) {
        noteDir.createFolder();
    }
    if (!isDirectory(noteDir)) {
        throw new IOException(noteDir.getName().toString() + " is not a directory");
    }

    FileObject noteJson = noteDir.resolveFile(".note.json", NameScope.CHILD);
    // false means not appending. creates file if not exists
    OutputStream out = noteJson.getContent().getOutputStream(false);
    out.write(json.getBytes(conf.getString(ConfVars.ZEPPELIN_ENCODING)));
    out.close();
    noteJson.moveTo(noteDir.resolveFile("note.json", NameScope.CHILD));
}