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:io.sloeber.core.managers.Manager.java

public static IStatus extract(ArchiveInputStream in, File destFolder, int stripPath, boolean overwrite,
        IProgressMonitor pMonitor) throws IOException, InterruptedException {

    // Folders timestamps must be set at the end of archive extraction
    // (because creating a file in a folder alters the folder's timestamp)
    Map<File, Long> foldersTimestamps = new HashMap<>();

    String pathPrefix = ""; //$NON-NLS-1$

    Map<File, File> hardLinks = new HashMap<>();
    Map<File, Integer> hardLinksMode = new HashMap<>();
    Map<File, String> symLinks = new HashMap<>();
    Map<File, Long> symLinksModifiedTimes = new HashMap<>();

    // Cycle through all the archive entries
    while (true) {
        ArchiveEntry entry = in.getNextEntry();
        if (entry == null) {
            break;
        }//from  w w w  . j  a  v a 2  s .  com

        // Extract entry info
        long size = entry.getSize();
        String name = entry.getName();
        boolean isDirectory = entry.isDirectory();
        boolean isLink = false;
        boolean isSymLink = false;
        String linkName = null;
        Integer mode = null;
        Long modifiedTime = new Long(entry.getLastModifiedDate().getTime());

        pMonitor.subTask("Processing " + name); //$NON-NLS-1$

        {
            // Skip MacOSX metadata
            // http://superuser.com/questions/61185/why-do-i-get-files-like-foo-in-my-tarball-on-os-x
            int slash = name.lastIndexOf('/');
            if (slash == -1) {
                if (name.startsWith("._")) { //$NON-NLS-1$
                    continue;
                }
            } else {
                if (name.substring(slash + 1).startsWith("._")) { //$NON-NLS-1$
                    continue;
                }
            }
        }

        // Skip git metadata
        // http://www.unix.com/unix-for-dummies-questions-and-answers/124958-file-pax_global_header-means-what.html
        if (name.contains("pax_global_header")) { //$NON-NLS-1$
            continue;
        }

        if (entry instanceof TarArchiveEntry) {
            TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
            mode = new Integer(tarEntry.getMode());
            isLink = tarEntry.isLink();
            isSymLink = tarEntry.isSymbolicLink();
            linkName = tarEntry.getLinkName();
        }

        // On the first archive entry, if requested, detect the common path
        // prefix to be stripped from filenames
        int localstripPath = stripPath;
        if (localstripPath > 0 && pathPrefix.isEmpty()) {
            int slash = 0;
            while (localstripPath > 0) {
                slash = name.indexOf("/", slash); //$NON-NLS-1$
                if (slash == -1) {
                    throw new IOException(Messages.Manager_no_single_root_folder);
                }
                slash++;
                localstripPath--;
            }
            pathPrefix = name.substring(0, slash);
        }

        // Strip the common path prefix when requested
        if (!name.startsWith(pathPrefix)) {
            throw new IOException(Messages.Manager_no_single_root_folder_while_file + name
                    + Messages.Manager_is_outside + pathPrefix);
        }
        name = name.substring(pathPrefix.length());
        if (name.isEmpty()) {
            continue;
        }
        File outputFile = new File(destFolder, name);

        File outputLinkedFile = null;
        if (isLink && linkName != null) {
            if (!linkName.startsWith(pathPrefix)) {
                throw new IOException(Messages.Manager_no_single_root_folder_while_file + linkName
                        + Messages.Manager_is_outside + pathPrefix);
            }
            linkName = linkName.substring(pathPrefix.length());
            outputLinkedFile = new File(destFolder, linkName);
        }
        if (isSymLink) {
            // Symbolic links are referenced with relative paths
            outputLinkedFile = new File(linkName);
            if (outputLinkedFile.isAbsolute()) {
                System.err.println(Messages.Manager_Warning_file + outputFile
                        + Messages.Manager_links_to_absolute_path + outputLinkedFile);
                System.err.println();
            }
        }

        // Safety check
        if (isDirectory) {
            if (outputFile.isFile() && !overwrite) {
                throw new IOException(
                        Messages.Manager_Cant_create_folder + outputFile + Messages.Manager_File_exists);
            }
        } else {
            // - isLink
            // - isSymLink
            // - anything else
            if (outputFile.exists() && !overwrite) {
                throw new IOException(
                        Messages.Manager_Cant_extract_file + outputFile + Messages.Manager_File_already_exists);
            }
        }

        // Extract the entry
        if (isDirectory) {
            if (!outputFile.exists() && !outputFile.mkdirs()) {
                throw new IOException(Messages.Manager_Cant_create_folder + outputFile);
            }
            foldersTimestamps.put(outputFile, modifiedTime);
        } else if (isLink) {
            hardLinks.put(outputFile, outputLinkedFile);
            hardLinksMode.put(outputFile, mode);
        } else if (isSymLink) {
            symLinks.put(outputFile, linkName);
            symLinksModifiedTimes.put(outputFile, modifiedTime);
        } else {
            // Create the containing folder if not exists
            if (!outputFile.getParentFile().isDirectory()) {
                outputFile.getParentFile().mkdirs();
            }
            copyStreamToFile(in, size, outputFile);
            outputFile.setLastModified(modifiedTime.longValue());
        }

        // Set file/folder permission
        if (mode != null && !isSymLink && outputFile.exists()) {
            chmod(outputFile, mode.intValue());
        }
    }

    for (Map.Entry<File, File> entry : hardLinks.entrySet()) {
        if (entry.getKey().exists() && overwrite) {
            entry.getKey().delete();
        }
        link(entry.getValue(), entry.getKey());
        Integer mode = hardLinksMode.get(entry.getKey());
        if (mode != null) {
            chmod(entry.getKey(), mode.intValue());
        }
    }

    for (Map.Entry<File, String> entry : symLinks.entrySet()) {
        if (entry.getKey().exists() && overwrite) {
            entry.getKey().delete();
        }
        symlink(entry.getValue(), entry.getKey());
        entry.getKey().setLastModified(symLinksModifiedTimes.get(entry.getKey()).longValue());
    }

    // Set folders timestamps
    for (Map.Entry<File, Long> entry : foldersTimestamps.entrySet()) {
        entry.getKey().setLastModified(entry.getValue().longValue());
    }

    return Status.OK_STATUS;

}

From source file:org.apache.hadoop.security.KerberosDiags.java

/**
 * A cursory look at the {@code kinit} executable.
 * If it is an absolute path: it must exist with a size > 0.
 * If it is just a command, it has to be on the path. There's no check
 * for that -but the PATH is printed out.
 *///from  w ww.jav a  2s  .com
private void validateKinitExecutable() {
    String kinit = conf.getTrimmed(KERBEROS_KINIT_COMMAND, "");
    if (!kinit.isEmpty()) {
        File kinitPath = new File(kinit);
        println("%s = %s", KERBEROS_KINIT_COMMAND, kinitPath);
        if (kinitPath.isAbsolute()) {
            failif(!kinitPath.exists(), CAT_KERBEROS, "%s executable does not exist: %s",
                    KERBEROS_KINIT_COMMAND, kinitPath);
            failif(!kinitPath.isFile(), CAT_KERBEROS, "%s path does not refer to a file: %s",
                    KERBEROS_KINIT_COMMAND, kinitPath);
            failif(kinitPath.length() == 0, CAT_KERBEROS, "%s file is empty: %s", KERBEROS_KINIT_COMMAND,
                    kinitPath);
        } else {
            println("Executable %s is relative -must be on the PATH", kinit);
            printEnv("PATH");
        }
    }
}

From source file:org.fornax.toolsupport.sculptor.maven.plugin.GeneratorMojo.java

/**
 * Returns a list with file names from the <code>checkFileSets</code>
 * parameter that have been modified since previous generator run. Empty if
 * no files changed or <code>null</code> if there is no status file to
 * compare against, i.e. always run the generator.
 *//*ww  w . j a v a  2s  .  c  o  m*/
protected Set<String> getChangedFiles() {

    // If there is no status file to compare against then always run the
    // generator
    if (!statusFile.exists()) {
        return null;
    }
    final long statusFileLastModified = statusFile.lastModified();
    final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    if (isVerbose() || getLog().isDebugEnabled()) {
        getLog().info("Last code generator execution: " + df.format(new Date(statusFileLastModified)));
    }

    // Create list of files to check - start with project pom.xml and
    // generator config files
    List<File> filesToCheck = new ArrayList<File>();
    filesToCheck.add(new File(project.getBasedir(), "pom.xml"));

    // Now add generator config files
    FileSet generatorFileSet = new FileSet();
    generatorFileSet.setDirectory(project.getBasedir() + "/src/main/resources/generator");
    generatorFileSet.addInclude("*");
    filesToCheck.addAll(toFileList(generatorFileSet));

    // Finally add files from configured filesets in 'checkFileSets'
    for (FileSet fs : checkFileSets) {
        filesToCheck.addAll(toFileList(fs));
    }

    // Check files for modification
    Set<String> changedFiles = new HashSet<String>();
    for (File checkFile : filesToCheck) {
        if (!checkFile.isAbsolute()) {
            checkFile = new File(project.getBasedir(), checkFile.getPath());
        }
        final boolean isModified = checkFile.lastModified() > statusFileLastModified;
        if (isModified) {
            changedFiles.add(checkFile.getAbsolutePath());
        }
        if (isVerbose() || getLog().isDebugEnabled()) {
            getLog().info(
                    "File '" + checkFile.getAbsolutePath() + "': " + (isModified ? "outdated" : "up-to-date")
                            + " (" + " " + df.format(new Date(checkFile.lastModified())) + ")");
        }
    }

    // Print info of result
    if (changedFiles.size() == 1) {
        String fileName = changedFiles.iterator().next();
        if (fileName.startsWith(project.getBasedir().getAbsolutePath())) {
            fileName = fileName.substring(project.getBasedir().getAbsolutePath().length() + 1);
        }
        final String message = MessageFormat.format(
                "\"{0}\" has been modified since last generator " + "run at {1}", fileName,
                df.format(new Date(statusFileLastModified)));
        getLog().info(message);
    } else if (changedFiles.size() > 1) {
        final String message = MessageFormat.format(
                "{0} checked resources have been modified since " + "last generator run at {1}",
                changedFiles.size(), df.format(new Date(statusFileLastModified)));
        getLog().info(message);
    } else {
        getLog().info("Everything is up to date - no generator run is needed");
    }
    return changedFiles;
}

From source file:org.deegree.services.wps.WPService.java

@Override
public void init(DeegreeServicesMetadataType serviceMetadata, DeegreeServiceControllerType mainConf,
        Object controllerConf) {/*w ww . j  a  va2s .  com*/
    LOG.info("Initializing WPS.");
    DeegreeWPS sc = (DeegreeWPS) controllerConf;

    String storage = "../var/wps";
    int trackedExecutions = 100;
    int inputDiskSwitchLimit = 1024 * 1024;
    if (sc.getAbstractExecutionManager() != null) {
        LOG.info("Explicit ExecutionManager config.");
        DefaultExecutionManager execManagerConfig = (DefaultExecutionManager) sc.getAbstractExecutionManager()
                .getValue();
        if (execManagerConfig.getStorageDir() != null && !execManagerConfig.getStorageDir().isEmpty()) {
            storage = execManagerConfig.getStorageDir();
        }
        if (execManagerConfig.getTrackedExecutions() != null) {
            trackedExecutions = execManagerConfig.getTrackedExecutions().intValue();
        }
        if (execManagerConfig.getInputDiskSwitchLimit() != null) {
            inputDiskSwitchLimit = execManagerConfig.getInputDiskSwitchLimit().intValue();
        }
    }

    File storageDir = null;
    try {
        File base = metadata.getLocation().resolveToFile(".");
        storageDir = new File(storage);
        if (!storageDir.isAbsolute()) {
            storageDir = new File(base, storage).getCanonicalFile();
        }
        FileUtils.forceMkdir(storageDir);
    } catch (Throwable t) {
        String msg = "Storage directory error: " + t.getMessage();
        throw new ResourceInitException(msg);
    }
    storageManager = new StorageManager(storageDir, inputDiskSwitchLimit);

    this.processManager = workspace.getResourceManager(ProcessManager.class);

    validateAndSetOfferedVersions(sc.getSupportedVersions().getVersion());

    executeHandler = new ExecutionManager(this, storageManager, trackedExecutions);
    mainMetadataConf = serviceMetadata;
}

From source file:azkaban.jobtype.HadoopSparkJob.java

@Override
protected List<String> getClassPaths() {
    // The classpath for the process that runs HadoopSecureSparkWrapper
    final String pluginDir = getSysProps().get("plugin.dir");
    final List<String> classPath = super.getClassPaths();

    // To add az-core jar classpath
    classPath.add(getSourcePathFromClass(Props.class));

    // To add az-common jar classpath
    classPath.add(getSourcePathFromClass(JavaProcessJob.class));
    classPath.add(getSourcePathFromClass(HadoopSecureHiveWrapper.class));
    classPath.add(getSourcePathFromClass(HadoopSecurityManager.class));

    classPath.add(HadoopConfigurationInjector.getPath(getJobProps(), getWorkingDirectory()));

    final List<String> typeClassPath = getSysProps().getStringList("jobtype.classpath", null, ",");
    info("Adding jobtype.classpath: " + typeClassPath);
    if (typeClassPath != null) {
        // fill in this when load this jobtype
        for (final String jar : typeClassPath) {
            File jarFile = new File(jar);
            if (!jarFile.isAbsolute()) {
                jarFile = new File(pluginDir + File.separatorChar + jar);
            }//  ww  w . java  2 s. c o  m
            if (!classPath.contains(jarFile.getAbsolutePath())) {
                classPath.add(jarFile.getAbsolutePath());
            }
        }
    }

    // Decide spark home/conf and append Spark classpath for the client.
    final String[] sparkHomeConf = getSparkLibConf();

    classPath.add(sparkHomeConf[0] + "/*");
    classPath.add(sparkHomeConf[1]);

    final List<String> typeGlobalClassPath = getSysProps().getStringList("jobtype.global.classpath", null, ",");
    info("Adding jobtype.global.classpath: " + typeGlobalClassPath);
    if (typeGlobalClassPath != null) {
        for (final String jar : typeGlobalClassPath) {
            if (!classPath.contains(jar)) {
                classPath.add(jar);
            }
        }
    }

    info("Final classpath: " + classPath);
    return classPath;
}

From source file:com.boundlessgeo.geoserver.api.controllers.StoreController.java

private String source(URL url) {
    File baseDirectory = dataDir().getResourceLoader().getBaseDirectory();

    if (url.getProtocol().equals("file")) {
        File file = Files.url(baseDirectory, url.toExternalForm());
        if (file != null && !file.isAbsolute()) {
            return Paths.convert(baseDirectory, file);
        }/* ww  w .j  a  v a  2s .  c o m*/
    }
    return url.toExternalForm();
}

From source file:com.boundlessgeo.geoserver.api.controllers.StoreController.java

private String source(File file) {
    File baseDirectory = dataDir().getResourceLoader().getBaseDirectory();
    return file.isAbsolute() ? file.toString() : Paths.convert(baseDirectory, file);
}

From source file:com.anrisoftware.sscontrol.profile.service.ProfilePropertiesImpl.java

/**
 * Returns the profile path property. If the profile property was not set
 * return the default value from the default properties. If the path is not
 * absolute then it is assume to be under the specified parent directory.
 *
 * @param key//from w  w w. ja va  2  s.c o m
 *            the key of the profile property.
 *
 * @param parent
 *            the parent {@link File} directory.
 *
 * @param p
 *            default {@link ContextProperties} properties.
 *
 * @return the profile file {@link File} path.
 *
 * @throws ServiceException
 *             if the profile property was not found.
 */
public File profileFileProperty(String key, File parent, ContextProperties defaults) throws ServiceException {
    Object value = profileProperty(key, defaults);
    File path;
    if (value instanceof File) {
        path = (File) value;
    } else {
        path = new File(value.toString());
    }
    return path.isAbsolute() ? path : new File(parent, path.getPath());
}

From source file:languageTools.analyzer.mas.MASValidator.java

@Override
public Void visitEnvironment(EnvironmentContext ctx) {
    /**/*from   w w w  .j  a  v a 2 s.c o  m*/
     * Get the reference to the environment interface file.
     */
    String filename;
    if (ctx.string() == null) {
        filename = "";
    } else {
        filename = visitString(ctx.string());
    }
    if (filename.isEmpty()) {
        reportWarning(MASWarning.ENVIRONMENT_NO_REFERENCE, ctx);
    }
    File environmentfile = new File(filename);
    if (!environmentfile.isAbsolute()) {
        // relative to path specified for MAS file
        environmentfile = new File(getPathRelativeToSourceFile(filename));
    }

    // If extension is "jar", the file must exist;
    // otherwise it can be a reference to an existing environment.
    String ext = FilenameUtils.getExtension(filename);
    if (ext.equals("jar") && !environmentfile.isFile()) {
        reportError(MASError.ENVIRONMENT_COULDNOT_FIND, ctx, environmentfile.getPath());
    } else {
        getProgram().setEnvironmentfile(environmentfile);
    }

    /**
     * Get list of key-value initialization parameters.
     */
    for (InitKeyValueContext pair : ctx.initKeyValue()) {
        visitInitKeyValue(pair);
    }

    return null; // Java says must return something even when Void
}

From source file:com.baidu.jprotobuf.mojo.PreCompileMojo.java

private void addAdditionalClasspathElements(List<URL> path) {
    if (additionalClasspathElements != null) {
        for (String classPathElement : additionalClasspathElements) {
            try {
                File file = new File(classPathElement);
                if (!file.isAbsolute()) {
                    file = new File(project.getBasedir(), classPathElement);
                }/*from ww  w  .j a va  2s  .c  o m*/
                URL url = file.toURI().toURL();
                getLog().debug("Adding additional classpath element: " + url + " to classpath");
                path.add(url);
            } catch (MalformedURLException e) {
                getLog().warn("Skipping additional classpath element: " + classPathElement, e);
            }
        }
    }
}