Example usage for java.nio.file FileSystem close

List of usage examples for java.nio.file FileSystem close

Introduction

In this page you can find the example usage for java.nio.file FileSystem close.

Prototype

@Override
public abstract void close() throws IOException;

Source Link

Document

Closes this file system.

Usage

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();// w  ww  . j a v a 2s . c o  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:com.sastix.cms.server.services.content.impl.ZipHandlerServiceImpl.java

@Override
public ResourceDTO handleZip(Resource zipResource) {

    final Path zipPath;
    try {//from   ww  w  .j a  va 2  s.c om
        zipPath = hashedDirectoryService.getDataByURI(zipResource.getUri(), zipResource.getResourceTenantId());
    } catch (IOException | URISyntaxException e) {
        throw new ResourceAccessError(e.getMessage());
    }

    FileSystem zipfs = null;
    try {
        zipfs = FileSystems.newFileSystem(zipPath, null);
        final Path root = zipfs.getPath("/");
        final int maxDepth = 1;

        // Search for specific files.
        final Map<String, Path> map = Files
                .find(root, maxDepth, (path_,
                        attr) -> path_.getFileName() != null && (path_.toString().endsWith(METADATA_JSON_FILE)
                                || path_.toString().endsWith(METADATA_XML_FILE)))
                .collect(Collectors.toMap(p -> p.toAbsolutePath().toString().substring(1), p -> p));

        final String zipType;
        final String startPage;

        // Check if it is a cms file
        if (map.containsKey(METADATA_JSON_FILE)) {
            zipType = METADATA_JSON_FILE;
            LOG.info("Found CMS Metadata File " + map.get(zipType).toString());
            startPage = findStartPage(map.get(zipType));
            // Check if it is a Scrom file
        } else if (map.containsKey(METADATA_XML_FILE)) {
            zipType = METADATA_XML_FILE;
            LOG.info("Found CMS Metadata File " + map.get(zipType).toString());
            startPage = findScormStartPage(map.get(zipType));

        } else {
            throw new ResourceAccessError("Zip " + zipResource.getName() + " is not supported. "
                    + METADATA_JSON_FILE + " and " + METADATA_XML_FILE + " are missing");
        }

        LOG.trace(startPage);

        final List<ResourceDTO> resourceDTOs = new LinkedList<>();

        /* Path inside ZIP File */
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                final String parentContext = zipResource.getUri().split("-")[0] + "-"
                        + zipResource.getResourceTenantId();
                final CreateResourceDTO createResourceDTO = new CreateResourceDTO();
                createResourceDTO.setResourceMediaType(tika.detect(file.toString()));
                createResourceDTO.setResourceAuthor(zipResource.getAuthor());
                createResourceDTO.setResourceExternalURI(file.toUri().toString());
                createResourceDTO.setResourceName(file.toString().substring(1));
                createResourceDTO.setResourceTenantId(zipResource.getResourceTenantId());

                final Resource resource = resourceService.insertChildResource(createResourceDTO, parentContext,
                        zipResource);

                distributedCacheService.cacheIt(resource.getUri(), resource.getResourceTenantId());

                if (file.toString().substring(1).equals(startPage)) {
                    resourceDTOs.add(0, crs.convertToDTO(resource));
                } else {
                    resourceDTOs.add(crs.convertToDTO(resource));
                }

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        });

        final ResourceDTO parentResourceDto = resourceDTOs.remove(0);
        parentResourceDto.setResourcesList(resourceDTOs);
        return parentResourceDto;

    } catch (IOException e) {
        throw new ResourceAccessError("Error while analyzing " + zipResource.toString());
    } finally {
        if (zipfs != null && zipfs.isOpen()) {
            try {
                LOG.info("Closing FileSystem");
                zipfs.close();
            } catch (IOException e) {
                LOG.error(e.getMessage());
                e.printStackTrace();
                throw new ResourceAccessError("Error while analyzing " + zipResource.toString());
            }
        }
    }
}