Search in sources :

Example 56 with FileSystem

use of java.nio.file.FileSystem in project OpenAM by OpenRock.

the class ZipUtils method generateZip.

/**
     * Generate a zip
     *
     * Due to a bug in Java 7 corrected in Java 8 http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7156873
     * srcFolder and outputZip can't be URL encoded if you're using java 7.
     *
     * @param srcFolder source folder
     * @param outputZip zip folder
     * @return the list of files that were included in the archive.
     * @throws IOException if an error occurs creating the zip archive.
     * @throws URISyntaxException if an error occurs creating the zip archive.
     */
public static List<String> generateZip(String srcFolder, String outputZip) throws IOException, URISyntaxException {
    final Path targetZip = Paths.get(outputZip);
    final Path sourceDir = Paths.get(srcFolder);
    final URI uri = new URI("jar", URLDecoder.decode(targetZip.toUri().toString(), "UTF-8"), null);
    final List<String> files = new ArrayList<>();
    try (FileSystem zipfs = FileSystems.newFileSystem(uri, singletonMap("create", "true"))) {
        Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                // In case the target zip is being created in the folder being zipped (e.g. Fedlet), ignore it.
                if (targetZip.equals(file)) {
                    return FileVisitResult.CONTINUE;
                }
                Path target = zipfs.getPath(sourceDir.relativize(file).toString());
                if (target.getParent() != null) {
                    Files.createDirectories(target.getParent());
                }
                Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING);
                files.add(file.toString());
                return FileVisitResult.CONTINUE;
            }
        });
    }
    return files;
}
Also used : Path(java.nio.file.Path) FileSystem(java.nio.file.FileSystem) ArrayList(java.util.ArrayList) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) URI(java.net.URI) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 57 with FileSystem

use of java.nio.file.FileSystem in project jackson-databind by FasterXML.

the class TestJava7Types method testPathRoundtrip.

public void testPathRoundtrip() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
    Path input = fs.getPath("/tmp", "foo.txt");
    String json = mapper.writeValueAsString(input);
    assertNotNull(json);
    Path p = mapper.readValue(json, Path.class);
    assertNotNull(p);
    assertEquals(input.toUri(), p.toUri());
    assertEquals(input, p);
    fs.close();
}
Also used : Path(java.nio.file.Path) FileSystem(java.nio.file.FileSystem)

Example 58 with FileSystem

use of java.nio.file.FileSystem in project graylog2-server by Graylog2.

the class WebInterfaceAssetsResource method getResponse.

private Response getResponse(Request request, String filename, URL resourceUrl, boolean fromPlugin) throws IOException, URISyntaxException {
    final Date lastModified;
    final InputStream stream;
    final HashCode hashCode;
    switch(resourceUrl.getProtocol()) {
        case "file":
            final File file = new File(resourceUrl.toURI());
            lastModified = new Date(file.lastModified());
            stream = new FileInputStream(file);
            hashCode = Files.hash(file, Hashing.sha256());
            break;
        case "jar":
            final URI uri = resourceUrl.toURI();
            final FileSystem fileSystem = fileSystemCache.getUnchecked(uri);
            final java.nio.file.Path path = fileSystem.getPath(pluginPrefixFilename(fromPlugin, filename));
            final FileTime lastModifiedTime = java.nio.file.Files.getLastModifiedTime(path);
            lastModified = new Date(lastModifiedTime.toMillis());
            stream = resourceUrl.openStream();
            hashCode = Resources.asByteSource(resourceUrl).hash(Hashing.sha256());
            break;
        default:
            throw new IllegalArgumentException("Not a JAR or local file: " + resourceUrl);
    }
    final EntityTag entityTag = new EntityTag(hashCode.toString());
    final Response.ResponseBuilder response = request.evaluatePreconditions(lastModified, entityTag);
    if (response != null) {
        return response.build();
    }
    final String contentType = firstNonNull(mimeTypes.getContentType(filename), MediaType.APPLICATION_OCTET_STREAM);
    final CacheControl cacheControl = new CacheControl();
    cacheControl.setMaxAge((int) TimeUnit.DAYS.toSeconds(365));
    cacheControl.setNoCache(false);
    cacheControl.setPrivate(false);
    return Response.ok(stream).header(HttpHeaders.CONTENT_TYPE, contentType).tag(entityTag).cacheControl(cacheControl).lastModified(lastModified).build();
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileTime(java.nio.file.attribute.FileTime) URI(java.net.URI) Date(java.util.Date) FileInputStream(java.io.FileInputStream) Response(javax.ws.rs.core.Response) HashCode(com.google.common.hash.HashCode) FileSystem(java.nio.file.FileSystem) EntityTag(javax.ws.rs.core.EntityTag) CacheControl(javax.ws.rs.core.CacheControl) File(java.io.File)

Example 59 with FileSystem

use of java.nio.file.FileSystem in project jdk8u_jdk by JetBrains.

the class CustomLauncherTest method main.

public static void main(String[] args) throws Exception {
    if (TEST_CLASSPATH == null || TEST_CLASSPATH.isEmpty()) {
        System.out.println("Test is designed to be run from jtreg only");
        return;
    }
    if (getPlatform() == null) {
        System.out.println("Test not designed to run on this operating " + "system (" + OSNAME + "), skipping...");
        return;
    }
    final FileSystem FS = FileSystems.getDefault();
    Path libjvmPath = findLibjvm(FS);
    if (libjvmPath == null) {
        throw new Error("Unable to locate 'libjvm.so' in " + TEST_JDK);
    }
    Process serverPrc = null, clientPrc = null;
    try {
        String[] launcher = getLauncher();
        System.out.println("Starting custom launcher:");
        System.out.println("=========================");
        System.out.println("  launcher  : " + launcher[0]);
        System.out.println("  libjvm    : " + libjvmPath.toString());
        System.out.println("  classpath : " + TEST_CLASSPATH);
        ProcessBuilder server = new ProcessBuilder(launcher[1], libjvmPath.toString(), TEST_CLASSPATH, "TestApplication");
        final AtomicReference<String> port = new AtomicReference<>();
        final AtomicReference<String> pid = new AtomicReference<>();
        serverPrc = ProcessTools.startProcess("Launcher", server, (String line) -> {
            if (line.startsWith("port:")) {
                port.set(line.split("\\:")[1]);
            } else if (line.startsWith("pid:")) {
                pid.set(line.split("\\:")[1]);
            } else if (line.startsWith("waiting")) {
                return true;
            }
            return false;
        }, 5, TimeUnit.SECONDS);
        System.out.println("Attaching test manager:");
        System.out.println("=========================");
        System.out.println("  PID           : " + pid.get());
        System.out.println("  shutdown port : " + port.get());
        ProcessBuilder client = ProcessTools.createJavaProcessBuilder("-cp", TEST_CLASSPATH + File.pathSeparator + TEST_JDK + File.separator + "lib" + File.separator + "tools.jar", "TestManager", pid.get(), port.get(), "true");
        clientPrc = ProcessTools.startProcess("TestManager", client, (String line) -> line.startsWith("Starting TestManager for PID"), 10, TimeUnit.SECONDS);
        int clientExitCode = clientPrc.waitFor();
        int serverExitCode = serverPrc.waitFor();
        if (clientExitCode != 0 || serverExitCode != 0) {
            throw new Error("Test failed");
        }
    } finally {
        if (clientPrc != null) {
            clientPrc.destroy();
            clientPrc.waitFor();
        }
        if (serverPrc != null) {
            serverPrc.destroy();
            serverPrc.waitFor();
        }
    }
}
Also used : Path(java.nio.file.Path) FileSystem(java.nio.file.FileSystem) AtomicReference(java.util.concurrent.atomic.AtomicReference)

Example 60 with FileSystem

use of java.nio.file.FileSystem in project android by JetBrains.

the class PatchGenerator method generateFullPackage.

/**
   * Read a zip containing a complete sdk package and generate an equivalent patch that includes the complete content of the package.
   */
public static boolean generateFullPackage(@NotNull File srcRoot, @Nullable final File existingRoot, @NotNull File outputJar, @NotNull String oldDescription, @NotNull String description, @NotNull ProgressIndicator progress) {
    Digester digester = new Digester("md5");
    Runner.initLogger();
    progress.logInfo("Generating patch...");
    final Set<String> srcFiles = new HashSet<>();
    try {
        Files.walkFileTree(srcRoot.toPath(), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String relativePath = srcRoot.toPath().relativize(file).toString();
                srcFiles.add(relativePath.replace(srcRoot.separatorChar, '/'));
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        progress.logWarning("Failed to read unzipped files!", e);
        return false;
    }
    final List<String> deleteFiles = new ArrayList<>();
    if (existingRoot != null) {
        try {
            Files.walkFileTree(existingRoot.toPath(), new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    String relativePath = existingRoot.toPath().relativize(file).toString();
                    String path = relativePath.replace(srcRoot.separatorChar, '/');
                    if (!srcFiles.contains(path)) {
                        deleteFiles.add(path);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            progress.logWarning("Failed to read existing files!", e);
            return false;
        }
    }
    PatchSpec spec = new PatchSpec().setOldVersionDescription(oldDescription).setNewVersionDescription(description).setRoot("").setBinary(true).setOldFolder(existingRoot == null ? "" : existingRoot.getAbsolutePath()).setNewFolder(srcRoot.getAbsolutePath()).setStrict(true).setCriticalFiles(new ArrayList<>(srcFiles)).setDeleteFiles(deleteFiles).setHashAlgorithm("md5");
    ProgressUI ui = new ProgressUI(progress);
    File patchZip = new File(outputJar.getParent(), "patch-file.zip");
    try {
        Patch patchInfo = new Patch(spec, ui);
        if (!patchZip.getParentFile().exists()) {
            patchZip.getParentFile().mkdirs();
        }
        patchZip.createNewFile();
        PatchFileCreator.create(spec, patchZip, ui);
        // The expected format is for the patch to be inside the package zip.
        try (FileSystem destFs = FileSystems.newFileSystem(URI.create("jar:" + outputJar.toURI()), ImmutableMap.of("create", "true", "useTempFile", true));
            InputStream is = new BufferedInputStream(new FileInputStream(patchZip))) {
            Files.copy(is, destFs.getPath("patch-file.zip"));
        }
    } catch (IOException | OperationCancelledException e) {
        progress.logWarning("Failed to create patch", e);
        return false;
    }
    return true;
}
Also used : FileSystem(java.nio.file.FileSystem) ZipFile(java.util.zip.ZipFile) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

FileSystem (java.nio.file.FileSystem)159 Path (java.nio.file.Path)112 Test (org.junit.Test)66 IOException (java.io.IOException)25 File (java.io.File)17 ArrayList (java.util.ArrayList)14 FilterFileSystem (org.apache.lucene.mockfile.FilterFileSystem)13 URI (java.net.URI)11 FilterPath (org.apache.lucene.mockfile.FilterPath)11 InputStream (java.io.InputStream)10 OutputStream (java.io.OutputStream)10 FileStore (java.nio.file.FileStore)8 ProjectFilesystem (com.facebook.buck.io.ProjectFilesystem)6 HashMap (java.util.HashMap)6 DefaultProjectFilesystemDelegate (com.facebook.buck.io.DefaultProjectFilesystemDelegate)5 ProjectFilesystemDelegate (com.facebook.buck.io.ProjectFilesystemDelegate)5 WindowsFS (org.apache.lucene.mockfile.WindowsFS)5 FSDirectory (org.apache.lucene.store.FSDirectory)5 BuckConfig (com.facebook.buck.cli.BuckConfig)4 FakeBuckConfig (com.facebook.buck.cli.FakeBuckConfig)4