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.nuxeo.connect.update.standalone.PackageTestCase.java
protected File getTestPackageZip(String name) throws IOException, URISyntaxException { File zip = Framework.createTempFile("nuxeo-" + name + "-", ".zip"); Framework.trackFile(zip, zip);//from ww w . j av a 2 s. co m URI uri = getResource(TEST_PACKAGES_PREFIX + name).toURI(); if (uri.getScheme().equals("jar")) { String part = uri.getSchemeSpecificPart(); // file:/foo/bar.jar!/a/b String basePath = part.substring(part.lastIndexOf("!") + 1); try (FileSystem fs = FileSystems.newFileSystem(uri, Collections.emptyMap())) { createZip(zip, fs.getPath(basePath)); } } else { // file: scheme createZip(zip, new File(uri).toPath()); } return zip; }
From source file:org.lamport.tla.toolbox.jcloud.PayloadHelper.java
public static Payload appendModel2Jar(final Path modelPath, String mainClass, Properties properties, IProgressMonitor monitor) throws IOException { /*// w w w .j a v a2s .c o m * Get the standard tla2tools.jar from the classpath as a blueprint. * It's located in the org.lamport.tla.toolbox.jclouds bundle in the * files/ directory. It uses OSGi functionality to read files/tla2tools.jar * from the .jclouds bundle. * The copy of the blueprint will contain the spec & model and * additional metadata (properties, amended manifest). */ final Bundle bundle = FrameworkUtil.getBundle(PayloadHelper.class); final URL toolsURL = bundle.getEntry("files/tla2tools.jar"); if (toolsURL == null) { throw new RuntimeException("No tlatools.jar and/or spec to deploy"); } /* * Copy the tla2tools.jar blueprint to a temporary location on * disk to append model files below. */ final File tempFile = File.createTempFile("tla2tools", ".jar"); tempFile.deleteOnExit(); try (FileOutputStream out = new FileOutputStream(tempFile)) { IOUtils.copy(toolsURL.openStream(), out); } /* * Create a virtual filesystem in jar format. */ final Map<String, String> env = new HashMap<>(); env.put("create", "true"); final URI uri = URI.create("jar:" + tempFile.toURI()); try (FileSystem fs = FileSystems.newFileSystem(uri, env)) { /* * Copy the spec and model into the jar's model/ folder. * Also copy any module override (.class file) into the jar. */ try (DirectoryStream<Path> modelDirectoryStream = Files.newDirectoryStream(modelPath, "*.{cfg,tla,class}")) { for (final Path file : modelDirectoryStream) { final Path to = fs.getPath("/model/" + file.getFileName()); Files.copy(file, to, StandardCopyOption.REPLACE_EXISTING); } } /* * Add given class as Main-Class statement to jar's manifest. This * causes Java to launch this class when no other Main class is * given on the command line. Thus, it shortens the command line * for us. */ final Path manifestPath = fs.getPath("/META-INF/", "MANIFEST.MF"); final Manifest manifest = new Manifest(Files.newInputStream(manifestPath)); manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, mainClass); final PipedOutputStream ps = new PipedOutputStream(); final PipedInputStream is = new PipedInputStream(ps); manifest.write(ps); ps.close(); Files.copy(is, manifestPath, StandardCopyOption.REPLACE_EXISTING); /* * Add properties file to archive. The property file contains the * result email address... from where TLC eventually reads it. */ // On Windows 7 and above the file has to be created in the system's // temp folder. Otherwise except file creation to fail with a // AccessDeniedException final File f = File.createTempFile("generated", "properties"); OutputStream out = new FileOutputStream(f); // Append all entries in "properties" to the temp file f properties.store(out, "This is an optional header comment string"); // Copy the temp file f into the jar with path /model/generated.properties. final Path to = fs.getPath("/model/generated.properties"); Files.copy(f.toPath(), to, StandardCopyOption.REPLACE_EXISTING); } catch (final IOException e1) { throw new RuntimeException("No model directory found to deploy", e1); } /* * Compress archive with pack200 to achieve a much higher compression rate. We * are going to send the file on the wire after all: * * effort: take more time choosing codings for better compression segment: use * largest-possible archive segments (>10% better compression) mod time: smear * modification times to a single value deflate: ignore all JAR deflation hints * in original archive */ final Packer packer = Pack200.newPacker(); final Map<String, String> p = packer.properties(); p.put(Packer.EFFORT, "9"); p.put(Packer.SEGMENT_LIMIT, "-1"); p.put(Packer.MODIFICATION_TIME, Packer.LATEST); p.put(Packer.DEFLATE_HINT, Packer.FALSE); // Do not reorder which changes package names. Pkg name changes e.g. break // SimpleFilenameToStream. p.put(Packer.KEEP_FILE_ORDER, Packer.TRUE); // Throw an error if any of the above attributes is unrecognized. p.put(Packer.UNKNOWN_ATTRIBUTE, Packer.ERROR); final File packTempFile = File.createTempFile("tla2tools", ".pack.gz"); try (final JarFile jarFile = new JarFile(tempFile); final GZIPOutputStream fos = new GZIPOutputStream(new FileOutputStream(packTempFile));) { packer.pack(jarFile, fos); } catch (IOException ioe) { throw new RuntimeException("Failed to pack200 the tla2tools.jar file", ioe); } /* * Convert the customized tla2tools.jar into a jClouds payload object. This is * the format it will be transfered on the wire. This is handled by jClouds * though. */ Payload jarPayLoad = null; try { final InputStream openStream = new FileInputStream(packTempFile); jarPayLoad = Payloads.newInputStreamPayload(openStream); // manually set length of content to prevent a NPE bug jarPayLoad.getContentMetadata().setContentLength(Long.valueOf(openStream.available())); } catch (final IOException e1) { throw new RuntimeException("No tlatools.jar to deploy", e1); } finally { monitor.worked(5); } return jarPayLoad; }
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 .ja va 2 s . com 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()); } } } }
From source file:org.apdplat.superword.tools.WordClassifierForWebster.java
public static void parseZip(String zipFile) { LOGGER.info("?ZIP" + zipFile); try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifierForWebster.class.getClassLoader())) { for (Path path : fs.getRootDirectories()) { LOGGER.info("?" + path); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override/*from w w w . ja va 2s. c o m*/ 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.WordClassifierForOxford.java
public static void parseZip(String zipFile) { LOGGER.info("?ZIP" + zipFile); try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifierForOxford.class.getClassLoader())) { for (Path path : fs.getRootDirectories()) { LOGGER.info("?" + path); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override// w w w .ja v a 2s . c o m 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.easyrec.plugin.profilesolr.SolrSimilarityGenerator.java
@Override protected void doInstall() throws Exception { logger.info("Using plugin folder: " + pluginFolder.getURL()); logger.info("Using solr folder: " + solrFolder.getURL().toString()); String t = solrFolder.getURI().getRawSchemeSpecificPart().substring(0, solrFolder.getURI().getRawSchemeSpecificPart().lastIndexOf("!")); File target = pluginFolder.getFile(); logger.info(target.isDirectory());//from w w w. ja va 2 s . com File source = null; for (File f : target.listFiles()) { logger.info(f.getName()); if (t.contains(f.getName().replaceAll(" ", "%20"))) { source = f; break; } } Path p = Paths.get(source.toURI()); FileSystem fs = FileSystems.newFileSystem(p, null); Path solr = fs.getPath("/solr"); solrHomeFolder = Paths.get(target.getPath(), "solr"); TreeCopy tc = new TreeCopy(solr, solrHomeFolder); Files.walkFileTree(solr, tc); // EmbeddedSolrServer solrServer = new EmbeddedSolrServer(solrHomeFolder,"easyrec"); // String urlString = "http://localhost:8983/solr/easyrec"; // SolrClient solrClient = new HttpSolrClient(urlString); // if (solrServer == null) throw new Exception("Could not initialized Solr server!"); // solrSimilarityService.setSolrClient(solrServer); }
From source file:ratpack.spring.config.RatpackProperties.java
static Path resourceToPath(URL resource) { Objects.requireNonNull(resource, "Resource URL cannot be null"); URI uri;// ww w .j av a2 s.co m try { uri = resource.toURI(); } catch (URISyntaxException e) { throw new IllegalArgumentException("Could not extract URI", e); } String scheme = uri.getScheme(); if (scheme.equals("file")) { String path = uri.toString().substring("file:".length()); if (path.contains("//")) { path = StringUtils.cleanPath(path.replace("//", "")); } return Paths.get(new FileSystemResource(path).getFile().toURI()); } if (!scheme.equals("jar")) { throw new IllegalArgumentException("Cannot convert to Path: " + uri); } String s = uri.toString(); int separator = s.indexOf("!/"); String entryName = s.substring(separator + 2); URI fileURI = URI.create(s.substring(0, separator)); FileSystem fs; try { fs = FileSystems.newFileSystem(fileURI, Collections.<String, Object>emptyMap()); return fs.getPath(entryName); } catch (IOException e) { throw new IllegalArgumentException("Could not create file system for resource: " + resource, e); } }
From source file:de.codesourcery.asm.util.ASMUtil.java
/** * Create an ASM <code>ClassReader</code> for a given class , searching an optional classpath. * /* w ww. j a v a 2s.com*/ * <p>If a classpath is specified, it is searched before the system class path.</p> * * @param classToAnalyze * @param classPathEntries optional classpath that may contain directories or ZIP/JAR archives, may be <code>null</code>. * @param logger Logger used to output debug messages * @return * @throws IOException */ public static ClassReader createClassReader(String classToAnalyze, File[] classPathEntries, ILogger logger) throws IOException { if (!ArrayUtils.isEmpty(classPathEntries)) { // convert class name file-system path String relPath = classToAnalyze.replace(".", File.separator); if (!relPath.endsWith(".class")) { relPath += ".class"; } // look through search-path entries for (File parent : classPathEntries) { logger.logVerbose("Searching class in " + parent.getAbsolutePath()); if (parent.isDirectory()) // path entry is a directory { final File classFile = new File(parent, relPath); if (!classFile.exists()) { continue; } try { logger.logVerbose( "Loading class '" + classToAnalyze + "' from " + classFile.getAbsolutePath() + ""); return new ClassReader(new FileInputStream(classFile)); } catch (IOException e) { throw new IOException( "Failed to load class '" + classToAnalyze + "' from " + classFile.getAbsolutePath(), e); } } else if (parent.isFile()) // path entry is a (ZIP/JAR) file { final Path archive = Paths.get(parent.getAbsolutePath()); final FileSystem fs = FileSystems.newFileSystem(archive, null); final Path classFilePath = fs.getPath(relPath); if (Files.exists(classFilePath)) { // load class from archive try { logger.logVerbose("Loading class '" + classToAnalyze + "' from archive " + archive.toAbsolutePath()); InputStream in = fs.provider().newInputStream(classFilePath); return new ClassReader(in); } catch (IOException e) { throw new IOException("Failed to load class '" + classToAnalyze + "' from " + classFilePath.toAbsolutePath(), e); } } continue; } throw new IOException("Invalid entry on search classpath: '" + parent.getAbsolutePath() + "' is neither a directory nor JAR/ZIP archive"); } } // fall-back to using standard classpath logger.logVerbose("Trying to load class " + classToAnalyze + " using system classloader."); try { return new ClassReader(classToAnalyze); } catch (IOException e) { throw new IOException("Failed to load class '" + classToAnalyze + "'", e); } }
From source file:org.apdplat.superword.tools.WordClassifier.java
public static void parseZip(String zipFile) { 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 ww .jav a 2 s .c o m*/ 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:com.quartercode.jtimber.rh.agent.util.ResourceLister.java
/** * Creates a new resource lister that lists all occurrences of the given classpath resource on the classpath as {@link Path}s. * It is possible that multiple paths are listed if multiple classpath entries (e.g. jars) contain the resource. * For example, if two jars contain the directory {@code /test1/test2}, this class lists both both.<br> * <br>//from w w w . j a v a 2s . com * Note that this class uses a workaround to create path objects for files which are located inside a jar. * Because of that, each instance of this class should be closed after the paths have been used. * However, the paths might no longer be accessible after the lister has been closed. * * @param resourcePath The path that defines the classpath resource whose occurrences should be listed. * @param throwAll Whether {@link IOException}s, which are thrown during the retrieval of one specific resource and would therefore also interrupt * the retrieval of other resources, should be thrown. * If this is {@code false}, the regarding exceptions are logged as errors. * @throws IOException Something goes wrong while retrieving the resource occurrences. * If {@code throwAll} is {@code true} and an occurrence is located inside a jar, a jar reading exception is also possible. * @throws IllegalArgumentException The resource path doesn't start with "/" (this method cannot list relative resources). * @see #getResourcePaths() */ public ResourceLister(String resourcePath, boolean throwAll) throws IOException { Validate.isTrue(resourcePath.startsWith("/"), "Cannot retrieve relative resources, make sure your path starts with '/'"); // Retrieve all occurrences of the given path in the classpath Enumeration<URL> locations = ResourceLister.class.getClassLoader() .getResources(StringUtils.stripStart(resourcePath, "/")); // Iterate over those occurrences while (locations.hasMoreElements()) { URL location = locations.nextElement(); // Check whether the found location is inside a jar file if (location.getProtocol().equals("jar")) { try { // Resolve the path of the jar file and load the resources from there Path jarFile = Paths.get(toURI(((JarURLConnection) location.openConnection()).getJarFileURL())); // Load the resources from the jar file FileSystem jarFS = FileSystems.newFileSystem(jarFile, null); resourcePaths.add(jarFS.getPath(resourcePath)); jarFileSystems.add(jarFS); } catch (IOException e) { if (throwAll) { throw e; } else { LOGGER.error("Cannot read resource '{}' from jar file '{}'", resourcePath, location, e); } } } else { // Directly load the resources from the main file system resourcePaths.add(Paths.get(toURI(location))); } } }