下面列出了java.nio.file.FileSystems#getDefault ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void monitorInputConfigChanges(final InputConfigMonitor inputConfigMonitor, final LogLevelFilterMonitor logLevelFilterMonitor, String clusterName) throws Exception {
final JsonParser parser = new JsonParser();
final JsonArray globalConfigNode = new JsonArray();
for (String globalConfigJsonString : inputConfigMonitor.getGlobalConfigJsons()) {
JsonElement globalConfigJson = parser.parse(globalConfigJsonString);
globalConfigNode.add(globalConfigJson.getAsJsonObject().get("global"));
Path filePath = Paths.get(configDir, "global.config.json");
String strData = InputConfigGson.gson.toJson(globalConfigJson);
byte[] data = strData.getBytes(StandardCharsets.UTF_8);
Files.write(filePath, data);
}
File[] inputConfigFiles = new File(configDir).listFiles(inputConfigFileFilter);
if (inputConfigFiles != null) {
for (File inputConfigFile : inputConfigFiles) {
tryLoadingInputConfig(inputConfigMonitor, parser, globalConfigNode, inputConfigFile);
}
}
final FileSystem fs = FileSystems.getDefault();
final WatchService ws = fs.newWatchService();
Path configPath = Paths.get(configDir);
LogSearchConfigLocalUpdater updater = new LogSearchConfigLocalUpdater(configPath, ws, inputConfigMonitor, inputFileContentsMap,
parser, globalConfigNode, serviceNamePattern);
executorService.submit(updater);
}
@Override
public String toString(final Object obj) {
final Path path = (Path)obj;
if (path.getFileSystem() == FileSystems.getDefault()) {
final String localPath = path.toString();
if (File.separatorChar != '/') {
return localPath.replace(File.separatorChar, '/');
} else {
return localPath;
}
} else {
return path.toUri().toString();
}
}
public static void main(String[] args)
throws IOException, URISyntaxException {
String os = System.getProperty("os.name");
FileSystem fs = FileSystems.getDefault();
// close should throw UOE
try {
fs.close();
throw new RuntimeException("UnsupportedOperationException expected");
} catch (UnsupportedOperationException e) { }
check(fs.isOpen(), "should be open");
check(!fs.isReadOnly(), "should provide read-write access");
check(fs.provider().getScheme().equals("file"),
"should use 'file' scheme");
// sanity check FileStores
checkFileStores(fs);
// sanity check supportedFileAttributeViews
checkSupported(fs, "basic");
if (os.equals("SunOS"))
checkSupported(fs, "posix", "unix", "owner", "acl", "user");
if (os.equals("Linux"))
checkSupported(fs, "posix", "unix", "owner", "dos", "user");
if (os.contains("OS X"))
checkSupported(fs, "posix", "unix", "owner");
if (os.equals("Windows"))
checkSupported(fs, "owner", "dos", "acl", "user");
}
private static void openAndCloseWatcher(Path dir) {
FileSystem fs = FileSystems.getDefault();
for (int i = 0; i < ITERATIONS_COUNT; i++) {
try (WatchService watcher = fs.newWatchService()) {
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
} catch (IOException ioe) {
// ignore
}
}
}
private static String[] getLauncher() throws IOException {
String platform = getPlatform();
if (platform == null) {
return null;
}
String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
File.separator + "launcher";
final FileSystem FS = FileSystems.getDefault();
Path launcherPath = FS.getPath(launcher);
final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
Files.isReadable(launcherPath);
if (!hasLauncher) {
System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
return null;
}
// It is impossible to store an executable file in the source control
// We need to copy the launcher to the working directory
// and set the executable flag
Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
Files.copy(launcherPath, localLauncherPath,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);
if (!Files.isExecutable(localLauncherPath)) {
Set<PosixFilePermission> perms = new HashSet<>(
Files.getPosixFilePermissions(
localLauncherPath,
LinkOption.NOFOLLOW_LINKS
)
);
perms.add(PosixFilePermission.OWNER_EXECUTE);
Files.setPosixFilePermissions(localLauncherPath, perms);
}
return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
private static void openAndCloseWatcher(Path dir) {
FileSystem fs = FileSystems.getDefault();
for (int i = 0; i < ITERATIONS_COUNT; i++) {
out.printf("open %d begin%n", i);
try (WatchService watcher = fs.newWatchService()) {
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
} catch (IOException ioe) {
// ignore
} finally {
out.printf("open %d end%n", i);
}
}
}
public static void main(String[] args)
throws IOException, URISyntaxException {
String os = System.getProperty("os.name");
FileSystem fs = FileSystems.getDefault();
// close should throw UOE
try {
fs.close();
throw new RuntimeException("UnsupportedOperationException expected");
} catch (UnsupportedOperationException e) { }
check(fs.isOpen(), "should be open");
check(!fs.isReadOnly(), "should provide read-write access");
check(fs.provider().getScheme().equals("file"),
"should use 'file' scheme");
// sanity check FileStores
checkFileStores(fs);
// sanity check supportedFileAttributeViews
checkSupported(fs, "basic");
if (os.equals("SunOS"))
checkSupported(fs, "posix", "unix", "owner", "acl", "user");
if (os.equals("Linux"))
checkSupported(fs, "posix", "unix", "owner", "dos", "user");
if (os.contains("OS X"))
checkSupported(fs, "posix", "unix", "owner");
if (os.equals("Windows"))
checkSupported(fs, "owner", "dos", "acl", "user");
}
private static String[] getLauncher() throws IOException {
String platform = getPlatform();
if (platform == null) {
return null;
}
String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
File.separator + "launcher";
final FileSystem FS = FileSystems.getDefault();
Path launcherPath = FS.getPath(launcher);
final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
Files.isReadable(launcherPath);
if (!hasLauncher) {
System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
return null;
}
// It is impossible to store an executable file in the source control
// We need to copy the launcher to the working directory
// and set the executable flag
Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
Files.copy(launcherPath, localLauncherPath,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);
if (!Files.isExecutable(localLauncherPath)) {
Set<PosixFilePermission> perms = new HashSet<>(
Files.getPosixFilePermissions(
localLauncherPath,
LinkOption.NOFOLLOW_LINKS
)
);
perms.add(PosixFilePermission.OWNER_EXECUTE);
Files.setPosixFilePermissions(localLauncherPath, perms);
}
return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
private static String[] getLauncher() throws IOException {
String platform = getPlatform();
if (platform == null) {
return null;
}
String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
File.separator + "launcher";
final FileSystem FS = FileSystems.getDefault();
Path launcherPath = FS.getPath(launcher);
final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
Files.isReadable(launcherPath);
if (!hasLauncher) {
System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
return null;
}
// It is impossible to store an executable file in the source control
// We need to copy the launcher to the working directory
// and set the executable flag
Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
Files.copy(launcherPath, localLauncherPath,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);
if (!Files.isExecutable(localLauncherPath)) {
Set<PosixFilePermission> perms = new HashSet<>(
Files.getPosixFilePermissions(
localLauncherPath,
LinkOption.NOFOLLOW_LINKS
)
);
perms.add(PosixFilePermission.OWNER_EXECUTE);
Files.setPosixFilePermissions(localLauncherPath, perms);
}
return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
/**
* Copy the src file/dir to the dest path recursively.
* This will replace the file if it's already exists.
*
* @param src source file /dir path
* @param dest destination path to copy
* @param globPattern glob patterns to filter out when copying.
* Note: Glob pattern matching is case sensitive.
* @throws IOException throws if any error copying the file/dir.
*/
public static void copy(Path src, Path dest, List<String> globPattern) throws IOException {
// Make sure the target dir exists.
dest.toFile().mkdirs();
// Create path matcher from list of glob pattern strings.
FileSystem fs = FileSystems.getDefault();
List<PathMatcher> matchers = globPattern.stream()
.map(pattern -> fs.getPathMatcher("glob:" + pattern))
.collect(Collectors.toList());
try (Stream<Path> stream = Files.walk(src)) {
// Filter out Glob pattern
stream.filter(path -> {
Path name = src.relativize(path);
return matchers.stream().noneMatch(m -> m.matches(name));
}).forEach(srcPath -> {
try {
Path target = dest.resolve(src.relativize(srcPath));
// Don't try to copy existing dir entry.
if (!target.toFile().isDirectory()) {
Files.copy(srcPath, target, REPLACE_EXISTING);
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
});
}
}
private static Path[] getExcludeDirs() {
final String excludeDirs[] = System.getProperty(TEST_JS_EXCLUDE_DIR, "test/script/currently-failing").split(" ");
final Path[] excludePaths = new Path[excludeDirs.length];
final FileSystem fileSystem = FileSystems.getDefault();
int i = 0;
for (final String excludeDir : excludeDirs) {
excludePaths[i++] = fileSystem.getPath(excludeDir);
}
return excludePaths;
}
/**
* Returns true if the {@code ignoreGlob} is inside the current repository.
* Produces log messages when the invalid {@code ignoreGlob} is skipped.
*/
private static boolean isValidIgnoreGlob(File repoRoot, String ignoreGlob) {
String validPath = ignoreGlob;
FileSystem fileSystem = FileSystems.getDefault();
if (ignoreGlob.isEmpty()) {
return false;
} else if (ignoreGlob.startsWith("/") || ignoreGlob.startsWith("\\")) {
// Ignore globs cannot start with a slash
logger.log(Level.WARNING, ignoreGlob + " cannot start with / or \\.");
return false;
} else if (ignoreGlob.contains("/*") || ignoreGlob.contains("\\*")) {
// contains directories
validPath = ignoreGlob.substring(0, ignoreGlob.indexOf("/*"));
} else if (ignoreGlob.contains("*")) {
// no directories
return true;
}
try {
String fileGlobPath = "glob:" + repoRoot.getCanonicalPath().replaceAll("\\\\+", "\\/") + "/**";
PathMatcher pathMatcher = fileSystem.getPathMatcher(fileGlobPath);
validPath = new File(repoRoot, validPath).getCanonicalPath();
if (pathMatcher.matches(Paths.get(validPath))) {
return true;
}
} catch (IOException ioe) {
logger.log(Level.WARNING, ioe.getMessage(), ioe);
return false;
}
logger.log(Level.WARNING, ignoreGlob + " will be skipped as this glob points to the outside of "
+ "the repository.");
return false;
}
SystemModuleFinder() {
if (Files.isRegularFile(Paths.get(JAVA_HOME, "lib", "modules"))) {
// jrt file system
this.fileSystem = FileSystems.getFileSystem(URI.create("jrt:/"));
this.root = fileSystem.getPath("/modules");
this.systemModules = walk(root);
} else {
// exploded image
this.fileSystem = FileSystems.getDefault();
root = Paths.get(JAVA_HOME, "modules");
this.systemModules = ModuleFinder.ofSystem().findAll().stream()
.collect(toMap(mref -> mref.descriptor().name(), Function.identity()));
}
}
@Before
public void start() throws Exception {
fs = new MockFileSystem(FileSystems.getDefault());
config = new TestConfiguration(tempFolder, fs);
config.setProperty("satellites.basepath.location", tempFolder.getRoot().getAbsolutePath());
config.update();
setupMocks();
}
private static Path[] getExcludeDirs() {
final String excludeDirs[] = System.getProperty(TEST_JS_EXCLUDE_DIR, "test/script/currently-failing").split(" ");
final Path[] excludePaths = new Path[excludeDirs.length];
final FileSystem fileSystem = FileSystems.getDefault();
int i = 0;
for (final String excludeDir : excludeDirs) {
excludePaths[i++] = fileSystem.getPath(excludeDir);
}
return excludePaths;
}
public static void main(String[] args)
throws InterruptedException, IOException {
// Use 'which' to verify that 'nc' is available and skip the test
// if it is not.
Process proc = Runtime.getRuntime().exec("which nc");
InputStream stdout = proc.getInputStream();
int b = stdout.read();
proc.destroy();
if (b == -1) {
System.err.println("Netcat command unavailable; skipping test.");
return;
}
// Create a new sub-directory of the nominal test directory in which
// 'nc' will create the socket file.
String testSubDir = System.getProperty("test.dir", ".")
+ File.separator + TEST_SUB_DIR;
Path socketTestDir = Paths.get(testSubDir);
Files.createDirectory(socketTestDir);
// Set the path of the socket file.
String socketFilePath = testSubDir + File.separator
+ SOCKET_FILE_NAME;
// Create a process which executes the nc (netcat) utility to create
// a socket file at the indicated location.
FileSystem fs = FileSystems.getDefault();
try (WatchService ws = fs.newWatchService()) {
// Watch the test sub-directory to receive notification when an
// entry, i.e., the socket file, is added to the sub-directory.
WatchKey wk = socketTestDir.register(ws,
StandardWatchEventKinds.ENTRY_CREATE);
// Execute the 'nc' command.
proc = Runtime.getRuntime().exec(CMD_BASE + " " + socketFilePath);
// Wait until the socket file is created.
WatchKey key = ws.take();
if (key != wk) {
throw new RuntimeException("Unknown entry created - expected: "
+ wk.watchable() + ", actual: " + key.watchable());
}
wk.cancel();
}
// Verify that the socket file in fact exists.
Path socketPath = fs.getPath(socketFilePath);
if (!Files.exists(socketPath)) {
throw new RuntimeException("Socket file " + socketFilePath
+ " was not created by \"nc\" command.");
}
// Retrieve the most recent access and modification times of the
// socket file; print the values.
BasicFileAttributeView attributeView = Files.getFileAttributeView(
socketPath, BasicFileAttributeView.class);
BasicFileAttributes oldAttributes = attributeView.readAttributes();
FileTime oldAccessTime = oldAttributes.lastAccessTime();
FileTime oldModifiedTime = oldAttributes.lastModifiedTime();
System.out.println("Old times: " + oldAccessTime
+ " " + oldModifiedTime);
// Calculate the time to which the access and modification times of the
// socket file will be changed.
FileTime newFileTime =
FileTime.fromMillis(oldAccessTime.toMillis() + 1066);
try {
// Set the access and modification times of the socket file.
attributeView.setTimes(newFileTime, newFileTime, null);
// Retrieve the updated access and modification times of the
// socket file; print the values.
FileTime newAccessTime = null;
FileTime newModifiedTime = null;
BasicFileAttributes newAttributes = attributeView.readAttributes();
newAccessTime = newAttributes.lastAccessTime();
newModifiedTime = newAttributes.lastModifiedTime();
System.out.println("New times: " + newAccessTime + " "
+ newModifiedTime);
// Verify that the updated times have the expected values.
if ((newAccessTime != null && !newAccessTime.equals(newFileTime))
|| (newModifiedTime != null
&& !newModifiedTime.equals(newFileTime))) {
throw new RuntimeException("Failed to set correct times.");
}
} finally {
// Destry the process running netcat and delete the socket file.
proc.destroy();
Files.delete(socketPath);
}
}
public DirectorySourceProvider(FileSupport fileSupport) {
this.fileSupport = fileSupport;
fileSystem = FileSystems.getDefault();
}
@Before
public void start() throws Exception {
tempDirectory = new File(tempFolder.getRoot(), "tmp");
if (!tempDirectory.mkdirs()) {
throw new RuntimeException("unable to create temp dir: " + tempDirectory.getAbsolutePath());
}
celestrak = new CelestrakServer();
celestrak.start();
celestrak.mockResponse(TestUtil.loadExpected("sample-tle.txt"));
rtlTestServer = new RtlTestServer();
rtlTestServer.mockDefault();
rtlTestServer.start();
rtlSdrMock = TestUtil.setupScript(new File(System.getProperty("java.io.tmpdir") + File.separator + "rtl_sdr_mock.sh"));
rtlTestMock = TestUtil.setupScript(new File(System.getProperty("java.io.tmpdir") + File.separator + "rtl_test_mock.sh"));
File userSettingsLocation = new File(tempFolder.getRoot(), ".r2cloud-" + UUID.randomUUID().toString());
try (InputStream is = BaseTest.class.getClassLoader().getResourceAsStream("config-dev.properties")) {
config = new Configuration(is, userSettingsLocation.getAbsolutePath(), FileSystems.getDefault());
}
File setupKeyword = new File(tempFolder.getRoot(), "r2cloud.txt");
try (Writer w = new FileWriter(setupKeyword)) {
w.append("ittests");
}
config.setProperty("celestrak.hostname", celestrak.getUrl());
config.setProperty("locaiton.lat", "56.189");
config.setProperty("locaiton.lon", "38.174");
config.setProperty("satellites.rtlsdr.path", rtlSdrMock.getAbsolutePath());
config.setProperty("rtltest.path", rtlTestMock.getAbsolutePath());
config.setProperty("satellites.sox.path", "sox");
config.setProperty("r2server.hostname", "http://localhost:8001");
config.setProperty("server.tmp.directory", tempDirectory.getAbsolutePath());
config.setProperty("server.static.location", tempFolder.getRoot().getAbsolutePath() + File.separator + "data");
config.setProperty("metrics.basepath.location", tempFolder.getRoot().getAbsolutePath() + File.separator + "data" + File.separator + "rrd");
config.setProperty("auto.update.basepath.location", tempFolder.getRoot().getAbsolutePath() + File.separator + "data" + File.separator + "auto-udpate");
config.setProperty("acme.basepath", tempFolder.getRoot().getAbsolutePath() + File.separator + "data" + File.separator + "ssl");
config.setProperty("acme.webroot", tempFolder.getRoot().getAbsolutePath() + File.separator + "data" + File.separator + "html");
config.setProperty("satellites.basepath.location", tempFolder.getRoot().getAbsolutePath() + File.separator + "data" + File.separator + "satellites");
config.setProperty("satellites.wxtoimg.license.path", tempFolder.getRoot().getAbsolutePath() + File.separator + "data" + File.separator + "wxtoimg" + File.separator + ".wxtoimglic");
config.setProperty("server.keyword.location", setupKeyword.getAbsolutePath());
server = new R2Cloud(config);
server.start();
assertStarted();
client = new RestClient(System.getProperty("r2cloud.baseurl"));
}
@Before
public void start() throws Exception {
fs = new MockFileSystem(FileSystems.getDefault());
tempfile = fs.getPath(tempFolder.getRoot().getAbsolutePath(), UUID.randomUUID().toString());
temp = new Temperature(tempfile);
}
static <T> void findAllTests(final List<T> tests, final Set<String> orphans, final TestFactory<T> testFactory) throws Exception {
final String framework = System.getProperty(TEST_JS_FRAMEWORK);
final String testList = System.getProperty(TEST_JS_LIST);
final String failedTestFileName = System.getProperty(TEST_FAILED_LIST_FILE);
if (failedTestFileName != null) {
final File failedTestFile = new File(failedTestFileName);
if (failedTestFile.exists() && failedTestFile.length() > 0L) {
try (final BufferedReader r = new BufferedReader(new FileReader(failedTestFile))) {
for (;;) {
final String testFileName = r.readLine();
if (testFileName == null) {
break;
}
handleOneTest(framework, new File(testFileName).toPath(), tests, orphans, testFactory);
}
}
return;
}
}
if (testList == null || testList.length() == 0) {
// Run the tests under the test roots dir, selected by the
// TEST_JS_INCLUDES patterns
final String testRootsString = System.getProperty(TEST_JS_ROOTS, "test/script");
if (testRootsString == null || testRootsString.length() == 0) {
throw new Exception("Error: " + TEST_JS_ROOTS + " must be set");
}
final String testRoots[] = testRootsString.split(" ");
final FileSystem fileSystem = FileSystems.getDefault();
final Set<String> testExcludeSet = getExcludeSet();
final Path[] excludePaths = getExcludeDirs();
for (final String root : testRoots) {
final Path dir = fileSystem.getPath(root);
findTests(framework, dir, tests, orphans, excludePaths, testExcludeSet, testFactory);
}
} else {
// TEST_JS_LIST contains a blank speparated list of test file names.
final String strArray[] = testList.split(" ");
for (final String ss : strArray) {
handleOneTest(framework, new File(ss).toPath(), tests, orphans, testFactory);
}
}
}