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

The following examples show how to use java.nio.file.Path#toUri() . 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: CodeStoreAndPathTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void pathHandlingTest() {
    System.setProperty("nashorn.persistent.code.cache", codeCache);
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();

    fac.getScriptEngine(ENGINE_OPTIONS_NOOPT);

    final Path expectedCodeCachePath = FileSystems.getDefault().getPath(oldUserDir + File.separator + codeCache);
    final Path actualCodeCachePath = FileSystems.getDefault().getPath(System.getProperty(
                        "nashorn.persistent.code.cache")).toAbsolutePath();
    // Check that nashorn code cache is created in current working directory
    assertEquals(actualCodeCachePath, expectedCodeCachePath);
    // Check that code cache dir exists and it's not empty
    final File file = new File(actualCodeCachePath.toUri());
    assertFalse(!file.isDirectory(), "No code cache directory was created!");
    assertFalse(file.list().length == 0, "Code cache directory is empty!");
}
 
Example 2
Source File: KryoPersistenceTest.java    From recheck with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
void incompatible_version_should_give_persisting_version( @TempDir final Path temp ) throws IOException {
	final Path file = temp.resolve( "incompatible-test.test" );
	Files.createFile( file );
	final URI identifier = file.toUri();

	final KryoPersistence<de.retest.recheck.test.Test> kryoPersistence = new KryoPersistence<>();
	kryoPersistence.save( identifier, createDummyTest() );

	final Kryo kryoMock = mock( Kryo.class );
	when( kryoMock.readClassAndObject( any() ) ).thenThrow( KryoException.class );
	final KryoPersistence<de.retest.recheck.test.Test> differentKryoPersistence =
			new KryoPersistence<>( kryoMock, "old Version" );

	assertThatThrownBy( () -> differentKryoPersistence.load( identifier ) )
			.isInstanceOf( IncompatibleReportVersionException.class )
			.hasMessageContaining( "Incompatible recheck versions: report was written with "
					+ VersionProvider.RECHECK_VERSION + ", but read with old Version." );
}
 
Example 3
Source File: ModuleSource.java    From jolie with GNU Lesser General Public License v2.1 6 votes vote down vote up
public JapSource( Path f ) throws IOException {
	this.japFile = new JarFile( f.toFile() );
	this.uri = f.toUri();
	Manifest manifest = this.japFile.getManifest();

	if( manifest != null ) { // See if a main program is defined through a Manifest attribute
		Attributes attrs = manifest.getMainAttributes();
		this.filePath = attrs.getValue( Constants.Manifest.MAIN_PROGRAM );
		this.parentPath = Paths.get( this.filePath ).getParent().toString();
		moduleEntry = japFile.getEntry( this.filePath );
		if( moduleEntry == null ) {
			throw new IOException();
		}
	} else {
		throw new IOException();
	}
}
 
Example 4
Source File: FileSystemStorageService.java    From tensorflow-java-examples-spring with Do What The F*ck You Want To Public License 6 votes vote down vote up
@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = load(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        }
        else {
            throw new StorageFileNotFoundException(
                    "Could not read file: " + filename);

        }
    }
    catch (MalformedURLException e) {
        throw new StorageFileNotFoundException("Could not read file: " + filename, e);
    }
}
 
Example 5
Source File: FileUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new directory nested with the given parent folder and desredSubPath. The newly created folder will be
 * deleted on graceful VM shutdown.
 *
 * @param parent
 *            the path of the parent folder.
 * @param nestedPath
 *            the nested path to the created folder.
 * @return the path to the new directory.
 */
public static Path createNestedDirectory(final Path parent, final String nestedPath) {
	if (!parent.toFile().isDirectory())
		throw new RuntimeException(
				"Invalid parent at " + parent + ".");

	Path desiredPath = parent.resolve(nestedPath);
	final File file = new File(desiredPath.toUri());
	if (!file.exists())
		if (!file.mkdirs())
			throw new RuntimeException(
					"Error while trying to create folder at " + parent + " with " + nestedPath + ".");

	file.deleteOnExit();
	return file.toPath();
}
 
Example 6
Source File: LocalStorage.java    From mall with MIT License 5 votes vote down vote up
@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = load(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        } else {
            return null;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 7
Source File: SerializerTest.java    From liblevenshtein-java with MIT License 5 votes vote down vote up
@Test(dataProvider = "serializerParams")
public void testDeserializeUriString(
    final Serializer serializer,
    final SortedDawg dictionary,
    final Transducer<?, ?> transducer) throws Exception {

  final Path dictionaryPath = createTempFile(DICTIONARY);
  try {
    final URI dictionaryUri = dictionaryPath.toUri();
    final String dictionaryUriString = dictionaryUri.toString();
    serializer.serialize(dictionary, dictionaryPath);
    final SortedDawg deserializedDictionary =
      serializer.deserialize(SortedDawg.class, dictionaryUriString);
    assertThat(deserializedDictionary).isEqualTo(dictionary);
  }
  finally {
    Files.delete(dictionaryPath);
  }

  final Path transducerPath = createTempFile(TRANSDUCER);
  try {
    final URI transducerUri = transducerPath.toUri();
    final String transducerUriString = transducerUri.toString();
    serializer.serialize(transducer, transducerPath);
    final Transducer<?, ?> deserializedTransducer =
      serializer.deserialize(Transducer.class, transducerUriString);
    assertThat(deserializedTransducer).isEqualTo(transducer);
  }
  finally {
    Files.delete(transducerPath);
  }
}
 
Example 8
Source File: TestDataBundles.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
@Test
  public void resolveURIs() throws Exception {
  	Path inputs = DataBundles.getInputs(dataBundle);
Path list = DataBundles.getPort(inputs, "in1");
DataBundles.createList(list);
// 0 string value
Path test0 = DataBundles.newListItem(list);
DataBundles.setStringValue(test0, "test0");
// 1 http:// reference
URI reference = URI.create("http://example.com/");
DataBundles.setReference(DataBundles.newListItem(list), reference);
// 2 file:/// reference
Path tmpFile = Files.createTempFile("test", ".txt");
URI fileRef = tmpFile.toUri();
assertEquals("file", fileRef.getScheme());
DataBundles.setReference(DataBundles.newListItem(list), fileRef);
// 3 empty (null)
// 4 error
Path error4 = DataBundles.getListItem(list,  4);
DataBundles.setError(error4, "Example error", "1. Tried it\n2. Didn't work");

List resolved = (List) DataBundles.resolve(list, ResolveOptions.URI);
assertEquals(test0.toUri(), resolved.get(0));
assertEquals(reference, resolved.get(1));
assertEquals(fileRef, resolved.get(2));
assertNull(resolved.get(3));
// NOTE: Need to get the Path again due to different file extension
assertTrue(resolved.get(4) instanceof ErrorDocument);		
//assertTrue(DataBundles.getListItem(list,  4).toUri(), resolved.get(4));
  }
 
Example 9
Source File: TestManifest.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
@Test
public void repopulateFromBundle() throws Exception {
	Path r = bundle.getRoot();
	URI base = r.toUri();

	Manifest manifest = new Manifest(bundle);
	manifest.populateFromBundle();
	// Second populate should not add additional entries
	manifest.populateFromBundle();

	List<String> paths = new ArrayList<>();
	for (PathMetadata s : manifest.getAggregates()) {
		Path path = s.getFile();
		paths.add(s.toString());
		assertNotNull(path.getParent());
		assertEquals(path.getParent(), s.getBundledAs().getFolder());
		if (s.getFile().equals(URI.create("/f/nested/empty/"))) {
			continue;
			// Folder's don't need proxy and createdOn
		}
		assertEquals("urn", s.getProxy().getScheme());
		UUID.fromString(s.getProxy().getSchemeSpecificPart()
				.replace("uuid:", ""));
		assertEquals(s.getCreatedOn(), Files.getLastModifiedTime(path));
	}
	//System.out.println(uris);
	assertFalse(paths.contains("/mimetype"));
	assertFalse(paths.contains("/META-INF"));
	assertTrue(paths.remove("/hello.txt"));
	assertTrue(paths.remove("/f/file1.txt"));
	assertTrue(paths.remove("/f/file2.txt"));
	assertTrue(paths.remove("/f/file3.txt"));
	assertTrue(paths.remove("/f/nested/file1.txt"));
	assertTrue(paths.remove("/f/nested/empty/"));
	assertTrue("Unexpected path: " + paths, paths.isEmpty());
}
 
Example 10
Source File: FileSystemStorageServiceImpl.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = load(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        } else {
            throw new StorageFileNotFoundException("Could not read file: " + filename);
        }
    } catch (MalformedURLException e) {
        throw new StorageFileNotFoundException("Could not read file: " + filename, e);
    }
}
 
Example 11
Source File: JDTUtilsTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGetPackageNameSrc() throws Exception {
	Path foo = getTmpFile("projects/eclipse/hello/src/Foo.java");
	foo.toFile().getParentFile().mkdirs();
	FileUtils.copyFile(Paths.get("projects", "eclipse", "hello", "src", "Foo.java").toFile(), foo.toFile());
	URI uri = foo.toUri();
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri.toString());
	String packageName = JDTUtils.getPackageName(cu.getJavaProject(), uri);
	assertEquals("", packageName);
}
 
Example 12
Source File: ModuleSource.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
public JapSource( Path f, List< String > path ) throws IOException {
	this.japFile = new JarFile( f.toFile() );
	this.uri = f.toUri();
	this.filePath = String.join( "/", path );
	moduleEntry = japFile.getEntry( this.filePath + ".ol" );
	if( moduleEntry == null ) {
		throw new FileNotFoundException(
			this.filePath + " in " + f.toString() );
	}
	this.parentPath = Paths.get( this.filePath ).getParent().toString();
}
 
Example 13
Source File: LocalFileSystemRepository.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public URI resolve(URI baseUri, String... pathComponents) {
  Preconditions.checkArgument(pathComponents.length > 0);

  Path result = Paths.get(baseUri);
  for (int i = 0; i < pathComponents.length; i++) {
    result = result.resolve(pathComponents[i]);
  }

  return result.toUri();
}
 
Example 14
Source File: LogBuilder.java    From V8LogScanner with MIT License 5 votes vote down vote up
/**
 * Construct a logcfg.xml file from the object model and save it to specified
 * location (put in the conctructor or a setter)
 *
 * @return written file by the specified location
 */
public File writeToXmlFile() throws IOException {
    File logFile = null;
    for (Path path : cfgPaths) {
        logFile = new File(path.toUri());
        fsys.writeInNewFile(content, path.toString());
    }
    return logFile;
}
 
Example 15
Source File: OperatorSubCommandTest.java    From besu with Apache License 2.0 4 votes vote down vote up
private void runCmdAndCheckOutput(
    final Cmd cmd,
    final String configFile,
    final Path outputDirectoryPath,
    final String genesisFileName,
    final boolean generate,
    final Collection<String> expectedKeyFiles)
    throws IOException {
  final URL configFilePath = this.getClass().getResource(configFile);
  parseCommand(
      cmd(
              OperatorSubCommand.COMMAND_NAME,
              OperatorSubCommand.GENERATE_BLOCKCHAIN_CONFIG_SUBCOMMAND_NAME,
              "--config-file",
              configFilePath.getPath(),
              "--to",
              outputDirectoryPath.toString())
          .args(cmd.argsArray())
          .argsArray());
  assertThat(commandErrorOutput.toString()).isEmpty();

  final Path outputGenesisExpectedPath = outputDirectoryPath.resolve(genesisFileName);
  final File outputGenesisFile = new File(outputGenesisExpectedPath.toUri());
  assertThat(outputGenesisFile).withFailMessage("Output genesis file must exist.").exists();
  final String genesisString = contentOf(outputGenesisFile, UTF_8);
  final JsonObject genesisContent = new JsonObject(genesisString);
  assertThat(genesisContent.containsKey("extraData")).isTrue();

  final Path expectedKeysPath = outputDirectoryPath.resolve("keys");
  final File keysDirectory = new File(expectedKeysPath.toUri());
  assertThat(keysDirectory).exists();
  final File[] nodesKeysFolders = keysDirectory.listFiles();
  assertThat(nodesKeysFolders).isNotNull();
  if (generate) {
    final JsonFactory jsonFactory = new JsonFactory();
    final JsonParser jp = jsonFactory.createParser(configFilePath);
    jp.setCodec(new ObjectMapper());
    final JsonNode jsonNode = jp.readValueAsTree();
    final int nodeCount = jsonNode.get("blockchain").get("nodes").get("count").asInt();
    assertThat(nodeCount).isEqualTo(nodesKeysFolders.length);
  }
  final Stream<File> nodesKeysFoldersStream = stream(nodesKeysFolders);

  nodesKeysFoldersStream.forEach(
      nodeFolder -> assertThat(nodeFolder.list()).containsAll(expectedKeyFiles));
}
 
Example 16
Source File: PathConverter.java    From sis with Apache License 2.0 4 votes vote down vote up
@Override public URI doConvert(final Path source) {
    return source.toUri();
}
 
Example 17
Source File: SystemStoragePluginInitializer.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
/**
 * To wrap plugins creation
 * @param provider
 * @param sabotContext
 * @throws Exception
 */
private void pluginsCreation(final BindingProvider provider, final SabotContext sabotContext) throws Exception {
  final DremioConfig config = provider.lookup(DremioConfig.class);
  final CatalogService catalogService = provider.lookup(CatalogService.class);
  final NamespaceService ns = provider.lookup(SabotContext.class).getNamespaceService(SYSTEM_USERNAME);
  final DeferredException deferred = new DeferredException();

  final Path supportPath = Paths.get(sabotContext.getOptionManager().getOption(TEMPORARY_SUPPORT_PATH));
  final Path logPath = Paths.get(System.getProperty(DREMIO_LOG_PATH_PROPERTY, "/var/log/dremio"));

  final URI homePath = config.getURI(DremioConfig.UPLOADS_PATH_STRING);
  final URI accelerationPath = config.getURI(DremioConfig.ACCELERATOR_PATH_STRING);
  final URI resultsPath = config.getURI(DremioConfig.RESULTS_PATH_STRING);
  final URI scratchPath = config.getURI(DremioConfig.SCRATCH_PATH_STRING);
  final URI downloadPath = config.getURI(DremioConfig.DOWNLOADS_PATH_STRING);
  // Do not construct URI simply by concatenating, as it might not be encoded properly
  final URI logsPath = new URI("pdfs", "///" + logPath.toUri().getPath(), null);
  final URI supportURI = supportPath.toUri();

  SourceConfig home = new SourceConfig();
  HomeFileConf hfc = new HomeFileConf(config);
  home.setConnectionConf(hfc);
  home.setName(HomeFileSystemStoragePlugin.HOME_PLUGIN_NAME);
  home.setMetadataPolicy(CatalogService.NEVER_REFRESH_POLICY);

  createSafe(catalogService, ns, home, deferred);

  final int maxCacheSpacePercent = config.hasPath(DremioConfig.DEBUG_DIST_MAX_CACHE_SPACE_PERCENT)?
    config.getInt(DremioConfig.DEBUG_DIST_MAX_CACHE_SPACE_PERCENT) : MAX_CACHE_SPACE_PERCENT;

  final boolean enableAsyncForAcceleration = enable(config, DremioConfig.DEBUG_DIST_ASYNC_ENABLED);

  boolean enableCachingForAcceleration = enable(config, DremioConfig.DEBUG_DIST_CACHING_ENABLED);
  if (FileSystemConf.isCloudFileSystemScheme(accelerationPath.getScheme())) {
    enableCachingForAcceleration = sabotContext.getOptionManager().getOption(CLOUD_CACHING_ENABLED) ;
  }
  createSafe(catalogService, ns,
      AccelerationStoragePluginConfig.create(accelerationPath, enableAsyncForAcceleration,
          enableCachingForAcceleration, maxCacheSpacePercent), deferred);

  final boolean enableAsyncForJobs = enable(config, DremioConfig.DEBUG_JOBS_ASYNC_ENABLED);
  createSafe(catalogService, ns,
    InternalFileConf.create(DACDaemonModule.JOBS_STORAGEPLUGIN_NAME, resultsPath, SchemaMutability.SYSTEM_TABLE,
      CatalogService.DEFAULT_METADATA_POLICY_WITH_AUTO_PROMOTE, enableAsyncForJobs), deferred);

  final boolean enableAsyncForScratch = enable(config, DremioConfig.DEBUG_SCRATCH_ASYNC_ENABLED);
  createSafe(catalogService, ns,
    InternalFileConf.create(DACDaemonModule.SCRATCH_STORAGEPLUGIN_NAME, scratchPath, SchemaMutability.USER_TABLE,
      CatalogService.NEVER_REFRESH_POLICY_WITH_AUTO_PROMOTE, enableAsyncForScratch), deferred);

  final boolean enableAsyncForDownload = enable(config, DremioConfig.DEBUG_DOWNLOAD_ASYNC_ENABLED);
  createSafe(catalogService, ns,
    InternalFileConf.create(DATASET_DOWNLOAD_STORAGE_PLUGIN, downloadPath, SchemaMutability.USER_TABLE,
      CatalogService.NEVER_REFRESH_POLICY, enableAsyncForDownload), deferred);

  final boolean enableAsyncForLogs = enable(config, DremioConfig.DEBUG_LOGS_ASYNC_ENABLED);
  createSafe(catalogService, ns,
    InternalFileConf.create(LOGS_STORAGE_PLUGIN, logsPath, SchemaMutability.NONE,
      CatalogService.NEVER_REFRESH_POLICY, enableAsyncForLogs), deferred);

  final boolean enableAsyncForSupport = enable(config, DremioConfig.DEBUG_SUPPORT_ASYNC_ENABLED);
  createSafe(catalogService, ns,
    InternalFileConf.create(LOCAL_STORAGE_PLUGIN, supportURI, SchemaMutability.SYSTEM_TABLE,
      CatalogService.NEVER_REFRESH_POLICY, enableAsyncForSupport), deferred);

  deferred.throwAndClear();
}
 
Example 18
Source File: ExplodedImage.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
void testCanCompileAgainstExplodedImage(String loc) throws IOException {
    System.err.println("testCanCompileAgainstExplodedImage(" + loc + ")");
    Path javaHome = prepareJavaHome();
    Path targetPath = javaHome.resolve(loc.replace("*", "/java.base").replace("/", sep));
    try (StandardJavaFileManager fm = javaCompiler.getStandardFileManager(null, null, null)) {
        for (String pack : REQUIRED_PACKAGES) {
            Iterable<JavaFileObject> content = fm.list(StandardLocation.PLATFORM_CLASS_PATH,
                                                       pack,
                                                       EnumSet.allOf(JavaFileObject.Kind.class),
                                                       false);

            for (JavaFileObject jfo : content) {
                String name = jfo.getName();
                int lastSlash = name.lastIndexOf('/');
                name = lastSlash >= 0 ? name.substring(lastSlash + 1) : name;
                Path target = targetPath.resolve(pack.replace(".", sep) + sep + name);
                Files.createDirectories(target.getParent());
                try (InputStream in = jfo.openInputStream()) {
                    Files.copy(in, target);
                }
            }
        }
    }

    System.setProperty("java.home", javaHome.toString());

    try (StandardJavaFileManager fm = javaCompiler.getStandardFileManager(null, null, null)) {
        DiagnosticListener<JavaFileObject> noErrors = d -> {
            if (d.getKind() == Diagnostic.Kind.ERROR)
                throw new IllegalStateException("Unexpected error: " + d);
        };
        ToolBox.JavaSource inputFile =
                new ToolBox.JavaSource("import java.util.List; class Test { List l; }");
        List<JavaFileObject> inputFiles = Arrays.asList(inputFile);
        boolean result =
                javaCompiler.getTask(null, fm, noErrors, null, null, inputFiles).call();
        if (!result) {
            throw new IllegalStateException("Could not compile correctly!");
        }
        JavacTask task =
                (JavacTask) javaCompiler.getTask(null, fm, noErrors, null, null, inputFiles);
        task.parse();
        TypeElement juList = task.getElements().getTypeElement("java.util.List");
        if (juList == null)
            throw new IllegalStateException("Cannot resolve java.util.List!");
        URI listSource = ((ClassSymbol) juList).classfile.toUri();
        if (!listSource.toString().startsWith(javaHome.toUri().toString()))
            throw new IllegalStateException(  "Did not load java.util.List from correct place, " +
                                              "actual location: " + listSource.toString() +
                                            "; expected prefix: " + javaHome.toUri());
    }

    System.err.println("finished.");
}
 
Example 19
Source File: RecursiveCopyFileVisitor.java    From incubator-taverna-language with Apache License 2.0 4 votes vote down vote up
private URI uriWithSlash(Path dir) {
	URI uri = dir.toUri();
	if (!uri.toString().endsWith("/"))
		return URI.create(uri.toString() + "/");
	return uri;
}
 
Example 20
Source File: ConversionResult.java    From eplmp with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Constructor with converted file and materials
 *
 * @param convertedFile
 *            the converted file
 */
public ConversionResult(Path convertedFile, List<Path> materials) {
    this.convertedFile = convertedFile.toUri();
    this.materials = new ArrayList<>();
    materials.forEach((path) -> this.materials.add(path.toUri()));
}