List of usage examples for java.nio.file FileSystem close
@Override public abstract void close() throws IOException;
From source file:Main.java
public static void main(String[] args) throws IOException { FileSystem fileSystem = FileSystems.getDefault(); Iterable<Path> dirs = fileSystem.getRootDirectories(); for (Path name : dirs) { System.out.println(name); }// w w w. jav a 2 s . co m fileSystem.close(); }
From source file:org.hawkular.apm.api.services.ConfigurationLoader.java
/** * This method constructs a path based on potentially accessing * one or more archive files (jar/war).//from w w w.j a v a 2 s . co m * * @param startindex The start index * @param uriParts The parts of the URI * @return The path */ protected static Path getPath(int startindex, String[] uriParts) { Path ret = Paths.get("/"); List<FileSystem> toClose = new ArrayList<FileSystem>(); try { for (int i = startindex; i < uriParts.length; i++) { String name = uriParts[i]; if (name.endsWith("!")) { name = name.substring(0, name.length() - 1); } ret = ret.resolve(name); if (name.endsWith(".jar") || name.endsWith(".war")) { try (FileSystem jarfs = FileSystems.newFileSystem(ret, Thread.currentThread().getContextClassLoader())) { ret = jarfs.getRootDirectories().iterator().next(); } catch (IOException e) { log.log(Level.SEVERE, "Failed to access archive '" + name + "'", e); } } } } finally { for (FileSystem fs : toClose) { try { fs.close(); } catch (IOException e) { log.log(Level.SEVERE, "Failed to close file system '" + fs + "'", e); } } } return ret; }
From source file:com.quartercode.jtimber.rh.agent.util.ResourceLister.java
@Override public void close() throws IOException { for (FileSystem jarFileSystem : jarFileSystems) { jarFileSystem.close(); }/*from w w w.j a v a 2s . com*/ }
From source file:org.objectpocket.storage.blob.MultiZipBlobStore.java
private synchronized void closeReadFileSystem(String name) throws IOException { FileSystem fileSystem = readFileSystems.get(name); if (fileSystem != null) { fileSystem.close(); readFileSystems.remove(name);/*from w w w. ja v a2s . c om*/ } }
From source file:org.objectpocket.storage.blob.MultiZipBlobStore.java
@Override public void close() throws IOException { for (FileSystem fs : readFileSystems.values()) { if (fs != null && fs.isOpen()) { fs.close(); }//from w ww .jav a2s . c om } }
From source file:com.romeikat.datamessie.core.base.util.FileUtil.java
private Path createZipFile(final String dir, String filename, final List<Path> files) throws IOException { filename = normalizeFilename(filename); // Create ZIP file Path zipFile = Paths.get(dir, filename + ".zip"); zipFile = getNonExisting(zipFile);/*from w ww.j av a2 s. c o m*/ Files.createFile(zipFile); final URI zipUri = URI.create("jar:file:" + zipFile.toUri().getPath()); Files.delete(zipFile); final Map<String, String> zipProperties = new HashMap<String, String>(); zipProperties.put("create", "true"); zipProperties.put("encoding", "UTF-8"); final FileSystem zipFS = FileSystems.newFileSystem(zipUri, zipProperties); // Copy TXT files to ZIP file for (final Path file : files) { final Path fileToZip = file; final Path pathInZipfile = zipFS.getPath(file.getFileName().toString()); Files.copy(fileToZip, pathInZipfile); } // Done zipFS.close(); return zipFile; }
From source file:org.objectpocket.storage.blob.MultiZipBlobStore.java
@Override public void writeBlobs(Set<Blob> blobs) throws IOException { if (blobs == null || blobs.isEmpty()) { return;//w w w.j av a 2s . co m } if (blobContainerIndex == null) { initIndexAndReadFileSystems(); } FileSystem currentWriteFileSystem = null; for (Blob blob : blobs) { // get blob path String path = blob.getPath(); if (path == null || path.trim().isEmpty()) { path = blob.getId(); } path = path.replaceAll("\\\\", "/"); String selectedBlobContainerName = null; // case 1: replace blob data String blobContainer = blobContainerIndex.get(path); if (blobContainer != null) { currentWriteFileSystem = getWriteFileSystem(blobContainer); selectedBlobContainerName = blobContainer; } // case 2: add blob data else { // create new blob container if (lastBlobContainer == null || blob.getBytes().length + lastBlobContainerSize > MAX_BINARY_FILE_SIZE) { if (currentWriteFileSystem != null) { currentWriteFileSystem.close(); } createNextBinary(); } currentWriteFileSystem = getWriteFileSystem(lastBlobContainer.getName()); selectedBlobContainerName = lastBlobContainer.getName(); } // write data to blob container String name = path; if (path.contains("/")) { name = path.substring(path.lastIndexOf("/")); path = path.substring(0, path.lastIndexOf("/")); while (path.startsWith("/")) { path = path.substring(1); } Path pathInZip = currentWriteFileSystem.getPath(path); if (!Files.exists(pathInZip)) { Files.createDirectories(pathInZip); } if (!Files.exists(pathInZip)) { throw new IOException("Could not create directory for blob. " + path); } path = path + name; } Path fileInZip = currentWriteFileSystem.getPath(path); try (OutputStream out = Files.newOutputStream(fileInZip, StandardOpenOption.CREATE)) { out.write(blob.getBytes()); } blobContainerIndex.put(path, selectedBlobContainerName); blob.setPersisted(); if (lastBlobContainer.getName().equals(selectedBlobContainerName)) { lastBlobContainerSize = lastBlobContainerSize + blob.getBytes().length; } } for (FileSystem fs : writeFileSystems.values()) { if (fs != null && fs.isOpen()) { fs.close(); } } writeFileSystems.clear(); }
From source file:org.schedulesdirect.grabber.Grabber.java
/** * Execute the grabber app/* ww w . jav a2 s . c o m*/ * @param args The command line args * @throws IOException Thrown on any unexpected IO error * @throws InvalidCredentialsException Thrown if the login attempt to Schedules Direct failed * @return {@link GrabberReturnCodes#OK OK} on success, one of the other constants in the interface otherwise; typically one would return this value back to the OS level caller * @see GrabberReturnCodes */ public int execute(String[] args) throws IOException, InvalidCredentialsException { if (!parseArgs(args)) return ARGS_PARSE_ERR; else if (parser.getParsedCommand() == null) { parser.usage(); return NO_CMD_ERR; } NetworkEpgClient clnt = null; try { if (!parser.getParsedCommand().equals("audit")) { try { clnt = new NetworkEpgClient(globalOpts.getUsername(), globalOpts.getPassword(), globalOpts.getUserAgent(), globalOpts.getUrl().toString(), true, factory); LOG.debug(String.format("Client details: %s", clnt.getUserAgent())); } catch (ServiceOfflineException e) { LOG.error("Web service is offline! Please try again later."); return SERVICE_OFFLINE_ERR; } } action = Action.valueOf(parser.getParsedCommand().toUpperCase()); int rc = CMD_FAILED_ERR; switch (action) { case LIST: if (!listOpts.isHelp()) { listLineups(clnt); rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case GRAB: if (!grabOpts.isHelp()) { updateZip(clnt); rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case ADD: if (!addOpts.isHelp()) addLineup(clnt); else parser.usage(action.toString().toLowerCase()); break; case DELETE: if (!delOpts.isHelp()) rc = removeHeadend(clnt) ? OK : CMD_FAILED_ERR; else parser.usage(action.toString().toLowerCase()); break; case INFO: if (!infoOpts.isHelp()) { dumpAccountInfo(clnt); rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case SEARCH: if (!searchOpts.isHelp()) { listLineupsForZip(clnt); rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case AUDIT: if (!auditOpts.isHelp()) { Auditor a = new Auditor(auditOpts); a.run(); if (!a.isFailed()) rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case LISTMSGS: if (!listMsgsOpts.isHelp()) { listAllMessages(clnt); rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case DELMSG: if (!delMsgsOpts.isHelp()) { if (deleteMessages(clnt, clnt.getUserStatus().getSystemMessages()) < delMsgsOpts.getIds() .size()) deleteMessages(clnt, clnt.getUserStatus().getUserMessages()); rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case AVAILABLE: if (!availOpts.isHelp()) { String type = availOpts.getType(); if (type == null) listAvailableThings(clnt); else listAvailableThings(clnt, type); // TODO: change rc = OK; } else parser.usage(action.toString().toLowerCase()); break; } return rc; } catch (ParameterException e) { System.out.println(e.getMessage()); parser.usage(); return ARGS_PARSE_ERR; } catch (JSONException e) { throw new RuntimeException(e); } finally { if (clnt != null) clnt.close(); if (grabOpts.getTarget().exists() && action == Action.GRAB) { FileSystem target; try { target = FileSystems.newFileSystem( new URI(String.format("jar:%s", grabOpts.getTarget().toURI())), Collections.<String, Object>emptyMap()); } catch (URISyntaxException e1) { throw new RuntimeException(e1); } if (action == Action.GRAB && !grabOpts.isHelp() && grabOpts.isPurge() && !freshZip) { LOG.warn("Performing a cache cleanup, this will take a few minutes!"); try { removeExpiredSchedules(target); } catch (JSONException e) { throw new IOException(e); } removeUnusedPrograms(target); } target.close(); if (action == Action.GRAB && !grabOpts.isHelp()) LOG.info(String.format("Created '%s' successfully! [%dms]", target, System.currentTimeMillis() - start)); } if (globalOpts.isSaveCreds()) { String user = globalOpts.getUsername(); String pwd = globalOpts.getPassword(); if (user != null && user.length() > 0 && pwd != null && pwd.length() > 0) { Properties props = new Properties(); props.setProperty("user", globalOpts.getUsername()); props.setProperty("password", globalOpts.getPassword()); Writer w = new FileWriter(OPTS_FILE); props.store(w, "Generated by sdjson-grabber"); w.close(); LOG.info(String.format("Credentials saved for future use in %s!", OPTS_FILE.getAbsoluteFile())); } } } }
From source file:org.testeditor.fixture.swt.SwtBotFixture.java
/** * Cleans the Workspace of the AUT and creates a demo Project. * /*from w w w . ja v a 2s. c o m*/ * @throws IOException * on reset the workspace. * @throws URISyntaxException * on reset the workspace. */ private void prepareAUTWorkspace() throws IOException, URISyntaxException { File wsPathFile = new File(getWorkspacePath()); Path wsPath = wsPathFile.toPath(); if (wsPathFile.exists()) { Files.walkFileTree(wsPath, getDeleteFileVisitor()); LOGGER.info("Removed AUT_WS: " + getWorkspacePath()); } Files.createDirectory(wsPath); Map<String, String> env = new HashMap<String, String>(); env.put("create", "true"); FileSystem fs = FileSystems.newFileSystem(getClass().getResource("/DemoWebTests.zip").toURI(), env); Iterable<Path> rootDirectories = fs.getRootDirectories(); for (Path root : rootDirectories) { DirectoryStream<Path> directoryStream = Files.newDirectoryStream(root); for (Path path : directoryStream) { if (path.getFileName().startsWith("DemoWebTests.zip")) { LOGGER.info("Found DemoWebTest."); Files.copy(path, Paths.get(wsPath.toString(), "DemoWebTests.zip")); URI uriDemoZip = new URI("jar:" + Paths.get(wsPath.toString(), "/DemoWebTests.zip").toUri()); LOGGER.info(uriDemoZip); FileSystem zipFs = FileSystems.newFileSystem(uriDemoZip, env); copyFolder(zipFs.getPath("/"), Paths.get(getWorkspacePath())); zipFs.close(); } } } fs.close(); LOGGER.info("Created Demoproject in: " + getWorkspacePath()); }
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. *//* www . ja v a 2 s.c om*/ 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()); } } }