Example usage for java.nio.file Path toAbsolutePath

List of usage examples for java.nio.file Path toAbsolutePath

Introduction

In this page you can find the example usage for java.nio.file Path toAbsolutePath.

Prototype

Path toAbsolutePath();

Source Link

Document

Returns a Path object representing the absolute path of this path.

Usage

From source file:org.jboss.as.test.manualmode.elytron.CustomCredentialSecurityFactoryTestCase.java

public static void prepareServerConfiguration() throws Exception {
    tempFolder = Files/*from  w w  w .  j  av  a  2 s .c o m*/
            .createTempDirectory("ely-" + CustomCredentialSecurityFactoryTestCase.class.getSimpleName());

    Path fsRealmPath = tempFolder.resolve("fs-realm-users");

    try (CLIWrapper cli = new CLIWrapper(true)) {
        final String levelStr = "";

        Path moduleJar = createJar("testJar", CustomCredentialSecurityFactoryImpl.class);
        try {
            cli.sendLine("module add --name=" + CUSTOM_CREDENTIAL_SECURITY_FACTORY_MODULE_NAME
                    + " --slot=main --dependencies=org.wildfly.security.elytron,org.wildfly.extension.elytron --resources="
                    + moduleJar.toAbsolutePath());
        } finally {
            Files.deleteIfExists(moduleJar);
        }

        cli.sendLine(String.format(
                "/subsystem=elytron/custom-credential-security-factory=%s:add(class-name=%s, module=%s)",
                CUSTOM_CRED_SEC_FACTORY_NAME, CustomCredentialSecurityFactoryImpl.class.getName(),
                CUSTOM_CREDENTIAL_SECURITY_FACTORY_MODULE_NAME));

        cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add(path=\"%s\", %s)",
                MANAGEMENT_FILESYSTEM_NAME, escapePath(fsRealmPath.toAbsolutePath().toString()), levelStr));
        cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add-identity(identity=%s)",
                MANAGEMENT_FILESYSTEM_NAME, USER));
        cli.sendLine(String.format(
                "/subsystem=elytron/filesystem-realm=%s:set-password(identity=%s, clear={password=\"%s\"})",
                MANAGEMENT_FILESYSTEM_NAME, USER, CORRECT_PASSWORD));

        cli.sendLine(String.format(
                "/subsystem=elytron/security-domain=%1$s:add(realms=[{realm=%1$s,role-decoder=groups-to-roles},{realm=local,role-mapper=super-user-mapper}],default-realm=%1$s,permission-mapper=default-permission-mapper)",
                MANAGEMENT_FILESYSTEM_NAME));
        cli.sendLine(String.format(
                "/subsystem=elytron/http-authentication-factory=%1$s:add(http-server-mechanism-factory=%2$s,security-domain=%1$s,"
                        + "mechanism-configurations=[{mechanism-name=BASIC,mechanism-realm-configurations=[{realm-name=\"%1$s\"}]}, credential-security-factory=%3$s])",
                MANAGEMENT_FILESYSTEM_NAME, PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY,
                CUSTOM_CRED_SEC_FACTORY_NAME));
        cli.sendLine(String.format(
                "/core-service=management/management-interface=http-interface:write-attribute(name=http-authentication-factory,value=%s)",
                MANAGEMENT_FILESYSTEM_NAME));
        ServerReload.executeReloadAndWaitForCompletion(CONTROLLER.getClient().getControllerClient());
    }
}

From source file:org.apache.geode.management.internal.cli.util.MergeLogs.java

public static void mergeLogsInNewProcess(Path logDirectory) {
    // create a new process for merging
    LogWrapper.getInstance().fine("Exporting logs merging logs" + logDirectory);
    List<String> commandList = new ArrayList<String>();
    commandList.add(System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar + "java");
    commandList.add("-classpath");
    commandList.add(System.getProperty("java.class.path", "."));
    commandList.add(MergeLogs.class.getName());

    commandList.add(logDirectory.toAbsolutePath().toString());

    ProcessBuilder procBuilder = new ProcessBuilder(commandList);
    StringBuilder output = new StringBuilder();
    String errorString = new String();
    try {/*ww  w. jav a2s.c  o m*/
        LogWrapper.getInstance().fine("Exporting logs now merging logs");
        Process mergeProcess = procBuilder.redirectErrorStream(true).start();

        mergeProcess.waitFor();

        InputStream inputStream = mergeProcess.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;

        while ((line = br.readLine()) != null) {
            output.append(line).append(GfshParser.LINE_SEPARATOR);
        }
        mergeProcess.destroy();
    } catch (Exception e) {
        LogWrapper.getInstance().severe(e.getMessage());
    }
    if (output.toString().contains("Merged logs to: ")) {
        LogWrapper.getInstance().fine("Exporting logs Sucessfully merged logs");
    } else {
        LogWrapper.getInstance().severe("Could not merge");
    }
}

From source file:divconq.tool.Updater.java

static public boolean tryUpdate() {
    @SuppressWarnings("resource")
    final Scanner scan = new Scanner(System.in);

    FuncResult<RecordStruct> ldres = Updater.loadDeployed();

    if (ldres.hasErrors()) {
        System.out.println("Error reading deployed.json file: " + ldres.getMessage());
        return false;
    }//  ww  w  .  j  a  va 2 s. c o  m

    RecordStruct deployed = ldres.getResult();

    String ver = deployed.getFieldAsString("Version");
    String packfolder = deployed.getFieldAsString("PackageFolder");
    String packprefix = deployed.getFieldAsString("PackagePrefix");

    if (StringUtil.isEmpty(ver) || StringUtil.isEmpty(packfolder)) {
        System.out.println("Error reading deployed.json file: Missing Version or PackageFolder");
        return false;
    }

    if (StringUtil.isEmpty(packprefix))
        packprefix = "DivConq";

    System.out.println("Current Version: " + ver);

    Path packpath = Paths.get(packfolder);

    if (!Files.exists(packpath) || !Files.isDirectory(packpath)) {
        System.out.println("Error reading PackageFolder - it may not exist or is not a folder.");
        return false;
    }

    File pp = packpath.toFile();
    RecordStruct deployment = null;
    File matchpack = null;

    for (File f : pp.listFiles()) {
        if (!f.getName().startsWith(packprefix + "-") || !f.getName().endsWith("-bin.zip"))
            continue;

        System.out.println("Checking: " + f.getName());

        // if not a match before, clear this
        deployment = null;

        try {
            ZipFile zf = new ZipFile(f);

            Enumeration<ZipArchiveEntry> entries = zf.getEntries();

            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();

                if (entry.getName().equals("deployment.json")) {
                    //System.out.println("crc: " + entry.getCrc());

                    FuncResult<CompositeStruct> pres = CompositeParser.parseJson(zf.getInputStream(entry));

                    if (pres.hasErrors()) {
                        System.out.println("Error reading deployment.json file");
                        break;
                    }

                    deployment = (RecordStruct) pres.getResult();

                    break;
                }
            }

            zf.close();
        } catch (IOException x) {
            System.out.println("Error reading deployment.json file: " + x);
        }

        if (deployment != null) {
            String fndver = deployment.getFieldAsString("Version");
            String fnddependson = deployment.getFieldAsString("DependsOn");

            if (ver.equals(fnddependson)) {
                System.out.println("Found update: " + fndver);
                matchpack = f;
                break;
            }
        }
    }

    if ((matchpack == null) || (deployment == null)) {
        System.out.println("No updates found!");
        return false;
    }

    String fndver = deployment.getFieldAsString("Version");
    String umsg = deployment.getFieldAsString("UpdateMessage");

    if (StringUtil.isNotEmpty(umsg)) {
        System.out.println("========================================================================");
        System.out.println(umsg);
        System.out.println("========================================================================");
    }

    System.out.println();
    System.out.println("Do you want to install?  (y/n)");
    System.out.println();

    String p = scan.nextLine().toLowerCase();

    if (!p.equals("y"))
        return false;

    System.out.println();

    System.out.println("Intalling: " + fndver);

    Set<String> ignorepaths = new HashSet<>();

    ListStruct iplist = deployment.getFieldAsList("IgnorePaths");

    if (iplist != null) {
        for (Struct df : iplist.getItems())
            ignorepaths.add(df.toString());
    }

    ListStruct dflist = deployment.getFieldAsList("DeleteFiles");

    // deleting
    if (dflist != null) {
        for (Struct df : dflist.getItems()) {
            Path delpath = Paths.get(".", df.toString());

            if (Files.exists(delpath)) {
                System.out.println("Deleting: " + delpath.toAbsolutePath());

                try {
                    Files.delete(delpath);
                } catch (IOException x) {
                    System.out.println("Unable to Delete: " + x);
                }
            }
        }
    }

    // copying updates

    System.out.println("Checking for updated files: ");

    try {
        @SuppressWarnings("resource")
        ZipFile zf = new ZipFile(matchpack);

        Enumeration<ZipArchiveEntry> entries = zf.getEntries();

        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();

            String entryname = entry.getName().replace('\\', '/');
            boolean xfnd = false;

            for (String exculde : ignorepaths)
                if (entryname.startsWith(exculde)) {
                    xfnd = true;
                    break;
                }

            if (xfnd)
                continue;

            System.out.print(".");

            Path localpath = Paths.get(".", entryname);

            if (entry.isDirectory()) {
                if (!Files.exists(localpath))
                    Files.createDirectories(localpath);
            } else {
                boolean hashmatch = false;

                if (Files.exists(localpath)) {
                    String local = null;
                    String update = null;

                    try (InputStream lin = Files.newInputStream(localpath)) {
                        local = HashUtil.getMd5(lin);
                    }

                    try (InputStream uin = zf.getInputStream(entry)) {
                        update = HashUtil.getMd5(uin);
                    }

                    hashmatch = (StringUtil.isNotEmpty(local) && StringUtil.isNotEmpty(update)
                            && local.equals(update));
                }

                if (!hashmatch) {
                    System.out.print("[" + entryname + "]");

                    try (InputStream uin = zf.getInputStream(entry)) {
                        Files.createDirectories(localpath.getParent());

                        Files.copy(uin, localpath, StandardCopyOption.REPLACE_EXISTING);
                    } catch (Exception x) {
                        System.out.println("Error updating: " + entryname + " - " + x);
                        return false;
                    }
                }
            }
        }

        zf.close();
    } catch (IOException x) {
        System.out.println("Error reading update package: " + x);
    }

    // updating local config
    deployed.setField("Version", fndver);

    OperationResult svres = Updater.saveDeployed(deployed);

    if (svres.hasErrors()) {
        System.out.println("Intalled: " + fndver
                + " but could not update deployed.json.  Repair the file before continuing.\nError: "
                + svres.getMessage());
        return false;
    }

    System.out.println("Intalled: " + fndver);

    return true;
}

From source file:com.qwazr.server.configuration.ServerConfiguration.java

protected static Map<String, String> argsToMap(final String... args) throws IOException {
    final Map<String, String> props = argsToMapPrefix("--", args);

    // Load the QWAZR_PROPERTIES
    String propertyFile = props.get(QWAZR_PROPERTIES);
    if (propertyFile == null)
        propertyFile = System.getProperty(QWAZR_PROPERTIES, System.getenv(QWAZR_PROPERTIES));
    if (propertyFile != null) {
        final Path propFile = Paths.get(propertyFile);
        LOGGER.info(() -> "Load QWAZR_PROPERTIES file: " + propFile.toAbsolutePath());
        final Properties properties = new Properties();
        try (final BufferedReader reader = Files.newBufferedReader(propFile, StandardCharsets.UTF_8)) {
            properties.load(reader);//  w  w  w  .  j a v a 2 s .c  o m
        }
        // Priority to program argument, we only put the value if the key is not present
        properties.forEach((key, value) -> props.putIfAbsent(key.toString(), value.toString()));
    }

    return props;
}

From source file:org.esa.snap.smart.configurator.PerformanceParameters.java

/**
 * Save the actual configuration/*from   w  w  w .  ja v  a 2  s  .c o  m*/
 *
 * @param confToSave The configuration to save
 */
synchronized static void saveConfiguration(PerformanceParameters confToSave)
        throws IOException, BackingStoreException {

    if (!loadConfiguration().getVMParameters().equals(confToSave.getVMParameters())) {
        confToSave.vmParameters.save();
    }

    Config configuration = EngineConfig.instance().load();
    Preferences preferences = configuration.preferences();

    Path cachePath = confToSave.getCachePath();

    if (!Files.exists(cachePath)) {
        Files.createDirectories(cachePath);
    }

    if (Files.exists(cachePath)) {
        preferences.put(SystemUtils.SNAP_CACHE_DIR_PROPERTY_NAME, cachePath.toAbsolutePath().toString());
    } else {
        SystemUtils.LOG.severe("Directory for cache path does not exist");
    }

    JAI ff = JAI.getDefaultInstance();

    int parallelism = confToSave.getNbThreads();
    //int defaultTileSize = confToSave.getDefaultTileSize();
    int jaiCacheSize = confToSave.getCacheSize();
    String tileWidth = confToSave.getTileWidth();
    String tileHeight = confToSave.getTileHeight();

    preferences.putInt(SystemUtils.SNAP_PARALLELISM_PROPERTY_NAME, parallelism);

    /*if(tileWidth == null) {
    preferences.remove(SYSPROP_READER_TILE_WIDTH);
    } else {
    preferences.put(SYSPROP_READER_TILE_WIDTH,tileWidth);
    }
    if(tileHeight == null) {
    preferences.remove(SYSPROP_READER_TILE_HEIGHT);
    } else {
    preferences.put(SYSPROP_READER_TILE_HEIGHT,tileHeight);
    }*/

    preferences.putInt(PROPERTY_JAI_CACHE_SIZE, jaiCacheSize);

    preferences.flush();

    // effective change of jai parameters
    JAIUtils.setDefaultTileCacheCapacity(jaiCacheSize);
    JAI.getDefaultInstance().getTileScheduler().setParallelism(parallelism);

}

From source file:org.apache.openaz.xacml.rest.XACMLPdpLoader.java

public static synchronized Path getPDPConfig() throws PAPException {
    Path config = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_CONFIG));
    if (Files.notExists(config)) {
        logger.warn(config.toAbsolutePath().toString() + " does NOT exist.");
        ///*  w w w  . ja v a2  s.c o m*/
        // Try to create the directory
        //
        try {
            Files.createDirectories(config);
        } catch (IOException e) {
            logger.error("Failed to create config directory: " + config.toAbsolutePath().toString(), e);
            throw new PAPException("Failed to create config directory: " + config.toAbsolutePath().toString());
        }
    }
    return config;
}

From source file:com.qwazr.server.configuration.ServerConfiguration.java

private static Set<Path> getEtcDirectories(final String value) {
    final Set<Path> set = new LinkedHashSet<>();
    fillStringListProperty(value == null ? "etc" : value, File.pathSeparator, true, part -> {
        // By design relative path are relative to the working directory
        final Path etcPath = Paths.get(part);
        set.add(etcPath);//from  ww w  .j a v  a2  s .  com
        LOGGER.info("Configuration (ETC) directory: " + etcPath.toAbsolutePath());
    });
    return Collections.unmodifiableSet(set);
}

From source file:org.tinymediamanager.core.ImageCache.java

/**
 * Invalidate cached image./*  w  w  w  .jav a  2s .com*/
 * 
 * @param path
 *          the path
 */
public static void invalidateCachedImage(Path path) {
    Path cachedFile = getCacheDir()
            .resolve(ImageCache.getMD5(path.toAbsolutePath().toString()) + "." + Utils.getExtension(path));
    if (Files.exists(cachedFile)) {
        Utils.deleteFileSafely(cachedFile);
    }
}

From source file:org.tinymediamanager.core.ImageCache.java

/**
 * Gets the cached file, if ImageCache is activated<br>
 * If not found, cache original first//ww w .  j  a v  a 2  s  .  c om
 * 
 * @param path
 *          the path
 * @return the cached file
 */
public static Path getCachedFile(Path path) {
    if (path == null) {
        return null;
    }
    path = path.toAbsolutePath();

    Path cachedFile = ImageCache.getCacheDir()
            .resolve(getMD5(path.toString()) + "." + Utils.getExtension(path));
    if (Files.exists(cachedFile)) {
        LOGGER.trace("found cached file :) " + path);
        return cachedFile;
    }

    // TODO: when does this happen?!?!
    // is the path already inside the cache dir? serve direct
    if (path.startsWith(CACHE_DIR.toAbsolutePath())) {
        return path;
    }

    // is the image cache activated?
    if (!Globals.settings.isImageCache()) {
        LOGGER.trace("ImageCache not activated - return original file 1:1");
        return path;
    }

    try {
        Path p = ImageCache.cacheImage(path);
        LOGGER.trace("cached file successfully :) " + p);
        return p;
    } catch (EmptyFileException e) {
        LOGGER.warn("failed to cache file (file is empty): " + path);
    } catch (FileNotFoundException e) {
        LOGGER.trace(e.getMessage());
    } catch (Exception e) {
        LOGGER.warn("problem caching file: " + e.getMessage());
    }

    // fallback
    return path;
}

From source file:de.codesourcery.asm.util.ASMUtil.java

/**
 * Create an ASM <code>ClassReader</code> for a given class , searching an optional classpath.
 * //from w w w . j av  a  2 s  .  c  o  m
 * <p>If a classpath is specified, it is searched before the system class path.</p>
 * 
 * @param classToAnalyze
 * @param classPathEntries optional classpath that may contain directories or ZIP/JAR archives, may be <code>null</code>.
 * @param logger Logger used to output debug messages
 * @return
 * @throws IOException
 */
public static ClassReader createClassReader(String classToAnalyze, File[] classPathEntries, ILogger logger)
        throws IOException {
    if (!ArrayUtils.isEmpty(classPathEntries)) {
        // convert class name file-system path         
        String relPath = classToAnalyze.replace(".", File.separator);
        if (!relPath.endsWith(".class")) {
            relPath += ".class";
        }
        // look through search-path entries
        for (File parent : classPathEntries) {
            logger.logVerbose("Searching class in " + parent.getAbsolutePath());
            if (parent.isDirectory()) // path entry is a directory
            {
                final File classFile = new File(parent, relPath);
                if (!classFile.exists()) {
                    continue;
                }
                try {
                    logger.logVerbose(
                            "Loading class '" + classToAnalyze + "' from " + classFile.getAbsolutePath() + "");
                    return new ClassReader(new FileInputStream(classFile));
                } catch (IOException e) {
                    throw new IOException(
                            "Failed to load class '" + classToAnalyze + "' from " + classFile.getAbsolutePath(),
                            e);
                }
            } else if (parent.isFile()) // path entry is a (ZIP/JAR) file 
            {
                final Path archive = Paths.get(parent.getAbsolutePath());
                final FileSystem fs = FileSystems.newFileSystem(archive, null);
                final Path classFilePath = fs.getPath(relPath);

                if (Files.exists(classFilePath)) {
                    // load class from archive
                    try {
                        logger.logVerbose("Loading class '" + classToAnalyze + "' from archive "
                                + archive.toAbsolutePath());
                        InputStream in = fs.provider().newInputStream(classFilePath);
                        return new ClassReader(in);
                    } catch (IOException e) {
                        throw new IOException("Failed to load class '" + classToAnalyze + "' from "
                                + classFilePath.toAbsolutePath(), e);
                    }
                }
                continue;
            }
            throw new IOException("Invalid entry on search classpath: '" + parent.getAbsolutePath()
                    + "' is neither a directory nor JAR/ZIP archive");
        }
    }

    // fall-back to using standard classpath
    logger.logVerbose("Trying to load class " + classToAnalyze + " using system classloader.");

    try {
        return new ClassReader(classToAnalyze);
    } catch (IOException e) {
        throw new IOException("Failed to load class '" + classToAnalyze + "'", e);
    }
}