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

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

Introduction

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

Prototype

FileObject getParent() throws FileSystemException;

Source Link

Document

Returns the folder that contains this file.

Usage

From source file:org.datacleaner.user.upgrade.DataCleanerHomeUpgrader.java

private static FileObject overwriteFileWithDefaults(FileObject targetDirectory, String targetFilename)
        throws FileSystemException {
    FileObject file = targetDirectory.resolveFile(targetFilename);
    FileObject parentFile = file.getParent();
    if (!parentFile.exists()) {
        parentFile.createFolder();//from ww w .ja  va  2 s. co m
    }

    final ResourceManager resourceManager = ResourceManager.get();
    final URL url = resourceManager.getUrl("datacleaner-home/" + targetFilename);
    if (url == null) {
        return null;
    }

    InputStream in = null;
    OutputStream out = null;
    try {
        in = url.openStream();
        out = file.getContent().getOutputStream();

        FileHelper.copy(in, out);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } finally {
        FileHelper.safeClose(in, out);
    }

    return file;
}

From source file:org.eobjects.datacleaner.actions.SaveAnalysisJobActionListener.java

@Override
public void actionPerformed(ActionEvent event) {
    final String actionCommand = event.getActionCommand();

    _window.setStatusLabelNotice();// w ww  .  j a  va2 s  .c o m
    _window.setStatusLabelText(LABEL_TEXT_SAVING_JOB);

    AnalysisJob analysisJob = null;
    try {
        _window.applyPropertyValues();
        analysisJob = _analysisJobBuilder.toAnalysisJob();
    } catch (Exception e) {
        if ("No Analyzers in job".equals(e.getMessage())) {
            // TODO: Have a better way to diagnose this issue
            int result = JOptionPane.showConfirmDialog(_window.toComponent(),
                    "You job does not have any analyzer components in it, and is thus 'incomplete'. Do you want to save it anyway?",
                    "No analyzers in job", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (result == JOptionPane.YES_OPTION) {
                analysisJob = _analysisJobBuilder.toAnalysisJob(false);
            } else {
                return;
            }
        } else {
            String detail = _window.getStatusLabelText();
            if (LABEL_TEXT_SAVING_JOB.equals(detail)) {
                detail = e.getMessage();
            }
            WidgetUtils.showErrorMessage("Errors in job",
                    "Please fix the errors that exist in the job before saving it:\n\n" + detail, e);
            return;
        }
    }

    final FileObject existingFile = _window.getJobFile();

    final FileObject file;
    if (existingFile == null || ACTION_COMMAND_SAVE_AS.equals(actionCommand)) {
        // ask the user to select a file to save to ("Save as" scenario)
        final DCFileChooser fileChooser = new DCFileChooser(_userPreferences.getAnalysisJobDirectory());
        fileChooser.setFileFilter(FileFilters.ANALYSIS_XML);

        final int result = fileChooser.showSaveDialog(_window.toComponent());
        if (result != JFileChooser.APPROVE_OPTION) {
            return;
        }
        FileObject candidate = fileChooser.getSelectedFileObject();

        final boolean exists;
        try {
            final String baseName = candidate.getName().getBaseName();
            if (!baseName.endsWith(".xml")) {
                final FileObject parent = candidate.getParent();
                file = parent.resolveFile(baseName + FileFilters.ANALYSIS_XML.getExtension());
            } else {
                file = candidate;
            }
            exists = file.exists();
        } catch (FileSystemException e) {
            throw new IllegalStateException("Failed to prepare file for saving", e);
        }

        if (exists) {
            int overwrite = JOptionPane.showConfirmDialog(_window.toComponent(),
                    "Are you sure you want to overwrite the file '" + file.getName() + "'?",
                    "Overwrite existing file?", JOptionPane.YES_NO_OPTION);
            if (overwrite != JOptionPane.YES_OPTION) {
                return;
            }
        }
    } else {
        // overwrite existing file ("Save" scenario).
        file = existingFile;
    }

    try {
        final FileObject parent = file.getParent();
        final File parentFile = VFSUtils.toFile(parent);
        if (parentFile != null) {
            _userPreferences.setAnalysisJobDirectory(parentFile);
        }
    } catch (FileSystemException e) {
        logger.warn("Failed to determine parent of {}: {}", file, e.getMessage());
    }

    final String author = System.getProperty("user.name");
    final String jobName = null;
    final String jobDescription = "Created with DataCleaner " + Version.getEdition() + " "
            + Version.getVersion();
    final String jobVersion = null;

    final JaxbJobWriter writer = new JaxbJobWriter(_configuration,
            new JaxbJobMetadataFactoryImpl(author, jobName, jobDescription, jobVersion));

    OutputStream outputStream = null;
    try {
        outputStream = file.getContent().getOutputStream();
        writer.write(analysisJob, outputStream);
    } catch (IOException e1) {
        throw new IllegalStateException(e1);
    } finally {
        FileHelper.safeClose(outputStream);
    }

    if (file instanceof DelegateFileObject) {
        // this "file" is probably a HTTP URL resource (often provided by DC
        // monitor)
        final DelegateFileObject delegateFileObject = (DelegateFileObject) file;
        final String scheme = file.getName().getScheme();

        if ("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme)) {
            final String uri = delegateFileObject.getName().getURI();
            final MonitorConnection monitorConnection = _userPreferences.getMonitorConnection();
            if (monitorConnection.matchesURI(uri) && monitorConnection.isAuthenticationEnabled()
                    && monitorConnection.getEncodedPassword() == null) {
                // password is not configured, ask for it.
                final MonitorConnectionDialog dialog = new MonitorConnectionDialog(_window.getWindowContext(),
                        _userPreferences);
                dialog.openBlocking();
            }

            final PublishJobToMonitorActionListener publisher = new PublishJobToMonitorActionListener(
                    delegateFileObject, _window.getWindowContext(), _userPreferences);
            publisher.actionPerformed(event);
        } else {
            throw new UnsupportedOperationException("Unexpected delegate file object: " + delegateFileObject
                    + " (delegate: " + delegateFileObject.getDelegateFile() + ")");
        }
    } else {
        _userPreferences.addRecentJobFile(file);
    }

    _window.setJobFile(file);

    _window.setStatusLabelNotice();
    _window.setStatusLabelText("Saved job to file " + file.getName().getBaseName());
}

From source file:org.eobjects.datacleaner.user.DataCleanerHome.java

private static void copyIfNonExisting(FileObject candidate, FileSystemManager manager, String filename)
        throws FileSystemException {
    FileObject file = candidate.resolveFile(filename);
    if (file.exists()) {
        logger.info("File already exists in DATACLEANER_HOME: " + filename);
        return;/*  w ww .jav a 2s .  com*/
    }
    FileObject parentFile = file.getParent();
    if (!parentFile.exists()) {
        parentFile.createFolder();
    }

    final ResourceManager resourceManager = ResourceManager.get();
    final URL url = resourceManager.getUrl("datacleaner-home/" + filename);

    InputStream in = null;
    OutputStream out = null;
    try {
        in = url.openStream();
        out = file.getContent().getOutputStream();

        FileHelper.copy(in, out);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } finally {
        FileHelper.safeClose(in, out);
    }
}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

@Override
public boolean renameFile(String path, String title, SharedUserPortletParameters userParameters) {
    try {//from   w  ww  .ja va 2 s  .c om
        FileObject file = cd(path, userParameters);
        FileObject newFile = file.getParent().resolveFile(title);
        if (!newFile.exists()) {
            file.moveTo(newFile);
            return true;
        } else {
            log.info("file " + title + " already exists !");
        }
    } catch (FileSystemException e) {
        log.info("can't rename file because of FileSystemException : " + e.getMessage(), e);
    }
    return false;
}

From source file:org.freedesktop.wallpapers.Wallpaper.java

public Wallpaper(FileObject... base) throws IOException, ParseException {
    super(WALLPAPER, base);
    for (FileObject b : base) {
        FileObject f = b.getParent().resolveFile(b.getName() + ".desktop");
        if (f.exists()) {
            themeFile = f;/*from   w w w. j a v a 2s .  c o  m*/
            break;
        }
    }
    if (themeFile == null) {
        throw new FileNotFoundException();
    }
}

From source file:org.fuin.vfs2.filter.BaseFilterTest.java

/**
 * Creates a file select info object for the given file.
 * /*w w w . j  a  va 2  s  . c o  m*/
 * @param file
 *            File to create an info for.
 * 
 * @return File selct info.
 */
protected static FileSelectInfo createFSI(final File file) {
    try {
        final FileSystemManager fsManager = VFS.getManager();
        final FileObject fileObject = fsManager.toFileObject(file);
        return new FileSelectInfo() {
            @Override
            public FileObject getFile() {
                return fileObject;
            }

            @Override
            public int getDepth() {
                return 0;
            }

            @Override
            public FileObject getBaseFolder() {
                try {
                    return fileObject.getParent();
                } catch (FileSystemException ex) {
                    throw new RuntimeException(ex);
                }
            }
        };
    } catch (FileSystemException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

/**
 * Allows to know the nodetype associated to a filetype.
 *
 * @param fileObject the file object that we want to know the associated nodetype
 * @return the associated nodetype//from   w w w  . j  av  a2 s.  c o m
 * @throws FileSystemException
 */
@Override
public String getDataType(FileObject fileObject) throws FileSystemException {
    String relativeName = getFile("/").getName().getRelativeName(fileObject.getName());
    int relativeDepth = ".".equals(relativeName) ? 0 : StringUtils.split(relativeName, "/").length;
    String type = null;
    if (fileObject.getType().equals(FileType.FOLDER)) {
        if (relativeDepth == ROOT_DEPTH_TOKEN) {
            // we are in root
            type = Constants.JAHIANT_MODULEVERSIONFOLDER;
        } else {
            if (relativeDepth == TARGET_DEPTH_TOKEN
                    && StringUtils.equals("target", fileObject.getName().getBaseName())) {
                type = "jnt:mavenTargetFolder";
            } else if (StringUtils.equals("resources", fileObject.getName().getBaseName())
                    && relativeDepth == SOURCES_DEPTH_TOKEN) {
                type = "jnt:folder";
            } else if (relativeDepth == NODETYPE_FOLDER_DEPTH_TOKEN
                    && isNodeType(fileObject.getName().getBaseName())) {
                type = Constants.JAHIANT_NODETYPEFOLDER;
            } else if (relativeDepth == TEMPLATE_TYPE_FOLDER_DEPTH_TOKEN) {
                FileObject parent = fileObject.getParent();
                if (parent != null && Constants.JAHIANT_NODETYPEFOLDER.equals(getDataType(parent))) {
                    type = Constants.JAHIANT_TEMPLATETYPEFOLDER;
                }
            } else if (StringUtils.split(relativeName, "/").length >= SOURCES_DEPTH_TOKEN && StringUtils
                    .equals(StringUtils.split(relativeName, "/")[SOURCES_DEPTH_TOKEN - 1], "java")) {
                type = "jnt:javaPackageFolder";
            }
        }
        if (type == null) {
            type = folderTypeMapping.get(fileObject.getName().getBaseName());
        }
    } else {
        String extension = fileObject.getName().getExtension();
        if (StringUtils.isNotEmpty(extension)) {
            type = fileTypeMapping.get(extension);
            if (type == null) {
                try {
                    if (ScriptEngineUtils.canFactoryForExtensionProcessViews(extension,
                            module.getBundle().getHeaders())) {
                        type = Constants.JAHIANT_VIEWFILE;
                    }
                } catch (IllegalArgumentException e) {
                    // ignore: no ScriptEngineFactory exists for the provided extension
                }
            }
        }

    }
    if (type != null && StringUtils.equals(type, "jnt:propertiesFile")) {
        // we've detected a properties file, check if its parent is of type jnt:resourceBundleFolder
        // -> than this one gets the type jnt:resourceBundleFile; otherwise just jnt:file
        FileObject parent = fileObject.getParent();
        type = parent != null
                && StringUtils.equals(Constants.JAHIANT_RESOURCEBUNDLE_FOLDER, getDataType(parent))
                        ? Constants.JAHIANT_RESOURCEBUNDLE_FILE
                        : type;
    }
    boolean isFile = fileObject.getType() == FileType.FILE;
    if (isFile && relativeDepth == VIEWS_FOLDER_DEPTH_TOKEN && (fileObject.getParent() != null
            && StringUtils.equals(Constants.JAHIANT_TEMPLATETYPEFOLDER, getDataType(fileObject.getParent())))) {
        if (StringUtils.endsWith(fileObject.getName().toString(), PROPERTIES_EXTENSION)) {
            type = JNT_EDITABLE_FILE;
        } else {
            type = Constants.JAHIANT_VIEWFILE;
        }
    }

    String contentType = getContentType(fileObject.getContent());
    if (type == null && isFile) {
        boolean isMedia = contentType != null && (contentType.contains("image") || contentType.contains("video")
                || contentType.contains("audio") || contentType.contains("flash"));
        if (!isMedia) {
            type = JNT_EDITABLE_FILE;
        }
    }

    // in case of the file name ends with .xml.generated we should have no type.
    if (StringUtils.endsWith(fileObject.getName().toString(), ".xml.generated")) {
        type = null;
    }
    return type != null ? type : super.getDataType(fileObject);
}

From source file:org.kalypso.commons.io.VFSUtilities.java

/**
 * Moves the complete content of one directory into another.
 *
 * @throws IOException//from   w  ww.  j  a  va2s .  c om
 *           If the move failed.
 */
public static void moveContents(final File sourceDir, final File dest) throws IOException {
    final FileSystemManager vfsManager = VFSUtilities.getManager();
    final FileObject source = vfsManager.toFileObject(sourceDir);
    final FileObject destDir = vfsManager.toFileObject(dest);

    final FileObject[] findFiles = source.findFiles(new AllFileSelector());
    // Might happen, if source does not exists... shouldn't we check this?
    if (findFiles == null)
        return;

    for (final FileObject fileObject : findFiles) {
        if (FileType.FILE.equals(fileObject.getType())) {
            final String relPath = source.getName().getRelativeName(fileObject.getName());
            final FileObject destFile = destDir.resolveFile(relPath, NameScope.DESCENDENT_OR_SELF);
            final FileObject folder = destFile.getParent();
            folder.createFolder();
            fileObject.moveTo(destFile);
        }
    }
}

From source file:org.kalypso.kalypsomodel1d2d.conv.results.ResultMeta1d2dHelper.java

public static Date resolveDateFromResultStep(final FileObject pFileResult) {
    try {//from   w ww . j av  a 2 s  .c o m
        return interpreteDateFromURL(pFileResult.getParent().getURL());
    } catch (final FileSystemException e0) {
        // FIXME: will never happen due to gerneric exception caught in the first call
        try {
            // DEAD CODE:
            return interpreteRMA10TimeLine(findFirstSpecifiedLine2dFile(pFileResult, "DA")); //$NON-NLS-1$
        } catch (final Exception e1) {
        }
    }

    return null;
}

From source file:org.kalypso.kalypsomodel1d2d.conv.SWANDataConverterHelper.java

public static GM_Position readCoordinateShiftValues(final FileObject pFile) {
    GM_Position lPosRes = null;//from   w  w w  . j  a  va 2s.  c  o  m

    Scanner scannerFile = null;
    Scanner scannerLine = null;
    try {

        FileObject swanShiftCoordFileObject = pFile.getParent()
                .getChild(ISimulation1D2DConstants.SIM_SWAN_COORD_SHIFT_FILE);
        if (swanShiftCoordFileObject == null) {
            return lPosRes;
        }
        File lFile = new File(swanShiftCoordFileObject.getURL().toURI());

        scannerFile = new Scanner(lFile);
        Double lDoubleShiftY = null;
        Double lDoubleShiftX = null;
        while (scannerFile.hasNextLine()) {
            String lStrNextLine = scannerFile.nextLine();
            if (lStrNextLine.contains("=")) { //$NON-NLS-1$
                scannerLine = new Scanner(lStrNextLine);
                scannerLine.useDelimiter("="); //$NON-NLS-1$
                String lStrValueName = scannerLine.next();
                String lStrValue = scannerLine.next();
                if (ISimulation1D2DConstants.SIM_SWAN_COORD_SHIFT_X.equalsIgnoreCase(lStrValueName)) {
                    lDoubleShiftX = Double.parseDouble(lStrValue);
                } else if (ISimulation1D2DConstants.SIM_SWAN_COORD_SHIFT_Y.equalsIgnoreCase(lStrValueName)) {
                    lDoubleShiftY = Double.parseDouble(lStrValue);
                }
                scannerLine.close();
            } else {
                // System.out.println("Empty or invalid line. Unable to process. Processing the results without shift!");
            }
        }
        if (lDoubleShiftX != null && lDoubleShiftY != null)
            lPosRes = GeometryFactory.createGM_Position(lDoubleShiftX, lDoubleShiftY);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (scannerFile != null)
            scannerFile.close();
        if (scannerLine != null)
            scannerLine.close();
    }

    return lPosRes;
}