Java Code Examples for java.nio.file.FileSystems

The following are top voted examples for showing how to use java.nio.file.FileSystems. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: tscfg-docgen   File: PathMatcherConfigProvider.java   View source code 8 votes vote down vote up
@Override
public Config getConfig() throws IOException {
  PathMatcher pathMatcher;

  try {
    pathMatcher = FileSystems.getDefault().getPathMatcher(inputFilePattern);
  } catch (IllegalArgumentException e) {
    throw new IllegalArgumentException(
        "Invalid input file pattern: " + inputFilePattern);
  }

  try (Stream<Path> pathStream = Files.walk(baseDirectory)) {
    return pathStream
        .filter(p -> Files.isRegularFile(p) && pathMatcher.matches(p))
        .map(p -> ConfigFactory.parseFile(p.toFile()))
        .reduce(ConfigFactory.empty(), Config::withFallback)
        .resolve(
            ConfigResolveOptions.defaults()
                .setAllowUnresolved(true)
                .setUseSystemEnvironment(false)
        );
  }
}
 
Example 2
Project: manifold   File: PathUtil.java   View source code 8 votes vote down vote up
public static Path create( URI uri )
{
  try
  {
    return Paths.get( uri );
  }
  catch( FileSystemNotFoundException nfe )
  {
    try
    {
      Map<String, String> env = new HashMap<>();
      env.put( "create", "true" ); // creates zip/jar file if not already exists
      FileSystem fs = FileSystems.newFileSystem( uri, env );
      return fs.provider().getPath( uri );
    }
    catch( IOException e )
    {
      throw new RuntimeException( e );
    }
  }
}
 
Example 3
Project: vind   File: FileSystemUtils.java   View source code 7 votes vote down vote up
/**
 * Convert a local URL (file:// or jar:// protocol) to a {@link Path}
 * @param resource the URL resource
 * @return the Path
 * @throws URISyntaxException
 * @throws IOException
 */
public static Path toPath(URL resource) throws IOException, URISyntaxException {
    if (resource == null) return null;

    final String protocol = resource.getProtocol();
    if ("file".equals(protocol)) {
        return Paths.get(resource.toURI());
    } else if ("jar".equals(protocol)) {
        final String s = resource.toString();
        final int separator = s.indexOf("!/");
        final String entryName = s.substring(separator + 2);
        final URI fileURI = URI.create(s.substring(0, separator));

        final FileSystem fileSystem;
        synchronized (jarFileSystems) {
            if (jarFileSystems.add(fileURI)) {
                fileSystem = FileSystems.newFileSystem(fileURI, Collections.<String, Object>emptyMap());
            } else {
                fileSystem = FileSystems.getFileSystem(fileURI);
            }
        }
        return fileSystem.getPath(entryName);
    } else {
        throw new IOException("Can't read " + resource + ", unknown protocol '" + protocol + "'");
    }
}
 
Example 4
Project: distmq   File: BrokerStateMachine.java   View source code 6 votes vote down vote up
@Override
public void writeSnapshot(String snapshotDir) {
    // 采用软链接形式,提升速度和节省空间
    try {
        File messageDirFile = new File(messageDir);
        File snapshotDirFile = new File(snapshotDir);
        if (snapshotDirFile.exists()) {
            FileUtils.deleteDirectory(snapshotDirFile);
        }
        if (messageDirFile.exists()) {
            Path link = FileSystems.getDefault().getPath(snapshotDir);
            Path target = FileSystems.getDefault().getPath(messageDir).toRealPath();
            Files.createSymbolicLink(link, target);
        }
    } catch (IOException ex) {
        LOG.warn("write snapshot failed, exception:", ex);
    }
}
 
Example 5
Project: openjdk-jdk10   File: Basic.java   View source code 6 votes vote down vote up
@BeforeClass
public void setup() {
    theFileSystem = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path modulesPath = Paths.get(System.getProperty("java.home"),
            "lib", "modules");
    isExplodedBuild = Files.notExists(modulesPath);
    if (isExplodedBuild) {
        System.out.printf("%s doesn't exist.", modulesPath.toString());
        System.out.println();
        System.out.println("It is most probably an exploded build."
                + " Skip non-default FileSystem testing.");
        return;
    }

    Map<String, String> env = new HashMap<>();
    // set java.home property to be underlying java.home
    // so that jrt-fs.jar loading is exercised.
    env.put("java.home", System.getProperty("java.home"));
    try {
        fs = FileSystems.newFileSystem(URI.create("jrt:/"), env);
    } catch (IOException ioExp) {
        throw new RuntimeException(ioExp);
    }
}
 
Example 6
Project: openssp   File: Watchdog.java   View source code 6 votes vote down vote up
/**
 * Initiates a Watchdog for specific resource. File must be located within
 * the resources location of a dev machine or within
 * {@code {catalina.home}/properties}
 * 
 */
public Watchdog(final DynamicLoadable loader, final boolean startImmediately) {
	if (loader == null) {
		throw new IllegalArgumentException("loader must be set");
	}
	resource = loader.getResourceFilename();
	if (resource == null) {
		throw new IllegalArgumentException("resource in loader must be set");
	}
	autostart = startImmediately;
	this.loader = loader;
	try {
		watchService = FileSystems.getDefault().newWatchService();
		final String path = loader.getResourceLocation();
		logger.info("Watchdog [" + path + "]");
		logger.info("INFO: Watchdog [" + path + resource + "]");
		Paths.get(path).register(watchService, ENTRY_MODIFY);
	} catch (final IOException e) {
		logger.warning(e.getMessage());
	}
}
 
Example 7
Project: handycapper   File: WatchDir.java   View source code 6 votes vote down vote up
/**
 * Creates a WatchService and registers the given directory
 */
WatchDir(Path dir, boolean recursive) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.keys = new HashMap<WatchKey, Path>();
    this.recursive = recursive;

    if (recursive) {
        System.out.format("Scanning %s ...\n", dir);
        registerAll(dir);
        System.out.println("Done.");
    } else {
        register(dir);
    }

    // enable trace after initial registration
    this.trace = true;
}
 
Example 8
Project: elasticsearch-full   File: CreateIndexDemo.java   View source code 6 votes vote down vote up
@Test
public void test() throws Exception {
    Path path = FileSystems.getDefault().getPath("", "index");
    Directory directory = FSDirectory.open(path);
    Analyzer analyzer = new StandardAnalyzer();
    IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer).setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
    Document document = new Document();
    document.add(new LegacyLongField("id", 5499, Field.Store.YES));
    document.add(new Field("title", "小米6", TYPE_STORED));
    document.add(new Field("sellPoint", "骁龙835,6G内存,双摄!", TYPE_STORED));
    document.
    indexWriter.addDocument(document);
    indexWriter.commit();
    indexWriter.close();
}
 
Example 9
Project: Re-Collector   File: FileNamingStrategyTest.java   View source code 6 votes vote down vote up
@Test
public void testNumberSuffixMatches() {
    final FileSystem fs = FileSystems.getDefault();
    final Path baseName = fs.getPath("/tmp", "logfile.log");
    final NumberSuffixStrategy m = new NumberSuffixStrategy(baseName);

    assertTrue("same file matches", m.pathMatches(fs.getPath("/tmp", "logfile.log")));
    assertTrue("number suffix matches", m.pathMatches(fs.getPath("/tmp", "logfile.log.1")));
    assertTrue("multi-digit suffix matches", m.pathMatches(fs.getPath("/tmp", "logfile.log.1345345")));
    assertFalse("separator must be '.'", m.pathMatches(fs.getPath("/tmp", "logfile.log-123")));
    assertFalse("more suffixes don't match", m.pathMatches(fs.getPath("/tmp", "logfile.log.1234.gz")));
    assertFalse("wrong base path doesn't match", m.pathMatches(fs.getPath("/var/log", "logfile.log.1234")));

    assertTrue("paths are normalized", m.pathMatches(fs.getPath("/tmp/bar/..", "logfile.log.1")));
    assertTrue("relative paths are resolved", m.pathMatches(fs.getPath("logfile.log.1")));

}
 
Example 10
Project: dfx   File: PluginManagerVerticle.java   View source code 6 votes vote down vote up
private Map<String, Accessible> loadExtensions() {
    Map<String, Accessible> accessibleMap = new HashMap<>();

    pluginManager = new DefaultPluginManager(
            FileSystems.getDefault().getPath(MainVerticle.pluginDir).toAbsolutePath());
    pluginManager.loadPlugins();
    pluginManager.startPlugins();
    List<Accessible> accessibleList = pluginManager.getExtensions(Accessible.class);
    for (Accessible accessible : accessibleList) {
        String pluginName = accessible.getClass().getDeclaringClass().getName();

        logger.info("{} is loaded ...", pluginName);

        accessibleMap.put(pluginName, accessible);
    }

    return accessibleMap;
}
 
Example 11
Project: r8   File: JumboString.java   View source code 6 votes vote down vote up
public static void generate() throws IOException {
  int stringsPerFile = (1 << 14);
  for (int fileNumber = 0; fileNumber < 2; fileNumber++) {
    Path path = FileSystems.getDefault().getPath("StringPool" + fileNumber + ".java");
    PrintStream out = new PrintStream(
        Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND));

    out.println(
        "// Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file");
    out.println(
        "// for details. All rights reserved. Use of this source code is governed by a");
    out.println("// BSD-style license that can be found in the LICENSE file.");
    out.println("package jumbostring;");
    out.println();
    out.println("class StringPool" + fileNumber + " {");

    int offset = fileNumber * stringsPerFile;
    for (int i = offset; i < offset + stringsPerFile; i++) {
      out.println("  public static final String s" + i + " = \"" + i + "\";");
    }
    out.println("}");
    out.close();
  }
}
 
Example 12
Project: elasticsearch_my   File: ESClientYamlSuiteTestCase.java   View source code 6 votes vote down vote up
/**
 * Returns a new FileSystem to read REST resources, or null if they
 * are available from classpath.
 */
@SuppressForbidden(reason = "proper use of URL, hack around a JDK bug")
protected static FileSystem getFileSystem() throws IOException {
    // REST suite handling is currently complicated, with lots of filtering and so on
    // For now, to work embedded in a jar, return a ZipFileSystem over the jar contents.
    URL codeLocation = FileUtils.class.getProtectionDomain().getCodeSource().getLocation();
    boolean loadPackaged = RandomizedTest.systemPropertyAsBoolean(REST_LOAD_PACKAGED_TESTS, true);
    if (codeLocation.getFile().endsWith(".jar") && loadPackaged) {
        try {
            // hack around a bug in the zipfilesystem implementation before java 9,
            // its checkWritable was incorrect and it won't work without write permissions.
            // if we add the permission, it will open jars r/w, which is too scary! so copy to a safe r-w location.
            Path tmp = Files.createTempFile(null, ".jar");
            try (InputStream in = FileSystemUtils.openFileURLStream(codeLocation)) {
                Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING);
            }
            return FileSystems.newFileSystem(new URI("jar:" + tmp.toUri()), Collections.emptyMap());
        } catch (URISyntaxException e) {
            throw new IOException("couldn't open zipfilesystem: ", e);
        }
    } else {
        return null;
    }
}
 
Example 13
Project: openjdk-jdk10   File: Main.java   View source code 6 votes vote down vote up
static void validate(Module module) throws IOException {
    ModuleDescriptor md = module.getDescriptor();

    // read m1/module-info.class
    FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"),
                                              Collections.emptyMap());
    Path path = fs.getPath("/", "modules", module.getName(), "module-info.class");
    ModuleDescriptor md1 = ModuleDescriptor.read(Files.newInputStream(path));


    // check the module descriptor of a system module and read from jimage
    checkPackages(md.packages(), "p1", "p2");
    checkPackages(md1.packages(), "p1", "p2");

    try (InputStream in = Files.newInputStream(path)) {
        checkModuleTargetAttribute(in, "p1");
    }
}
 
Example 14
Project: truevfs   File: TFileSystemTest.java   View source code 6 votes vote down vote up
@Test
public void testNewFileSystem() throws IOException {
    for (String[] params : new String[][] {
        // $uri, $mountPoint
        { "tpath:/", "file:/" },
        { "tpath:///", "file:/" },
        { "tpath:/foo", "file:/" },
        { "tpath:/foo/", "file:/" },
        { "tpath:/foo/bar", "file:/foo/" },
        { "tpath:/foo/bar/", "file:/foo/" },
        { "tpath:/foo/bar.mok/", "mok:file:/foo/bar.mok!/" },
        { "tpath:/foo.mok/bar", "mok:file:/foo.mok!/" },
        { "tpath:/foo.mok/bar.mok", "mok:mok:file:/foo.mok!/bar.mok!/" },
    }) {
        final URI uri = URI.create(params[0]);
        final FsMountPoint mountPoint = FsMountPoint.create(
                URI.create(params[1]));
        final TFileSystem fs = (TFileSystem) FileSystems.newFileSystem(
                uri, getEnvironment(), TFileSystemTest.class.getClassLoader());
        fs.close();
        assertThat(fs.isOpen(), is(true));
        assertThat(fs.getMountPoint(), is(mountPoint));
    }
}
 
Example 15
Project: httpstub   File: DirectoryWatcher.java   View source code 6 votes vote down vote up
/**
 * Run the handler, wait for file change and interval.
 * This function exits if {@link InterruptedException} is occurred.
 * @param baseDirectory
 * @param interval
 * @param handler
 */
public void watch(File baseDirectory, Duration interval, Runnable handler) {
    while (true) {
        try {
            handler.run();
            try (val watchService = FileSystems.getDefault().newWatchService()) {
                register(watchService, baseDirectory);
                log.info("Waiting for change of file or directory in {}", baseDirectory.getAbsolutePath());
                waitForFileChange(watchService);
                log.info("File or directory has been changed, waiting {} sec...", interval.getSeconds());
                Thread.sleep(interval.toMillis());
            } catch (InterruptedException e) {
                log.info("Thread has been interrupted: {}", e.toString());
                return;
            }
        } catch (Exception e1) {
            log.warn("Error occurred while watching directory, retrying...", e1);
            try {
                Thread.sleep(interval.toMillis());
            } catch (InterruptedException e2) {
                log.info("Thread has been interrupted: {}", e2.toString());
                return;
            }
        }
    }
}
 
Example 16
Project: neoscada   File: BaseWatcher.java   View source code 6 votes vote down vote up
public BaseWatcher ( final StorageManager storageManager, final File base ) throws IOException
{
    this.storageManager = storageManager;
    this.base = base.toPath ();
    this.watcher = FileSystems.getDefault ().newWatchService ();

    this.baseKey = base.toPath ().register ( this.watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE );

    logger.debug ( "Checking for initial storages" );

    for ( final File child : this.base.toFile ().listFiles () )
    {
        logger.debug ( "Found initial storage dir - {}", child );
        checkAddStorage ( child.toPath () );
    }

    startWatcher ();
}
 
Example 17
Project: ios-device-control   File: IosAppInfo.java   View source code 6 votes vote down vote up
/** Returns the application info read from either an app folder or ipa archive */
public static IosAppInfo readFromPath(Path ipaOrAppPath) throws IOException {
  NSObject plistDict;
  if (Files.isDirectory(ipaOrAppPath)) {
    plistDict = PlistParser.fromPath(ipaOrAppPath.resolve("Info.plist"));
  } else {
    try (FileSystem ipaFs = FileSystems.newFileSystem(ipaOrAppPath, null)) {
      Path appPath =
          MoreFiles.listFiles(ipaFs.getPath("Payload"))
              .stream()
              // Can't use Files.isDirectory, because no entry is a "directory" in a zip.
              .filter(e -> e.toString().endsWith(".app/"))
              .collect(MoreCollectors.onlyElement());
      plistDict = PlistParser.fromPath(appPath.resolve("Info.plist"));
    }
  }
  return readFromPlistDictionary((NSDictionary) plistDict);
}
 
Example 18
Project: openjdk-jdk10   File: Main.java   View source code 6 votes vote down vote up
private static void checkModule(String mn, String... packages) throws IOException {
    // verify ModuleDescriptor from the runtime module
    ModuleDescriptor md = ModuleLayer.boot().findModule(mn).get()
                               .getDescriptor();
    checkModuleDescriptor(md, packages);

    // verify ModuleDescriptor from module-info.class read from ModuleReader
    try (InputStream in = ModuleFinder.ofSystem().find(mn).get()
        .open().open("module-info.class").get()) {
        checkModuleDescriptor(ModuleDescriptor.read(in), packages);
    }

    // verify ModuleDescriptor from module-info.class read from jimage
    FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"), Map.of());
    Path path = fs.getPath("/", "modules", mn, "module-info.class");
    checkModuleDescriptor(ModuleDescriptor.read(Files.newInputStream(path)), packages);
}
 
Example 19
Project: OperatieBRP   File: TimestampMojo.java   View source code 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (artifact.endsWith("jar") || artifact.endsWith("war")) {
        getLog().debug("Setting fixed timestamp for " + artifact);
        try {
            final Path tmpFolderPath = createTmpFolderPath();
            if (tmpFolderPath.toFile().exists()) {
                deleteTmpFolder(tmpFolderPath);
            }
            final Path tmpFolder = Files.createDirectory(tmpFolderPath);
            backupArtifact();
            Set<String> keys = pakArchiefBestandUit(tmpFolder);
            pakArchiefBestandOpnieuwIn(tmpFolder, keys);
            Files.deleteIfExists(FileSystems.getDefault().getPath(artifact + ".bak"));
            deleteTmpFolder(tmpFolder);
        } catch (IOException e) {
            throw new MojoExecutionException("Cannot create temp folder", e);
        }
    } else {
        getLog().debug("Artifact is not a jar or war file");
    }
}
 
Example 20
Project: tdd-pingpong   File: SubmissionPackagingService.java   View source code 6 votes vote down vote up
private void addTemplateFiles(ArchiveOutputStream archive) throws IOException {
  // TODO: maybe get the template path from config?
  Path templateDirectory = FileSystems.getDefault().getPath("tmc-assets", "submission-template");
  List<Path> templateEntries = getDirectoryEntries(templateDirectory);

  for (Path entry : templateEntries) {
    // Paths must be relativized against the template directory root
    // before including them into the Tar archive.
    // I.e. a file at ./tmc-assets/submission-template/directory/file.txt will be added to
    // the archive as ./directory/file.txt.
    String tarEntryName = templateDirectory.relativize(entry).toString();

    // TODO: special case for build.xml for renaming the project.
    addFile(archive, tarEntryName, entry);
  }
}
 
Example 21
Project: xtf   File: SshUtil.java   View source code 6 votes vote down vote up
public String getPrivateKeyPath() {

		Path p;

		String keyPath = TestConfiguration.masterSshKeyPath();

		if (keyPath != null) {
			p = FileSystems.getDefault().getPath(keyPath);

			if (p.toFile().exists()) {
				return p.toString();
			}

			p = IOUtils.findProjectRoot().resolve(keyPath);
			if (p.toFile().exists()) {
				return p.toString();
			}
		}
		
		p = FileSystems.getDefault().getPath("/ssh", "ssh-key");
		if (p.toFile().exists()) {
			return p.toString();
		}
		throw new SshPrivateKeyNotFoundException("Cannot load SSH private key.");
	}
 
Example 22
Project: openjdk-jdk10   File: ModuleSourceProviderTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() {
    classLoader = new FakeClassLoader();
    fileSupport = new FileSupport() {

        @Override
        public boolean isDirectory(Path path) {
            return true;
        }

        @Override
        public Path getSubDirectory(FileSystem fileSystem, Path root, Path path) throws IOException {
            if (getSubDirectory == null) {
                throw new IOException("Nope");
            }
            return getSubDirectory.apply(root, path);
        }
    };
    target = new ModuleSourceProvider(FileSystems.getDefault(), classLoader, fileSupport);
}
 
Example 23
Project: ditb   File: TestUpdateConfiguration.java   View source code 6 votes vote down vote up
@Test
public void testMasterOnlineConfigChange() throws IOException {
  LOG.debug("Starting the test");
  Path cnfPath = FileSystems.getDefault().getPath("target/test-classes/hbase-site.xml");
  Path cnf2Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site2.xml");
  Path cnf3Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site3.xml");
  // make a backup of hbase-site.xml
  Files.copy(cnfPath, cnf3Path, StandardCopyOption.REPLACE_EXISTING);
  // update hbase-site.xml by overwriting it
  Files.copy(cnf2Path, cnfPath, StandardCopyOption.REPLACE_EXISTING);

  Admin admin = TEST_UTIL.getHBaseAdmin();
  ServerName server = TEST_UTIL.getHBaseCluster().getMaster().getServerName();
  admin.updateConfiguration(server);
  Configuration conf = TEST_UTIL.getMiniHBaseCluster().getMaster().getConfiguration();
  int custom = conf.getInt("hbase.custom.config", 0);
  assertEquals(custom, 1000);
  // restore hbase-site.xml
  Files.copy(cnf3Path, cnfPath, StandardCopyOption.REPLACE_EXISTING);
}
 
Example 24
Project: Java-9-Programming-Blueprints   File: FileFinder.java   View source code 6 votes vote down vote up
public void find() {
    matchers = patterns.stream()
            .map(s -> !s.startsWith("**") ? "**/" + s : s)
            .map(p -> FileSystems.getDefault().getPathMatcher("glob:" + p))
            .collect(Collectors.toList());
    sourcePaths.stream()
            .map(p -> new FindFileTask(p, matchers, factory))
            .forEach(fft -> es.execute(fft));
    try {
        es.shutdown();
        es.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }

    postProcessFiles();
    factory.close();
}
 
Example 25
Project: openjdk-jdk10   File: Basic.java   View source code 6 votes vote down vote up
@Test
public void testNewFileSystemWithJavaHome() throws Exception {
    if (isExplodedBuild) {
        System.out.println("Skip testNewFileSystemWithJavaHome"
                + " since this is an exploded build");
        return;
    }

    Map<String, String> env = new HashMap<>();
    // set java.home property to be underlying java.home
    // so that jrt-fs.jar loading is exercised.
    env.put("java.home", System.getProperty("java.home"));
    try (FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"), env)) {
        checkFileSystem(fs);
        // jrt-fs.jar classes are loaded by another (non-boot) loader in this case
        assertNotNull(fs.provider().getClass().getClassLoader());
    }
}
 
Example 26
Project: hype   File: Hypelet.java   View source code 5 votes vote down vote up
private static FileSystemProvider loadFileSystemProvider(URI uri) throws IOException {
  if (Objects.equals(uri.getScheme(), "file")) {
    return FileSystems.getFileSystem(URI.create("file:///")).provider();
  } else {
    return FileSystems.newFileSystem(uri, emptyMap(), Hypelet.class.getClassLoader()).provider();
  }
}
 
Example 27
Project: openjdk-jdk10   File: ExternalEditor.java   View source code 5 votes vote down vote up
/**
 * Creates a WatchService and registers the given directory
 */
private void setupWatch(String initialText) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.dir = Files.createTempDirectory("extedit");
    this.tmpfile = Files.createTempFile(dir, null, ".java");
    Files.write(tmpfile, initialText.getBytes(Charset.forName("UTF-8")));
    dir.register(watcher,
            ENTRY_CREATE,
            ENTRY_DELETE,
            ENTRY_MODIFY);
    watchedThread = new Thread(() -> {
        for (;;) {
            WatchKey key;
            try {
                key = watcher.take();
            } catch (ClosedWatchServiceException ex) {
                // The watch service has been closed, we are done
                break;
            } catch (InterruptedException ex) {
                // tolerate an interrupt
                continue;
            }

            if (!key.pollEvents().isEmpty()) {
                saveFile();
            }

            boolean valid = key.reset();
            if (!valid) {
                // The watch service has been closed, we are done
                break;
            }
        }
    });
    watchedThread.start();
}
 
Example 28
Project: distmq   File: BrokerStateMachine.java   View source code 5 votes vote down vote up
@Override
public void readSnapshot(String snapshotDir) {
    try {
        isAvailable.compareAndSet(true, false);
        Path link = FileSystems.getDefault().getPath(snapshotDir);
        if (!Files.isSymbolicLink(link)) {
            // 非符号链接,表示从leader节点同步拷贝的
            if (logManager != null) {
                logManager.close();
            }
            File snapshotDirFile = new File(snapshotDir);
            if (snapshotDirFile.exists() && snapshotDirFile.listFiles().length > 0) {
                File messageDirFile = new File(messageDir);
                if (messageDirFile.exists()) {
                    FileUtils.deleteDirectory(messageDirFile);
                }
                FileUtils.copyDirectory(snapshotDirFile, messageDirFile);
            }
        }
        logManager = new LogManager(messageDir, this);
    } catch (IOException ex) {
        LOG.error("readSnapshot exception:", ex);
        throw new RuntimeException(ex);
    } finally {
        isAvailable.compareAndSet(false,  true);
    }
}
 
Example 29
Project: distmq   File: Segment.java   View source code 5 votes vote down vote up
public Segment(String dirName, String fileName) {
    this.dirName = dirName;
    this.fileName = fileName;
    String[] splitArray = fileName.split("-");
    if (splitArray.length != 2) {
        LOG.error("segment filename is not valid, segmentDir={}, file={}",
                dirName, fileName);
        throw new RuntimeException("invalid segmentDir=" + dirName);
    }
    try {
        if (splitArray[0].equals("open")) {
            this.setCanWrite(true);
            this.setStartOffset(Long.valueOf(splitArray[1]));
            this.setEndOffset(0);
        } else {
            try {
                this.setCanWrite(false);
                this.setStartOffset(Long.parseLong(splitArray[0]));
                this.setEndOffset(Long.parseLong(splitArray[1]));
            } catch (NumberFormatException ex) {
                LOG.error("invalid segment file name:{}", fileName);
                throw new RuntimeException("invalid segmentDir=" + dirName);
            }
        }
        File file = new File(dirName + File.separator + fileName);
        if (!file.exists()) {
            Path path = FileSystems.getDefault().getPath(dirName, fileName);
            Files.createFile(path);
        }
        this.setRandomAccessFile(RaftFileUtils.openFile(dirName, fileName, "rw"));
        this.setChannel(this.randomAccessFile.getChannel());
        this.setFileSize(this.randomAccessFile.length());
    } catch (IOException ioException) {
        LOG.warn("open segment file error, file={}, msg={}",
                fileName, ioException.getMessage());
        throw new RuntimeException("open segment file error");
    }
}
 
Example 30
Project: axway-b2b-plugins   File: GlobValidator.java   View source code 5 votes vote down vote up
@Override
public boolean isValid(String input, String pattern) {
	PathMatcher matcher = FileSystems.getDefault().getPathMatcher(GLOB_KEYWORD + pattern);
	Path keyPath = Paths.get(input, new String[0]);

	return matcher.matches(keyPath);
}
 
Example 31
Project: openjdk-jdk10   File: JmodTask.java   View source code 5 votes vote down vote up
@Override
public PathMatcher convert(String pattern) {
    try {
        return Utils.getPathMatcher(FileSystems.getDefault(), pattern);
    } catch (PatternSyntaxException e) {
        throw new CommandException("err.bad.pattern", pattern);
    }
}
 
Example 32
Project: openjdk-jdk10   File: CustomLauncherTest.java   View source code 5 votes vote down vote up
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);
    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()};
}
 
Example 33
Project: incubator-netbeans   File: FileUtils.java   View source code 5 votes vote down vote up
public static File getNormalizedPathFile(File file) {
    if (file != null && !file.getPath().isEmpty()) {
        try {
            Path path = FileSystems.getDefault().getPath(file.getPath());
            
            if (path != null) {
                return path.normalize().toFile();
            }
        } catch(InvalidPathException ex) {
            LogManager.log("Trying to normalize invalid path", ex);
        }                            
    }
    
    return file;
}
 
Example 34
Project: openjdk-jdk10   File: CodeStoreAndPathTest.java   View source code 5 votes vote down vote up
private static Path getCodeCachePath(final boolean optimistic) {
    final String codeCache = System.getProperty("nashorn.persistent.code.cache");
    final Path codeCachePath = FileSystems.getDefault().getPath(codeCache).toAbsolutePath();
    final String[] files = codeCachePath.toFile().list();
    for (final String file : files) {
        if (file.endsWith("_opt") == optimistic) {
            return codeCachePath.resolve(file);
        }
    }
    throw new AssertionError("Code cache path not found: " + codeCachePath.toString());
}
 
Example 35
Project: springboot-shiro-cas-mybatis   File: JsonServiceRegistryConfigWatcher.java   View source code 5 votes vote down vote up
/**
 * Instantiates a new Json service registry config watcher.
 *
 * @param serviceRegistryDao the registry to callback
 */
public JsonServiceRegistryConfigWatcher(final JsonServiceRegistryDao serviceRegistryDao) {
    try {
        this.serviceRegistryDao = serviceRegistryDao;
        this.watcher = FileSystems.getDefault().newWatchService();
        final WatchEvent.Kind[] kinds = (WatchEvent.Kind[])
                Arrays.asList(ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY).toArray();
        this.serviceRegistryDao.getServiceRegistryDirectory().register(this.watcher, kinds);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 36
Project: powsybl-core   File: Main.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    int status = new CommandLineTools().run(args, new ToolInitializationContext() {
        @Override
        public PrintStream getOutputStream() {
            return System.out;
        }

        @Override
        public PrintStream getErrorStream() {
            return System.err;
        }

        @Override
        public FileSystem getFileSystem() {
            return FileSystems.getDefault();
        }

        @Override
        public Options getAdditionalOptions() {
            return new Options();
        }

        @Override
        public ComputationManager createComputationManager(CommandLine commandLine) {
            try {
                return new LocalComputationManager();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    });
    if (status != CommandLineTools.COMMAND_OK_STATUS) {
        System.exit(status);
    }
}
 
Example 37
Project: openjdk-jdk10   File: FSInfo.java   View source code 5 votes vote down vote up
public List<Path> getJarClassPath(Path file) throws IOException {
    Path parent = file.getParent();
    try (JarFile jarFile = new JarFile(file.toFile())) {
        Manifest man = jarFile.getManifest();
        if (man == null)
            return Collections.emptyList();

        Attributes attr = man.getMainAttributes();
        if (attr == null)
            return Collections.emptyList();

        String path = attr.getValue(Attributes.Name.CLASS_PATH);
        if (path == null)
            return Collections.emptyList();

        List<Path> list = new ArrayList<>();

        for (StringTokenizer st = new StringTokenizer(path);
             st.hasMoreTokens(); ) {
            String elt = st.nextToken();
            Path f = FileSystems.getDefault().getPath(elt);
            if (!f.isAbsolute() && parent != null)
                f = parent.resolve(f).toAbsolutePath();
            list.add(f);
        }

        return list;
    }
}
 
Example 38
Project: vrap   File: WebJarHandler.java   View source code 5 votes vote down vote up
private FileSystem initJarFileSystem(final URI uri) {
    try {
        return FileSystems.newFileSystem(uri, Collections.emptyMap());
    } catch (IOException e) {
        throw uncheck(e);
    }
}
 
Example 39
Project: cas-5.1.0   File: ConfigurationDirectoryPathWatchService.java   View source code 5 votes vote down vote up
public ConfigurationDirectoryPathWatchService(final Path directory, final ApplicationEventPublisher eventPublisher) {
    this.eventPublisher = eventPublisher;

    try {
        this.directory = directory;
        this.watcher = FileSystems.getDefault().newWatchService();
        this.directory.register(this.watcher,
                ENTRY_CREATE,
                ENTRY_DELETE,
                ENTRY_MODIFY);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 40
Project: cas-5.1.0   File: ServiceRegistryConfigWatcher.java   View source code 5 votes vote down vote up
/**
 * Instantiates a new Json service registry config watcher.
 *
 * @param serviceRegistryDao the registry to callback
 */
ServiceRegistryConfigWatcher(final ResourceBasedServiceRegistryDao serviceRegistryDao,
                             final ApplicationEventPublisher eventPublisher) {
    try {
        this.serviceRegistryDao = serviceRegistryDao;
        this.watcher = FileSystems.getDefault().newWatchService();
        final WatchEvent.Kind[] kinds = new WatchEvent.Kind[]{ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY};
        LOGGER.debug("Created service registry watcher for events of type [{}]", (Object[]) kinds);
        this.serviceRegistryDao.getWatchableResource().register(this.watcher, kinds);
        
        this.applicationEventPublisher = eventPublisher;
    } catch (final IOException e) {
        throw Throwables.propagate(e);
    }
}