aboutsummaryrefslogtreecommitdiffstats
path: root/bundle-plugin/src/main/java/com/yahoo/container/plugin/util/JarFiles.java
blob: ade8a4984e8c4ed894e6c1a27cf815f8e44a0205 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.plugin.util;

import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @author Tony Vaagenes
 * @author ollivir
 */
public class JarFiles {

    public static List<ProvidedArtifact> providedArtifactsFromClassPath(File jarFile) {
        return getManifest(jarFile).map(mf -> getMainAttributeValue(mf, "Class-Path")
                        .map(s -> Arrays.stream(s.split(" "))
                                .map(ProvidedArtifact::fromStringValue)
                                .toList())
                        .orElse(Collections.emptyList()))
                .orElse(Collections.emptyList());

    }

    public static <T> T withJarFile(File file, ThrowingFunction<JarFile, T> action) {
        try (JarFile jar = new JarFile(file)) {
            return action.apply(jar);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T withInputStream(ZipFile zipFile, ZipEntry zipEntry, ThrowingFunction<InputStream, T> action) {
        try (InputStream is = zipFile.getInputStream(zipEntry)) {
            return action.apply(is);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Optional<String> getMainAttributeValue(Manifest manifest, String attributeName) {
        return Optional.ofNullable(manifest.getMainAttributes().getValue(attributeName));
    }

    public static Optional<Manifest> getManifest(File jarFile) {
        return withJarFile(jarFile, jar -> Optional.ofNullable(jar.getManifest()));
    }
}