Example usage for java.io File isAbsolute

List of usage examples for java.io File isAbsolute

Introduction

In this page you can find the example usage for java.io File isAbsolute.

Prototype

public boolean isAbsolute() 

Source Link

Document

Tests whether this abstract pathname is absolute.

Usage

From source file:com.basistech.m2e.code.quality.pmd.MavenPluginConfigurationTranslator.java

private List<String> convertFileFoldersToRelativePathStrings(final Iterable<? extends File> sources) {
    final List<String> folders = new ArrayList<String>();
    //No null check as internally we *know*
    for (File f : sources) {
        String relativePath;/*from w  w  w.  j  ava2s .  co m*/
        if (!f.isAbsolute()) {
            relativePath = URIUtils.resolve(this.basedirUri, f.toURI()).getPath();
            //TODO this.basedirUri.relativize(f.toURI()).getPath();
        } else {
            relativePath = f.getAbsolutePath();
        }

        if ("\\".equals(File.separator)) {
            relativePath = relativePath.replace("\\", "/");
        }
        if (relativePath.endsWith("/")) {
            relativePath = relativePath.substring(0, relativePath.length() - 1);
        }
        // we append the .* pattern regardless
        relativePath = relativePath + ".*";
        folders.add(relativePath);
    }
    return folders;
}

From source file:org.apache.struts2.spring.ClassReloadingXMLWebApplicationContext.java

public void setupReloading(String[] watchList, String acceptClasses, ServletContext servletContext,
        boolean reloadConfig) {
    this.reloadConfig = reloadConfig;

    classLoader = new ReloadingClassLoader(ClassReloadingXMLWebApplicationContext.class.getClassLoader());

    //make a list of accepted classes
    if (StringUtils.isNotBlank(acceptClasses)) {
        String[] splitted = acceptClasses.split(",");
        Set<Pattern> patterns = new HashSet<Pattern>(splitted.length);
        for (String pattern : splitted)
            patterns.add(Pattern.compile(pattern));

        classLoader.setAccepClasses(patterns);
    }//  www  .ja  v a 2 s . com

    fam = new FilesystemAlterationMonitor();

    //setup stores
    for (String watch : watchList) {
        File file = new File(watch);

        //make it absolute, if it is a relative path
        if (!file.isAbsolute())
            file = new File(servletContext.getRealPath(watch));

        if (watch.endsWith(".jar")) {
            classLoader.addResourceStore(new JarResourceStore(file));
            //register with the fam
            fam.addListener(file, this);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Watching [#0] for changes", file.getAbsolutePath());
            }
        } else {
            //get all subdirs
            List<File> dirs = new ArrayList<File>();
            getAllPaths(file, dirs);

            classLoader.addResourceStore(new FileResourceStore(file));

            for (File dir : dirs) {
                //register with the fam
                fam.addListener(dir, this);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Watching [#0] for changes", dir.getAbsolutePath());
                }
            }
        }
    }
    //setup the bean factory
    beanFactory = new ClassReloadingBeanFactory();
    beanFactory.setInstantiationStrategy(new ClassReloadingInstantiationStrategy());
    beanFactory.setBeanClassLoader(classLoader);

    //start watch thread
    fam.start();
}

From source file:org.fuin.esmp.EventStoreDownloadMojo.java

private void unzip(final File zipFile, final File destDir) throws MojoExecutionException {

    try {/* w w  w .j  av  a 2  s . c  o m*/
        final ZipFile zip = new ZipFile(zipFile);
        try {
            final Enumeration<? extends ZipEntry> enu = zip.entries();
            while (enu.hasMoreElements()) {
                final ZipEntry entry = (ZipEntry) enu.nextElement();
                final File file = new File(entry.getName());
                if (file.isAbsolute()) {
                    throw new IllegalArgumentException(
                            "Only relative path entries are allowed! [" + entry.getName() + "]");
                }
                if (entry.isDirectory()) {
                    final File dir = new File(destDir, entry.getName());
                    createIfNecessary(dir);
                } else {
                    final File outFile = new File(destDir, entry.getName());
                    createIfNecessary(outFile.getParentFile());
                    final InputStream in = new BufferedInputStream(zip.getInputStream(entry));
                    try {
                        final OutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
                        try {
                            final byte[] buf = new byte[4096];
                            int len;
                            while ((len = in.read(buf)) > 0) {
                                out.write(buf, 0, len);
                            }
                        } finally {
                            out.close();
                        }
                    } finally {
                        in.close();
                    }
                }
            }
        } finally {
            zip.close();
        }

    } catch (final IOException ex) {
        throw new MojoExecutionException("Error unzipping event store archive: " + zipFile, ex);
    }
}

From source file:com.github.htfv.maven.plugins.buildconfigurator.core.configurators.propertyfiles.PropertyFileConfigurator.java

protected File getFile(final ConfigurationContext ctx, final PropertyFileConfiguration propertyFile) {
    if (StringUtils.isEmpty(propertyFile.getFile())) {
        throw new RequiredParameterNotSpecifiedException("propertyFiles/propertyFile/file");
    }/*from   w ww.j  a  v a  2s .  co m*/

    File file = new File(ctx.getStringValue(propertyFile.getFile()));

    if (!file.isAbsolute()) {
        file = new File(ctx.getProject().getBasedir(), file.getPath());
    }

    return file;
}

From source file:net.ymate.platform.configuration.Cfgs.java

private File __doSearch(String cfgFile) {
    //  cfgFile ???
    File _result = new File(cfgFile);
    if (_result.isAbsolute()) {
        return _result;
    }/*from  ww  w  . j av  a2s. c  om*/
    //  moduleHome(?) cfgFile 
    if (StringUtils.isNotBlank(__moduleHome)) {
        _result = new File(__moduleHome, cfgFile);
        if (_result.canRead() && _result.isAbsolute() && _result.exists()) {
            return _result;
        }
    }
    //  projectHome() cfgFile 
    if (StringUtils.isNotBlank(__projectHome)) {
        _result = new File(__projectHome, cfgFile);
        if (_result.canRead() && _result.isAbsolute() && _result.exists()) {
            return _result;
        }
    }
    //  configHome() cfgFile 
    if (StringUtils.isNotBlank(__configHome)) {
        _result = new File(__configHome, cfgFile);
        if (_result.canRead() && _result.isAbsolute() && _result.exists()) {
            return _result;
        }
    }
    //  userDir() cfgFile 
    if (StringUtils.isNotBlank(__userDir)) {
        _result = new File(__userDir, cfgFile);
        if (_result.canRead() && _result.isAbsolute() && _result.exists()) {
            return _result;
        }
    }
    //  osUserHome() cfgFile 
    if (StringUtils.isNotBlank(__userHome)) {
        _result = new File(__userHome, cfgFile);
        if (_result.canRead() && _result.isAbsolute() && _result.exists()) {
            return _result;
        }
    }
    return null;
}

From source file:org.codehaus.plexus.redback.struts2.action.admin.BackupRestoreAction.java

public File getFile(String filename) {
    if (filename == null) {
        return null;
    }//w ww  .j  a v a  2  s  . c  om

    File f = null;

    if (filename != null && filename.length() != 0) {
        f = new File(filename);

        if (!f.isAbsolute()) {
            f = new File(applicationHome, filename);
        }
    }

    try {
        return f.getCanonicalFile();
    } catch (IOException e) {
        return f;
    }
}

From source file:catalina.realm.MemoryRealm.java

/**
 * Prepare for active use of the public methods of this Component.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents it from being started/*from  w ww.  j  a  v a  2  s  .  co m*/
 */
public synchronized void start() throws LifecycleException {

    // Validate the existence of our database file
    File file = new File(pathname);
    if (!file.isAbsolute())
        file = new File(System.getProperty("catalina.base"), pathname);
    if (!file.exists() || !file.canRead())
        throw new LifecycleException(sm.getString("memoryRealm.loadExist", file.getAbsolutePath()));

    // Load the contents of the database file
    if (debug >= 1)
        log(sm.getString("memoryRealm.loadPath", file.getAbsolutePath()));
    Digester digester = getDigester();
    try {
        synchronized (digester) {
            digester.push(this);
            digester.parse(file);
        }
    } catch (Exception e) {
        throw new LifecycleException("memoryRealm.readXml", e);
    }

    // Perform normal superclass initialization
    super.start();

}

From source file:org.ebayopensource.turmeric.plugins.maven.stubs.TurmericProjectStub.java

@SuppressWarnings("unchecked")
public TurmericProjectStub(String projectDirName) {
    basedir = new File(super.getBasedir(), toOS("target/tests/" + projectDirName));

    File pom = new File(getBasedir(), "plugin-config.xml");
    MavenXpp3Reader pomReader = new MavenXpp3Reader();
    Model model = null;//from w w w.j  a  v  a 2  s .c om

    try {
        model = pomReader.read(new FileReader(pom));
        setModel(model);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    setGroupId(model.getGroupId());
    setArtifactId(model.getArtifactId());
    setVersion(model.getVersion());
    setName(model.getName());
    setUrl(model.getUrl());
    setPackaging(model.getPackaging());
    setFile(pom);

    if (model.getDependencies() != null) {
        dependencies.addAll(model.getDependencies());
    }
    if (model.getProperties() != null) {
        properties.putAll(model.getProperties());
    }
    setBuild(model.getBuild());

    File srcDir = ensureDirExists(getBuild().getSourceDirectory(), "src/main/java");
    getBuild().setSourceDirectory(srcDir.getAbsolutePath());

    File targetDir = ensureDirExists(getBuild().getDirectory(), "target");
    getBuild().setDirectory(targetDir.getAbsolutePath());

    File outputDir = ensureDirExists(getBuild().getOutputDirectory(), "target/classes");
    getBuild().setOutputDirectory(outputDir.getAbsolutePath());

    List<Resource> resources = new ArrayList<Resource>();
    resources.addAll(getBuild().getResources());

    // Only add resource dir if none are defined.
    if (resources.isEmpty()) {
        resources = new ArrayList<Resource>();
        Resource resource = new Resource();
        File resourceDir = new File(getBasedir(), toOS("src/main/resources"));
        resource.setDirectory(resourceDir.getAbsolutePath());
        ensureDirExists(resourceDir);
        resources.add(resource);
    } else {
        // Fix any relative resource paths.
        for (Resource resource : resources) {
            String resDir = toOS(resource.getDirectory());
            File dir = new File(resDir);
            if (!dir.isAbsolute()) {
                dir = new File(getBasedir(), resDir);
                resource.setDirectory(dir.getAbsolutePath());
            }
        }
    }

    getBuild().setResources(resources);

    // Process Dependencies into Compile Artifacts (if possible)
    List<Artifact> artifacts = new ArrayList<Artifact>();
    final List<Dependency> dependencies = getDependencies();
    if (dependencies != null) {
        for (Dependency dep : dependencies) {
            File artiFile = getArtifactFile(dep);
            if (artiFile != null && artiFile.exists()) {
                artifacts.add(new CompileArtifact(artiFile, dep));
            }
        }
    }

    setCompileArtifacts(artifacts);
}

From source file:org.ebayopensource.turmeric.plugins.stubs.TestProjectStub.java

public TestProjectStub(String projectDirName) {
    this.basedir = new File(super.getBasedir(), "target/tests/" + projectDirName);

    File pom = new File(getBasedir(), "plugin-config.xml");
    MavenXpp3Reader pomReader = new MavenXpp3Reader();
    Model model = null;/* w  ww  . j  a  va 2  s. com*/

    try {
        model = pomReader.read(new FileReader(pom));
        setModel(model);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    setGroupId(model.getGroupId());
    setArtifactId(model.getArtifactId());
    setVersion(model.getVersion());
    setName(model.getName());
    setUrl(model.getUrl());
    setPackaging(model.getPackaging());
    setFile(pom);

    if (model.getDependencies() != null) {
        dependencies.addAll(model.getDependencies());
    }
    if (model.getProperties() != null) {
        properties.putAll(model.getProperties());
    }

    setBuild(model.getBuild());

    File srcDir = ensureDirExists(getBuild().getSourceDirectory(), "src/main/java");
    getBuild().setSourceDirectory(srcDir.getAbsolutePath());

    File targetDir = ensureDirExists(getBuild().getDirectory(), "target");
    getBuild().setDirectory(targetDir.getAbsolutePath());

    File outputDir = ensureDirExists(getBuild().getOutputDirectory(), "target/classes");
    getBuild().setOutputDirectory(outputDir.getAbsolutePath());

    List<Resource> resources = new ArrayList<Resource>();
    resources.addAll(getBuild().getResources());

    // Only add resource dir if none are defined.
    if (resources.isEmpty()) {
        resources = new ArrayList<Resource>();
        Resource resource = new Resource();
        File resourceDir = new File(getBasedir(), toOS("src/main/resources"));
        resource.setDirectory(resourceDir.getAbsolutePath());
        ensureDirExists(resourceDir);
        resources.add(resource);
        getBuild().setResources(resources);
    } else {
        // Fix any relative resource paths.
        for (Resource resource : resources) {
            String resDir = toOS(resource.getDirectory());
            File dir = new File(resDir);
            if (!dir.isAbsolute()) {
                dir = new File(getBasedir(), resDir);
                resource.setDirectory(dir.getAbsolutePath());
            }
        }
    }

    getBuild().setResources(resources);

    // Process Dependencies into Compile Artifacts (if possible)
    List<Artifact> artifacts = new ArrayList<Artifact>();
    final List<Dependency> dependencies = getDependencies();
    if (dependencies != null) {
        for (Dependency dep : dependencies) {
            File artiFile = getArtifactFile(dep);
            if (artiFile != null && artiFile.exists()) {
                artifacts.add(new CompileArtifact(artiFile, dep));
            }
        }
    }

    setCompileArtifacts(artifacts);
}

From source file:net.sf.jabref.external.MoveFileAction.java

@Override
public void actionPerformed(ActionEvent event) {
    int selected = editor.getSelectedRow();

    if (selected == -1) {
        return;/*  www.  jav a2  s  .  c o  m*/
    }

    FileListEntry entry = editor.getTableModel().getEntry(selected);

    // Check if the current file exists:
    String ln = entry.link;
    boolean httpLink = ln.toLowerCase(Locale.ENGLISH).startsWith("http");
    if (httpLink) {
        // TODO: notify that this operation cannot be done on remote links
        return;
    }

    // Get an absolute path representation:
    List<String> dirs = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectory();
    int found = -1;
    for (int i = 0; i < dirs.size(); i++) {
        if (new File(dirs.get(i)).exists()) {
            found = i;
            break;
        }
    }
    if (found < 0) {
        JOptionPane.showMessageDialog(frame, Localization.lang("File_directory_is_not_set_or_does_not_exist!"),
                MOVE_RENAME, JOptionPane.ERROR_MESSAGE);
        return;
    }
    File file = new File(ln);
    if (!file.isAbsolute()) {
        file = FileUtil.expandFilename(ln, dirs).orElse(null);
    }
    if ((file != null) && file.exists()) {
        // Ok, we found the file. Now get a new name:
        String extension = null;
        if (entry.type.isPresent()) {
            extension = "." + entry.type.get().getExtension();
        }

        File newFile = null;
        boolean repeat = true;
        while (repeat) {
            repeat = false;
            String chosenFile;
            if (toFileDir) {
                // Determine which name to suggest:
                String suggName = FileUtil
                        .createFileNameFromPattern(eEditor.getDatabase(), eEditor.getEntry(),
                                Globals.journalAbbreviationLoader, Globals.prefs)
                        .concat(entry.type.isPresent() ? "." + entry.type.get().getExtension() : "");
                CheckBoxMessage cbm = new CheckBoxMessage(Localization.lang("Move file to file directory?"),
                        Localization.lang("Rename to '%0'", suggName),
                        Globals.prefs.getBoolean(JabRefPreferences.RENAME_ON_MOVE_FILE_TO_FILE_DIR));
                int answer;
                // Only ask about renaming file if the file doesn't have the proper name already:
                if (suggName.equals(file.getName())) {
                    answer = JOptionPane.showConfirmDialog(frame,
                            Localization.lang("Move file to file directory?"), MOVE_RENAME,
                            JOptionPane.YES_NO_OPTION);
                } else {
                    answer = JOptionPane.showConfirmDialog(frame, cbm, MOVE_RENAME, JOptionPane.YES_NO_OPTION);
                }
                if (answer != JOptionPane.YES_OPTION) {
                    return;
                }
                Globals.prefs.putBoolean(JabRefPreferences.RENAME_ON_MOVE_FILE_TO_FILE_DIR, cbm.isSelected());
                StringBuilder sb = new StringBuilder(dirs.get(found));
                if (!dirs.get(found).endsWith(File.separator)) {
                    sb.append(File.separator);
                }
                if (cbm.isSelected()) {
                    // Rename:
                    sb.append(suggName);
                } else {
                    // Do not rename:
                    sb.append(file.getName());
                }
                chosenFile = sb.toString();
            } else {
                chosenFile = FileDialogs.getNewFile(frame, file, Collections.singletonList(extension),
                        JFileChooser.SAVE_DIALOG, false);
            }
            if (chosenFile == null) {
                return; // canceled
            }
            newFile = new File(chosenFile);
            // Check if the file already exists:
            if (newFile.exists() && (JOptionPane.showConfirmDialog(frame,
                    Localization.lang("'%0' exists. Overwrite file?", newFile.getName()), MOVE_RENAME,
                    JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION)) {
                if (toFileDir) {
                    return;
                } else {
                    repeat = true;
                }
            }
        }

        if (!newFile.equals(file)) {
            try {
                boolean success = file.renameTo(newFile);
                if (!success) {
                    success = FileUtil.copyFile(file, newFile, true);
                }
                if (success) {
                    // Remove the original file:
                    if (!file.delete()) {
                        LOGGER.info("Cannot delete original file");
                    }
                    // Relativise path, if possible.
                    String canPath = new File(dirs.get(found)).getCanonicalPath();
                    if (newFile.getCanonicalPath().startsWith(canPath)) {
                        if ((newFile.getCanonicalPath().length() > canPath.length()) && (newFile
                                .getCanonicalPath().charAt(canPath.length()) == File.separatorChar)) {

                            String newLink = newFile.getCanonicalPath().substring(1 + canPath.length());
                            editor.getTableModel().setEntry(selected,
                                    new FileListEntry(entry.description, newLink, entry.type));
                        } else {
                            String newLink = newFile.getCanonicalPath().substring(canPath.length());
                            editor.getTableModel().setEntry(selected,
                                    new FileListEntry(entry.description, newLink, entry.type));
                        }

                    } else {
                        String newLink = newFile.getCanonicalPath();
                        editor.getTableModel().setEntry(selected,
                                new FileListEntry(entry.description, newLink, entry.type));
                    }
                    eEditor.updateField(editor);
                    //JOptionPane.showMessageDialog(frame, Globals.lang("File moved"),
                    //        Globals.lang("Move/Rename file"), JOptionPane.INFORMATION_MESSAGE);
                    frame.output(Localization.lang("File moved"));
                } else {
                    JOptionPane.showMessageDialog(frame, Localization.lang("Move file failed"), MOVE_RENAME,
                            JOptionPane.ERROR_MESSAGE);
                }

            } catch (SecurityException | IOException ex) {
                LOGGER.warn("Could not move file", ex);
                JOptionPane.showMessageDialog(frame,
                        Localization.lang("Could not move file '%0'.", file.getAbsolutePath())
                                + ex.getMessage(),
                        MOVE_RENAME, JOptionPane.ERROR_MESSAGE);
            }

        }
    } else {
        // File doesn't exist, so we can't move it.
        JOptionPane.showMessageDialog(frame, Localization.lang("Could not find file '%0'.", entry.link),
                Localization.lang("File not found"), JOptionPane.ERROR_MESSAGE);
    }

}