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:org.apache.cayenne.util.ResourceLocator.java

/**
 * Returns a resource URL using the lookup strategy configured for this
 * Resourcelocator or <code>null</code> if no readable resource can be found for the
 * given name./*from   www  .ja va  2s . com*/
 */
public URL findResource(String name) {
    if (!willSkipAbsolutePath()) {
        File f = new File(name);
        if (f.isAbsolute() && f.exists()) {
            logObj.debug("File found at absolute path: " + name);
            try {
                return f.toURL();
            } catch (MalformedURLException ex) {
                // ignoring
                logObj.debug("Malformed url, ignoring.", ex);
            }
        } else {
            logObj.debug("No file at absolute path: " + name);
        }
    }

    if (!willSkipHomeDirectory()) {
        File f = findFileInHomeDirectory(name);
        if (f != null) {

            try {
                return f.toURL();
            } catch (MalformedURLException ex) {
                // ignoring
                logObj.debug("Malformed url, ignoring", ex);
            }
        }
    }

    if (!willSkipCurrentDirectory()) {
        File f = findFileInCurrentDirectory(name);
        if (f != null) {

            try {
                return f.toURL();
            } catch (MalformedURLException ex) {
                // ignoring
                logObj.debug("Malformed url, ignoring", ex);
            }
        }
    }

    if (!additionalFilesystemPaths.isEmpty()) {
        logObj.debug("searching additional paths: " + this.additionalFilesystemPaths);
        for (String filePath : this.additionalFilesystemPaths) {
            File f = new File(filePath, name);
            logObj.debug("searching for: " + f.getAbsolutePath());
            if (f.exists()) {
                try {
                    return f.toURL();
                } catch (MalformedURLException ex) {
                    // ignoring
                    logObj.debug("Malformed URL, ignoring.", ex);
                }
            }
        }
    }

    if (!willSkipClasspath()) {

        // start with custom classpaths and then move to the default one
        if (!this.additionalClassPaths.isEmpty()) {
            logObj.debug("searching additional classpaths: " + this.additionalClassPaths);

            for (String classPath : this.additionalClassPaths) {
                String fullName = classPath + "/" + name;
                logObj.debug("searching for: " + fullName);
                URL url = findURLInClassLoader(fullName, getClassLoader());
                if (url != null) {
                    return url;
                }
            }
        }

        URL url = findURLInClassLoader(name, getClassLoader());
        if (url != null) {
            return url;
        }
    }

    return null;
}

From source file:org.fao.geonet.kernel.ThesaurusManager.java

/**
 * // ww w  . ja v a  2s .  c o m
 * @param context ServiceContext used to check when servlet is up only
 * @param appPath to find conversion XSLTs etc
 * @param DataManager to retrieve metadata to convert to SKOS
 * @param resourceManager for database connections
 * @param thesauriRepository
 * @throws Exception
 */
private ThesaurusManager(ServiceContext context, String appPath, DataManager dm, ResourceManager rm,
        String thesauriRepository) throws Exception {
    // Get Sesame interface
    service = Sesame.getService();

    File thesauriDir = new File(thesauriRepository);

    if (!thesauriDir.isAbsolute())
        thesauriDir = new File(appPath + thesauriDir);

    thesauriDirectory = thesauriDir.getAbsolutePath();

    this.dm = dm;
    this.rm = rm;
    THESAURUS_MANAGER_NOTIFIER_ID = UUID.randomUUID().toString();

    batchBuildTable(context, thesauriDir);
}

From source file:org.paxml.bean.AntTag.java

@Override
protected Object doInvoke(Context context) throws Exception {

    File dirFile = StringUtils.isBlank(dir) ? null : ResourceUtils.getFile(dir);

    if (dirFile != null && !dirFile.isDirectory()) {
        throw new PaxmlRuntimeException(
                "The given 'dir' property is not a directory: " + dirFile.getAbsolutePath());
    }/*from   w  w w .j a  v a2 s.  c om*/
    String antFile = StringUtils.isBlank(file) ? DEFAULT_ANT_FILE : file;
    File antFileFile = new File(antFile);

    File buildFile;
    // classpath is logically absolute path!
    if (antFile.startsWith("classpath:") || antFile.startsWith("classpath*:")) {
        buildFile = ResourceUtils.getFile(antFile);
    } else if (antFileFile.isFile() && antFileFile.isAbsolute()) {
        buildFile = antFileFile;
    } else if (dirFile == null) {
        buildFile = new File(antFile);
    } else {
        buildFile = new File(dirFile, antFile);
    }
    if (buildFile == null) {
        throw new PaxmlRuntimeException("Ant build fild not found: " + antFile + " under dir: " + dir);
    }

    Project p = new Project();

    DefaultLogger consoleLogger = new DefaultLogger();
    consoleLogger.setErrorPrintStream(System.err);
    consoleLogger.setOutputPrintStream(System.out);
    consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
    p.addBuildListener(consoleLogger);

    if (shareContext) {
        Map<String, Object> map = context.getIdMap(true, true);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            final String key = entry.getKey();
            final Object value = entry.getValue();

            if (value != null) {
                if (log.isDebugEnabled()) {
                    String svalue = value.toString();
                    final int MAX_LEN = 100;
                    if (svalue.length() > MAX_LEN) {
                        svalue = svalue.substring(0, 100) + " ...";
                    }
                    log.debug("Setting user property: " + key + " = " + svalue);
                }
                p.setUserProperty(key, value.toString());
            }
        }
    }

    p.setUserProperty("ant.file", buildFile.getAbsolutePath());
    if (dirFile != null) {
        p.setUserProperty("basedir", dirFile.getAbsolutePath());
    }

    boolean result = true;
    try {
        p.fireBuildStarted();
        p.init();
        ProjectHelper helper = ProjectHelper.getProjectHelper();
        p.addReference("ant.projectHelper", helper);
        helper.parse(p, buildFile);

        String target = StringUtils.isBlank(this.target) ? p.getDefaultTarget() : this.target;
        StringTokenizer st = new StringTokenizer(target, " \r\n\t,;|");
        while (st.hasMoreTokens()) {
            String t = st.nextToken();
            if (log.isInfoEnabled()) {
                log.info("Running target '" + t + "' in ant file: " + buildFile);
            }
            p.executeTarget(t);
        }
        p.fireBuildFinished(null);
    } catch (Throwable e) {
        p.fireBuildFinished(e);
        if (failOnError) {
            throw new PaxmlRuntimeException(e);
        }
        result = false;
    }
    return result;

}

From source file:it.greenvulcano.util.zip.ZipHelper.java

/**
 * Performs the <code>ZIP</code> compression of a file/directory, whose name
 * and parent directory are passed as arguments, on the local filesystem.
 * The result is written into a target file with the <code>zip</code>
 * extension.<br>/*from  w ww  .  j ava2  s .  c o m*/
 * The source filename may contain a regualr expression: in this
 * case, all the filenames matching the pattern will be compressed and put
 * in the same target <code>zip</code> file.<br>
 *
 *
 * @param srcDirectory
 *            the source parent directory of the file/s to be zipped. Must
 *            be an absolute pathname.
 * @param fileNamePattern
 *            the name of the file to be zipped. May contain a regular expression,
 *            possibly matching multiple files/directories.
 *            If matching a directory, the directory is zipped with all its content as well.
 * @param targetDirectory
 *            the target parent directory of the created <code>zip</code>
 *            file. Must be an absolute pathname.
 * @param zipFilename
 *            the name of the zip file to be created. Cannot be
 *            <code>null</code>, and must have the <code>.zip</code>
 *            extension. If a target file already exists with the same name
 *            in the same directory, it will be overwritten.
 * @throws IOException
 *             If any error occurs during file compression.
 * @throws IllegalArgumentException
 *             if the arguments are invalid.
 */
public void zipFile(String srcDirectory, String fileNamePattern, String targetDirectory, String zipFilename)
        throws IOException {

    File srcDir = new File(srcDirectory);

    if (!srcDir.isAbsolute()) {
        throw new IllegalArgumentException(
                "The pathname of the source parent directory is NOT absolute: " + srcDirectory);
    }

    if (!srcDir.exists()) {
        throw new IllegalArgumentException(
                "Source parent directory " + srcDirectory + " NOT found on local filesystem.");
    }

    if (!srcDir.isDirectory()) {
        throw new IllegalArgumentException("Source parent directory " + srcDirectory + " is NOT a directory.");
    }

    File targetDir = new File(targetDirectory);

    if (!targetDir.isAbsolute()) {
        throw new IllegalArgumentException(
                "The pathname of the target parent directory is NOT absolute: " + targetDirectory);
    }

    if (!targetDir.exists()) {
        throw new IllegalArgumentException(
                "Target parent directory " + targetDirectory + " NOT found on local filesystem.");
    }

    if (!targetDir.isDirectory()) {
        throw new IllegalArgumentException(
                "Target parent directory " + targetDirectory + " is NOT a directory.");
    }

    if ((zipFilename == null) || (zipFilename.length() == 0)) {
        throw new IllegalArgumentException("Target zip file name is missing.");
    }

    ZipOutputStream zos = null;
    try {
        zos = new ZipOutputStream(new FileOutputStream(new File(targetDir, zipFilename)));
        zos.setLevel(compressionLevel);

        URI base = srcDir.toURI();
        File[] files = srcDir.listFiles(new RegExFilenameFilter(fileNamePattern));

        for (File file : files) {
            internalZipFile(file, zos, base);
        }
    } finally {
        try {
            if (zos != null) {
                zos.close();
            }
        } catch (Exception exc) {
            // Do nothing
        }
    }
}

From source file:org.apache.cocoon.transformation.LuceneIndexTransformer.java

private IndexReader openReader() throws IOException {
    File indexDirectory = new File(queryConfiguration.indexDirectory);
    if (!indexDirectory.isAbsolute()) {
        indexDirectory = new File(workDir, queryConfiguration.indexDirectory);
    }//from ww w .  jav  a  2s . c  o m

    Directory directory = LuceneCocoonHelper.getDirectory(indexDirectory, createIndex);
    IndexReader reader = IndexReader.open(directory);
    return reader;
}

From source file:com.googlecode.psiprobe.AbstractTomcatContainer.java

public void remove(String contextName) throws Exception {
    contextName = formatContextName(contextName);
    Context ctx = findContext(contextName);

    if (ctx != null) {

        try {/*from   ww  w  .  j  av  a 2  s.c  o m*/
            stop(contextName);
        } catch (Throwable e) {
            logger.info("Stopping " + contextName + " threw this exception:", e);
            //
            // make sure we always re-throw ThreadDeath
            //
            if (e instanceof ThreadDeath) {
                throw (ThreadDeath) e;
            }
        }

        File appDir;
        File docBase = new File(ctx.getDocBase());

        if (!docBase.isAbsolute()) {
            appDir = new File(getAppBase(), ctx.getDocBase());
        } else {
            appDir = docBase;
        }

        logger.debug("Deleting " + appDir.getAbsolutePath());
        Utils.delete(appDir);

        String warFilename = formatContextFilename(contextName);
        File warFile = new File(getAppBase(), warFilename + ".war");
        logger.debug("Deleting " + warFile.getAbsolutePath());
        Utils.delete(warFile);

        File configFile = getConfigFile(ctx);
        if (configFile != null) {
            logger.debug("Deleting " + configFile.getAbsolutePath());
            Utils.delete(configFile);
        }

        removeInternal(contextName);
    }
}

From source file:it.geosolutions.geobatch.actions.freemarker.FreeMarkerAction.java

private File computeOutputDir() throws ActionException {
    File outputDir = null;/*from   w  w w. j  a  va 2s  . co m*/

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Computing output dir");
        LOGGER.debug(" - tempDir:        " + getTempDir());
        LOGGER.debug(" - conf.getOutput: " + conf.getOutput());
    }

    if (conf.getOutput() == null) {

        // no output path in the configuration: just put the output into the temp dir
        outputDir = this.getTempDir();

    } else {

        final File out = new File(conf.getOutput());
        if (out.isAbsolute()) {
            if (!out.exists()) {
                if (!out.mkdirs()) {
                    final String message = "Unable to create the output dir : " + out.getAbsolutePath();
                    if (LOGGER.isErrorEnabled()) {
                        LOGGER.error(message);
                    }
                    throw new ActionException(this, message);
                }
            }
            outputDir = out;
        } else {
            try {

                outputDir = it.geosolutions.tools.commons.file.Path.findLocation(conf.getOutput(),
                        this.getTempDir());

                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("Output directory name: " + outputDir);
                }

            } catch (NullPointerException npe) { // da cosa dovrebbe esser causato? non  meglio fare una verifica == null?
                outputDir = new File(this.getTempDir(), conf.getOutput());
                // failed to absolutize conf.getOutput()
                if (!outputDir.exists()) {
                    if (!outputDir.mkdirs()) {
                        final String message = "Unable to build the output dir path from : " + conf.getOutput();

                        if (LOGGER.isErrorEnabled()) {
                            LOGGER.error(message);
                        }
                        final ActionException e = new ActionException(this, message);
                        listenerForwarder.failed(e);
                        throw e;
                    }
                } else if (!outputDir.canWrite()) {
                    final String message = "Output dir is not writeable : " + conf.getOutput();

                    if (LOGGER.isErrorEnabled()) {
                        LOGGER.error(message);
                    }

                    final ActionException e = new ActionException(this, message);
                    listenerForwarder.failed(e);
                    throw e;
                }
            }
        }
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Output dir : " + outputDir);
    }

    return outputDir;
}

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

/**
 * Construct a File object pointing to the file linked, whether the link is
 * absolute or relative to the main directory.
 *
 * @param directory The main directory./*from   ww w  .j  av a 2 s . co  m*/
 * @param link      The absolute or relative link.
 * @return The expanded File.
 */
private File expandFilename(String directory, String link) {
    File toFile = new File(link);
    // If this is a relative link, we should perhaps append the directory:
    String dirPrefix = directory + System.getProperty("file.separator");
    if (!toFile.isAbsolute()) {
        toFile = new File(dirPrefix + link);
    }
    return toFile;
}

From source file:org.eclipse.jubula.app.dbtool.core.DBToolClient.java

/**
 * Import a project from an export file/*ww w.  j a  v a 2s. c  o m*/
 * @param fileName export file name
 * @param exportDir directory to use
 * @param monitor the progress monitor to use
 */
private void importProject(String fileName, String exportDir, IProgressMonitor monitor) {
    File impFile = new File(fileName);
    if (!impFile.isAbsolute()) {
        impFile = new File(new File(exportDir), fileName);
    }
    try {
        List<URL> fileURLs = new ArrayList<URL>(1);
        fileURLs.add(impFile.toURI().toURL());
        FileStorageBP.importFiles(fileURLs, monitor, this, false);
    } catch (PMException pme) {
        writeErrorLine(pme.getLocalizedMessage());
    } catch (ProjectDeletedException gdpde) {
        writeErrorLine(gdpde.getLocalizedMessage());
    } catch (MalformedURLException e) {
        writeErrorLine(e.getLocalizedMessage());
    }
}