下面列出了java.io.File#toURI ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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());
}
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());
}
@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);
}
/**
* 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;
}
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;
}
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;
}
@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());
}
@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;
}
@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());
}
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;
}
@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());
}
}
@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?
}
@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();
}
@Override
protected URI createBaseURI() {
rootTmpDir = createTmpDir();
if (rootTmpDir != null) {
File tmp = rootTmpDir;
try {
tmp = rootTmpDir.getCanonicalFile();
} catch (Exception ex) {}
return tmp.toURI();
}
return null;
}
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() });
}
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();
}
}
/**
* {@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);
}
@Test
public void createFromUri() {
File file = new File(TEST_FILE);
PathResource resource = new PathResource(file.toURI());
assertThat(resource.getPath(), equalTo(file.getAbsoluteFile().toString()));
}
private FsStateBackend createStateBackendInternal() throws IOException {
File checkpointDir = temporaryFolder.newFolder();
return new FsStateBackend(checkpointDir.toURI());
}
/**
* 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;
}