Example usage for java.util.jar JarFile stream

List of usage examples for java.util.jar JarFile stream

Introduction

In this page you can find the example usage for java.util.jar JarFile stream.

Prototype

public Stream<JarEntry> stream() 

Source Link

Document

Returns an ordered Stream over the jar file entries.

Usage

From source file:com.kantenkugel.discordbot.moduleutils.DocParser.java

private static void parse() {
    LOG.info("Parsing source-file");
    try {//from ww  w  .  java 2s .  c om
        JarFile file = new JarFile(LOCAL_SRC_PATH.toFile());
        file.stream().filter(entry -> !entry.isDirectory() && entry.getName().startsWith(JDA_CODE_BASE)
                && entry.getName().endsWith(".java")).forEach(entry -> {
                    try {
                        parse(entry.getName(), file.getInputStream(entry));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
        LOG.info("Done parsing source-file");
    } catch (IOException e) {
        LOG.log(e);
    }
}

From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java

private static Pair<Artifact, byte[]> extractPacked(JarFile jar, ModList modlist, File... modDirs)
        throws IOException {
    Attributes attrs;/*from  ww w  . ja va2 s .  c o  m*/
    if (jar.getManifest() == null)
        return null;

    JarEntry manifest_entry = jar.getJarEntry(JarFile.MANIFEST_NAME);
    if (manifest_entry == null)
        manifest_entry = jar.stream()
                .filter(e -> JarFile.MANIFEST_NAME.equals(e.getName().toUpperCase(Locale.ENGLISH))).findFirst()
                .get(); //We know that getManifest returned non-null so we know there is *some* entry that matches the manifest file. So we dont need to empty check.

    attrs = jar.getManifest().getMainAttributes();

    String modSide = attrs.getValue(LibraryManager.MODSIDE);
    if (modSide != null && !"BOTH".equals(modSide) && !FMLLaunchHandler.side().name().equals(modSide))
        return null;

    if (attrs.containsKey(MODCONTAINSDEPS)) {
        for (String dep : attrs.getValue(MODCONTAINSDEPS).split(" ")) {
            if (!dep.endsWith(".jar")) {
                FMLLog.log.error("Contained Dep is not a jar file: {}", dep);
                throw new IllegalStateException("Invalid contained dep, Must be jar: " + dep);
            }

            if (jar.getJarEntry(dep) == null && jar.getJarEntry("META-INF/libraries/" + dep) != null)
                dep = "META-INF/libraries/" + dep;

            JarEntry depEntry = jar.getJarEntry(dep);
            if (depEntry == null) {
                FMLLog.log.error("Contained Dep is not in the jar: {}", dep);
                throw new IllegalStateException("Invalid contained dep, Missing from jar: " + dep);
            }

            String depEndName = new File(dep).getName(); // extract last part of name
            if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName)) {
                FMLLog.log.error("Skipping dep at request: {}", dep);
                continue;
            }

            Attributes meta = null;
            byte[] data = null;
            byte[] manifest_data = null;

            JarEntry metaEntry = jar.getJarEntry(dep + ".meta");
            if (metaEntry != null) {
                manifest_data = readAll(jar.getInputStream(metaEntry));
                meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes();
            } else {
                data = readAll(jar.getInputStream(depEntry));
                try (ZipInputStream zi = new ZipInputStream(new ByteArrayInputStream(data))) //We use zip input stream directly, as the current Oracle implementation of JarInputStream only works when the manifest is the First/Second entry in the jar...
                {
                    ZipEntry ze = null;
                    while ((ze = zi.getNextEntry()) != null) {
                        if (ze.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME)) {
                            manifest_data = readAll(zi);
                            meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes();
                            break;
                        }
                    }
                }
            }

            if (meta == null || !meta.containsKey(MAVEN_ARTIFACT)) //Ugh I really don't want to do backwards compatibility here, I want to force modders to provide information... TODO: Remove in 1.13?
            {
                boolean found = false;
                for (File dir : modDirs) {
                    File target = new File(dir, depEndName);
                    if (target.exists()) {
                        FMLLog.log.debug("Found existing ContainDep extracted to {}, skipping extraction",
                                target.getCanonicalPath());
                        found = true;
                    }
                }
                if (!found) {
                    File target = new File(modDirs[0], depEndName);
                    FMLLog.log.debug("Extracting ContainedDep {} from {} to {}", dep, jar.getName(),
                            target.getCanonicalPath());
                    try {
                        Files.createParentDirs(target);
                        try (FileOutputStream out = new FileOutputStream(target);
                                InputStream in = data == null ? jar.getInputStream(depEntry)
                                        : new ByteArrayInputStream(data)) {
                            ByteStreams.copy(in, out);
                        }
                        FMLLog.log.debug("Extracted ContainedDep {} from {} to {}", dep, jar.getName(),
                                target.getCanonicalPath());
                        extractPacked(target, modlist, modDirs);
                    } catch (IOException e) {
                        FMLLog.log.error("An error occurred extracting dependency", e);
                    }
                }
            } else {
                try {
                    Artifact artifact = readArtifact(modlist.getRepository(), meta);
                    File target = artifact.getFile();
                    if (target.exists()) {
                        FMLLog.log.debug(
                                "Found existing ContainedDep {}({}) from {} extracted to {}, skipping extraction",
                                dep, artifact.toString(), target.getCanonicalPath(), jar.getName());
                        if (!ENABLE_AUTO_MOD_MOVEMENT) {
                            Pair<?, ?> child = extractPacked(target, modlist, modDirs); //If we're not building a real list we have to re-build the dep list every run. So search down.
                            if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one.
                            {
                                modlist.add(artifact);
                            }
                        }
                    } else {
                        FMLLog.log.debug("Extracting ContainedDep {}({}) from {} to {}", dep,
                                artifact.toString(), jar.getName(), target.getCanonicalPath());
                        Files.createParentDirs(target);
                        try (FileOutputStream out = new FileOutputStream(target);
                                InputStream in = data == null ? jar.getInputStream(depEntry)
                                        : new ByteArrayInputStream(data)) {
                            ByteStreams.copy(in, out);
                        }
                        FMLLog.log.debug("Extracted ContainedDep {}({}) from {} to {}", dep,
                                artifact.toString(), jar.getName(), target.getCanonicalPath());

                        if (artifact.isSnapshot()) {
                            SnapshotJson json = SnapshotJson.create(artifact.getSnapshotMeta());
                            json.add(new SnapshotJson.Entry(artifact.getTimestamp(), meta.getValue(MD5)));
                            json.write(artifact.getSnapshotMeta());
                        }

                        if (!DISABLE_EXTERNAL_MANIFEST) {
                            File meta_target = new File(target.getAbsolutePath() + ".meta");
                            Files.write(manifest_data, meta_target);
                        }
                        Pair<?, ?> child = extractPacked(target, modlist, modDirs);
                        if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one.
                        {
                            modlist.add(artifact);
                        }
                    }
                } catch (NumberFormatException nfe) {
                    FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage(
                            "An error occurred extracting dependency. Invalid Timestamp: {}",
                            meta.getValue(TIMESTAMP)), nfe);
                } catch (IOException e) {
                    FMLLog.log.error("An error occurred extracting dependency", e);
                }
            }
        }
    }

    if (attrs.containsKey(MAVEN_ARTIFACT)) {
        Artifact artifact = readArtifact(modlist.getRepository(), attrs);
        modlist.add(artifact);
        return Pair.of(artifact, readAll(jar.getInputStream(manifest_entry)));
    }
    return null;
}

From source file:org.jsweet.transpiler.candies.CandiesProcessor.java

private void extractCandy( //
        CandyDescriptor descriptor, //
        JarFile jarFile, //
        File javaOutputDirectory, //
        File tsDefOutputDirectory, //
        File jsOutputDirectory, //
        Predicate<String> isTsDefToBeExtracted) {
    logger.info("extract candy: " + jarFile.getName() + " javaOutputDirectory=" + javaOutputDirectory
            + " tsDefOutputDirectory=" + tsDefOutputDirectory + " jsOutputDir=" + jsOutputDirectory);

    jarFile.stream().filter(entry -> entry.getName().endsWith(".d.ts")
            && (entry.getName().startsWith("src/") || entry.getName().startsWith("META-INF/resources/"))) //
            .forEach(entry -> {// w  w w.  j  a  v  a2 s  .c  o m

                File out;
                if (entry.getName().endsWith(".java")) {
                    // RP: this looks like dead code...
                    out = new File(javaOutputDirectory + "/" + entry.getName().substring(4));
                } else if (entry.getName().endsWith(".d.ts")) {
                    if (isTsDefToBeExtracted != null && !isTsDefToBeExtracted.test(entry.getName())) {
                        return;
                    }
                    out = new File(tsDefOutputDirectory + "/" + entry.getName());
                } else {
                    out = null;
                }
                extractEntry(jarFile, entry, out);
            });

    for (String jsFilePath : descriptor.jsFilesPaths) {
        JarEntry entry = jarFile.getJarEntry(jsFilePath);
        String relativeJsPath = jsFilePath.substring(descriptor.jsDirPath.length());

        File out = new File(jsOutputDirectory, relativeJsPath);
        extractEntry(jarFile, entry, out);
    }
}

From source file:org.jsweet.transpiler.candies.CandyDescriptor.java

public static CandyDescriptor fromCandyJar(JarFile jarFile, String jsOutputDirPath) throws IOException {
    JarEntry pomEntry = null;//ww  w . ja  v a  2s .co m
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry current = entries.nextElement();
        if (current.getName().endsWith("pom.xml")) {
            pomEntry = current;
        }
    }

    String pomContent = IOUtils.toString(jarFile.getInputStream(pomEntry));

    // take only general part
    int dependenciesIndex = pomContent.indexOf("<dependencies>");
    String pomGeneralPart = dependenciesIndex > 0 ? pomContent.substring(0, dependenciesIndex) : pomContent;

    // extract candy model version from <groupId></groupId>
    Matcher matcher = MODEL_VERSION_PATTERN.matcher(pomGeneralPart);
    String modelVersion = "unknown";
    if (matcher.find()) {
        modelVersion = matcher.group(1);
    }

    // extract name from <artifactId></artifactId>
    matcher = ARTIFACT_ID_PATTERN.matcher(pomGeneralPart);
    String name = "unknown";
    if (matcher.find()) {
        name = matcher.group(1);
    }

    matcher = VERSION_PATTERN.matcher(pomGeneralPart);
    String version = "unknown";
    if (matcher.find()) {
        version = matcher.group(1);
    }

    long lastUpdateTimestamp = jarFile.getEntry("META-INF/MANIFEST.MF").getTime();

    String transpilerVersion = null;

    ZipEntry metadataEntry = jarFile.getEntry("META-INF/candy-metadata.json");
    if (metadataEntry != null) {
        String metadataContent = IOUtils.toString(jarFile.getInputStream(metadataEntry));

        @SuppressWarnings("unchecked")
        Map<String, ?> metadata = gson.fromJson(metadataContent, Map.class);

        transpilerVersion = (String) metadata.get("transpilerVersion");
    }

    String jsDirPath = "META-INF/resources/webjars/" + name + "/" + version;
    ZipEntry jsDirEntry = jarFile.getEntry(jsDirPath);
    List<String> jsFilesPaths = new LinkedList<>();
    if (jsDirEntry != null) {
        // collects js files
        jarFile.stream() //
                .filter(entry -> entry.getName().startsWith(jsDirPath) && entry.getName().endsWith(".js")) //
                .map(entry -> entry.getName()) //
                .forEach(jsFilesPaths::add);
    }

    return new CandyDescriptor( //
            name, //
            version, //
            lastUpdateTimestamp, //
            modelVersion, //
            transpilerVersion, //
            jsOutputDirPath, //
            jsDirPath, //
            jsFilesPaths);
}