Java Code Examples for java.io.File#toURI()

The following examples show how to use java.io.File#toURI() .
Example 1
Project: flink   File: SnapshotDirectoryTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests if mkdirs for snapshot directories works.
 */
@Test
public void mkdirs() throws Exception {
	File folderRoot = temporaryFolder.getRoot();
	File newFolder = new File(folderRoot, String.valueOf(UUID.randomUUID()));
	File innerNewFolder = new File(newFolder, String.valueOf(UUID.randomUUID()));
	Path path = new Path(innerNewFolder.toURI());

	Assert.assertFalse(newFolder.isDirectory());
	Assert.assertFalse(innerNewFolder.isDirectory());
	SnapshotDirectory snapshotDirectory = SnapshotDirectory.permanent(path);
	Assert.assertFalse(snapshotDirectory.exists());
	Assert.assertFalse(newFolder.isDirectory());
	Assert.assertFalse(innerNewFolder.isDirectory());

	Assert.assertTrue(snapshotDirectory.mkdirs());
	Assert.assertTrue(newFolder.isDirectory());
	Assert.assertTrue(innerNewFolder.isDirectory());
	Assert.assertTrue(snapshotDirectory.exists());
}
 
Example 2
Project: flow   File: NodeUpdater.java    License: Apache License 2.0 6 votes vote down vote up
static Set<String> getGeneratedModules(File directory,
        Set<String> excludes) {
    if (!directory.exists()) {
        return Collections.emptySet();
    }

    final Function<String, String> unixPath = str -> str.replace("\\", "/");

    final URI baseDir = directory.toURI();

    return FileUtils.listFiles(directory, new String[] { "js" }, true)
            .stream().filter(file -> {
                String path = unixPath.apply(file.getPath());
                if (path.contains("/node_modules/")) {
                    return false;
                }
                return excludes.stream().noneMatch(
                        postfix -> path.endsWith(unixPath.apply(postfix)));
            })
            .map(file -> GENERATED_PREFIX + unixPath
                    .apply(baseDir.relativize(file.toURI()).getPath()))
            .collect(Collectors.toSet());
}
 
Example 3
Project: EasyRouter   File: DirectoryContentProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void forEach(QualifiedContent content, ClassHandler processor) throws IOException {
    if (processor.onStart(content)) {
        Log.i("start trans dir "+content.getName());

        File root = content.getFile();
        URI base = root.toURI();
        for (File f : Files.fileTreeTraverser().preOrderTraversal(root)) {
            if (f.isFile()) {
                byte[] data = Files.toByteArray(f);
                String relativePath = base.relativize(f.toURI()).toString();
                processor.onClassFetch(content, Status.ADDED, relativePath, data);
            }
        }
    }
    processor.onComplete(content);
}
 
Example 4
Project: JVoiceXML   File: IRTestCaseLibrary.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * guess URI by string.
 * 
 * @param location
 *            of resource
 * @return URI
 * @throws URISyntaxException
 */
private URI guessURI(final String location) throws URISyntaxException {
    URI uri = new URI(location);
    if (uri.getScheme() == null) {
        // default is file
        File f = new File(location);
        uri = f.toURI();
    }
    return uri;
}
 
Example 5
Project: openjdk-jdk8u   File: GetInstance.java    License: GNU General Public License v2.0 5 votes vote down vote up
private int testURIParam(int testnum) throws Exception {
    // get an instance of JavaLoginConfig
    // from SUN and have it read from the URI

    File file = new File(System.getProperty("test.src", "."),
                            "GetInstance.configURI");
    URI uri = file.toURI();
    URIParameter uriParam = new URIParameter(uri);
    Configuration c = Configuration.getInstance(JAVA_CONFIG, uriParam);
    doTestURI(c, uriParam, testnum++);

    return testnum;
}
 
Example 6
Project: jdk8u60   File: GetInstance.java    License: GNU General Public License v2.0 5 votes vote down vote up
private int testURIParam(int testnum) throws Exception {
    // get an instance of JavaLoginConfig
    // from SUN and have it read from the URI

    File file = new File(System.getProperty("test.src", "."),
                            "GetInstance.configURI");
    URI uri = file.toURI();
    URIParameter uriParam = new URIParameter(uri);
    Configuration c = Configuration.getInstance(JAVA_CONFIG, uriParam);
    doTestURI(c, uriParam, testnum++);

    return testnum;
}
 
Example 7
Project: crate   File: URLFileInputTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetStream() throws IOException {
    Path tempDir = createTempDir();
    File file = new File(tempDir.toFile(), "doesnt_exist");
    URLFileInput input = new URLFileInput(file.toURI());

    String expectedMessage = "doesnt_exist (No such file or directory)";
    if (isRunningOnWindows()) {
        expectedMessage = "doesnt_exist (The system cannot find the file specified)";
    }

    expectedException.expect(FileNotFoundException.class);
    expectedException.expectMessage(expectedMessage);
    input.getStream(file.toURI());
}
 
Example 8
Project: Eclipse-Postfix-Code-Completion   File: EclipseFileManager.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException {
	Iterable<? extends File> files = getLocation(location);
	if (files == null) {
		throw new IllegalArgumentException("Unknown location : " + location);//$NON-NLS-1$
	}
	String normalizedFileName = normalized(packageName) + '/' + relativeName.replace('\\', '/');
	for (File file : files) {
		if (file.isDirectory()) {
			// handle directory
			File f = new File(file, normalizedFileName);
			if (f.exists()) {
				return new EclipseFileObject(packageName + File.separator + relativeName, f.toURI(), getKind(f), this.charset);
			} else {
				continue; // go to next entry in the location
			}
		} else if (isArchive(file)) {
			// handle archive file
			Archive archive = getArchive(file);
			if (archive != Archive.UNKNOWN_ARCHIVE) {
				if (archive.contains(normalizedFileName)) {
					return archive.getArchiveFileObject(normalizedFileName, this.charset);
				}
			}
		}
	}
	return null;
}
 
Example 9
Project: Flink-CEPplus   File: BucketsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOnProcessingTime() throws Exception {
	final File outDir = TEMP_FOLDER.newFolder();
	final Path path = new Path(outDir.toURI());

	final OnProcessingTimePolicy<String, String> rollOnProcessingTimeCountingPolicy =
			new OnProcessingTimePolicy<>(2L);

	final Buckets<String, String> buckets =
			createBuckets(path, rollOnProcessingTimeCountingPolicy, 0);

	// it takes the current processing time of the context for the creation time,
	// and for the last modification time.
	buckets.onElement("test", new TestUtils.MockSinkContext(1L, 2L, 3L));

	// now it should roll
	buckets.onProcessingTime(7L);
	Assert.assertEquals(1L, rollOnProcessingTimeCountingPolicy.getOnProcessingTimeRollCounter());

	final Map<String, Bucket<String, String>> activeBuckets = buckets.getActiveBuckets();
	Assert.assertEquals(1L, activeBuckets.size());
	Assert.assertTrue(activeBuckets.keySet().contains("test"));

	final Bucket<String, String> bucket = activeBuckets.get("test");
	Assert.assertEquals("test", bucket.getBucketId());
	Assert.assertEquals(new Path(path, "test"), bucket.getBucketPath());
	Assert.assertEquals("test", bucket.getBucketId());

	Assert.assertNull(bucket.getInProgressPart());
	Assert.assertEquals(1L, bucket.getPendingPartsForCurrentCheckpoint().size());
	Assert.assertTrue(bucket.getPendingPartsPerCheckpoint().isEmpty());
}
 
Example 10
Project: hottub   File: GetInstance.java    License: GNU General Public License v2.0 5 votes vote down vote up
private int testURIParam(int testnum) throws Exception {
    // get an instance of JavaPolicy from SUN and have it read from the URL

    File file = new File(System.getProperty("test.src", "."),
                            "GetInstance.policyURL");
    URI uri = file.toURI();
    Policy p = Policy.getInstance(JAVA_POLICY, new URIParameter(uri));

    doTest(p, testnum++);
    Policy.setPolicy(p);
    doTestSM(testnum++);

    return testnum;
}
 
Example 11
Project: Flink-CEPplus   File: FileInputFormatTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testExcludeFiles() {
	try {
		final String contents = "CONTENTS";

		// create some accepted, some ignored files

		File child1 = temporaryFolder.newFile("dataFile1.txt");
		File child2 = temporaryFolder.newFile("another_file.bin");

		File[] files = { child1, child2 };

		createTempFiles(contents.getBytes(ConfigConstants.DEFAULT_CHARSET), files);

		// test that only the valid files are accepted

		Configuration configuration = new Configuration();

		final DummyFileInputFormat format = new DummyFileInputFormat();
		format.setFilePath(temporaryFolder.getRoot().toURI().toString());
		format.configure(configuration);
		format.setFilesFilter(new GlobFilePathFilter(
			Collections.singletonList("**"),
			Collections.singletonList("**/another_file.bin")));
		FileInputSplit[] splits = format.createInputSplits(1);

		Assert.assertEquals(1, splits.length);

		final URI uri1 = splits[0].getPath().toUri();

		final URI childUri1 = child1.toURI();

		Assert.assertEquals(uri1, childUri1);
	}
	catch (Exception e) {
		System.err.println(e.getMessage());
		e.printStackTrace();
		Assert.fail(e.getMessage());
	}
}
 
Example 12
Project: DataVec   File: SingleImageRecordTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testImageRecord() throws Exception {
    File f0 = new ClassPathResource("/testimages/class0/0.jpg").getFile();
    File f1 = new ClassPathResource("/testimages/class1/A.jpg").getFile();

    SingleImageRecord imgRecord = new SingleImageRecord(f0.toURI());

    // need jackson test?
}
 
Example 13
Project: flink   File: RollingPolicyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRollOnCheckpointPolicy() throws Exception {
	final File outDir = TEMP_FOLDER.newFolder();
	final Path path = new Path(outDir.toURI());

	final MethodCallCountingPolicyWrapper<String, String> rollingPolicy =
			new MethodCallCountingPolicyWrapper<>(OnCheckpointRollingPolicy.build());

	final Buckets<String, String> buckets = createBuckets(path, rollingPolicy);

	rollingPolicy.verifyCallCounters(0L, 0L, 0L, 0L, 0L, 0L);

	buckets.onElement("test1", new TestUtils.MockSinkContext(1L, 1L, 2L));
	buckets.onElement("test1", new TestUtils.MockSinkContext(2L, 1L, 2L));
	buckets.onElement("test1", new TestUtils.MockSinkContext(3L, 1L, 3L));

	// ... we have a checkpoint so we roll ...
	buckets.snapshotState(1L, new TestUtils.MockListState<>(), new TestUtils.MockListState<>());
	rollingPolicy.verifyCallCounters(1L, 1L, 2L, 0L, 0L, 0L);

	// ... create a new in-progress file (before we had closed the last one so it was null)...
	buckets.onElement("test1", new TestUtils.MockSinkContext(5L, 1L, 5L));

	// ... we have a checkpoint so we roll ...
	buckets.snapshotState(2L, new TestUtils.MockListState<>(), new TestUtils.MockListState<>());
	rollingPolicy.verifyCallCounters(2L, 2L, 2L, 0L, 0L, 0L);

	buckets.close();
}
 
Example 14
Project: CloverETL-Engine   File: LocalOperationHandlerTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected URI createBaseURI() {
	rootTmpDir = createTmpDir();
	if (rootTmpDir != null) {
		File tmp = rootTmpDir;
		try {
			tmp = rootTmpDir.getCanonicalFile();
		} catch (Exception ex) {}
		return tmp.toURI();
	}
	return null;
}
 
Example 15
Project: difido-reports   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
public static void addPath(String s) throws Exception {
	File f = new File(s);
	URI u = f.toURI();
	URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
	Class<URLClassLoader> urlClass = URLClassLoader.class;
	Method method = urlClass.getDeclaredMethod("addURL", new Class[] { URL.class });
	method.setAccessible(true);
	method.invoke(urlClassLoader, new Object[] { u.toURL() });
}
 
Example 16
Project: google-cloud-eclipse   File: NewDataflowProjectWizardLandingPage.java    License: Apache License 2.0 5 votes vote down vote up
private void validateAndSetProjectLocationListener(ModifyEvent event) {
  String locationInputString = locationInput.getText();
  if (Strings.isNullOrEmpty(locationInputString)) {
    targetCreator.setProjectLocation(null);
    validateAndSetError();
  } else {
    File file = new File(locationInputString);
    URI location = file.toURI();
    targetCreator.setProjectLocation(location);
    validateAndSetError();
  }
}
 
Example 17
Project: JVoiceXML   File: Assert207.java    License: GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void test() throws Exception {
    final PrepareRequest request1 = new PrepareRequest();
    final String contextId = getContextId();
    request1.setContext(contextId);
    final String requestId1 = createRequestId();
    request1.setRequestId(requestId1);
    final File file1 = new File("vxml/helloworld1.vxml");
    final URI uri1 = file1.toURI();
    request1.setContentURL(uri1);
    send(request1);
    final LifeCycleEvent prepareReponse1 =
            waitForResponse("PrepareResponse");
    if (!(prepareReponse1 instanceof PrepareResponse)) {
        throw new TestFailedException("expected a PrepareReponse but got a "
                + prepareReponse1.getClass());
    }
    checkIds(prepareReponse1, contextId, requestId1);
    final PrepareRequest request2 = new PrepareRequest();
    request2.setContext(contextId);
    final String requestId2 = createRequestId();
    request2.setRequestId(requestId2);
    final File file2 = new File("vxml/helloworld2.vxml");
    final URI uri2 = file2.toURI();
    request2.setContentURL(uri2);
    send(request2);
    final LifeCycleEvent prepareReponse2 =
            waitForResponse("PrepareResponse");
    if (!(prepareReponse2 instanceof PrepareResponse)) {
        throw new TestFailedException("expected a PrepareReponse but got a "
                + prepareReponse2.getClass());
    }
    checkIds(prepareReponse2, contextId, requestId2);
    final PrepareRequest request3 = new PrepareRequest();
    request3.setContext(contextId);
    final String requestId3 = createRequestId();
    request3.setRequestId(requestId3);
    final File file3 = new File("vxml/helloworld.vxml");
    final URI uri3 = file3.toURI();
    request3.setContentURL(uri3);
    send(request3);
    final LifeCycleEvent prepareReponse3 =
            waitForResponse("PrepareResponse");
    if (!(prepareReponse3 instanceof PrepareResponse)) {
        throw new TestFailedException("expected a PrepareReponse but got a "
                + prepareReponse3.getClass());
    }
    checkIds(prepareReponse3, contextId, requestId3);
}
 
Example 18
Project: java-technology-stack   File: PathResourceTests.java    License: MIT License 4 votes vote down vote up
@Test
public void createFromUri() {
	File file = new File(TEST_FILE);
	PathResource resource = new PathResource(file.toURI());
	assertThat(resource.getPath(), equalTo(file.getAbsoluteFile().toString()));
}
 
Example 19
Project: flink   File: StreamOperatorSnapshotRestoreTest.java    License: Apache License 2.0 4 votes vote down vote up
private FsStateBackend createStateBackendInternal() throws IOException {
	File checkpointDir = temporaryFolder.newFolder();
	return new FsStateBackend(checkpointDir.toURI());
}
 
Example 20
Project: mycore   File: MCRDerivateCommands.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * Loads or updates an MCRDerivates from an XML file.
 *
 * @param file
 *            the location of the xml file
 * @param update
 *            if true, object will be updated, else object is created
 * @param importMode
 *            if true, servdates are taken from xml file
 * @throws SAXParseException
 * @throws MCRAccessException see {@link MCRMetadataManager#update(MCRDerivate)}
 * @throws MCRPersistenceException
 */
private static boolean processFromFile(File file, boolean update, boolean importMode) throws SAXParseException,
    IOException, MCRPersistenceException, MCRAccessException {
    if (!file.getName().endsWith(".xml")) {
        LOGGER.warn("{} ignored, does not end with *.xml", file);
        return false;
    }

    if (!file.isFile()) {
        LOGGER.warn("{} ignored, is not a file.", file);
        return false;
    }

    LOGGER.info("Reading file {} ...", file);

    MCRDerivate derivate = new MCRDerivate(file.toURI());
    derivate.setImportMode(importMode);

    // Replace relative path with absolute path of files
    if (derivate.getDerivate().getInternals() != null) {
        String path = derivate.getDerivate().getInternals().getSourcePath();
        path = path.replace('/', File.separatorChar).replace('\\', File.separatorChar);
        if (path.trim().length() <= 1) {
            // the path is the path name plus the name of the derivate -
            path = derivate.getId().toString();
        }
        File sPath = new File(path);

        if (!sPath.isAbsolute()) {
            // only change path to absolute path when relative
            String prefix = file.getParent();

            if (prefix != null) {
                path = prefix + File.separator + path;
            }
        }

        derivate.getDerivate().getInternals().setSourcePath(path);
        LOGGER.info("Source path --> {}", path);
    }

    LOGGER.info("Label --> {}", derivate.getLabel());

    if (update) {
        MCRMetadataManager.update(derivate);
        LOGGER.info("{} updated.", derivate.getId());
        LOGGER.info("");
    } else {
        MCRMetadataManager.create(derivate);
        LOGGER.info("{} loaded.", derivate.getId());
        LOGGER.info("");
    }

    return true;
}