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.rapidminer.tools.Tools.java

/**
 * Creates a file relative to the given parent if name is not an absolute file name. Returns
 * null if name is null.//from ww  w  . j  a  v  a  2 s .  c o m
 */
public static File getFile(File parent, String name) {
    if (name == null) {
        return null;
    }
    File file = new File(name);
    if (file.isAbsolute()) {
        return file;
    } else {
        return new File(parent, name);
    }
}

From source file:org.corpus_tools.pepper.impl.BeforeAfterAction.java

/**
 * Reads customization property//from  w  w  w.j  av  a  2  s  .c  o m
 * {@link PepperModuleProperties#PROP_AFTER_COPY_RES} and copies the listed
 * resources to the named target folder.
 */
public void copyResources(String resString) {
    if ((resString != null) && (!resString.isEmpty())) {
        String[] resources = resString.split(";");
        if (resources.length > 0) {
            for (String resource : resources) {
                resource = resource.trim();
                String[] parts = resource.split("->");
                if (parts.length == 2) {
                    String sourceStr = parts[0];
                    String targetStr = parts[1];
                    sourceStr = sourceStr.trim();
                    targetStr = targetStr.trim();

                    // check if source and target is given
                    boolean copyOk = true;
                    if ((sourceStr == null) || (sourceStr.isEmpty())) {
                        logger.warn("Cannot copy resources for '" + getPepperModule().getName()
                                + "' because no source file was given in property value '" + resource + "'. ");
                        copyOk = false;
                    }
                    if ((targetStr == null) || (targetStr.isEmpty())) {
                        logger.warn("Cannot copy resources for '" + getPepperModule().getName()
                                + "' because no target file was given in property value '" + resource + "'. ");
                        copyOk = false;
                    }
                    if (copyOk) {
                        File source = new File(sourceStr);
                        File target = new File(targetStr);

                        // in case of source or target aren't absolute
                        // resolve them against current Job's base directory
                        String baseDir = getPepperModule().getModuleController().getJob().getBaseDir()
                                .toFileString();
                        if (!baseDir.endsWith("/")) {
                            baseDir = baseDir + "/";
                        }
                        if (!source.isAbsolute()) {
                            source = new File(baseDir + sourceStr);
                        }
                        if (!source.exists()) {
                            logger.warn("Cannot copy resources for '" + getPepperModule().getName()
                                    + "' because source does not exist '" + source.getAbsolutePath()
                                    + "'. Check the property value '" + resource + "'. ");
                        } else {
                            // only copy if source exists

                            if (!target.isAbsolute()) {
                                target = new File(baseDir + targetStr);
                            }
                            if (!target.exists()) {
                                if (!target.mkdirs()) {
                                    logger.warn("Cannot create folder {}. ", target);
                                }
                            }
                            try {
                                if (source.isDirectory()) {
                                    targetStr = target.getAbsolutePath();
                                    if (!targetStr.endsWith("/")) {
                                        targetStr = targetStr + "/";
                                    }
                                    target = new File(targetStr + source.getName());
                                    FileUtils.copyDirectory(source, target);
                                    logger.trace("Copied resource from '" + source.getAbsolutePath() + "' to '"
                                            + target.getAbsolutePath() + "'.");
                                } else {
                                    targetStr = target.getCanonicalPath();
                                    if (!targetStr.endsWith("/")) {
                                        targetStr = targetStr + "/";
                                    }
                                    target = new File(targetStr + source.getName());
                                    FileUtils.copyFile(source, target);
                                    logger.trace("Copied resource from '" + source.getAbsolutePath() + "' to '"
                                            + target.getAbsolutePath() + "'.");
                                }
                            } catch (IOException e) {
                                logger.warn("Cannot copy resources for '" + getPepperModule().getName()
                                        + "' because of '" + e.getMessage() + "'. Check the property value '"
                                        + resource + "'. ");
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.dita.dost.module.GenMapAndTopicListModule.java

private void parseInputParameters(final AbstractPipelineInput input) {
    ditaDir = toFile(input.getAttribute(ANT_INVOKER_EXT_PARAM_DITADIR));
    if (!ditaDir.isAbsolute()) {
        throw new IllegalArgumentException("DITA-OT installation directory " + ditaDir + " must be absolute");
    }/*from   www . ja v a  2 s.com*/
    ditavalFile = toFile(input.getAttribute(ANT_INVOKER_PARAM_DITAVAL));
    xmlValidate = Boolean.valueOf(input.getAttribute(ANT_INVOKER_EXT_PARAM_VALIDATE));
    transtype = input.getAttribute(ANT_INVOKER_EXT_PARAM_TRANSTYPE);
    gramcache = "yes".equalsIgnoreCase(input.getAttribute(ANT_INVOKER_EXT_PARAM_GRAMCACHE));
    setSystemid = "yes".equalsIgnoreCase(input.getAttribute(ANT_INVOKER_EXT_PARAN_SETSYSTEMID));
    final String mode = input.getAttribute(ANT_INVOKER_EXT_PARAM_PROCESSING_MODE);
    processingMode = mode != null ? Mode.valueOf(mode.toUpperCase()) : Mode.LAX;
    genDebugInfo = Boolean.valueOf(input.getAttribute(ANT_INVOKER_EXT_PARAM_GENERATE_DEBUG_ATTR));

    // For the output control
    job.setGeneratecopyouter(input.getAttribute(ANT_INVOKER_EXT_PARAM_GENERATECOPYOUTTER));
    job.setOutterControl(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTTERCONTROL));
    job.setOnlyTopicInMap(Boolean.valueOf(input.getAttribute(ANT_INVOKER_EXT_PARAM_ONLYTOPICINMAP)));

    // Set the OutputDir
    final File path = toFile(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTPUTDIR));
    if (path.isAbsolute()) {
        job.setOutputDir(path);
    } else {
        throw new IllegalArgumentException("Output directory " + path + " must be absolute");
    }

    final File basedir = toFile(input.getAttribute(ANT_INVOKER_PARAM_BASEDIR));

    final URI ditaInputDir = toURI(input.getAttribute(ANT_INVOKER_EXT_PARAM_INPUTDIR));
    if (ditaInputDir != null) {
        if (ditaInputDir.isAbsolute()) {
            baseInputDir = ditaInputDir;
        } else if (ditaInputDir.getPath() != null && ditaInputDir.getPath().startsWith(URI_SEPARATOR)) {
            baseInputDir = setScheme(ditaInputDir, "file");
        } else {
            // XXX Shouldn't this be resolved to current directory, not Ant script base directory?
            baseInputDir = basedir.toURI().resolve(ditaInputDir);
        }
        assert baseInputDir.isAbsolute();
    }

    final URI ditaInput = toURI(input.getAttribute(ANT_INVOKER_PARAM_INPUTMAP));
    if (ditaInput.isAbsolute()) {
        rootFile = ditaInput;
    } else if (ditaInput.getPath() != null && ditaInput.getPath().startsWith(URI_SEPARATOR)) {
        rootFile = setScheme(ditaInput, "file");
    } else if (baseInputDir != null) {
        rootFile = baseInputDir.resolve(ditaInput);
    } else {
        rootFile = basedir.toURI().resolve(ditaInput);
    }
    assert rootFile.isAbsolute();

    if (baseInputDir == null) {
        baseInputDir = rootFile.resolve(".");
    }
    assert baseInputDir.isAbsolute();

    profilingEnabled = true;
    if (input.getAttribute(ANT_INVOKER_PARAM_PROFILING_ENABLED) != null) {
        profilingEnabled = Boolean.parseBoolean(input.getAttribute(ANT_INVOKER_PARAM_PROFILING_ENABLED));
    }
    if (profilingEnabled) {
        if (ditavalFile != null && !ditavalFile.isAbsolute()) {
            // XXX Shouldn't this be resolved to current directory, not Ant script base directory?
            ditavalFile = new File(basedir, ditavalFile.getPath()).getAbsoluteFile();
        }
    }

    // create the keydef file for scheme files
    schemekeydefMap = new HashMap<>();

    // Set the mapDir
    job.setInputFile(rootFile);
}

From source file:org.dbgl.model.Mount.java

public File canBeUsedFor(final File hostFile) {
    if (!unmounted) {
        File canHostFile = FileUtils.getCanMainFile(hostFile);
        File mountFile = FileUtils.canonicalToDosroot(getPathAsString());
        if (mountingType != MountingType.DIR && (FileUtils.isIsoFile(canHostFile.getPath())
                || FileUtils.isArchive(canHostFile.getPath()) || FileUtils.isFatImage(canHostFile.getPath()))) {
            return (mountFile.equals(canHostFile))
                    ? FileUtils.makeRelativeTo(FileUtils.canonicalToDosroot(hostFile.getPath()),
                            FileUtils.canonicalToDosroot(getHostPathAsString()))
                    : null;/*from  w  w w  .j ava 2  s. co  m*/
        }
        if (FileUtils.areRelated(mountFile, canHostFile)) {
            if ((hostFile.getPath().indexOf('~') > 0)) {
                if (hostFile.isAbsolute())
                    canHostFile = hostFile;
                else
                    canHostFile = new File(FileUtils.getDosRoot(), hostFile.getPath());
            }
            return FileUtils.makeRelativeTo(canHostFile, mountFile);
        }
    }
    return null;
}

From source file:org.alfresco.solr.AlfrescoCoreAdminHandler.java

private InputStream openResource(CoreContainer coreContainer, String resource) {
    InputStream is = null;/*from   w  w  w. j  a  v a 2 s .c  o  m*/
    try {
        File f0 = new File(resource);
        File f = f0;
        if (!f.isAbsolute()) {
            // try $CWD/$configDir/$resource
            f = new File(coreContainer.getSolrHome() + resource);
        }
        if (f.isFile() && f.canRead()) {
            return new FileInputStream(f);
        } else if (f != f0) { // no success with $CWD/$configDir/$resource
            if (f0.isFile() && f0.canRead())
                return new FileInputStream(f0);
        }
        // delegate to the class loader (looking into $INSTANCE_DIR/lib jars)
        is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
    } catch (Exception e) {
        throw new RuntimeException("Error opening " + resource, e);
    }
    if (is == null) {
        throw new RuntimeException("Can't find resource '" + resource + "' in classpath or '"
                + coreContainer.getSolrHome() + "', cwd=" + System.getProperty("user.dir"));
    }
    return is;
}

From source file:org.energy_home.jemma.ah.internal.configurator.Configuratore.java

/**
 * Load HAC configuration. It is useful to describe the algorithm used to
 * instantiate the virtual appliances trough virtual appliances factory
 * services Each <va></va> section contains the properties of the virtual
 * appliance that the section represents. The load procedure stores all
 * these properties and tries to match them in an already installed bundles
 * or to download them on demand.//  www  . ja  va2s. c om
 * 
 * The procedure for doing that is identical to the Device Attachment
 * Algorithm described in the "Device Access Specification v1.1" The
 * HacService implements the DeviceLocator interface but doesn't register
 * it.
 * 
 * 
 * 1. If a DRIVER_ID property is present, the algorithm tries to locate an
 * already registered IApplianceType service exposing the same DERVICE_ID
 * property. If such an IApplianceType service is not found, an attempt to
 * download the maching driver bundle. If the
 * 
 * 
 * @param configName
 *            Filename. The filename must not include the .xml extension
 * 
 * @param storageArea
 *            If this parameter is true the configuration file is got from
 *            the r/w data area reserved to the bundle
 * 
 * @return true if the configuration has been read and applied correctly. In
 *         case of errors returns false
 */

public boolean loadConfiguration(String configName, boolean storageArea) {
    File configFile;
    InputStream stream = null;

    if (configName == null) {
        configName = "defaultconfig";
        storageArea = true;
    }

    log.debug("try to load configuration '" + configName + "'");

    try {
        if (storageArea) {
            String configFilename = SCENARIOS_PATH + configName + ".xml";
            configFile = bc.getDataFile(configFilename);
            log.debug("storage area is " + configFile);
            stream = new FileInputStream(configFile);
        } else {

            File f = new File(configName);
            if (f.isAbsolute()) {
                stream = new FileInputStream(configName);
            } else {
                String configFilename = SCENARIOS_PATH + configName + ".xml";
                //URL url = new URL("platform:/plugin/jemma.osgi.ah.configurator/"+configFilename);
                URL url = bc.getBundle().getEntry(configFilename);
                if (url == null) {
                    log.error("unable to open file " + configFilename);
                    return false;
                }
                stream = url.openStream();
            }
        }
    } catch (FileNotFoundException e) {
        log.error("unable to open file " + configName);
        return false;
    } catch (IOException e) {
        log.error("unable to open file " + configName);
        return false;
    }

    try {
        importConfiguration(stream);
    } catch (Exception e) {
        log.error(e);
        return false;
    }

    log.info("configuration '" + configName + "' loaded successfully");
    return true;
}

From source file:com.izforge.izpack.installer.unpacker.UnpackerBase.java

/**
 * Performs update checks.//from  w w  w .  j  ava2  s.  co  m
 *
 * @param checks the update checks. May be {@code null}
 * @throws IzPackException for any error
 */
protected void performUpdateChecks(List<UpdateCheck> checks) {
    if (checks != null && !checks.isEmpty()) {
        logger.info("Cleaning up the target folder ...");

        File absoluteInstallPath = new File(installData.getInstallPath()).getAbsoluteFile();
        FileSet fileset = new FileSet();
        List<File> filesToDelete = new ArrayList<File>();
        List<File> dirsToDelete = new ArrayList<File>();

        try {
            fileset.setDir(absoluteInstallPath);

            for (UpdateCheck check : checks) {
                if (check.includesList != null) {
                    for (String include : check.includesList) {
                        fileset.createInclude().setName(variableSubstitutor.substitute(include));
                    }
                }

                if (check.excludesList != null) {
                    for (String exclude : check.excludesList) {
                        fileset.createExclude().setName(variableSubstitutor.substitute(exclude));
                    }
                }
            }
            DirectoryScanner scanner = fileset.getDirectoryScanner();
            scanner.scan();
            String[] srcFiles = scanner.getIncludedFiles();
            String[] srcDirs = scanner.getIncludedDirectories();

            Set<File> installedFiles = new TreeSet<File>();

            for (String name : uninstallData.getInstalledFilesList()) {
                File file = new File(name);

                if (!file.isAbsolute()) {
                    file = new File(absoluteInstallPath, name);
                }

                installedFiles.add(file);
            }
            for (String srcFile : srcFiles) {
                File newFile = new File(scanner.getBasedir(), srcFile);

                // skip files we just installed
                if (!installedFiles.contains(newFile)) {
                    filesToDelete.add(newFile);
                }
            }
            for (String srcDir : srcDirs) {
                // All directories except INSTALL_PATH
                if (!srcDir.isEmpty()) {
                    File newDir = new File(scanner.getBasedir(), srcDir);

                    // skip directories we just installed
                    if (!installedFiles.contains(newDir)) {
                        dirsToDelete.add(newDir);
                    }
                }
            }
        } catch (IzPackException exception) {
            throw exception;
        } catch (Exception exception) {
            throw new IzPackException(exception);
        }

        for (File f : filesToDelete) {
            if (!f.delete()) {
                logger.warning("Cleanup: Unable to delete file " + f);
            } else {
                logger.fine("Cleanup: Deleted file " + f);
            }
        }

        // Sort directories, deepest path first to be able to
        // delete recursively
        Collections.sort(dirsToDelete);
        Collections.reverse(dirsToDelete);

        for (File d : dirsToDelete) {
            if (!d.exists()) {
                break;
            }

            // Don't try to delete non-empty directories, because they
            // probably must have been implicitly created as parents
            // of regular installation files
            File[] files = d.listFiles();
            if (files != null && files.length != 0) {
                break;
            }

            // Only empty directories will be deleted
            if (!d.delete()) {
                logger.warning("Cleanup: Unable to delete directory " + d);
            } else {
                logger.fine("Cleanup: Deleted directory " + d);
            }
        }
    }
}

From source file:com.sshtools.j2ssh.SftpClient.java

private File resolveLocalPath(String path) throws IOException {
    File f = new File(path);

    if (!f.isAbsolute()) {
        f = new File(lcwd, path);
    }/*from  w w w .  ja v  a2 s  .  co  m*/

    return f;
}

From source file:eu.asterics.mw.services.ResourceRegistry.java

/**
 * Returns the URI of the requested resource.
 * Generally the URI is not tested for existence it just constructs a valid URI for the given parameters.
 * The returned URI can be opened with {@link URI#toURL()} and {@link URL#openStream()}, or better use directly {@link ResourceRegistry#getResourceInputStream(String, RES_TYPE)}.
 * If you know that it is a file path URI and need to perform file operations, convert it to a file with {@link ResourceRegistry#toFile(URI)}.
 * /* www  .  j a  va 2s .c o m*/
 * resourcePath can be 
 *     an absolute URL-conforming string (e.g. file://, http://). In this case the string must be encoded correctly.
 *   or an absolute or relative file path (windows or unix-style). In this case {@link File} class and its method {@link File#toURI()} is used. The file path may contain both \\ and / seperators. Relative resourcePaths are resolved against the ARE.baseURI or a subfolder depending on the provided type ({@link RES_TYPE}). 
        
 * The type ({@link RES_TYPE}) determines the type of the resource which is used to append the respective subfolder for the resource type (e.g. data, models).
 * In case of {@value RES_TYPE#DATA} a 4 step approach is used to guess the correct subfolder (e.g. a sensor.facetrackerLK or pictures):
 *   Step 1: If resource ARE.baseURI/data/{resourcePath} exists, return
 *   Step 2: If componentTypeId!=null and resource ARE.baseURI/{DATA_FOLDER}/{componentTypeId}/{resourcePath} exists, return
 *   Step 3: If componentTypeId!=null and resource ARE.baseURI/{DATA_FOLDER}/{*componentTypeId*}/{resourcePath} exists, return
 *   Step 4: If resource ARE.baseURI/{DATA_FOLDER}/{*}/{resourcePath} exists, return
 *   Default: If none of the above was successful, ARE.baseURI/data/{resourcePath} is returned.
 * In case of {@value RES_TYPE#ANY} no subfolder is appended. 
 * 
 * @param resourcePath an absolute URL-conforming string or an absolute or relative file path string
 * @param type The resource type {@link RES_TYPE} for the requested resource
 * @param componentTypeId Hint for a better guessing of a {@value RES_TYPE#DATA} resource.
 * @param runtimeComponentInstanceId Hint for a better guessing of a {@value RES_TYPE#DATA} resource.
 * @return a valid URI.
 * @throws URISyntaxException
 */
public URI getResource(String resourcePath, RES_TYPE type, String componentTypeId,
        String runtimeComponentInstanceId) throws URISyntaxException {
    URI uri = null;
    File resFilePath = null;

    try {
        URL url = new URL(resourcePath);
        AstericsErrorHandling.instance.getLogger().fine("Resource URL: " + url);
        uri = url.toURI();
    } catch (MalformedURLException e) {
        //Fix the string first, because it could have \ and / mixed up and stuff and convert it to path with unix-style path seperator (/)
        //Thanks to apache commons io lib this is very easy!! :-)
        final String resourcePathSlashified = FilenameUtils.separatorsToUnix(resourcePath);
        //AstericsErrorHandling.instance.getLogger().fine("resourceNameArg: "+resourcePath+", resourceName after normalization: "+resourcePathSlashified+", concat: "+FilenameUtils.concat(getAREBaseURI().getPath(), resourcePath));

        File resourceNameAsFile = new File(resourcePathSlashified);
        //AstericsErrorHandling.instance.getLogger().fine("resourceName: "+resourcePathSlashified+", resourceNameAsFile: "+resourceNameAsFile+", resourceNameAsFile.toURI: "+resourceNameAsFile.toURI());

        if (!resourceNameAsFile.isAbsolute()) {
            switch (type) {
            case MODEL:
                resFilePath = resolveRelativeFilePath(toAbsolute(MODELS_FOLDER), resourcePathSlashified, false);
                break;
            case PROFILE:
                resFilePath = resolveRelativeFilePath(toAbsolute(PROFILE_FOLDER), resourcePathSlashified,
                        false);
                break;
            case LICENSE:
                resFilePath = resolveRelativeFilePath(toAbsolute(LICENSES_FOLDER), resourcePathSlashified,
                        false);
                break;
            case DATA:
                /*
                 * 1) Check resourceName directly, if it exists return
                 * 2) Check resourceName with exactly matching componentTypeId, if it exists return
                 * 3) Check resourceName with first subfolder containing componentTypeId, if it exists return
                 * 4) Check all subfolders (only first level) and resolve against the given resourceName, if it exists return 
                 */
                URI dataFolderURI = toAbsolute(DATA_FOLDER);
                File dataFolderFile = ResourceRegistry.toFile(dataFolderURI);

                //1) Check resourceName directly, if it exists return
                resFilePath = resolveRelativeFilePath(dataFolderFile, resourcePathSlashified, false);
                if (resFilePath.exists()) {
                    break;
                }

                if (componentTypeId != null) {
                    //2) Check resourceName with exactly matching componentTypeId, if it exists return
                    resFilePath = resolveRelativeFilePath(dataFolderFile,
                            componentTypeId + "/" + resourcePathSlashified, false);
                    if (resFilePath.exists()) {
                        break;
                    }

                    //3) Check resourceName with first subfolder containing componentTypeId (but only last part of asterics.facetrackerLK or sensor.facetrackerLK)
                    //if it exists return
                    String[] componentTypeIdSplit = componentTypeId.split("\\.");
                    //split returns the given string as element 0 if the regex patterns was not found.
                    final String componentTypeIdLC = componentTypeIdSplit[componentTypeIdSplit.length - 1]
                            .toLowerCase();

                    File[] dataSubFolderFiles = dataFolderFile.listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File dirFile) {
                            //AstericsErrorHandling.instance.getLogger().fine("Step3, dirFile: "+dirFile);
                            if (dirFile.isDirectory() && dirFile.exists()) {
                                //lowercase name contains lowercase componentTypeId
                                return (dirFile.getName().toLowerCase().indexOf(componentTypeIdLC) > -1);
                            }
                            return false;
                        }
                    });
                    //AstericsErrorHandling.instance.getLogger().fine("Data, Step3, resourceName="+resourceName+", componentTypeIdLC="+componentTypeIdLC+", runtimeComponentInstanceId="+runtimeComponentInstanceId+", dataSubFolderFiless <"+Arrays.toString(dataSubFolderFiles)+">");
                    if (dataSubFolderFiles.length > 0) {
                        resFilePath = resolveRelativeFilePath(dataSubFolderFiles[0], resourcePathSlashified,
                                false);
                        if (resFilePath.exists()) {
                            break;
                        }
                    }
                }

                //4) Check all subfolders (only first level) and resolve against the given resourceName, if it exists return
                File[] dataSubFolderFiles = dataFolderFile.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File dirFile) {
                        //AstericsErrorHandling.instance.getLogger().fine("Step3, dirFile: "+dirFile);
                        if (dirFile.isDirectory() && dirFile.exists()) {
                            File resourceFile;
                            //resourceFile = toFile(dirFile.toURI().resolve(resourceName));
                            resourceFile = resolveRelativeFilePath(dirFile, resourcePathSlashified, false);
                            return resourceFile.exists();
                        }
                        return false;
                    }
                });
                //AstericsErrorHandling.instance.getLogger().fine("Data, Step4, resourceName="+resourceName+", componentTypeId="+componentTypeId+", runtimeComponentInstanceId="+runtimeComponentInstanceId+", dataSubFolderFiless <"+Arrays.toString(dataSubFolderFiles)+">");
                if (dataSubFolderFiles.length > 0) {
                    resFilePath = resolveRelativeFilePath(dataSubFolderFiles[0], resourcePathSlashified, false);
                    if (resFilePath.exists()) {
                        break;
                    }
                }

                break;
            case IMAGE:
                resFilePath = resolveRelativeFilePath(toAbsolute(IMAGES_FOLDER), resourcePathSlashified, false);
                break;
            case STORAGE:
                resFilePath = resolveRelativeFilePath(toAbsolute(STORAGE_FOLDER), resourcePathSlashified,
                        false);
                break;
            case TMP:
                resFilePath = resolveRelativeFilePath(toAbsolute(TMP_FOLDER), resourcePathSlashified, false);
                break;
            default:
                resFilePath = resolveRelativeFilePath(getAREBaseURIFile(), resourcePathSlashified, false);
                break;
            }

            uri = resFilePath.toURI();
        } else {
            uri = resourceNameAsFile.toURI();
        }
    }
    //System.out.println("file absolute: "+resourceNameAsFile.isAbsolute()+", uri absolute: "+uri.isAbsolute()+", uri opaque: "+uri.isOpaque());
    //System.out.println("resource File.toURI: "+resourceNameAsFile.toURI());
    //AstericsErrorHandling.instance.getLogger().fine("URI before normalize: "+uri.normalize());
    if (uri != null) {
        uri = uri.normalize();
    }
    AstericsErrorHandling.instance.getLogger()
            .fine("resourceName=" + resourcePath + ", componentTypeId=" + componentTypeId
                    + ", runtimeComponentInstanceId=" + runtimeComponentInstanceId + ", Resource URI <" + uri
                    + ">");
    return uri;
}

From source file:com.igormaznitsa.jcp.context.PreprocessorContext.java

/**
 * It finds a file for its path among files in source folder, it is prohibited to return files out of preprocessing folders.
 *
 * @param path the path to the needed file, it must not be null and the file must exist and be a file and be among files in preprocessing source folders
 * @return detected file object for the path
 * @throws IOException if it is impossible to find a file for the path
 *//*from   www. j  a  v  a 2 s . c o m*/
@Nonnull
public File findFileInSourceFolder(@Nonnull final String path) throws IOException {
    if (path == null) {
        throw makeException("Path is null", null);
    }

    if (path.isEmpty()) {
        throw makeException("Path is empty", null);
    }

    File result = null;

    final TextFileDataContainer theFile = currentState.peekFile();
    final String parentDir = theFile == null ? null : theFile.getFile().getParent();

    final File resultFile = new File(path);
    if (resultFile.isAbsolute()) {
        // absolute path

        // check that the file is a child of a preprocessing source root else usage of the file is prohibited
        final String normalizedPath = FilenameUtils.normalizeNoEndSeparator(resultFile.getAbsolutePath());
        for (final File root : getSourceDirectoryAsFiles()) {
            final String rootNormalizedPath = FilenameUtils.normalizeNoEndSeparator(root.getAbsolutePath())
                    + File.separatorChar;
            if (normalizedPath.startsWith(rootNormalizedPath)) {
                result = resultFile;
                break;
            }
        }

        if (result == null) {
            throw makeException("Can't find file for path \'" + path
                    + "\' in preprocessing source folders, allowed usage only files in preprocessing source folders!",
                    null);
        } else if (!result.isFile()) {
            throw makeException("File \'" + result + "\' is either not found or not a file", null);
        }

    } else if (parentDir != null) {
        // relative path
        result = new File(parentDir, path);
    } else {
        final List<File> setOfFoundFiles = new ArrayList<File>();
        for (final File root : getSourceDirectoryAsFiles()) {
            final File variant = new File(root, path);
            if (variant.exists() && variant.isFile()) {
                setOfFoundFiles.add(variant);
            }
        }

        if (setOfFoundFiles.size() == 1) {
            result = setOfFoundFiles.get(0);
        } else if (setOfFoundFiles.isEmpty()) {
            result = null;
        } else {
            throw makeException("Found several variants for path \'" + path + "\' in different source roots",
                    null);
        }

        if (result == null) {
            throw makeException("Can't find file for path \'" + path
                    + "\' among source files registered for preprocessing.", null);
        } else if (!result.isFile()) {
            throw makeException(
                    "File \'" + PreprocessorUtils.getFilePath(result) + "\' is either not found or not a file",
                    null);
        }
    }

    return result;
}