Example usage for java.nio.file FileSystems getFileSystem

List of usage examples for java.nio.file FileSystems getFileSystem

Introduction

In this page you can find the example usage for java.nio.file FileSystems getFileSystem.

Prototype

public static FileSystem getFileSystem(URI uri) 

Source Link

Document

Returns a reference to an existing FileSystem .

Usage

From source file:com.willwinder.universalgcodesender.utils.FirmwareUtils.java

/**
 * Copy any missing files from the the jar's resources/firmware_config/ dir
 * into the settings/firmware_config dir.
 *//* w w  w.j  ava  2s  .c  o  m*/
public synchronized static void initialize() {
    System.out.println("Initializing firmware... ...");
    File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME);

    // Create directory if it's missing.
    if (!firmwareConfig.exists()) {
        firmwareConfig.mkdirs();
    }

    FileSystem fileSystem = null;

    // Copy firmware config files.
    try {
        final String dir = "/resources/firmware_config/";

        URI location = FirmwareUtils.class.getResource(dir).toURI();

        Path myPath;
        if (location.getScheme().equals("jar")) {
            try {
                // In case the filesystem already exists.
                fileSystem = FileSystems.getFileSystem(location);
            } catch (FileSystemNotFoundException e) {
                // Otherwise create the new filesystem.
                fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap());
            }

            myPath = fileSystem.getPath(dir);
        } else {
            myPath = Paths.get(location);
        }

        Stream<Path> files = Files.walk(myPath, 1);
        for (Path path : (Iterable<Path>) () -> files.iterator()) {
            System.out.println(path);
            final String name = path.getFileName().toString();
            File fwConfig = new File(firmwareConfig, name);
            if (name.endsWith(".json")) {
                boolean copyFile = !fwConfig.exists();
                ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path));

                // If the file is outdated... ask the user (once).
                if (fwConfig.exists()) {
                    ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig));
                    boolean outOfDate = current.getVersion() < jarSetting.getVersion();
                    if (outOfDate && !userNotified && !overwriteOldFiles) {
                        int result = NarrowOptionPane.showNarrowConfirmDialog(200,
                                Localization.getString("settings.file.outOfDate.message"),
                                Localization.getString("settings.file.outOfDate.title"),
                                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        overwriteOldFiles = result == JOptionPane.OK_OPTION;
                        userNotified = true;
                    }

                    if (overwriteOldFiles) {
                        copyFile = true;
                        jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom;
                    }
                }

                // Copy file from jar to firmware_config directory.
                if (copyFile) {
                    try {
                        save(fwConfig, jarSetting);
                    } catch (IOException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    } catch (Exception ex) {
        String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"),
                ex.getLocalizedMessage());
        GUIHelpers.displayErrorDialog(errorMessage);
        logger.log(Level.SEVERE, errorMessage, ex);
    } finally {
        if (fileSystem != null) {
            try {
                fileSystem.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, "Problem closing filesystem.", ex);
            }
        }
    }

    configFiles.clear();
    for (File f : firmwareConfig.listFiles()) {
        try {
            ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class);
            //ConfigLoader config = new ConfigLoader(f);
            configFiles.put(config.getName(), new ConfigTuple(config, f));
        } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) {
            GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath());
        }
    }
}

From source file:com.massabot.codesender.utils.FirmwareUtils.java

public synchronized static void initialize() {
    System.out.println("Initializing firmware... ...");
    File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME);

    // Create directory if it's missing.
    if (!firmwareConfig.exists()) {
        firmwareConfig.mkdirs();//from  w w w .j ava 2  s.co m
    }

    FileSystem fileSystem = null;

    // Copy firmware config files.
    try {
        final String dir = "/resources/firmware_config/";

        URI location = FirmwareUtils.class.getResource(dir).toURI();

        Path myPath;
        if (location.getScheme().equals("jar")) {
            try {
                // In case the filesystem already exists.
                fileSystem = FileSystems.getFileSystem(location);
            } catch (FileSystemNotFoundException e) {
                // Otherwise create the new filesystem.
                fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap());
            }

            myPath = fileSystem.getPath(dir);
        } else {
            myPath = Paths.get(location);
        }

        Stream<Path> files = Files.walk(myPath, 1);
        for (Path path : (Iterable<Path>) () -> files.iterator()) {
            System.out.println(path);
            final String name = path.getFileName().toString();
            File fwConfig = new File(firmwareConfig, name);
            if (name.endsWith(".json")) {
                boolean copyFile = !fwConfig.exists();
                ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path));

                // If the file is outdated... ask the user (once).
                if (fwConfig.exists()) {
                    ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig));
                    boolean outOfDate = current.getVersion() < jarSetting.getVersion();
                    if (outOfDate && !userNotified && !overwriteOldFiles) {
                        int result = NarrowOptionPane.showNarrowConfirmDialog(200,
                                Localization.getString("settings.file.outOfDate.message"),
                                Localization.getString("settings.file.outOfDate.title"),
                                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        overwriteOldFiles = result == JOptionPane.OK_OPTION;
                        userNotified = true;
                    }

                    if (overwriteOldFiles) {
                        copyFile = true;
                        jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom;
                    }
                }

                // Copy file from jar to firmware_config directory.
                if (copyFile) {
                    try {
                        save(fwConfig, jarSetting);
                    } catch (IOException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    } catch (Exception ex) {
        String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"),
                ex.getLocalizedMessage());
        GUIHelpers.displayErrorDialog(errorMessage);
        logger.log(Level.SEVERE, errorMessage, ex);
    } finally {
        if (fileSystem != null) {
            try {
                fileSystem.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, "Problem closing filesystem.", ex);
            }
        }
    }

    configFiles.clear();
    for (File f : firmwareConfig.listFiles()) {
        try {
            ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class);
            // ConfigLoader config = new ConfigLoader(f);
            configFiles.put(config.getName(), new ConfigTuple(config, f));
        } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) {
            GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath());
        }
    }
}

From source file:io.kahu.hawaii.util.call.sql.DbRequestBuilderRepository.java

private void walkDirectory(final String directory) {
    try {//from  ww w . j  ava 2 s  .c o m
        URI uri = this.getClass().getResource(directory).toURI();
        Path myPath;
        if (uri.getScheme().equals("jar")) {
            FileSystem fileSystem = null;
            try {
                fileSystem = FileSystems.getFileSystem(uri);
            } catch (Exception e) {
                // ignore
            }
            if (fileSystem == null) {
                fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap());
            }
            myPath = fileSystem.getPath(directory);
        } else {
            myPath = Paths.get(uri);
        }
        Stream<Path> walk = Files.walk(myPath, 1);
        walk.forEach((path) -> {
            String name = path.getFileName().toString();
            if (name.endsWith(".sql")) {
                DbRequestPrototype p = createPrototype(directory, name);
                if (p != null) {
                    try {
                        add(new DbRequestBuilder(p));
                    } catch (ServerException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.cryptomator.cryptofs.CryptoFileSystemProviderIntegrationTest.java

@Test
public void testGetFsViaNioApi() throws IOException {
    URI fsUri = CryptoFileSystemUris.createUri(tmpPath);
    FileSystem fs = FileSystems.newFileSystem(fsUri,
            cryptoFileSystemProperties().withPassphrase("asd").build());
    Assert.assertTrue(fs instanceof CryptoFileSystemImpl);
    Assert.assertTrue(Files.exists(tmpPath.resolve("masterkey.cryptomator")));
    FileSystem fs2 = FileSystems.getFileSystem(fsUri);
    Assert.assertSame(fs, fs2);/*from  w  w w.  j a  v  a 2s  .co  m*/
}

From source file:org.kaaproject.kaa.server.common.dao.AbstractTest.java

protected String readSchemaFileAsString(String filePath) throws IOException {
    try {//w  w  w .ja  va 2s . c  om
        URI uri = this.getClass().getClassLoader().getResource(filePath).toURI();
        String[] array = uri.toString().split("!");
        Path path;
        if (array.length > 1) {
            LOG.info("Creating fs for {}", array[0]);
            FileSystem fs;
            try {
                fs = FileSystems.newFileSystem(URI.create(array[0]), new HashMap<String, String>());
            } catch (FileSystemAlreadyExistsException e) {
                fs = FileSystems.getFileSystem(URI.create(array[0]));
            }
            path = fs.getPath(array[1]);
        } else {
            path = Paths.get(uri);
        }
        return new String(Files.readAllBytes(path));
    } catch (URISyntaxException e) {
        LOG.error("Can't generate configs {}", e);
    }
    return null;
}

From source file:org.schedulesdirect.api.ZipEpgClient.java

/**
 * Constructor// w w  w.  ja  v  a 2 s .co  m
 * @param zip The zip file to be used as the data source for this client implementation
 * @param baseUrl The base URL used to construct absolute URLs from relative URL data in the raw JSON
 * @throws IOException Thrown on any IO error reading the zip file
 */
public ZipEpgClient(final File zip, final String baseUrl) throws IOException {
    super(null, baseUrl);
    src = zip;
    progCache = new HashMap<String, Program>();
    artCache = new HashMap<>();
    URI fsUri;
    try {
        fsUri = new URI(String.format("jar:%s", zip.toURI()));
    } catch (URISyntaxException e1) {
        throw new RuntimeException(e1);
    }
    try {
        try {
            this.vfs = FileSystems.newFileSystem(fsUri, Collections.<String, Object>emptyMap());
        } catch (FileSystemAlreadyExistsException e) {
            this.vfs = FileSystems.getFileSystem(fsUri);
        }
        Path verFile = vfs.getPath(ZIP_VER_FILE);
        if (Files.exists(verFile)) {
            try (InputStream ins = Files.newInputStream(verFile)) {
                int ver = Integer.parseInt(IOUtils.toString(ins, ZIP_CHARSET.toString()));
                if (ver != ZIP_VER)
                    throw new IOException(
                            String.format("Zip file is not expected version! [v=%d; e=%d]", ver, ZIP_VER));
            }
        } else
            throw new IOException(String.format("Zip file of version %d required!", ZIP_VER));
        LOG.debug(String.format("Zip file format validated! [version=%d]", ZIP_VER));
        lineups = new HashMap<String, Lineup>();
        try (InputStream ins = Files.newInputStream(vfs.getPath(LINEUPS_LIST))) {
            String input = IOUtils.toString(ins, ZIP_CHARSET.toString());
            JSONObject o;
            try {
                o = Config.get().getObjectMapper().readValue(input, JSONObject.class);
            } catch (JsonParseException e) {
                throw new JsonEncodingException(String.format("ZipLineups: %s", e.getMessage()), e, input);
            }
            try {
                JSONArray lineups = o.getJSONArray("lineups");
                for (int i = 0; i < lineups.length(); ++i) {
                    JSONObject l = lineups.getJSONObject(i);
                    this.lineups.put(l.getString("uri"), new Lineup(l.getString("name"),
                            l.getString("location"), l.getString("uri"), l.getString("transport"), this));
                }
            } catch (JSONException e) {
                throw new InvalidJsonObjectException(String.format("ZipLineups: %s", e.getMessage()), e,
                        o.toString(3));
            }
        }
        String vfsKey = getSrcZipKey(zip);
        AtomicInteger i = CLNT_COUNT.get(vfsKey);
        if (i == null) {
            i = new AtomicInteger(0);
            CLNT_COUNT.put(vfsKey, i);
        }
        i.incrementAndGet();
        closed = false;
        detailsFetched = false;
    } catch (Throwable t) {
        if (vfs != null)
            try {
                close();
            } catch (IOException e) {
                LOG.error("IOError closing VFS!", e);
            }
        throw t;
    }
}