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

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

Introduction

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

Prototype

FileObject resolveFile(String path) throws FileSystemException;

Source Link

Document

Finds a file, relative to this file.

Usage

From source file:org.pentaho.reporting.designer.extensions.pentaho.drilldown.PentahoParameterRefreshHandler.java

private static String getParameterServicePath(final AuthenticationData loginData,
        final PentahoPathModel pathModel) {
    try {//from w ww.j a  v a  2 s .c  o m
        final FileObject fileSystemRoot = PublishUtil.createVFSConnection(VFS.getManager(), loginData);
        final FileSystem fileSystem = fileSystemRoot.getFileSystem();

        // as of version 3.7 we do not need to check anything other than that the version information is there
        // later we may have to add additional checks in here to filter out known broken versions.

        final String localPath = pathModel.getLocalPath();
        final FileObject object = fileSystemRoot.resolveFile(localPath);
        final FileContent content = object.getContent();
        final String majorVersionText = (String) fileSystem.getAttribute(WebSolutionFileSystem.MAJOR_VERSION);

        if (StringUtils.isEmpty(majorVersionText) == false) {
            final String paramService = (String) content.getAttribute("param-service-url");
            if (StringUtils.isEmpty(paramService)) {
                return null;
            }
            if (paramService.startsWith("http://") || paramService.startsWith("https://")) {
                return paramService;
            }

            try {
                // Encode the URL (must use URI as URL encoding doesn't work on spaces correctly)
                final URL target = new URL(loginData.getUrl());
                final String host;
                if (target.getPort() != -1) {
                    host = target.getHost() + ":" + target.getPort();
                } else {
                    host = target.getHost();
                }

                return target.getProtocol() + "://" + host + paramService;
            } catch (MalformedURLException e) {
                UncaughtExceptionsModel.getInstance().addException(e);
                return null;
            }
        }

        final String extension = IOUtils.getInstance().getFileExtension(localPath);
        if (".prpt".equals(extension)) {
            logger.debug(
                    "Ancient pentaho system detected: parameter service does not deliver valid parameter values");

            final String name = pathModel.getName();
            final String path = pathModel.getPath();
            final String solution = pathModel.getSolution();

            final FastMessageFormat messageFormat = new FastMessageFormat(
                    "/content/reporting/?renderMode=XML&solution={0}&path={1}&name={2}");
            messageFormat.setNullString("");
            return loginData.getUrl() + messageFormat.format(new Object[] { solution, path, name });
        }

        logger.debug("Ancient pentaho system detected: We will not have access to a working parameter service");
        return null;
    } catch (FileSystemException e) {
        UncaughtExceptionsModel.getInstance().addException(e);
        return null;
    }
}

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

protected boolean validateInputs(final boolean onConfirm) {
    if (super.validateInputs(onConfirm) == false) {
        return false;
    }//from w  w  w.j a  va 2  s  .  c  o  m

    if (onConfirm == false) {
        return true;
    }

    final String reportName = getFileNameTextField().getText();
    if (StringUtils.isEmpty(reportName) == false && reportName.endsWith(REPORT_BUNDLE_EXTENSION) == false) {
        final String safeReportName = reportName + REPORT_BUNDLE_EXTENSION;
        getFileNameTextField().setText(safeReportName);
    }

    try {
        final FileObject selectedView = getSelectedView();
        final String validateName = getSelectedFile();
        if (validateName == null || selectedView == null) {
            return false;
        }

        String filename = getFileNameTextField().getText();
        if (!PublishUtil.validateName(filename)) {
            JOptionPane.showMessageDialog(RepositoryPublishDialog.this,
                    Messages.getInstance().formatMessage("PublishToServerAction.IllegalName", filename,
                            PublishUtil.getReservedCharsDisplay()),
                    Messages.getInstance().getString("PublishToServerAction.Error.Title"),
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }

        final FileObject targetFile = selectedView
                .resolveFile(URLEncoder.encodeUTF8(getFileNameTextField().getText()).replaceAll(":", "%3A")
                        .replaceAll("\\+", "%2B").replaceAll("\\!", "%21"));
        final FileObject fileObject = selectedView.getFileSystem().resolveFile(targetFile.getName());
        if (fileObject.getType() == FileType.IMAGINARY) {
            return true;
        }

        final int result = JOptionPane.showConfirmDialog(this,
                Messages.getInstance().formatMessage("PublishToServerAction.FileExistsOverride", validateName),
                Messages.getInstance().getString("PublishToServerAction.Information.Title"),
                JOptionPane.YES_NO_OPTION);
        return result == JOptionPane.YES_OPTION;
    } catch (FileSystemException fse) {
        UncaughtExceptionsModel.getInstance().addException(fse);
        return false;
    } catch (UnsupportedEncodingException uee) {
        UncaughtExceptionsModel.getInstance().addException(uee);
        return false;
    }
}

From source file:org.pentaho.reporting.designer.extensions.pentaho.repository.util.PublishUtil.java

public static ReportRenderContext openReport(final ReportDesignerContext context,
        final AuthenticationData loginData, final String path)
        throws IOException, ReportDataFactoryException, ResourceException {
    if (StringUtils.isEmpty(path)) {
        throw new IOException("Path is empty.");
    }//  ww  w .  j a v  a 2  s  . co m

    final String urlPath = path.replaceAll("%", "%25").replaceAll("%2B", "+").replaceAll("\\!", "%21")
            .replaceAll(":", "%3A");
    final FileObject connection = createVFSConnection(loginData);
    final FileObject object = connection.resolveFile(urlPath);
    if (object.exists() == false) {
        throw new FileNotFoundException(path);
    }

    final InputStream inputStream = object.getContent().getInputStream();
    try {
        final ByteArrayOutputStream out = new ByteArrayOutputStream(
                Math.max(8192, (int) object.getContent().getSize()));
        IOUtils.getInstance().copyStreams(inputStream, out);
        final MasterReport report = loadReport(out.toByteArray(), path);
        final int index = context.addMasterReport(report);
        return context.getReportRenderContext(index);
    } finally {
        inputStream.close();
    }
}

From source file:org.pentaho.reporting.designer.extensions.pentaho.repository.util.PublishUtil.java

public static int publish(final byte[] data, final String path, final AuthenticationData loginData)
        throws IOException {
    int responseCode = HTTP_RESPONSE_FAIL;
    final String versionText = loginData.getOption(SERVER_VERSION);
    final int version = ParserUtil.parseInt(versionText, SERVER_VERSION_SUGAR);

    if (SERVER_VERSION_SUGAR == version) {
        PublishRestUtil publishRestUtil = new PublishRestUtil(loginData.getUrl(), loginData.getUsername(),
                loginData.getPassword());
        responseCode = publishRestUtil.publishFile(path, data, true);

    } else {/*from   w w  w. jav a 2 s  . c  o  m*/
        final FileObject connection = createVFSConnection(loginData);
        final FileObject object = connection.resolveFile(path);
        final OutputStream out = object.getContent().getOutputStream(false);
        try {
            out.write(data);
            responseCode = HTTP_RESPONSE_OK;
        } finally {
            out.close();
        }
    }
    return responseCode;
}

From source file:org.pentaho.vfs.test.FileChooserTest.java

public static void main(String args[]) {
    FileSystemManager fsManager = null;/*from  w w w.j a  v  a  2s .co m*/
    FileObject maybeRootFile = null;
    try {
        fsManager = VFS.getManager();
        if (fsManager instanceof DefaultFileSystemManager) {
            File f = new File("."); //$NON-NLS-1$
            try {
                ((DefaultFileSystemManager) fsManager).setBaseFile(f.getCanonicalFile());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //maybeRootFile = fsManager.resolveFile("jar:lib/mail-1.3.2.jar"); //$NON-NLS-1$
        // rootFile = fsManager.resolveFile("file:/home/mdamour/workspace/apache-vfs-browser");
        maybeRootFile = fsManager.resolveFile("file:///c:/");
        // maybeRootFile = fsManager.resolveFile("jar:lib/mail.jar");
        // maybeRootFile = fsManager.resolveFile("ftp://ftpgolden.pentaho.org/");

        // maybeRootFile.getFileSystem().getParentLayer().

        // maybeRootFile.getFileSystem().getFileSystemManager().gets

    } catch (Exception e) {
        e.printStackTrace();
    }
    final FileObject rootFile = maybeRootFile;
    final Shell applicationShell = new Shell(SWT.SHELL_TRIM | SWT.CLOSE | SWT.MIN | SWT.MAX);
    applicationShell.setLayout(new FillLayout());
    applicationShell.setText(Messages.getString("FileChooserTest.application")); //$NON-NLS-1$
    applicationShell.setSize(640, 400);
    Menu bar = new Menu(applicationShell, SWT.BAR);
    applicationShell.setMenuBar(bar);
    MenuItem fileItem = new MenuItem(bar, SWT.CASCADE);
    fileItem.setText(Messages.getString("FileChooserTest.file")); //$NON-NLS-1$
    fileItem.setAccelerator(SWT.CTRL + 'F');
    Menu fileSubMenu = new Menu(applicationShell, SWT.DROP_DOWN);
    fileItem.setMenu(fileSubMenu);
    MenuItem fileOpenItem = new MenuItem(fileSubMenu, SWT.CASCADE);
    fileOpenItem.setText(Messages.getString("FileChooserTest.open")); //$NON-NLS-1$
    fileOpenItem.setAccelerator(SWT.CTRL + 'O');
    final String filters[] = new String[] { "*.*", "*.xml;*.XML;", "*.class", "*.map" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
    final String filterNames[] = new String[] { Messages.getString("FileChooserTest.allFiles"), //$NON-NLS-1$
            Messages.getString("FileChooserTest.xmlFiles"), Messages.getString("FileChooserTest.javaFiles"), //$NON-NLS-1$//$NON-NLS-2$
            Messages.getString("FileChooserTest.mapFiles") }; //$NON-NLS-1$
    fileOpenItem.addSelectionListener(new SelectionListener() {
        public void widgetDefaultSelected(SelectionEvent arg0) {
        }

        public void widgetSelected(SelectionEvent arg0) {
            FileObject initialFile = rootFile;
            // try {
            // // initialFile = rootFile.resolveFile("/home/mdamour");
            // } catch (FileSystemException e) {
            // e.printStackTrace();
            // }
            try {
                VfsFileChooserDialog fileOpenDialog = new VfsFileChooserDialog(applicationShell,
                        VFS.getManager(), rootFile, initialFile);
                fileOpenDialog.addVFSUIPanel(buildHDFSPanel("HDFS", fileOpenDialog));
                fileOpenDialog.addVFSUIPanel(buildHDFSPanel("S3", fileOpenDialog));
                fileOpenDialog.addVFSUIPanel(buildHDFSPanel("file", fileOpenDialog));
                FileObject selectedFile = fileOpenDialog.open(applicationShell, null, filters, filterNames,
                        VfsFileChooserDialog.VFS_DIALOG_OPEN_FILE);
                if (selectedFile != null) {
                    System.out.println(
                            Messages.getString("FileChooserTest.selectedFileEquals") + selectedFile.getName()); //$NON-NLS-1$
                } else {
                    System.out.println(Messages.getString("FileChooserTest.noFileSelected")); //$NON-NLS-1$
                }
            } catch (FileSystemException ex) {
                ex.printStackTrace();
            }
        }
    });
    MenuItem saveAsOpenItem = new MenuItem(fileSubMenu, SWT.CASCADE);
    saveAsOpenItem.setText(Messages.getString("FileChooserTest.saveAs")); //$NON-NLS-1$
    saveAsOpenItem.setAccelerator(SWT.CTRL + 'A');
    saveAsOpenItem.addSelectionListener(new SelectionListener() {
        public void widgetDefaultSelected(SelectionEvent arg0) {
        }

        public void widgetSelected(SelectionEvent arg0) {
            FileObject initialFile = null;
            try {
                initialFile = rootFile.resolveFile("/home/mdamour"); //$NON-NLS-1$
            } catch (FileSystemException e) {
                e.printStackTrace();
            }
            try {
                VfsFileChooserDialog fileOpenDialog = new VfsFileChooserDialog(applicationShell,
                        VFS.getManager(), rootFile, initialFile);
                FileObject selectedFile = fileOpenDialog.open(applicationShell,
                        Messages.getString("FileChooserTest.untitled"), filters, filterNames, //$NON-NLS-1$
                        VfsFileChooserDialog.VFS_DIALOG_SAVEAS);
                if (selectedFile != null) {
                    System.out.println(
                            Messages.getString("FileChooserTest.selectedFileEquals") + selectedFile.getName()); //$NON-NLS-1$
                } else {
                    System.out.println(Messages.getString("FileChooserTest.noFileSelected")); //$NON-NLS-1$
                }
            } catch (FileSystemException ex) {
                ex.printStackTrace();
            }
        }
    });
    applicationShell.open();
    while (!applicationShell.isDisposed()) {
        if (!applicationShell.getDisplay().readAndDispatch())
            applicationShell.getDisplay().sleep();
    }
}

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

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

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

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

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

    FileObject tmpInitialFile = initialFile;

    if (defaultInitialFile != null && rootFile == null) {
        try {//from  ww  w . ja v  a 2s  .  c  o m
            rootFile = defaultInitialFile.getFileSystem().getRoot();
            initialFile = defaultInitialFile;
        } catch (FileSystemException ignored) {
            // well we tried
        }
    }

    createDialog(applicationShell);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:org.renjin.primitives.files.Files.java

/**
 * Helper function to extract a zip entry to the given folder.
 *//*from   w w w .j  a va  2 s .co  m*/
private static void unzipExtract(ZipInputStream zin, ZipEntry entry, FileObject exdir, boolean junkpaths,
        boolean overwrite) throws IOException {
    if (junkpaths) {
        throw new EvalException("unzip(junpaths=false) not yet implemented");
    }

    FileObject exfile = exdir.resolveFile(entry.getName());
    if (exfile.exists() && !overwrite) {
        throw new EvalException("file to be extracted '%s' already exists", exfile.getName().getURI());
    }
    OutputStream out = exfile.getContent().getOutputStream();
    try {

        byte buffer[] = new byte[64 * 1024];
        int bytesRead;
        while ((bytesRead = zin.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    } finally {
        out.close();
    }
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.file.FilePollingConsumer.java

/**
 * Do the post processing actions/*from   w w w . j a v  a  2  s . c o  m*/
 * 
 * @param fileObject
 * @throws synapseException
 */
private void moveOrDeleteAfterProcessing(FileObject fileObject) throws SynapseException {

    String moveToDirectoryURI = null;
    try {
        switch (lastCycle) {
        case 1:
            if ("MOVE".equals(vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_ACTION_AFTER_PROCESS))) {
                moveToDirectoryURI = vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_MOVE_AFTER_PROCESS);
                //Postfix the date given timestamp format
                String strSubfoldertimestamp = vfsProperties.getProperty(VFSConstants.SUBFOLDER_TIMESTAMP);
                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 2:
            if ("MOVE".equals(vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_ACTION_AFTER_FAILURE))) {
                moveToDirectoryURI = vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_MOVE_AFTER_FAILURE);
            }
            break;

        default:
            return;
        }

        if (moveToDirectoryURI != null) {
            FileObject moveToDirectory = fsManager.resolveFile(moveToDirectoryURI, fso);
            String prefix;
            if (vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_MOVE_TIMESTAMP_FORMAT) != null) {
                prefix = new SimpleDateFormat(
                        vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_MOVE_TIMESTAMP_FORMAT))
                                .format(new Date());
            } else {
                prefix = "";
            }

            //Forcefully create the folder(s) if does not exists
            String strForceCreateFolder = vfsProperties.getProperty(VFSConstants.FORCE_CREATE_FOLDER);
            if (strForceCreateFolder != null && strForceCreateFolder.toLowerCase().equals("true")
                    && !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);
                if (VFSUtils.isFailRecord(fsManager, fileObject)) {
                    VFSUtils.releaseFail(fsManager, fileObject);
                }
            } catch (FileSystemException e) {
                if (!VFSUtils.isFailRecord(fsManager, fileObject)) {
                    VFSUtils.markFailRecord(fsManager, fileObject);
                }
                log.error("Error moving file : " + VFSUtils.maskURLPassword(fileObject.toString()) + " to "
                        + VFSUtils.maskURLPassword(moveToDirectoryURI), e);
            }
        } 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 SynapseException(msg);
                }
            } catch (FileSystemException e) {
                log.error("Error deleting file : " + VFSUtils.maskURLPassword(fileObject.toString()), e);
            }
        }
    } catch (FileSystemException e) {
        if (!VFSUtils.isFailRecord(fsManager, fileObject)) {
            VFSUtils.markFailRecord(fsManager, fileObject);
            log.error("Error resolving directory to move after processing : "
                    + VFSUtils.maskURLPassword(moveToDirectoryURI), e);
        }
    }
}

From source file:org.wso2.carbon.transport.filesystem.connector.server.FileSystemConsumer.java

/**
 * Do the post processing actions.//from w  w w .j av  a2s . co m
 *
 * @param file The file object which needs to be post processed
 * @param processFailed Whether processing of file failed
 */
synchronized void postProcess(FileObject file, boolean processFailed)
        throws FileSystemServerConnectorException {
    String moveToDirectoryURI = null;
    FileType fileType = getFileType(file);
    if (!processFailed) {
        if (postProcessAction.equals(Constants.ACTION_MOVE)) {
            moveToDirectoryURI = fileProperties.get(Constants.MOVE_AFTER_PROCESS);
        }
    } else {
        if (postFailureAction.equals(Constants.ACTION_MOVE)) {
            moveToDirectoryURI = fileProperties.get(Constants.MOVE_AFTER_FAILURE);
        }
    }

    if (moveToDirectoryURI != null) {
        try {
            if (getFileType(fsManager.resolveFile(moveToDirectoryURI, fso)) == FileType.FILE) {
                moveToDirectoryURI = null;
                if (processFailed) {
                    postFailureAction = Constants.ACTION_NONE;
                } else {
                    postProcessAction = Constants.ACTION_NONE;
                }
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Cannot move file because provided location is not a folder. File is kept at source");
                }
            }
        } catch (FileSystemException e) {
            errorHandler
                    .handleError(
                            new FileSystemServerConnectorException(
                                    "Error occurred when resolving move destination file: "
                                            + FileTransportUtils.maskURLPassword(listeningDirURI),
                                    e),
                            null, null);
        }
    }

    try {
        if (!(moveToDirectoryURI == null || fileType == FileType.FOLDER)) {
            FileObject moveToDirectory;
            String relativeName = file.getName().getURI().split(listeningDir.getName().getURI())[1];
            int index = relativeName.lastIndexOf(File.separator);
            moveToDirectoryURI += relativeName.substring(0, index);
            moveToDirectory = fsManager.resolveFile(moveToDirectoryURI, fso);
            String prefix;
            if (fileProperties.get(Constants.MOVE_TIMESTAMP_FORMAT) != null) {
                prefix = new SimpleDateFormat(fileProperties.get(Constants.MOVE_TIMESTAMP_FORMAT))
                        .format(new Date());
            } else {
                prefix = "";
            }

            //Forcefully create the folder(s) if does not exists
            String strForceCreateFolder = fileProperties.get(Constants.FORCE_CREATE_FOLDER);
            if (strForceCreateFolder != null && strForceCreateFolder.equalsIgnoreCase("true")
                    && !moveToDirectory.exists()) {
                moveToDirectory.createFolder();
            }

            FileObject dest = moveToDirectory.resolveFile(prefix + file.getName().getBaseName());
            if (log.isDebugEnabled()) {
                log.debug("Moving to file :" + FileTransportUtils.maskURLPassword(dest.getName().getURI()));
            }
            if (log.isInfoEnabled()) {
                log.info("Moving file :" + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
            }
            try {
                file.moveTo(dest);
                if (isFailRecord(file)) {
                    releaseFail(file);
                }
            } catch (FileSystemException e) {
                if (!isFailRecord(file)) {
                    markFailRecord(file);
                }
                errorHandler.handleError(
                        new FileSystemServerConnectorException(
                                "Error moving file : " + FileTransportUtils.maskURLPassword(file.toString())
                                        + " to " + FileTransportUtils.maskURLPassword(moveToDirectoryURI),
                                e),
                        null, null);
            }

        } else {
            if (log.isDebugEnabled()) {
                log.debug("Deleting file :" + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
            }
            if (log.isInfoEnabled()) {
                log.info("Deleting file :" + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
            }
            try {
                if (!file.delete()) {
                    if (log.isDebugEnabled()) {
                        log.debug("Could not delete file : "
                                + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
                    }
                } else {
                    if (isFailRecord(file)) {
                        releaseFail(file);
                    }
                }
            } catch (FileSystemException e) {
                errorHandler.handleError(
                        new FileSystemServerConnectorException("Could not delete file : "
                                + FileTransportUtils.maskURLPassword(file.getName().getBaseName()), e),
                        null, null);
            }
        }
    } catch (FileSystemException e) {
        if (!isFailRecord(file)) {
            markFailRecord(file);
            errorHandler.handleError(
                    new FileSystemServerConnectorException("Error resolving directory to move file : "
                            + FileTransportUtils.maskURLPassword(moveToDirectoryURI), e),
                    null, null);
        }
    }
}