View Javadoc
1   package org.codehaus.plexus.languages.java.jpms;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.nio.file.Files;
25  import java.nio.file.Path;
26  import java.util.jar.JarFile;
27  import java.util.jar.Manifest;
28  
29  /**
30   * Extracts the name of the module by reading the Automatic-Module-Name attribute of the manifest file
31   *
32   * @author Robert Scholte
33   * @since 1.0.0
34   */
35  class ManifestModuleNameExtractor implements ModuleNameExtractor {
36      @Override
37      public String extract(Path file) throws IOException {
38          Manifest manifest = extractManifest(file);
39  
40          String automaticModuleName;
41          if (manifest != null) {
42              automaticModuleName = manifest.getMainAttributes().getValue("Automatic-Module-Name");
43          } else {
44              automaticModuleName = null;
45          }
46  
47          return automaticModuleName;
48      }
49  
50      private Manifest extractManifest(Path file) throws IOException {
51          Manifest manifest;
52          if (Files.isRegularFile(file)) {
53              try (JarFile jarFile = new JarFile(file.toFile())) {
54                  manifest = jarFile.getManifest();
55              }
56          } else if (Files.exists(file.resolve("META-INF/MANIFEST.MF"))) {
57              try (InputStream is = Files.newInputStream(file.resolve("META-INF/MANIFEST.MF"))) {
58                  manifest = new Manifest(is);
59              }
60          } else {
61              manifest = null;
62          }
63  
64          return manifest;
65      }
66  }