Example usage for java.nio.file Path toUri

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

Introduction

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

Prototype

URI toUri();

Source Link

Document

Returns a URI to represent this path.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Path p2 = Paths.get("test2.txt");
    java.net.URI p2UriPath = p2.toUri();
    System.out.println("Absolute Path: " + p2.toAbsolutePath());
    System.out.println("URI Path: " + p2UriPath);

}

From source file:Test.java

public static void main(String[] args) throws Exception {
    Path path = Paths.get("users.txt");

    System.out.println("URI path: " + path.toUri());
}

From source file:Main.java

public static void main(String[] args) {

    Path path = Paths.get("C:", "tutorial/Java/JavaFX", "Topic.txt");
    //convert path to an URI (browser format)
    URI path_to_uri = path.toUri();
    System.out.println("Path to URI: " + path_to_uri);
}

From source file:Test.java

public static void main(String[] args) {
    Path path = Paths.get("/home/docs/../music/A.mp3");
    System.out.println("Absolute path: " + path.toAbsolutePath());
    System.out.println("URI: " + path.toUri());
    System.out.println("Normalized Path: " + path.normalize());
    System.out.println("Normalized URI: " + path.normalize().toUri());
    System.out.println();/*from w w  w. j a  va2 s  . c  om*/

    path = Paths.get("/home/./music/A.mp3");
    System.out.println("Absolute path: " + path.toAbsolutePath());
    System.out.println("URI: " + path.toUri());
    System.out.println("Normalized Path: " + path.normalize());
    System.out.println("Normalized URI: " + path.normalize().toUri());

}

From source file:Test.java

public static void main(String[] args) throws Exception {
    Path path1 = Paths.get("/home/docs/users.txt");
    Path path2 = Paths.get("/home/music/users.txt");

    System.out.println(Files.isSymbolicLink(path1));
    System.out.println(Files.isSymbolicLink(path2));

    Path path = Paths.get(new URI("C:/home/./music/users.txt"));
    System.out.println("Normalized: " + path.normalize());
    System.out.println("Absolute path: " + path.toAbsolutePath());
    System.out.println("URI: " + path.toUri());
    System.out.println("toRealPath (Do not follow links): " + path.toRealPath(LinkOption.NOFOLLOW_LINKS));
    System.out.println("toRealPath: " + path.toRealPath());

}

From source file:org.sonarsource.sonarlint.core.extractor.Main.java

public static void main(String[] args) throws MalformedURLException {

    String version = args[0];/*  w w w .j av a  2  s . c  o  m*/

    List<Path> pluginPaths = new ArrayList<>();
    for (int i = 1; i < args.length; i++) {
        pluginPaths.add(Paths.get(args[i]));
    }

    StandaloneGlobalConfiguration.Builder builder = StandaloneGlobalConfiguration.builder()
            .setLogOutput(new LogOutput() {
                @Override
                public void log(String formattedMessage, Level level) {
                    // Ignore
                }
            });

    for (Path path : pluginPaths) {
        builder.addPlugin(path.toUri().toURL());
    }
    StandaloneSonarLintEngineImpl client = new StandaloneSonarLintEngineImpl(builder.build());
    client.start();

    Table<String, String, RuleDetails> rulesByKeyAndLanguage = TreeBasedTable.create();
    for (String ruleKeyStr : ((StandaloneGlobalContainer) client.getGlobalContainer()).getActiveRuleKeys()) {
        RuleDetails ruleDetails = client.getRuleDetails(ruleKeyStr);
        RuleKey ruleKey = RuleKey.parse(ruleKeyStr);
        rulesByKeyAndLanguage.put(ruleKey.rule(), ruleDetails.getLanguage(), ruleDetails);
    }

    try {
        System.out.print("{");
        System.out.print("\"version\": \"");
        System.out.print(version);
        System.out.print("\",");

        System.out.print("\"rules\": [");
        boolean first = true;
        for (String ruleKey : rulesByKeyAndLanguage.rowKeySet()) {
            if (!first) {
                System.out.print(",");
            }
            first = false;
            System.out.print("{");
            System.out.print("\"key\": \"");
            System.out.print(ruleKey);
            System.out.print("\",");
            System.out.print("\"title\": \"");
            System.out
                    .print(escapeJson(rulesByKeyAndLanguage.row(ruleKey).values().iterator().next().getName()));
            System.out.print("\",");

            Set<String> mergedTags = new HashSet<>();
            for (RuleDetails rule : rulesByKeyAndLanguage.row(ruleKey).values()) {
                mergedTags.addAll(Arrays.asList(rule.getTags()));
            }
            writeTags(mergedTags);
            System.out.print(",");

            System.out.print("\"implementations\": [");

            boolean firstLang = true;
            for (Map.Entry<String, RuleDetails> detailPerLanguage : rulesByKeyAndLanguage.row(ruleKey)
                    .entrySet()) {
                if (!firstLang) {
                    System.out.print(",");
                }
                firstLang = false;
                RuleDetails ruleDetails = detailPerLanguage.getValue();
                System.out.print("{");
                System.out.print("\"key\": \"");
                System.out.print(ruleDetails.getKey());
                System.out.print("\",");
                System.out.print("\"language\": \"");
                System.out.print(languageLabel(detailPerLanguage.getKey()));
                System.out.print("\",");
                System.out.print("\"title\": \"");
                System.out.print(escapeJson(ruleDetails.getName()));
                System.out.print("\",");
                System.out.print("\"description\": \"");
                System.out.print(escapeJson(ruleDetails.getHtmlDescription()));
                System.out.print("\",");
                System.out.print("\"severity\": \"");
                System.out.print(StringUtils.capitalize(ruleDetails.getSeverity().toLowerCase()));
                System.out.print("\",");
                String[] tags = ruleDetails.getTags();
                writeTags(Arrays.asList(tags));
                System.out.print("}");
            }
            System.out.print("]");
            System.out.print("}");
        }
        System.out.print("]");
        System.out.print("}");
    } finally {
        client.stop();
    }

}

From source file:ratpack.spark.jobserver.Main.java

public static void main(String... args) throws Exception {
    RatpackServer ratpackServer = RatpackServer.start(spec -> spec.serverConfig(builder -> {
        Path basePath = BaseDir.find("application.properties");
        LOGGER.debug("BASE DIR: {}", basePath.toString());
        builder.baseDir(BaseDir.find("application.properties")).env().sysProps();

        Path localAppProps = Paths.get("../../config/application.properties");
        if (Files.exists(localAppProps)) {
            LOGGER.debug("LOCALLY OVERLOADED application.properties: {}", localAppProps.toUri().toString());
            builder.props(localAppProps);
        } else {/*from   w  w w .j a  va 2s.  c o m*/
            URL cpAppProps = Main.class.getClassLoader().getResource("config/application.properties");
            LOGGER.debug("CLASSPATH OVERLOADED application.properties: {}",
                    cpAppProps != null ? cpAppProps.toString() : "DEFAULT LOCATION");
            builder.props(cpAppProps != null ? cpAppProps
                    : Main.class.getClassLoader().getResource("application.properties"));
        }

        Path localSparkJobsProps = Paths.get("../../config/sparkjobs.properties");
        if (Files.exists(localSparkJobsProps)) {
            LOGGER.debug("LOCALLY OVERLOADED sparkjobs.properties: {}", localSparkJobsProps.toUri().toString());
            builder.props(localSparkJobsProps);
        } else {
            URL cpSparkJobsProps = Main.class.getClassLoader().getResource("config/sparkjobs.properties");
            LOGGER.debug("CLASSPATH OVERLOADED SPARKJOBS.PROPS: {}",
                    cpSparkJobsProps != null ? cpSparkJobsProps.toString() : "DEFAULT LOCATION");
            builder.props(cpSparkJobsProps != null ? cpSparkJobsProps
                    : Main.class.getClassLoader().getResource("sparkjobs.properties"));
        }

        builder.require("/spark", SparkConfig.class).require("/job", SparkJobsConfig.class);
    }).registry(Guice.registry(bindingsSpec -> bindingsSpec.bindInstance(ResponseTimer.decorator())
            .module(ContainersModule.class).module(SparkModule.class)
            .bindInstance(new ObjectMapper().writerWithDefaultPrettyPrinter())))
            .handlers(chain -> chain.all(ctx -> {
                LOGGER.debug("ALL");
                MDC.put("clientIP", ctx.getRequest().getRemoteAddress().getHostText());
                RequestId.Generator generator = ctx.maybeGet(RequestId.Generator.class)
                        .orElse(UuidBasedRequestIdGenerator.INSTANCE);
                RequestId requestId = generator.generate(ctx.getRequest());
                ctx.getRequest().add(RequestId.class, requestId);
                MDC.put("requestId", requestId.toString());
                ctx.next();
            }).prefix("v1", chain1 -> chain1.all(RequestLogger.ncsa()).get("api-def", ctx -> {
                LOGGER.debug("GET API_DEF.JSON");
                SparkJobsConfig config = ctx.get(SparkJobsConfig.class);
                LOGGER.debug("SPARK JOBS CONFIG: " + config.toString());
                ctx.render(ctx.file("public/apidef/apidef.json"));
            }).prefix("spark", JobsEndpoints.class))));
    LOGGER.debug("STARTED: {}://{}:{}", ratpackServer.getScheme(), ratpackServer.getBindHost(),
            ratpackServer.getBindPort());
}

From source file:com.bytelightning.opensource.pokerface.PokerFaceApp.java

public static void main(String[] args) {
    if (JavaVersionAsFloat() < (1.8f - Float.MIN_VALUE)) {
        System.err.println("PokerFace requires at least Java v8 to run.");
        return;//from w ww .  j  av  a  2  s.  c  om
    }
    // Configure the command line options parser
    Options options = new Options();
    options.addOption("h", false, "help");
    options.addOption("listen", true, "(http,https,secure,tls,ssl,CertAlias)=Address:Port for https.");
    options.addOption("keystore", true, "Filepath for PokerFace certificate keystore.");
    options.addOption("storepass", true, "The store password of the keystore.");
    options.addOption("keypass", true, "The key password of the keystore.");
    options.addOption("target", true, "Remote Target requestPattern=targetUri"); // NOTE: targetUri may contain user-info and if so will be interpreted as the alias of a cert to be presented to the remote target
    options.addOption("servercpu", true, "Number of cores the server should use.");
    options.addOption("targetcpu", true, "Number of cores the http targets should use.");
    options.addOption("trustany", false, "Ignore certificate identity errors from target servers.");
    options.addOption("files", true, "Filepath to a directory of static files.");
    options.addOption("config", true, "Path for XML Configuration file.");
    options.addOption("scripts", true, "Filepath for root scripts directory.");
    options.addOption("library", true, "JavaScript library to load into global context.");
    options.addOption("watch", false, "Dynamically watch scripts directory for changes.");
    options.addOption("dynamicTargetScripting", false,
            "WARNING! This option allows scripts to redirect requests to *any* other remote server.");

    CommandLine cmdLine = null;
    // parse the command line.
    try {
        CommandLineParser parser = new PosixParser();
        cmdLine = parser.parse(options, args);
        if (args.length == 0 || cmdLine.hasOption('h')) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.setWidth(120);
            formatter.printHelp(PokerFaceApp.class.getSimpleName(), options);
            return;
        }
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        return;
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        return;
    }

    XMLConfiguration config = new XMLConfiguration();
    try {
        if (cmdLine.hasOption("config")) {
            Path tmp = Utils.MakePath(cmdLine.getOptionValue("config"));
            if (!Files.exists(tmp))
                throw new FileNotFoundException("Configuration file does not exist.");
            if (Files.isDirectory(tmp))
                throw new FileNotFoundException("'config' path is not a file.");
            // This is a bit of a pain, but but let's make sure we have a valid configuration file before we actually try to use it.
            config.setEntityResolver(new DefaultEntityResolver() {
                @Override
                public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
                    InputSource retVal = super.resolveEntity(publicId, systemId);
                    if ((retVal == null) && (systemId != null)) {
                        try {
                            URL entityURL;
                            if (systemId.endsWith("/PokerFace_v1Config.xsd"))
                                entityURL = PokerFaceApp.class.getResource("/PokerFace_v1Config.xsd");
                            else
                                entityURL = new URL(systemId);
                            URLConnection connection = entityURL.openConnection();
                            connection.setUseCaches(false);
                            InputStream stream = connection.getInputStream();
                            retVal = new InputSource(stream);
                            retVal.setSystemId(entityURL.toExternalForm());
                        } catch (Throwable e) {
                            return retVal;
                        }
                    }
                    return retVal;
                }

            });
            config.setSchemaValidation(true);
            config.setURL(tmp.toUri().toURL());
            config.load();
            if (cmdLine.hasOption("listen"))
                System.out.println("IGNORING 'listen' option because a configuration file was supplied.");
            if (cmdLine.hasOption("target"))
                System.out.println("IGNORING 'target' option(s) because a configuration file was supplied.");
            if (cmdLine.hasOption("scripts"))
                System.out.println("IGNORING 'scripts' option because a configuration file was supplied.");
            if (cmdLine.hasOption("library"))
                System.out.println("IGNORING 'library' option(s) because a configuration file was supplied.");
        } else {
            String[] serverStrs;
            String[] addr = { null };
            String[] port = { null };
            serverStrs = cmdLine.getOptionValues("listen");
            if (serverStrs == null)
                throw new MissingOptionException("No listening addresses specified specified");
            for (int i = 0; i < serverStrs.length; i++) {
                String addrStr;
                String alias = null;
                String protocol = null;
                Boolean https = null;
                int addrPos = serverStrs[i].indexOf('=');
                if (addrPos >= 0) {
                    if (addrPos < 2)
                        throw new IllegalArgumentException("Invalid http argument.");
                    else if (addrPos + 1 >= serverStrs[i].length())
                        throw new IllegalArgumentException("Invalid http argument.");
                    addrStr = serverStrs[i].substring(addrPos + 1, serverStrs[i].length());
                    String[] types = serverStrs[i].substring(0, addrPos).split(",");
                    for (String type : types) {
                        if (type.equalsIgnoreCase("http"))
                            break;
                        else if (type.equalsIgnoreCase("https") || type.equalsIgnoreCase("secure"))
                            https = true;
                        else if (type.equalsIgnoreCase("tls") || type.equalsIgnoreCase("ssl"))
                            protocol = type.toUpperCase();
                        else
                            alias = type;
                    }
                } else
                    addrStr = serverStrs[i];
                ParseAddressString(addrStr, addr, port, alias != null ? 443 : 80);
                config.addProperty("server.listen(" + i + ")[@address]", addr[0]);
                config.addProperty("server.listen(" + i + ")[@port]", port[0]);
                if (alias != null)
                    config.addProperty("server.listen(" + i + ")[@alias]", alias);
                if (protocol != null)
                    config.addProperty("server.listen(" + i + ")[@protocol]", protocol);
                if (https != null)
                    config.addProperty("server.listen(" + i + ")[@secure]", https);
            }
            String servercpu = cmdLine.getOptionValue("servercpu");
            if (servercpu != null)
                config.setProperty("server[@cpu]", servercpu);
            String clientcpu = cmdLine.getOptionValue("targetcpu");
            if (clientcpu != null)
                config.setProperty("targets[@cpu]", clientcpu);

            // Configure static files
            if (cmdLine.hasOption("files")) {
                Path tmp = Utils.MakePath(cmdLine.getOptionValue("files"));
                if (!Files.exists(tmp))
                    throw new FileNotFoundException("Files directory does not exist.");
                if (!Files.isDirectory(tmp))
                    throw new FileNotFoundException("'files' path is not a directory.");
                config.setProperty("files.rootDirectory", tmp.toAbsolutePath().toUri());
            }

            // Configure scripting
            if (cmdLine.hasOption("scripts")) {
                Path tmp = Utils.MakePath(cmdLine.getOptionValue("scripts"));
                if (!Files.exists(tmp))
                    throw new FileNotFoundException("Scripts directory does not exist.");
                if (!Files.isDirectory(tmp))
                    throw new FileNotFoundException("'scripts' path is not a directory.");
                config.setProperty("scripts.rootDirectory", tmp.toAbsolutePath().toUri());
                config.setProperty("scripts.dynamicWatch", cmdLine.hasOption("watch"));
                String[] libraries = cmdLine.getOptionValues("library");
                if (libraries != null) {
                    for (int i = 0; i < libraries.length; i++) {
                        Path lib = Utils.MakePath(libraries[i]);
                        if (!Files.exists(lib))
                            throw new FileNotFoundException(
                                    "Script library does not exist [" + libraries[i] + "].");
                        if (Files.isDirectory(lib))
                            throw new FileNotFoundException(
                                    "Script library is not a file [" + libraries[i] + "].");
                        config.setProperty("scripts.library(" + i + ")", lib.toAbsolutePath().toUri());
                    }
                }
            } else if (cmdLine.hasOption("watch"))
                System.out.println("IGNORING 'watch' option as no 'scripts' directory was specified.");
            else if (cmdLine.hasOption("library"))
                System.out.println("IGNORING 'library' option as no 'scripts' directory was specified.");
        }
        String keyStorePath = cmdLine.getOptionValue("keystore");
        if (keyStorePath != null)
            config.setProperty("keystore", keyStorePath);
        String keypass = cmdLine.getOptionValue("keypass");
        if (keypass != null)
            config.setProperty("keypass", keypass);
        String storepass = cmdLine.getOptionValue("storepass");
        if (storepass != null)
            config.setProperty("storepass", keypass);
        if (cmdLine.hasOption("trustany"))
            config.setProperty("targets[@trustAny]", true);

        config.setProperty("scripts.dynamicTargetScripting", cmdLine.hasOption("dynamicTargetScripting"));

        String[] targetStrs = cmdLine.getOptionValues("target");
        if (targetStrs != null) {
            for (int i = 0; i < targetStrs.length; i++) {
                int uriPos = targetStrs[i].indexOf('=');
                if (uriPos < 2)
                    throw new IllegalArgumentException("Invalid target argument.");
                else if (uriPos + 1 >= targetStrs[i].length())
                    throw new IllegalArgumentException("Invalid target argument.");
                String patternStr = targetStrs[i].substring(0, uriPos);
                String urlStr = targetStrs[i].substring(uriPos + 1, targetStrs[i].length());
                String alias;
                try {
                    URL url = new URL(urlStr);
                    alias = url.getUserInfo();
                    String scheme = url.getProtocol();
                    if ((!"http".equals(scheme)) && (!"https".equals(scheme)))
                        throw new IllegalArgumentException("Invalid target uri scheme.");
                    int port = url.getPort();
                    if (port < 0)
                        port = url.getDefaultPort();
                    urlStr = scheme + "://" + url.getHost() + ":" + port + url.getPath();
                    String ref = url.getRef();
                    if (ref != null)
                        urlStr += "#" + ref;
                } catch (MalformedURLException ex) {
                    throw new IllegalArgumentException("Malformed target uri");
                }
                config.addProperty("targets.target(" + i + ")[@pattern]", patternStr);
                config.addProperty("targets.target(" + i + ")[@url]", urlStr);
                if (alias != null)
                    config.addProperty("targets.target(" + i + ")[@alias]", alias);
            }
        }
        //         config.save(System.out);
    } catch (Throwable e) {
        e.printStackTrace(System.err);
        return;
    }
    // If we get here, we have a possibly valid configuration.
    try {
        final PokerFace p = new PokerFace();
        p.config(config);
        if (p.start()) {
            PokerFace.Logger.warn("Started!");
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    try {
                        PokerFace.Logger.warn("Initiating shutdown...");
                        p.stop();
                        PokerFace.Logger.warn("Shutdown completed!");
                    } catch (Throwable e) {
                        PokerFace.Logger.error("Failed to shutdown cleanly!");
                        e.printStackTrace(System.err);
                    }
                }
            });
        } else {
            PokerFace.Logger.error("Failed to start!");
            System.exit(-1);
        }
    } catch (Throwable e) {
        e.printStackTrace(System.err);
    }
}

From source file:Main.java

private static FileSystem createZipFileSystem(String zipFilename, boolean create) throws IOException {
    final Path path = Paths.get(zipFilename);
    final URI uri = URI.create("jar:file:" + path.toUri().getPath());

    final Map<String, String> env = new HashMap<>();
    if (create) {
        env.put("create", "true");
    }// w ww.j av  a2  s . c om
    return FileSystems.newFileSystem(uri, env);
}

From source file:io.github.robwin.diff.DiffAssert.java

private static LinkedList<DiffMatchPatch.Diff> diff(Path actual, Path expected) {
    DiffMatchPatch differ = new DiffMatchPatch();
    try {//w w  w  .j  a  v a2s .  c  o m
        return differ.diff_main(IOUtils.toString(expected.toUri()), IOUtils.toString(actual.toUri()), false);
    } catch (IOException e) {
        throw new RuntimeException("Failed to diff files.", e);
    }
}