List of usage examples for java.nio.file FileSystems newFileSystem
public static FileSystem newFileSystem(Path path, Map<String, ?> env) throws IOException
From source file:org.apdplat.superword.tools.WordClassifierForYouDao.java
public static void parseZip(String zipFile) { LOGGER.info("?ZIP" + zipFile); try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifierForYouDao.class.getClassLoader())) { for (Path path : fs.getRootDirectories()) { LOGGER.info("?" + path); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override/*from w w w . j av a 2 s . c om*/ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { LOGGER.info("?" + file); // ? Path temp = Paths.get("target/origin-html-temp.txt"); Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING); parseFile(temp.toFile().getAbsolutePath()); return FileVisitResult.CONTINUE; } }); } } catch (Exception e) { LOGGER.error("?", e); } }
From source file:org.apdplat.superword.tools.PdfParser.java
public static void parseZip(String zipFile) { long start = System.currentTimeMillis(); LOGGER.info("?ZIP" + zipFile); try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifier.class.getClassLoader())) { for (Path path : fs.getRootDirectories()) { LOGGER.info("?" + path); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override//from w w w .j av a 2 s. co m public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { LOGGER.info("?" + file); // ? Path temp = Paths.get("target/it-software-domain-temp.pdf"); Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING); parseFile(temp.toFile().getAbsolutePath()); return FileVisitResult.CONTINUE; } }); } } catch (Exception e) { LOGGER.error("?", e); } long cost = System.currentTimeMillis() - start; LOGGER.info("?" + cost + ""); }
From source file:com.gitpitch.services.DiskService.java
public void copyDirectoryFromJar(Path jarPath, String jarDir, Path dest) { log.debug("copyDirectoryFromJar: jarPath={}, jarDir={}, dest={}", jarPath, jarDir, dest); try (FileSystem fs = FileSystems.newFileSystem(jarPath, null)) { final Path source = fs.getPath(jarDir); copyDirectory(source, dest);//from w ww . j a v a2s . c o m } catch (Exception cex) { log.warn("copyDirectoryFromJar: jarPath={}, jarDir={}, dest={}, ex={}", jarPath, jarDir, dest, cex); } }
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. *///from w w w .ja v a2 s. 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:org.apache.beam.runners.apex.ApexYarnLauncherTest.java
@Test public void testCreateJar() throws Exception { File baseDir = new File("./target/testCreateJar"); File srcDir = new File(baseDir, "src"); String file1 = "file1"; FileUtils.forceMkdir(srcDir);//from ww w .j a v a2 s . co m FileUtils.write(new File(srcDir, file1), "file1"); File jarFile = new File(baseDir, "test.jar"); ApexYarnLauncher.createJar(srcDir, jarFile); Assert.assertTrue("exists: " + jarFile, jarFile.exists()); URI uri = URI.create("jar:" + jarFile.toURI()); final Map<String, ?> env = Collections.singletonMap("create", "true"); try (final FileSystem zipfs = FileSystems.newFileSystem(uri, env);) { Assert.assertTrue("manifest", Files.isRegularFile(zipfs.getPath(JarFile.MANIFEST_NAME))); Assert.assertTrue("file1", Files.isRegularFile(zipfs.getPath(file1))); } }
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).//w ww .j a v a2s . c o 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.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 w w . j a va2 s.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.cloudbees.clickstack.util.Files2.java
/** * Returns a zip file system//from w ww . j a v a 2 s . c o m * * @param zipFile to construct the file system from * @param create true if the zip file should be created * @return a zip file system * @throws java.io.IOException */ private static FileSystem createZipFileSystem(Path zipFile, boolean create) throws IOException { // convert the filename to a URI final URI uri = URI.create("jar:file:" + zipFile.toUri().getPath()); final Map<String, String> env = new HashMap<>(); if (create) { env.put("create", "true"); } return FileSystems.newFileSystem(uri, env); }
From source file:org.schedulesdirect.api.ZipEpgClient.java
/** * Constructor/*from www .j a va 2 s .c om*/ * @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; } }
From source file:neembuu.uploader.zip.generator.NUZipFileGenerator.java
private void handleSmallModule(SmallModule moduleDescription, Class clzz, Path uploadersDirectory) throws IOException { Logger.getLogger(NUZipFileGenerator.class.getName()).log(Level.INFO, "Create zip for: {0}", clzz.getName()); Path outputModulePath = outputDirectory.resolve("sm").resolve(moduleDescription.name() + ".zip"); Files.createDirectories(outputModulePath.getParent()); while (Files.exists(outputModulePath)) { try {/*ww w. java2s . c o m*/ Files.deleteIfExists(outputModulePath); } catch (Exception a) { a.printStackTrace(); } } Map<String, String> env = new HashMap<>(); env.put("create", "true"); boolean destroyZipIsCorrupt = false; URI uri = URI.create("jar:" + outputModulePath.toUri()); try (FileSystem fs = FileSystems.newFileSystem(uri, env)) { smallModuleCreateZip(fs, moduleDescription, clzz, uploadersDirectory); } catch (Exception e) { e.printStackTrace(); destroyZipIsCorrupt = true; } if (destroyZipIsCorrupt) { Files.delete(outputModulePath); } else { String hash = HashUtil.hashFile(outputModulePath.toFile(), index.getHashalgorithm()); try { index.addSmallModule(moduleDescription, hash); } catch (Exception a) { a.printStackTrace();//ignore } } }