Java Code Examples for java.nio.file.Path#of()

The following examples show how to use java.nio.file.Path#of() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MavenArtifactResolver.java    From pro with GNU General Public License v3.0 6 votes vote down vote up
public static void resolve(String mavenId) throws IOException {
  var mavenLocalRepository = Path.of("target/deps/maven-local");
  
  var aether = Aether.create(mavenLocalRepository, List.of());
  
  var artifactQuery = aether.createArtifactQuery(mavenId);
  var dependencies = aether.dependencies(artifactQuery);
  var resolvedArtifacts = new ArrayList<>(aether.download(new ArrayList<>(dependencies)));
  
  var map = resolvedArtifacts.stream()
    .flatMap(artifact -> findArtifactModuleName(artifact).map(name -> entry(artifact, name)).stream())
    .collect(toUnmodifiableMap(Entry::getKey, Entry::getValue));
  
  resolvedArtifacts.sort(nullsLast(comparing(map::get)));
  
  for(var resolvedArtifact: resolvedArtifacts) {
    var artifactId = resolvedArtifact.getGroupId() + ':' + resolvedArtifact.getArtifactId() + ':' + resolvedArtifact.getVersion();
    System.out.println(
        Optional.ofNullable(map.get(resolvedArtifact))
          .map(name -> name + '=' + artifactId)
          .orElse(artifactId + " is not JPMS compatible"));
  }
}
 
Example 2
Source File: FormulaFactory.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get all installed cluster providers.
 * @return a list containing the metadata of all installed cluster providers
 */
public static List<Map<String, Object>> getClusterProvidersMetadata() {
    Path dir = Path.of(METADATA_DIR_CLUSTER_PROVIDERS);
    try {
        return Files.list(dir)
                .filter(Files::isDirectory)
                .map(p -> {
                    String provider = p.getFileName().toString();
                    Map<String, Object> m = getClusterProviderMetadata(provider);
                    m = new HashMap<>(m);
                    m.put("label", provider);
                    return m;
                })
                .collect(Collectors.toList());
    }
    catch (IOException e) {
        LOG.error("Error loading providers metadata", e);
        return Collections.emptyList();
    }
}
 
Example 3
Source File: CliJarWithVerdaccioJarTest.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** Test that n4js-cli@test is installed from local verdaccio and then call n4js-cli --help */
@Test
public void testN4JSCliHelp() {

	// Step 1: Call npm install in PSingleTestNpm folder
	npmInstall(PROJECT);

	// Step 2: List all installed packages and check version of n4js-runtime
	ProcessResult npmListResult1 = npmList(PROJECT);
	assertTrue(npmListResult1.toString(), npmListResult1.getStdOut().contains("[email protected]"));

	// Step 3: Install n4js-cli@latest in the project 'PSingleTestNpm'
	npmInstall(PROJECT, "n4js-cli@latest");

	// Step 4: List all installed packages and check version of n4js-cli
	ProcessResult npmListResult2 = npmList(PROJECT);
	assertEquals(npmListResult2.toString(), 0, npmListResult2.getExitCode());
	assertTrue(npmListResult2.toString(), npmListResult2.getStdOut().contains("[email protected]"));

	// Step 5: Test that calling n4js-cli is OK
	Path runFile = Path.of(N4JSGlobals.NODE_MODULES, ".bin", "n4jsc");
	ProcessResult nodeResult = runNodejs(PROJECT, runFile, "--help");
	assertTrue(nodeResult.toString(), nodeResult.getStdOut().contains("Usage"));
}
 
Example 4
Source File: TaskTrayTest.java    From shogun with Apache License 2.0 6 votes vote down vote up
@NotNull
private static Path createDummyJDK(String dummyVendor, String version) throws IOException {
    String home = System.getProperty("user.home");
    long time = System.currentTimeMillis();
    Path dummyJDKHome = Path.of(home + "/Downloads/shogun_dummyJDK" + time);
    Path bin = Path.of(home + "/Downloads/shogun_dummyJDK" + time + "/Contents/Home/bin");
    Path dummyJava = Path.of(home + "/Downloads/shogun_dummyJDK" + time + "/Contents/Home/bin/java");
    List<String> strings = Arrays.asList("#!/bin/sh",
            "echo openjdk version \\\"11.0.3\\\" 2019-04-16",
            String.format("echo OpenJDK Runtime Environment %s \\(build %s\\)", dummyVendor, version),
            String.format("echo OpenJDK 64-Bit Server VM %s \\(build %s, mixed mode\\)", dummyVendor, version));
    if (bin.toFile().mkdirs()) {
        Files.write(dummyJava, strings);
    } else {
        System.out.println("failed" + bin.toFile());
    }
    //noinspection ResultOfMethodCallIgnored
    dummyJava.toFile().setExecutable(true);
    return dummyJDKHome;
}
 
Example 5
Source File: JavaExecutionContext.java    From L2jOrg with GNU General Public License v3.0 5 votes vote down vote up
JavaExecutionContext(JavaScriptingEngine engine) {
    super(engine);

    sourcePath = getSettings(ServerSettings.class).dataPackDirectory().resolve(requireNonNullElse(getProperty("source.path"), "data/scripts"));
    destination = Path.of(requireNonNullElse(getProperty("compiled.path"), "compiledScripts"));
    forceCompile =  Boolean.parseBoolean(requireNonNullElse(getProperty("force.compile"), "true"));

    try {
        compileModuleInfo();
        compile(sourcePath);
    } catch (Exception e) {
        LOGGER.error("Could not compile Java Scripts", e);
    }
}
 
Example 6
Source File: HgTagCommitCheckTests.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
@Test
void multipleHunksShouldFail() {
    var targetHash = "12345789012345789012345678901234567890";
    var tag = "skara-11+22";

    var hunk1 = new Hunk(new Range(1, 0), List.of(),
                        new Range(1, 1), List.of(targetHash + " " + tag));
    var hunk2 = new Hunk(new Range(1, 0), List.of(),
                        new Range(2, 1), List.of(targetHash + " " + "skara-11+23"));
    var patch = new TextualPatch(Path.of(".hgtags"), FileType.fromOctal("100644"), Hash.zero(),
                                 Path.of(".hgtags"), FileType.fromOctal("100644"), Hash.zero(),
                                 Status.from('M'), List.of(hunk1, hunk2));
    var diff = new Diff(Hash.zero(), Hash.zero(), List.of(patch));
    var diffs = List.of(diff);

    var commitHash = "1111222233334444555566667777888899990000";
    var lines = List.of("Added tag " + tag + " for changeset " + targetHash);
    var commit = commit(new Hash(commitHash), lines, diffs);

    var check = new HgTagCommitCheck(new Utilities());
    var issues = toList(check.check(commit, message(commit), conf));

    assertEquals(1, issues.size());
    assertTrue(issues.get(0) instanceof HgTagCommitIssue);
    var issue = (HgTagCommitIssue) issues.get(0);
        assertEquals(HgTagCommitIssue.Error.TOO_MANY_CHANGES, issue.error());
    assertEquals(commit, issue.commit());
    assertEquals(check, issue.check());
    assertEquals(Severity.ERROR, issue.severity());
}
 
Example 7
Source File: PatchHeader.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
public static PatchHeader fromRawLine(String line) {
    if (line == null || line.isEmpty() || line.charAt(0) != ':') {
        throw new IllegalArgumentException("Raw line does not start with colon: " + line);
    }
    var sourceType = FileType.fromOctal(line.substring(1, 7));
    var targetType = FileType.fromOctal(line.substring(8, 14));

    var sourceHash = new Hash(line.substring(15, 55));
    var targetHash = new Hash(line.substring(56, 96));

    var rest = line.substring(97);
    var parts = rest.split("\t");
    var status = Status.from(parts[0]);

    Path sourcePath = null;
    Path targetPath = null;
    if (status.isModified()) {
        sourcePath = Path.of(parts[1]);
        targetPath = sourcePath;
    } else if (status.isAdded()) {
        targetPath = Path.of(parts[1]);
    } else if (status.isDeleted()) {
        sourcePath = Path.of(parts[1]);
    } else if (status.isUnmerged()) {
        sourcePath = Path.of(parts[1]);
    } else {
        // either copied or renamed
        sourcePath = Path.of(parts[1]);
        targetPath = Path.of(parts[2]);
    }

    return new PatchHeader(sourcePath, sourceType, sourceHash, targetPath, targetType, targetHash, status);
}
 
Example 8
Source File: Repository.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
static Repository clone(URI from) throws IOException {
    var to = Path.of(from).getFileName();
    if (to.toString().endsWith(".git")) {
        to = Path.of(to.toString().replace(".git", ""));
    }
    return clone(from, to);
}
 
Example 9
Source File: GenBuilder.java    From pro with GNU General Public License v3.0 5 votes vote down vote up
public static void generate() throws IOException {
  var pluginDir = Path.of("target/image/plugins");
  var invalidPlugins = Set.of("convention", "uberpackager");
  var directory = Path.of("src/main/java/com.github.forax.pro.builder/com/github/forax/pro/builder");

  var plugins = Plugins.getAllPlugins(pluginDir);

  System.out.println("generate builders to " + directory);
  template(directory,
      plugins.stream().filter(plugin -> !invalidPlugins.contains(plugin.name())));
}
 
Example 10
Source File: SecretManagerTest.java    From gcp-token-broker with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the name of a directory that doesn't yet exist.
 */
private static Path getAvailableDirectory() {
    while(true) {
        String randomDirectory = "/tmp/" + RandomStringUtils.random(6, true, true);
        if (! Files.exists(Paths.get(randomDirectory))) {
            return Path.of(randomDirectory);
        }
    }
}
 
Example 11
Source File: GraalUtilTest.java    From shogun with Apache License 2.0 5 votes vote down vote up
@NotNull
private static Path createDummyGraal(File file) throws IOException {
    long time = System.currentTimeMillis();
    Path dummyJDKHome = Path.of(file.getAbsolutePath() + "/shogun_dummyJDK" + time);
    Path bin = Path.of(file.getAbsolutePath() + "/shogun_dummyJDK" + time + "/Contents/Home/bin");
    Path dummyJava = Path.of(file.getAbsolutePath() + "/shogun_dummyJDK" + time + "/Contents/Home/bin/java");
    List<String> strings = Arrays.asList("#!/bin/sh",
            "echo openjdk version \\\"1.8.0_212\\\"",
            "echo OpenJDK Runtime Environment \\(build 1.8.0_212-20190523183630.graal2.jdk8u-src-tar-gz-b03\\)",
            "echo OpenJDK 64-Bit GraalVM CE 19.1.0 (build 25.212-b03-jvmci-20-b04, mixed mode)");
    if (bin.toFile().mkdirs()) {
        Files.write(dummyJava, strings);
        //noinspection ResultOfMethodCallIgnored
        dummyJava.toFile().setExecutable(true);

        Path dummyGu = Path.of(file.getAbsolutePath() + "/shogun_dummyJDK" + time + "/Contents/Home/bin/gu");
        Path dummyNativeImage = Path.of(file.getAbsolutePath() + "/shogun_dummyJDK" + time + "/Contents/Home/bin/native-image");
        List<String> gu = Arrays.asList("#!/bin/sh",
                "echo echo Downloading: Component catalog from www.graalvm.org",
                "echo Processing component archive: Native Image",
                "echo Downloading: Component native-image: Native Image  from github.com",
                "echo Installing new component: Native Image \\(org.graalvm.native-image, version 19.1.0\\)",
                "touch " + dummyNativeImage.toAbsolutePath()
        );
        Files.write(dummyGu, gu);
        //noinspection ResultOfMethodCallIgnored
        dummyGu.toFile().setExecutable(true);

    } else {
        logger.debug("failed" + bin.toFile());
    }

    return dummyJDKHome;
}
 
Example 12
Source File: MultiKeySubCommandTest.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
@Test
void parseCommandSuccessfullySetDirectory() {
  final Path expectedPath = Path.of("/keys/directory/path");

  commandLine.parse("--directory", expectedPath.toString());

  final ParseResult parseResult = commandLine.getParseResult();
  assertThat(parseResult.errors()).isEmpty();

  final Path path = multiKeySubCommand.getDirectoryPath();
  assertThat(path).isEqualTo(expectedPath);
}
 
Example 13
Source File: ModuleBootstrap.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a finder from the module path that is the value of the given
 * system property and optionally patched by --patch-module
 */
private static ModuleFinder finderFor(String prop) {
    String s = System.getProperty(prop);
    if (s == null) {
        return null;
    } else {
        String[] dirs = s.split(File.pathSeparator);
        Path[] paths = new Path[dirs.length];
        int i = 0;
        for (String dir: dirs) {
            paths[i++] = Path.of(dir);
        }
        return ModulePath.of(patcher, paths);
    }
}
 
Example 14
Source File: Main.java    From pro with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
  var mavenLocalRepository = Path.of("target/deps/maven-local");
  var aether = Aether.create(mavenLocalRepository, List.of());
  
  var artifactQuery = aether.createArtifactQuery("org.ow2.asm:asm-util:7.0-beta");
  var dependencies = aether.dependencies(artifactQuery);
  System.out.println("dependencies" + dependencies);
  
  var resolvedArtifacts = aether.download(new ArrayList<>(dependencies));
  System.out.println("downloaded " + resolvedArtifacts);
}
 
Example 15
Source File: Main.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {

        Path file1 = Path.of("file1.txt");
        Path file2 = Path.of("file2.txt");
        Path file3 = Path.of("file3.txt");
        Path file4 = Path.of("file4.txt");
        
        System.out.println("Mismatches between file1 and file2: " 
                + Mismatches.haveMismatches(file1, file2));
        System.out.println("Mismatches between file1 and file3: " 
                + Mismatches.haveMismatches(file1, file3));
        System.out.println("Mismatches between file1 and file4: " 
                + Mismatches.haveMismatches(file1, file4));
        System.out.println("Mismatches between file2 and file3: " 
                + Mismatches.haveMismatches(file2, file3));
        System.out.println("Mismatches between file2 and file4: " 
                + Mismatches.haveMismatches(file2, file4));
        System.out.println("Mismatches between file3 and file4: " 
                + Mismatches.haveMismatches(file3, file4));

        long mismatches12 = Files.mismatch(file1, file2);
        long mismatches13 = Files.mismatch(file1, file3);
        long mismatches14 = Files.mismatch(file1, file4);
        long mismatches23 = Files.mismatch(file2, file3);
        long mismatches24 = Files.mismatch(file2, file4);
        long mismatches34 = Files.mismatch(file3, file4);
        System.out.println("Mismatches between file1 and file2: " + mismatches12);
        System.out.println("Mismatches between file1 and file3: " + mismatches13);
        System.out.println("Mismatches between file1 and file4: " + mismatches14);
        System.out.println("Mismatches between file2 and file3: " + mismatches23);
        System.out.println("Mismatches between file2 and file4: " + mismatches24);
        System.out.println("Mismatches between file3 and file4: " + mismatches34);
        
    }
 
Example 16
Source File: JavaConfigRunner.java    From pro with GNU General Public License v3.0 5 votes vote down vote up
private static void run(Path configFile, PropertySequence propertySeq, List<String> arguments) {
  //System.out.println("run with java " + configFile);
  
  var javaHome = Path.of(System.getProperty("java.home"));
  var args =
      Stream.of(
        Stream.of(javaHome.resolve("bin").resolve(Platform.current().javaExecutableName()).toString()),
        Stream.of("-XX:+EnableValhalla").filter(__ -> System.getProperty("valhalla.enableValhalla") != null),
        Stream.of("-Dpro.exitOnError=true"),
        propertySeq.stream().map(entry -> "-D" + entry.getKey() + '=' + entry.getValue()),
        Stream.of(arguments).filter(a -> !a.isEmpty()).map(a -> "-Dpro.arguments=" + String.join(",", a)),
        Stream.of(configFile.toString())
        )
      .flatMap(s -> s)
      .toArray(String[]::new);
  
  //System.out.println("cmd " + String.join(" ", args));
  
  var exitCode = 1;
  try {
    var process = new ProcessBuilder(args)
        .redirectErrorStream(true)
        .start();
  
    process.getInputStream().transferTo(System.out);
    
    exitCode = process.waitFor();
  } catch (InterruptedException|IOException e) {
    System.err.println("i/o error " + e.getMessage() + "\n command " + String.join(" ", args));
  }
  System.exit(exitCode);
}
 
Example 17
Source File: TlsCertificateDefinition.java    From besu with Apache License 2.0 5 votes vote down vote up
public static TlsCertificateDefinition loadFromResource(
    final String resourcePath, final String password) {
  try {
    final URL sslCertificate = Resources.getResource(resourcePath);
    final Path keystorePath = Path.of(sslCertificate.getPath());

    return new TlsCertificateDefinition(keystorePath.toFile(), password);
  } catch (final Exception e) {
    throw new RuntimeException("Failed to load TLS certificates", e);
  }
}
 
Example 18
Source File: pro_wrapper.java    From loom-fiber with MIT License 5 votes vote down vote up
private static int installAndRun(String[] args) throws IOException {
  var specialBuild = specialBuild().map(build -> '-' + build).orElse("");
  var filename = "pro-" + platform() + specialBuild + ".zip";
  
  var cache = Path.of(userHome(), ".pro", "cache");
  var release = lastestReleaseVersionFromGitHub()
      .or(() -> latestReleaseVersionFromCache(cache, filename))
      .orElseThrow(() -> new IOException("no release found !"));
  
  
  System.out.println("require " + filename + " release " + release + " ...");
  
  var cachePath = cache.resolve(Path.of(release, filename));
  if (!exists(cachePath)) {
    retry(cachePath, 3, _cachedPath -> download(release, filename, _cachedPath));
  }
  
  var releaseTxt = Path.of("pro", "pro-release.txt");
  if (!exists(releaseTxt) || !firstLine(releaseTxt).equals(filename)) {
    deleteAllFiles(releaseTxt.getParent());
    
    unpack(cachePath, Path.of("."));
    write(releaseTxt, List.of(filename));
  }
  
  return exec("pro/bin/pro", args);
}
 
Example 19
Source File: AccountBalancesDownloaderTest.java    From hedera-mirror-node with Apache License 2.0 4 votes vote down vote up
@Override
protected Path getTestDataDir() {
    return Path.of("accountBalances");
}
 
Example 20
Source File: SecondaryAuthManager.java    From L2jOrg with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected Path getSchemaFilePath() {
    return Path.of("config/xsd/secondary-auth.xsd");
}