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:catalina.startup.Catalina.java

/**
 * Return a File object representing our configuration file.
 *//*from  w w  w .  j  a v  a 2 s .c o m*/
protected File configFile() {

    File file = new File(configFile);
    if (!file.isAbsolute())
        file = new File(System.getProperty("catalina.base"), configFile);
    return (file);

}

From source file:com.blackducksoftware.integration.hub.teamcity.agent.scan.HubBuildProcess.java

private HubScanConfig getScanConfig(final File workingDirectory, final File toolsDir, final IntLogger logger,
        final CIEnvironmentVariables commonVariables) throws IOException {

    final String dryRun = commonVariables.getValue(HubConstantValues.HUB_DRY_RUN);
    final String cleanupLogs = commonVariables.getValue(HubConstantValues.HUB_CLEANUP_LOGS_ON_SUCCESS);

    final String scanMemory = commonVariables.getValue(HubConstantValues.HUB_SCAN_MEMORY);

    final String codeLocationName = commonVariables.getValue(HubConstantValues.HUB_CODE_LOCATION_NAME);
    final String unmapPreviousCodeLocations = commonVariables
            .getValue(HubConstantValues.HUB_UNMAP_PREVIOUS_CODE_LOCATIONS);
    final String deletePreviousCodeLocations = commonVariables
            .getValue(HubConstantValues.HUB_DELETE_PREVIOUS_CODE_LOCATIONS);

    final String hubWorkspaceCheck = commonVariables.getValue(HubConstantValues.HUB_WORKSPACE_CHECK);

    String[] excludePatternArray = new String[0];
    final String excludePatternParameter = commonVariables.getValue(HubConstantValues.HUB_EXCLUDE_PATTERNS);
    if (StringUtils.isNotBlank(excludePatternParameter)) {
        excludePatternArray = excludePatternParameter.split("\\r?\\n");
    }/*w ww  .ja v  a2s.  c  o  m*/

    final List<String> scanTargets = new ArrayList<>();
    final String scanTargetParameter = commonVariables.getValue(HubConstantValues.HUB_SCAN_TARGETS);
    if (StringUtils.isNotBlank(scanTargetParameter)) {
        final String[] scanTargetPathsArray = scanTargetParameter.split("\\r?\\n");
        for (final String target : scanTargetPathsArray) {
            if (StringUtils.isNotBlank(target)) {
                final File tmpTarget = new File(target);
                if (tmpTarget.isAbsolute()) {
                    scanTargets.add(tmpTarget.getCanonicalPath());
                } else {
                    scanTargets.add(new File(workingDirectory, target).getCanonicalPath());
                }
            }
        }
    } else {
        scanTargets.add(workingDirectory.getAbsolutePath());
    }

    final HubScanConfigBuilder hubScanConfigBuilder = new HubScanConfigBuilder();
    hubScanConfigBuilder.setWorkingDirectory(workingDirectory);
    hubScanConfigBuilder.setDryRun(Boolean.valueOf(dryRun));
    hubScanConfigBuilder.setScanMemory(scanMemory);
    hubScanConfigBuilder.setCodeLocationAlias(codeLocationName);
    hubScanConfigBuilder.addAllScanTargetPaths(scanTargets);
    hubScanConfigBuilder.setToolsDir(toolsDir);
    hubScanConfigBuilder.setCleanupLogsOnSuccess(Boolean.valueOf(cleanupLogs));
    hubScanConfigBuilder.setUnmapPreviousCodeLocations(Boolean.valueOf(unmapPreviousCodeLocations));
    hubScanConfigBuilder.setDeletePreviousCodeLocations(Boolean.valueOf(deletePreviousCodeLocations));
    hubScanConfigBuilder.setExcludePatterns(excludePatternArray);
    if (Boolean.valueOf(hubWorkspaceCheck)) {
        hubScanConfigBuilder.enableScanTargetPathsWithinWorkingDirectoryCheck();
    }
    try {
        return hubScanConfigBuilder.build();
    } catch (final IllegalStateException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.AllocationFileLoaderService.java

/**
 * Path to XML file containing allocations. If the
 * path is relative, it is searched for in the
 * classpath, but loaded like a regular File.
 *//*from  w ww .j  a v a 2  s .c  o  m*/
public File getAllocationFile(Configuration conf) {
    String allocFilePath = conf.get(FairSchedulerConfiguration.ALLOCATION_FILE,
            FairSchedulerConfiguration.DEFAULT_ALLOCATION_FILE);
    File allocFile = new File(allocFilePath);
    if (!allocFile.isAbsolute()) {
        URL url = Thread.currentThread().getContextClassLoader().getResource(allocFilePath);
        if (url == null) {
            LOG.warn(allocFilePath + " not found on the classpath.");
            allocFile = null;
        } else if (!url.getProtocol().equalsIgnoreCase("file")) {
            throw new RuntimeException(
                    "Allocation file " + url + " found on the classpath is not on the local filesystem.");
        } else {
            allocFile = new File(url.getPath());
        }
    }
    return allocFile;
}

From source file:com.xebialabs.deployit.maven.packager.ManifestPackager.java

public void addDeployableArtifact(DeployableArtifactItem item) {
    if ("Dar".equals(item.getType()))
        return;/* w ww. j a v  a 2s.  c o  m*/

    if ("Pom".equals(item.getType()))
        return;

    final Map<String, Attributes> entries = manifest.getEntries();
    final Attributes attributes = new Attributes();
    final String type = item.getType();
    final File location = new File(item.getLocation());

    attributes.putValue("CI-Type", type);
    if (item.hasName())
        attributes.putValue("CI-Name", item.getName());

    String darLocation = (item.getDarLocation() == null ? type : item.getDarLocation());

    if (item.isFolder()) {
        entries.put(darLocation, attributes);
    } else {
        if (location.isAbsolute())
            entries.put(darLocation + "/" + location.getName(), attributes);
        else
            entries.put(darLocation + "/" + item.getLocation(), attributes);
    }

    final File targetDir = new File(targetDirectory, darLocation);
    if (generateManifestOnly) {
        System.out.println("Skip copying artifact " + item.getName() + " to " + targetDir);
        return;
    }
    targetDir.mkdirs();

    File locationTargetDirs;
    //do not create missing directories is there are no parents or if the file is absolute
    if (location.isAbsolute() || location.getParent() == null) {
        locationTargetDirs = targetDir;
    } else {
        locationTargetDirs = new File(targetDir, location.getParent());
        locationTargetDirs.mkdirs();
    }

    try {
        if (location.isDirectory()) {
            FileUtils.copyDirectoryToDirectory(location, locationTargetDirs);
        } else {
            FileUtils.copyFileToDirectory(location, locationTargetDirs);
        }
    } catch (IOException e) {
        throw new RuntimeException("Fail to copy of " + location + " to " + targetDir, e);

    }

}

From source file:it.geosolutions.geobatch.actions.xstream.XstreamAction.java

public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {

    // the output
    final Queue<EventObject> ret = new LinkedList<EventObject>();
    listenerForwarder.started();/* w w w. j av  a 2s .co  m*/
    while (events.size() > 0) {
        final EventObject event = events.remove();
        if (event == null) {
            final String message = "The passed event object is null";
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(message);
            if (conf.isFailIgnored()) {
                continue;
            } else {
                final ActionException e = new ActionException(this, message);
                listenerForwarder.failed(e);
                throw e;
            }
        }

        if (event instanceof FileSystemEvent) {
            // generate an object
            final File sourceFile = File.class.cast(event.getSource());
            if (!sourceFile.exists() || !sourceFile.canRead()) {
                final String message = "XstreamAction.adapter(): The passed FileSystemEvent "
                        + "reference to a not readable or not existent file: " + sourceFile.getAbsolutePath();
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn(message);
                if (conf.isFailIgnored()) {
                    continue;
                } else {
                    final ActionException e = new ActionException(this, message);
                    listenerForwarder.failed(e);
                    throw e;
                }
            }
            FileInputStream inputStream = null;
            try {
                inputStream = new FileInputStream(sourceFile);
                final Map<String, String> aliases = conf.getAlias();
                if (aliases != null && aliases.size() > 0) {
                    for (String alias : aliases.keySet()) {
                        final Class<?> clazz = Class.forName(aliases.get(alias));
                        xstream.alias(alias, clazz);
                    }
                }

                listenerForwarder.setTask("Converting file to a java object");

                // deserialize
                final Object res = xstream.fromXML(inputStream);
                // generate event
                final EventObject eo = new EventObject(res);
                // append to the output
                ret.add(eo);

            } catch (XStreamException e) {
                // the object cannot be deserialized
                if (LOGGER.isErrorEnabled())
                    LOGGER.error("The passed FileSystemEvent reference to a not deserializable file: "
                            + sourceFile.getAbsolutePath(), e);
                if (conf.isFailIgnored()) {
                    continue;
                } else {
                    listenerForwarder.failed(e);
                    throw new ActionException(this, e.getLocalizedMessage());
                }
            } catch (Throwable e) {
                // the object cannot be deserialized
                if (LOGGER.isErrorEnabled())
                    LOGGER.error("XstreamAction.adapter(): " + e.getLocalizedMessage(), e);
                if (conf.isFailIgnored()) {
                    continue;
                } else {
                    listenerForwarder.failed(e);
                    throw new ActionException(this, e.getLocalizedMessage());
                }
            } finally {
                IOUtils.closeQuietly(inputStream);
            }

        } else {

            // try to serialize
            // build the output absolute file name
            File outputDir;
            try {
                outputDir = new File(conf.getOutput());
                // the output
                if (!outputDir.isAbsolute())
                    outputDir = it.geosolutions.tools.commons.file.Path.findLocation(outputDir, getTempDir());

                if (!outputDir.exists()) {
                    if (!outputDir.mkdirs()) {
                        final String message = "Unable to create the ouptut dir named: " + outputDir.toString();
                        if (LOGGER.isInfoEnabled())
                            LOGGER.info(message);
                        if (conf.isFailIgnored()) {
                            continue;
                        } else {
                            final ActionException e = new ActionException(this, message);
                            listenerForwarder.failed(e);
                            throw e;
                        }
                    }
                }
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("Output dir name: " + outputDir.toString());
                }

            } catch (NullPointerException npe) {
                final String message = "Unable to get the output file path from :" + conf.getOutput();
                if (LOGGER.isErrorEnabled())
                    LOGGER.error(message, npe);
                if (conf.isFailIgnored()) {
                    continue;
                } else {
                    listenerForwarder.failed(npe);
                    throw new ActionException(this, npe.getLocalizedMessage());
                }
            }

            final File outputFile;
            try {
                outputFile = File.createTempFile(conf.getOutput(), null, outputDir);
            } catch (IOException ioe) {
                final String message = "Unable to build the output file writer: " + ioe.getLocalizedMessage();
                if (LOGGER.isErrorEnabled())
                    LOGGER.error(message, ioe);
                if (conf.isFailIgnored()) {
                    continue;
                } else {
                    listenerForwarder.failed(ioe);
                    throw new ActionException(this, ioe.getLocalizedMessage());
                }
            }

            // try to open the file to write into
            FileWriter fw = null;
            try {
                listenerForwarder.setTask("Serializing java object to " + outputFile);
                fw = new FileWriter(outputFile);

                final Map<String, String> aliases = conf.getAlias();
                if (aliases != null && aliases.size() > 0) {
                    for (String alias : aliases.keySet()) {
                        final Class<?> clazz = Class.forName(aliases.get(alias));
                        xstream.alias(alias, clazz);
                    }
                }
                xstream.toXML(event.getSource(), fw);

            } catch (XStreamException e) {
                if (LOGGER.isErrorEnabled())
                    LOGGER.error(
                            "The passed event object cannot be serialized to: " + outputFile.getAbsolutePath(),
                            e);
                if (conf.isFailIgnored()) {
                    continue;
                } else {
                    listenerForwarder.failed(e);
                    throw new ActionException(this, e.getLocalizedMessage());
                }
            } catch (Throwable e) {
                // the object cannot be deserialized
                if (LOGGER.isErrorEnabled())
                    LOGGER.error(e.getLocalizedMessage(), e);
                if (conf.isFailIgnored()) {
                    continue;
                } else {
                    listenerForwarder.failed(e);
                    throw new ActionException(this, e.getLocalizedMessage());
                }
            } finally {
                IOUtils.closeQuietly(fw);
            }

            // add the file to the queue
            ret.add(new FileSystemEvent(outputFile.getAbsoluteFile(), FileSystemEventType.FILE_ADDED));

        }
    }
    listenerForwarder.completed();
    return ret;
}

From source file:de.jflex.plugin.maven.JFlexMojo.java

/**
 * Check parameter lexFile./*from   w ww  .j a v  a  2  s. co m*/
 * 
 * Must not be null and file must exist.
 * 
 * @param lexFile
 *            input file to check.
 * @throws MojoExecutionException
 *             in case of error
 */
private void checkParameters(File lexFile) throws MojoExecutionException {
    if (lexFile == null) {
        throw new MojoExecutionException(
                "<lexDefinition> is empty. Please define input file with <lexDefinition>input.jflex</lexDefinition>");
    }
    assert lexFile.isAbsolute() : lexFile;
    if (!lexFile.isFile()) {
        throw new MojoExecutionException("Input file does not exist: " + lexFile);
    }
}

From source file:org.cloudifysource.dsl.cloud.compute.ComputeTemplate.java

private File findUploadDir(final DSLValidationContext context) throws DSLValidationException {
    final File relativeUploadDir = new File(this.getLocalDirectory());
    if (relativeUploadDir.isAbsolute()) {
        throw new DSLValidationException("Upload directory of a cloud template must be a relative path, "
                + "relative to the cloud configuration directory");
    }//from www.  j  a v a 2  s . c  om

    File dslDir = null;
    if (context.getFilePath() == null) {
        throw new IllegalStateException("The DSL File location is not set! Cannot validate!");
    } else {
        final File dslFile = new File(context.getFilePath());
        dslDir = dslFile.getParentFile();
    }

    final File uploadDir = new File(dslDir, getLocalDirectory());
    if (!uploadDir.exists()) {
        throw new DSLValidationException("Could not find upload directory at: " + uploadDir);
    }

    if (!uploadDir.isDirectory()) {
        throw new DSLValidationException("Upload directory, set to: " + uploadDir + " is not a directory");
    }
    return uploadDir;
}

From source file:au.org.ala.delta.model.ResourceSettings.java

/**
 * Find a file on the resource path. The individual resource path locations
 * are checked in turn until a file with the specified name is found. The
 * dataset path is also searched if the file cannot be found at any of the
 * resource path locations./*  w  w  w. ja  v a2 s. co  m*/
 * 
 * if ignoreCase is true then the exact case is test first, and if the file
 * could not be found a case insensitive search is performed. This is avoid
 * problems with older data sets developed under MS DOS or Windows in which
 * items inconsistently cased names.
 * 
 * If the cacheDir is not null, any files found on the resource path at
 * remote locations will be copied to the cacheDir and the returned URL will
 * point to the cached copy.
 * 
 * if the fileName is already a valid URL string, this URL will be used
 * without the resource path locations being searched. If the URL points to
 * a remote location, the file will still be cached as described above.
 * 
 * @param fileName
 *            The file name
 * @param ignoreRemoteLocations
 *            if true, any remote resource path locations (i.e. those
 *            specified by http URLS) are ignored when searching.
 * @return A URL for the found file. If the found file was at a remote
 *         location, the URL will point to a local cached copy of the file,
 *         or null if the file was not found.
 */
public URL findFileOnResourcePath(String fileName, boolean ignoreRemoteLocations, boolean ignoreCase) {
    // If the fileName is a valid URL in its own right, simply return it as
    // a URL object - don't search the resource path locations

    URL fileLocation = null;

    // Check if fileName is a valid URL in itself. If it is, don't bother
    // searching the resource path.
    try {
        fileLocation = new URL(fileName);
        try {
            URL urlForCachedFile = cacheFileIfRemote(fileName, fileLocation);
            return urlForCachedFile;
        } catch (IOException ex) {
            // cache operation failed. return location to the original file.
            return fileLocation;
        }
    } catch (MalformedURLException ex) {
        // do nothing
    }

    // Check to see if the filename is an absolute filename on the
    // file system
    File file = new File(fileName);
    if (file.exists() && file.isAbsolute()) {
        try {
            return file.toURI().toURL();
        } catch (MalformedURLException ex) {
            // Ignore
        }
    }

    if (ignoreCase) {
        file = FileUtils.findFileIgnoreCase(file);
        if (file != null) {
            try {
                return file.toURI().toURL();
            } catch (MalformedURLException ex) {
                // Ignore
            }
        }
    }

    // Finally, before searching the resource path, check if the file has previously been saved in the cache
    URL urlForPreviouslyCachedFile = loadFileFromCache(fileName);
    if (urlForPreviouslyCachedFile != null) {
        return urlForPreviouslyCachedFile;
    }

    List<String> locationsToSearch = getResourcePathLocations();
    // If file cannot be found at any of the resource path locations, also
    // search the
    // dataset path itself.
    locationsToSearch.add(getDataSetPath());

    for (String resourcePath : locationsToSearch) {
        try {
            if (_remoteResourceLocations.contains(resourcePath)) {
                if (ignoreRemoteLocations) {
                    continue;
                }

                if (resourcePath.endsWith("/")) {
                    fileLocation = new URL(resourcePath + fileName);
                } else {
                    fileLocation = new URL(resourcePath + "/" + fileName);
                }

                // Try opening a stream to the remote file. If no exceptions
                // are thrown, the file
                // was successfully found at that location. Unfortunately
                // there is no better way to
                // test existence of a remote file.
                InputStream stream = fileLocation.openStream();
                stream.close();
                break;
            } else {
                File f = new File(resourcePath + File.separator + fileName);
                if (f.exists()) {
                    fileLocation = f.toURI().toURL();
                    break;
                } else {
                    if (ignoreCase) {
                        f = FileUtils.findFileIgnoreCase(f);
                        if (f != null) {
                            fileLocation = f.toURI().toURL();
                            break;
                        }
                    }
                }

            }

        } catch (IOException ioexception) {
            // do nothing, keep searching on image path.
        }
    }

    if (fileLocation == null) {
        return fileLocation;
    } else {
        try {
            // Attempt to cache the file found on the resource path.
            URL urlForCachedFile = cacheFileIfRemote(fileName, fileLocation);
            return urlForCachedFile;
        } catch (IOException ex) {
            // cache operation failed. return location to the original file.
            return fileLocation;
        }
    }
}

From source file:org.eclipse.jubula.client.ui.rcp.widgets.autconfig.WinAutConfigComponent.java

/**
 * Handles the button event./* ww  w.  j  a v  a2s.  c  o  m*/
 * @param fileDialog The file dialog.
 */
void handleExecButtonEvent(FileDialog fileDialog) {
    String directory;
    fileDialog.setText(Messages.AUTConfigComponentSelectExecutable);
    String filterPath = Utils.getLastDirPath();
    File path = new File(getConfigValue(AutConfigConstants.EXECUTABLE));
    final String[] filterExe = { "*.exe" }; //$NON-NLS-1$
    fileDialog.setFilterExtensions(filterExe);
    if (!path.isAbsolute()) {
        path = new File(getConfigValue(AutConfigConstants.WORKING_DIR),
                getConfigValue(AutConfigConstants.EXECUTABLE));
    }
    if (path.exists()) {
        try {
            if (path.isDirectory()) {
                filterPath = path.getCanonicalPath();
            } else {
                filterPath = new File(path.getParent()).getCanonicalPath();
            }
        } catch (IOException e) {
            // Just use the default filter path which is already set
        }
    }
    fileDialog.setFilterPath(filterPath);
    directory = fileDialog.open();
    if (directory != null) {
        m_execTextField.setText(directory);
        Utils.storeLastDirPath(fileDialog.getFilterPath());
        putConfigValue(AutConfigConstants.EXECUTABLE, directory);
        executablePath = directory;
        setWorkingDirToExecFilePath(executablePath);
    }
}