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.File;
23  import java.io.FileInputStream;
24  import java.io.IOException;
25  import java.io.InputStream;
26  import java.nio.file.Path;
27  import java.util.jar.JarFile;
28  import java.util.jar.Manifest;
29  
30  /**
31   * Extracts the name of the module by reading the Automatic-Module-Name attribute of the manifest file
32   *
33   * @author Robert Scholte
34   * @since 1.0.0
35   */
36  class ManifestModuleNameExtractor implements ModuleNameExtractor {
37      @Override
38      public String extract(Path file) throws IOException {
39          Manifest manifest = extractManifest(file.toFile());
40  
41          String automaticModuleName;
42          if (manifest != null) {
43              automaticModuleName = manifest.getMainAttributes().getValue("Automatic-Module-Name");
44          } else {
45              automaticModuleName = null;
46          }
47  
48          return automaticModuleName;
49      }
50  
51      private Manifest extractManifest(File file) throws IOException {
52          Manifest manifest;
53          if (file.isFile()) {
54              try (JarFile jarFile = new JarFile(file)) {
55                  manifest = jarFile.getManifest();
56              }
57          } else if (new File(file, "META-INF/MANIFEST.MF").exists()) {
58              try (InputStream is = new FileInputStream(new File(file, "META-INF/MANIFEST.MF"))) {
59                  manifest = new Manifest(is);
60              }
61          } else {
62              manifest = null;
63          }
64  
65          return manifest;
66      }
67  }