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.fao.geonet.services.resources.DownloadArchive.java

private String getLicenseFilesPath(String licenseURL, ServiceContext context) throws MalformedURLException {
    // TODO: Ideally this method should probably read an xml file to map
    // license url's to the sub-directory containing mirrored files
    // but for the moment we'll just use the url path to identify this

    //--- Get license files subdirectory for license
    URL url = new URL(licenseURL);
    String licenseFilesPath = url.getHost() + url.getPath();
    if (context.isDebug())
        context.debug("licenseFilesPath= " + licenseFilesPath);

    //--- Get local mirror directory for license files
    String path = context.getAppPath();
    if (context.isDebug())
        context.debug("path= " + path);

    GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
    ServiceConfig configHandler = gc.getBean(ServiceConfig.class);
    String licenseDir = configHandler.getValue(Geonet.Config.LICENSE_DIR);
    if (context.isDebug())
        context.debug("licenseDir= " + licenseDir);
    if (licenseDir == null)
        return null;

    File directory = new File(licenseDir);
    if (!directory.isAbsolute())
        licenseDir = path + licenseDir;/*from   w ww.j a va  2s.c o m*/

    //--- return license files directory
    return licenseDir + '/' + licenseFilesPath;
}

From source file:org.freeplane.plugin.script.ScriptingConfiguration.java

/**
 * if <code>path</code> is not an absolute path, prepends the freeplane user
 * directory to it.//from ww w . j a v  a 2s .  com
 */
private File createFile(final String path) {
    File file = new File(path);
    if (!file.isAbsolute()) {
        file = new File(ResourceController.getResourceController().getFreeplaneUserDirectory(), path);
    }
    return file;
}

From source file:org.geoserver.monitor.auditlog.AuditLogger.java

void initDumper() throws IOException {
    if (getProperty("enabled", Boolean.class, false)) {
        // prepare the config
        rollLimit = getProperty("roll_limit", Integer.class, DEFAULT_ROLLING_LIMIT);
        path = System.getProperty("GEOSERVER_AUDIT_PATH");
        if (path == null || "".equals(path.trim())) {
            path = config.getProperty(AUDIT, "path", String.class);
        }//ww w. j a  v a2 s  . co m
        headerTemplate = getProperty("ftl.header", String.class, null);
        contentTemplate = getProperty("ftl.content", String.class, null);
        footerTemplate = getProperty("ftl.footer", String.class, null);

        // check the path
        File loggingDir = new File(path);
        if (!loggingDir.isAbsolute()) {
            loggingDir = new File(GeoserverDataDirectory.getGeoserverDataDirectory(), loggingDir.getPath());
        }
        if (!loggingDir.exists()) {
            if (!loggingDir.mkdirs()) {
                throw new IllegalArgumentException("Could not create the audit files directory");
            }
        }

        path = config.getProperty(AUDIT, "path", String.class);

        // setup the dumper
        this.dumper = new RequestDumper(loggingDir, rollLimit, headerTemplate, contentTemplate, footerTemplate);
    }
}

From source file:io.sloeber.core.managers.InternalPackageManager.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 = new String();

    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;
        }//w  w  w.j a  va 2 s . c  om

        // 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_archiver_eror_single_root_folder_required);
                }
                slash++;
                localstripPath--;
            }
            pathPrefix = name.substring(0, slash);
        }

        // Strip the common path prefix when requested
        if (!name.startsWith(pathPrefix)) {
            throw new IOException(Messages.Manager_archive_error_root_folder_name_mismatch.replace(FILE, name)
                    .replace(FOLDER, 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_archive_error_root_folder_name_mismatch
                        .replace(FILE, name).replace(FOLDER, 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_archive_error_symbolic_link_to_absolute_path
                        .replace(FILE, outputFile.toString()).replace(FOLDER, outputLinkedFile.toString()));
                System.err.println();
            }
        }

        // Safety check
        if (isDirectory) {
            if (outputFile.isFile() && !overwrite) {
                throw new IOException(
                        Messages.Manager_Cant_create_folder_exists.replace(FILE, outputFile.getPath()));
            }
        } else {
            // - isLink
            // - isSymLink
            // - anything else
            if (outputFile.exists() && !overwrite) {
                throw new IOException(
                        Messages.Manager_Cant_extract_file_exist.replace(FILE, outputFile.getPath()));
            }
        }

        // Extract the entry
        if (isDirectory) {
            if (!outputFile.exists() && !outputFile.mkdirs()) {
                throw new IOException(Messages.Manager_Cant_create_folder.replace(FILE, outputFile.getPath()));
            }
            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.jmeter.protocol.http.control.CookieManager.java

/**
 * Save the static cookie data to a file.
 * Cookies are only taken from the GUI - runtime cookies are not included.
 *///  w  w w .jav  a 2 s.c  o m
public void save(String authFile) throws IOException {
    File file = new File(authFile);
    if (!file.isAbsolute()) {
        file = new File(System.getProperty("user.dir") // $NON-NLS-1$
                + File.separator + authFile);
    }
    PrintWriter writer = new PrintWriter(new FileWriter(file));
    writer.println("# JMeter generated Cookie file");// $NON-NLS-1$
    PropertyIterator cookies = getCookies().iterator();
    long now = System.currentTimeMillis();
    while (cookies.hasNext()) {
        Cookie cook = (Cookie) cookies.next().getObjectValue();
        final long expiresMillis = cook.getExpiresMillis();
        if (expiresMillis == 0 || expiresMillis > now) { // only save unexpired cookies
            writer.println(cookieToString(cook));
        }
    }
    writer.flush();
    writer.close();
}

From source file:org.apache.velocity.test.BaseTestCase.java

protected String getFileName(final String dir, final String base, final String ext, final boolean mustExist) {
    StringBuffer buf = new StringBuffer();
    try {/* w  w w .  j  a v a  2s .c o m*/
        File baseFile = new File(base);
        if (dir != null) {
            if (!baseFile.isAbsolute()) {
                baseFile = new File(dir, base);
            }

            buf.append(baseFile.getCanonicalPath());
        } else {
            buf.append(baseFile.getPath());
        }

        if (org.apache.commons.lang.StringUtils.isNotEmpty(ext)) {
            buf.append('.').append(ext);
        }

        if (mustExist) {
            File testFile = new File(buf.toString());

            if (!testFile.exists()) {
                String msg = "getFileName() result " + testFile.getPath() + " does not exist!";
                info(msg);
                fail(msg);
            }

            if (!testFile.isFile()) {
                String msg = "getFileName() result " + testFile.getPath() + " is not a file!";
                info(msg);
                fail(msg);
            }
        }
    } catch (IOException e) {
        fail("IO Exception while running getFileName(" + dir + ", " + base + ", " + ext + ", " + mustExist
                + "): " + e.getMessage());
    }

    return buf.toString();
}

From source file:au.org.ala.delta.editor.model.EditorDataModel.java

@Override
public String getImagePath() {
    ImageSettings settings = getImageSettings();
    String imagePath = settings.getFirstResourcePathLocation();
    File file = new File(imagePath);
    if (!file.isAbsolute()) {
        imagePath = getDataSetPath() + imagePath;
    }/*from   w w  w .  j  a va2 s . c  om*/

    return imagePath;
}

From source file:com.funambol.ctp.server.config.CTPServerConfigBean.java

/**
 * Called by CTPServerConfiguration to say to the bean the config path.
 * In this waym the config bean can arrange relative path.
 * @param configPath the configuration path
 *///from  www . java  2s.  co  m
public void fixConfigPath(String configPath) {
    //
    // We updated the jgroups configuration files in order to have them
    // under config dir
    //
    if (notificationGroupConfigFileName != null) {
        File file = new File(notificationGroupConfigFileName);
        String filePath = file.getPath();
        if (!file.isAbsolute()) {
            File newFile = new File(configPath + File.separator + filePath);
            notificationGroupConfigFileName = newFile.getPath();
        }
    }

    //
    // We updated the clusterConfiguration objecct in order to have the
    // cluster configuration file under config dir
    //
    if (clusterConfiguration != null) {
        if (clusterConfiguration.getConfigurationFile() != null) {
            File file = new File(clusterConfiguration.getConfigurationFile());
            String filePath = file.getPath();
            if (!file.isAbsolute()) {
                File newFile = new File(configPath + File.separator + filePath);
                clusterConfiguration.setConfigurationFile(newFile.getPath());
            }
        }
    }

}

From source file:de.pdark.dsmp.Config.java

public void reload() {
    String fileName = System.getProperty("dsmp.conf", "dsmp.conf.xml");
    File configFile = new File(fileName);
    if (!configFile.isAbsolute())
        configFile = new File(getBaseDirectory(), fileName);

    // TODO This means one access to the file system per Config method call
    long lastModified = configFile.lastModified();
    if (config == null || lastModified != configLastModified) {
        log.info((config == null ? "Loading" : "Reloading") + " config from " + configFile.getAbsolutePath());
        configLastModified = lastModified;

        SAXBuilder builder = new SAXBuilder();
        Throwable t = null;/*from w  w w  . ja v  a 2 s . c om*/
        Document doc = config;
        List<MirrorEntry> tmpMirrors = mirrors;
        List<AllowDeny> tmpAllowDeny = allowDeny;
        String[] tmpNoProxy = noProxy;
        int tmpPort = serverPort;
        String tmpProxyHost = proxyHost;
        int tmpProxyPort = proxyPort;
        String tmpProxyUser = proxyUser;
        String tmpProxyPassword = proxyPassword;
        File tmpCacheDirectory = cacheDirectory;
        File tmpPatchesDirectory = patchesDirectory;

        try {
            doc = builder.build(configFile);
            Element root = doc.getRootElement();
            tmpCacheDirectory = getCacheDirectory(root);
            tmpPatchesDirectory = getPatchesDirectory(root);
            tmpMirrors = getMirrors(root);
            tmpAllowDeny = getAllowDeny(root);
            tmpNoProxy = getNoProxy(root);
            tmpPort = getPort(root);
            tmpProxyHost = getProxyHost(root);
            tmpProxyPort = getProxyPort(root);
            tmpProxyUser = getProxyUsername(root);
            tmpProxyPassword = getProxyPassword(root);
        } catch (JDOMException e) {
            t = e;
        } catch (IOException e) {
            t = e;
        }

        if (t != null) {
            String msg = "Error loading config from " + configFile.getAbsolutePath();
            log.error(msg, t);
            if (config == null)
                throw new Error(msg, t);
        }

        // TODO All options should be checked for errors

        // After the error checking, save the new parameters
        config = doc;
        cacheDirectory = tmpCacheDirectory;
        patchesDirectory = tmpPatchesDirectory;
        mirrors = tmpMirrors;
        allowDeny = tmpAllowDeny;
        noProxy = tmpNoProxy;
        serverPort = tmpPort;
        proxyHost = tmpProxyHost;
        proxyPort = tmpProxyPort;
        proxyUser = tmpProxyUser;
        proxyPassword = tmpProxyPassword;
    }
}

From source file:org.geoserver.security.jdbc.AbstractJDBCService.java

/**
 * Check for the existence of the file, if the
 * file exists do nothing./*from  w w  w. j ava 2 s  .c  o  m*/
 * 
 * If the file does not exist, check for a template
 * file contained in the jar with the same name, 
 * if found, use it.
 * 
 * If no template was found, use the default template
 * 
 * 
 * @param fileName, target location
 * @param namedRoot, parent dir if fileName is relative
 * @param defaultResource, the standard template
 * @throws IOException
 * @return the file to use
 */
protected File checkORCreateJDBCPropertyFile(String fileName, File namedRoot, String defaultResource)
        throws IOException {

    fileName = fileName != null ? fileName : defaultResource;
    File file = new File(fileName);
    if (file.isAbsolute() == false)
        file = new File(namedRoot, fileName);

    if (file.exists())
        return file; // we are happy

    // try to find a template with the same name
    URL url = this.getClass().getResource(fileName);
    if (url != null)
        FileUtils.copyURLToFile(url, file);
    else // use the default template
        FileUtils.copyURLToFile(getClass().getResource(defaultResource), file);

    return file;

}