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  {
38      @Override
39      public String extract( Path file )
40          throws IOException
41      {
42          Manifest manifest = extractManifest( file.toFile() );
43          
44          String automaticModuleName;
45          if ( manifest != null )
46          {
47              automaticModuleName = manifest.getMainAttributes().getValue( "Automatic-Module-Name" );
48          }
49          else
50          {
51              automaticModuleName = null;
52          }
53  
54          return automaticModuleName;
55      }
56      
57      private Manifest extractManifest( File file )
58          throws IOException
59      {
60          Manifest manifest;
61          if ( file.isFile() )
62          {
63              try ( JarFile jarFile = new JarFile( file ) )
64              {
65                  manifest = jarFile.getManifest();
66              }
67          }
68          else if ( new File( file, "META-INF/MANIFEST.MF" ).exists() )
69          {
70              try ( InputStream is = new FileInputStream( new File( file, "META-INF/MANIFEST.MF" ) ) )
71              {
72                  manifest = new Manifest( is );
73              }
74          }
75          else
76          {
77              manifest = null;
78          }
79  
80          return manifest;
81      }
82  }