Home > Software design >  How to read war-file manifest in its jar-dependency?
How to read war-file manifest in its jar-dependency?

Time:05-28

How do I read the war-file manifest property in its jar-dependency?

UPD: servlets are not used here (it's spring-bean initialization code).

CodePudding user response:

Since a .war file’s purpose is to handle servlets, I assume all of your code is called from servlets, or from a technology built on servlets, like JSP, JSF, or even Spring.

Call the current request’s getServletContext() method, and use the getResource or getResourceAsStream method of ServletContext. Those methods work just like the same methods of java.lang.Class, only they look in the .war file itself before searching the web application’s classpath for a matching path.

For example:

public Optional<Manifest> getWarManifest(ServletRequest request)
throws IOException {

    InputStream manifest =
        request.getServletContext().getResourceAsStream(
            "/META-INF/MANIFEST.MF");

    if (manifest == null) {
        return Optional.empty();
    }

    try (InputStream stream = new BufferedInputStream(manifest)) {
        return Optional.of(new Manifest(stream));
    }
}

Update:

Since you want to read the manifest when preparing a Spring bean, it appears you can autowire a ServletContext object:

@Configuration
public class MyAppConfig {
    @Bean
    public MyBean createMyBean(@Autowired ServletContext context)
    throws IOException {

        Optional<Manifest> manifest;

        InputStream source =
            context.getResourceAsStream("/META-INF/MANIFEST.MF");

        if (source == null) {
            manifest = Optional.empty();
        } else {
            try (InputStream stream = new BufferedInputStream(source)) {
                manifest = Optional.of(new Manifest(stream));
            }
        }

        return new MyBean(manifest);
    }
}
  • Related