1 /*
   2  * Copyright (c) 2015, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package jdk.packager.builders.linux;
  26 
  27 import com.oracle.tools.packager.BundlerParamInfo;
  28 import com.oracle.tools.packager.Log;
  29 import com.oracle.tools.packager.RelativeFileSet;
  30 import com.oracle.tools.packager.StandardBundlerParam;
  31 import com.oracle.tools.packager.linux.LinuxResources;
  32 import jdk.packager.builders.AbstractAppImageBuilder;
  33 import jdk.tools.jlink.plugin.Pool;
  34 
  35 import java.io.File;
  36 import java.io.FileInputStream;
  37 import java.io.FileOutputStream;
  38 import java.io.IOException;
  39 import java.io.InputStream;
  40 import java.io.OutputStream;
  41 import java.io.OutputStreamWriter;
  42 import java.io.UncheckedIOException;
  43 import java.io.Writer;
  44 import java.nio.file.Files;
  45 import java.nio.file.Path;
  46 import java.nio.file.attribute.PosixFilePermission;
  47 import java.text.MessageFormat;
  48 import java.util.HashMap;
  49 import java.util.List;
  50 import java.util.Map;
  51 import java.util.Objects;
  52 import java.util.ResourceBundle;
  53 import java.util.Set;
  54 
  55 import static com.oracle.tools.packager.StandardBundlerParam.*;
  56 
  57 /**
  58  *
  59  */
  60 public class LinuxAppImageBuilder extends AbstractAppImageBuilder {
  61 
  62     private static final ResourceBundle I18N =
  63             ResourceBundle.getBundle(LinuxAppImageBuilder.class.getName());
  64 
  65     protected static final String LINUX_BUNDLER_PREFIX =
  66             BUNDLER_PREFIX + "linux" + File.separator;
  67     private static final String EXECUTABLE_NAME = "JavaAppLauncher";
  68     private static final String LIBRARY_NAME = "libpackager.so";
  69 
  70     public static final BundlerParamInfo<File> ICON_PNG = new StandardBundlerParam<>(
  71             I18N.getString("param.icon-png.name"),
  72             I18N.getString("param.icon-png.description"),
  73             "icon.png",
  74             File.class,
  75             params -> {
  76                 File f = ICON.fetchFrom(params);
  77                 if (f != null && !f.getName().toLowerCase().endsWith(".png")) {
  78                     Log.info(MessageFormat.format(I18N.getString("message.icon-not-png"), f));
  79                     return null;
  80                 }
  81                 return f;
  82             },
  83             (s, p) -> new File(s));
  84 
  85 //    public static final BundlerParamInfo<URL> RAW_EXECUTABLE_URL = new StandardBundlerParam<>(
  86 //            I18N.getString("param.raw-executable-url.name"),
  87 //            I18N.getString("param.raw-executable-url.description"),
  88 //            "linux.launcher.url",
  89 //            URL.class,
  90 //            params -> LinuxResources.class.getResource(EXECUTABLE_NAME),
  91 //            (s, p) -> {
  92 //                try {
  93 //                    return new URL(s);
  94 //                } catch (MalformedURLException e) {
  95 //                    Log.info(e.toString());
  96 //                    return null;
  97 //                }
  98 //            });
  99 //
 100 
 101     private final Path root;
 102     private final Path appDir;
 103     private final Path runtimeRoot;
 104     private final Path mdir;
 105     private final String jimage;
 106 
 107     private final Map<String, ? super Object> params;
 108 
 109     public LinuxAppImageBuilder(Map<String, Object> config, Path imageOutDir) throws IOException {
 110         super(config, imageOutDir.resolve(APP_NAME.fetchFrom(config) + "/runtime"));
 111 
 112         Objects.requireNonNull(imageOutDir);
 113 
 114         @SuppressWarnings("unchecked")
 115         String img = (String) config.get("jimage.name"); // FIXME constant
 116         jimage = img == null ? "bootmodules.jimage" : img; //FIXME constant
 117 
 118         this.root = imageOutDir.resolve(APP_NAME.fetchFrom(config));
 119         this.appDir = root.resolve("app");
 120         this.runtimeRoot = root.resolve("runtime");
 121         this.mdir = runtimeRoot.resolve("lib").resolve("modules");
 122         this.params = new HashMap<String, Object>();
 123         config.entrySet().stream().forEach(e -> params.put(e.getKey().toString(), e.getValue()));
 124         Files.createDirectories(mdir);
 125         Files.createDirectories(appDir);
 126     }
 127 
 128     private Path destFile(String dir, String filename) {
 129         return runtimeRoot.resolve(dir).resolve(filename);
 130     }
 131 
 132     private void writeEntry(InputStream in, Path dstFile) throws IOException {
 133         Files.createDirectories(dstFile.getParent());
 134         Files.copy(in, dstFile);
 135     }
 136 
 137     private void writeSymEntry(Path dstFile, Path target) throws IOException {
 138         Files.createDirectories(dstFile.getParent());
 139         Files.createLink(dstFile, target);
 140     }
 141 
 142     /**
 143      * chmod ugo+x file
 144      */
 145     private void setExecutable(Path file) {
 146         try {
 147             Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file);
 148             perms.add(PosixFilePermission.OWNER_EXECUTE);
 149             perms.add(PosixFilePermission.GROUP_EXECUTE);
 150             perms.add(PosixFilePermission.OTHERS_EXECUTE);
 151             Files.setPosixFilePermissions(file, perms);
 152         } catch (IOException ioe) {
 153             throw new UncheckedIOException(ioe);
 154         }
 155     }
 156 
 157     private static void createUtf8File(File file, String content) throws IOException {
 158         try (OutputStream fout = new FileOutputStream(file);
 159              Writer output = new OutputStreamWriter(fout, "UTF-8")) {
 160             output.write(content);
 161         }
 162     }
 163 
 164 
 165     //it is static for the sake of sharing with "installer" bundlers
 166     // that may skip calls to validate/bundle in this class!
 167     public static File getRootDir(File outDir, Map<String, ? super Object> p) {
 168         return new File(outDir, APP_FS_NAME.fetchFrom(p));
 169     }
 170 
 171     public static String getLauncherName(Map<String, ? super Object> p) {
 172         return APP_FS_NAME.fetchFrom(p);
 173     }
 174 
 175     public static String getLauncherCfgName(Map<String, ? super Object> p) {
 176         return "app/" + APP_FS_NAME.fetchFrom(p) + ".cfg";
 177     }
 178 
 179     @Override
 180     protected InputStream getResourceAsStream(String name) {
 181         return LinuxResources.class.getResourceAsStream(name);
 182     }
 183 
 184     @Override
 185     protected void prepareApplicationFiles(Pool files, Set<String> modules) throws IOException {
 186         Map<String, ? super Object> originalParams = new HashMap<>(params);
 187         try {
 188 
 189             // create the primary launcher
 190             createLauncherForEntryPoint(params, root);
 191 
 192             // Copy library to the launcher folder
 193             writeEntry(LinuxResources.class.getResourceAsStream(LIBRARY_NAME), root.resolve(LIBRARY_NAME));
 194 
 195             // create the secondary launchers, if any
 196             List<Map<String, ? super Object>> entryPoints = StandardBundlerParam.SECONDARY_LAUNCHERS.fetchFrom(params);
 197             for (Map<String, ? super Object> entryPoint : entryPoints) {
 198                 Map<String, ? super Object> tmp = new HashMap<>(originalParams);
 199                 tmp.putAll(entryPoint);
 200                 createLauncherForEntryPoint(tmp, root);
 201             }
 202 
 203             // Copy class path entries to Java folder
 204             copyApplication();
 205 
 206             // Copy icon to Resources folder
 207 //FIXME            copyIcon(resourcesDirectory);
 208 
 209         } catch (IOException ex) {
 210             Log.info("Exception: " + ex);
 211             Log.debug(ex);
 212         }
 213     }
 214 
 215     private void createLauncherForEntryPoint(Map<String, ? super Object> p, Path rootDir) throws IOException {
 216         // Copy executable to Linux folder
 217         Path executableFile = root.resolve(getLauncherName(p));
 218 
 219         writeEntry(LinuxResources.class.getResourceAsStream(EXECUTABLE_NAME), executableFile);
 220 
 221         executableFile.toFile().setExecutable(true, false);
 222         executableFile.toFile().setWritable(true, true);
 223 
 224         writeCfgFile(p, root.resolve(getLauncherCfgName(p)).toFile(), "$APPDIR/runtime");
 225     }
 226 
 227     private void copyApplication() throws IOException {
 228         List<RelativeFileSet> appResourcesList = APP_RESOURCES_LIST.fetchFrom(params);
 229         if (appResourcesList == null) {
 230             throw new RuntimeException("Null app resources?");
 231         }
 232         for (RelativeFileSet appResources : appResourcesList) {
 233             if (appResources == null) {
 234                 throw new RuntimeException("Null app resources?");
 235             }
 236             File srcdir = appResources.getBaseDirectory();
 237             for (String fname : appResources.getIncludedFiles()) {
 238                 writeEntry(
 239                         new FileInputStream(new File(srcdir, fname)),
 240                         new File(appDir.toFile(), fname).toPath()
 241                 );
 242             }
 243         }
 244     }
 245 
 246     @Override
 247     protected String getCacheLocation(Map<String, ? super Object> params) {
 248         return "$CACHEDIR/";
 249     }
 250 
 251 }