1 /*
   2  * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 import java.io.InputStream;
  25 import java.io.IOException;
  26 import java.lang.module.ModuleReader;
  27 import java.lang.module.ModuleReference;
  28 import java.net.URI;
  29 import java.nio.file.Files;
  30 import java.nio.file.Path;
  31 import java.nio.file.Paths;
  32 
  33 import jdk.internal.module.ModuleInfo;
  34 import jdk.internal.module.ModuleInfo.Attributes;
  35 
  36 public class ModuleTargetHelper {
  37     private ModuleTargetHelper() {}
  38 
  39     public static final class ModuleTarget {
  40         private String targetPlatform;
  41 
  42         public ModuleTarget(String targetPlatform) {
  43             this.targetPlatform = targetPlatform;
  44         }
  45 
  46         public String targetPlatform() {
  47             return targetPlatform;
  48         }
  49     }
  50 
  51     public static ModuleTarget getJavaBaseTarget() throws IOException {
  52         Path p = Paths.get(URI.create("jrt:/modules/java.base/module-info.class"));
  53         try (InputStream in = Files.newInputStream(p)) {
  54             return read(in);
  55         }
  56     }
  57 
  58     public static ModuleTarget read(InputStream in) throws IOException {
  59         ModuleInfo.Attributes attrs = ModuleInfo.read(in, null);
  60         if (attrs.target() != null) {
  61             return new ModuleTarget(attrs.target().targetPlatform());
  62         } else {
  63             return null;
  64         }
  65     }
  66 
  67     public static ModuleTarget read(ModuleReference modRef) throws IOException {
  68         ModuleReader reader = modRef.open();
  69         try (InputStream in = reader.open("module-info.class").get()) {
  70             return read(in);
  71         } finally {
  72             reader.close();
  73         }
  74     }
  75 }