1 /*
   2  * Copyright (c) 2015, 2016, 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 
  28 import com.oracle.tools.packager.BundlerParamInfo;
  29 import com.oracle.tools.packager.IOUtils;
  30 import com.oracle.tools.packager.Log;
  31 import com.oracle.tools.packager.RelativeFileSet;
  32 import com.oracle.tools.packager.StandardBundlerParam;
  33 import com.oracle.tools.packager.linux.LinuxResources;
  34 import jdk.packager.builders.AbstractAppImageBuilder;
  35 
  36 import java.io.File;
  37 import java.io.FileInputStream;
  38 import java.io.FileOutputStream;
  39 import java.io.IOException;
  40 import java.io.InputStream;
  41 import java.io.OutputStream;
  42 import java.io.OutputStreamWriter;
  43 import java.io.UncheckedIOException;
  44 import java.io.Writer;
  45 import java.nio.file.Files;
  46 import java.nio.file.Path;
  47 import java.nio.file.attribute.PosixFilePermission;
  48 import java.text.MessageFormat;
  49 import java.util.HashMap;
  50 import java.util.List;
  51 import java.util.Map;
  52 import java.util.Objects;
  53 import java.util.ResourceBundle;
  54 import java.util.Set;
  55 
  56 import static com.oracle.tools.packager.StandardBundlerParam.*;
  57 
  58 
  59 public class LinuxAppImageBuilder extends AbstractAppImageBuilder {
  60 
  61     private static final ResourceBundle I18N =
  62             ResourceBundle.getBundle(LinuxAppImageBuilder.class.getName());
  63 
  64     protected static final String LINUX_BUNDLER_PREFIX =
  65             BUNDLER_PREFIX + "linux" + File.separator;
  66     private static final String EXECUTABLE_NAME = "JavaAppLauncher";
  67     private static final String LIBRARY_NAME = "libpackager.so";
  68 
  69     private final Path root;
  70     private final Path appDir;
  71     private final Path runtimeDir;
  72     private final Path resourcesDir;
  73     private final Path mdir;
  74 
  75     private final Map<String, ? super Object> params;
  76 
  77     public static final BundlerParamInfo<File> ICON_PNG = new StandardBundlerParam<>(
  78             I18N.getString("param.icon-png.name"),
  79             I18N.getString("param.icon-png.description"),
  80             "icon.png",
  81             File.class,
  82             params -> {
  83                 File f = ICON.fetchFrom(params);
  84                 if (f != null && !f.getName().toLowerCase().endsWith(".png")) {
  85                     Log.info(MessageFormat.format(I18N.getString("message.icon-not-png"), f));
  86                     return null;
  87                 }
  88                 return f;
  89             },
  90             (s, p) -> new File(s));
  91 
  92     public LinuxAppImageBuilder(Map<String, Object> config, Path imageOutDir) throws IOException {
  93         super(config, imageOutDir.resolve(APP_NAME.fetchFrom(config) + "/runtime"));
  94 
  95         Objects.requireNonNull(imageOutDir);
  96 
  97         this.root = imageOutDir.resolve(APP_NAME.fetchFrom(config));
  98         this.appDir = root.resolve("app");
  99         this.runtimeDir = root.resolve("runtime");
 100         this.resourcesDir = root.resolve("resources");
 101         this.mdir = runtimeDir.resolve("lib");
 102         this.params = new HashMap<String, Object>();
 103         config.entrySet().stream().forEach(e -> params.put(e.getKey().toString(), e.getValue()));
 104         Files.createDirectories(appDir);
 105         Files.createDirectories(runtimeDir);
 106         Files.createDirectories(resourcesDir);
 107     }
 108 
 109     private Path destFile(String dir, String filename) {
 110         return runtimeDir.resolve(dir).resolve(filename);
 111     }
 112 
 113     private void writeEntry(InputStream in, Path dstFile) throws IOException {
 114         Files.createDirectories(dstFile.getParent());
 115         Files.copy(in, dstFile);
 116     }
 117 
 118     private void writeSymEntry(Path dstFile, Path target) throws IOException {
 119         Files.createDirectories(dstFile.getParent());
 120         Files.createLink(dstFile, target);
 121     }
 122 
 123     /**
 124      * chmod ugo+x file
 125      */
 126     private void setExecutable(Path file) {
 127         try {
 128             Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file);
 129             perms.add(PosixFilePermission.OWNER_EXECUTE);
 130             perms.add(PosixFilePermission.GROUP_EXECUTE);
 131             perms.add(PosixFilePermission.OTHERS_EXECUTE);
 132             Files.setPosixFilePermissions(file, perms);
 133         } catch (IOException ioe) {
 134             throw new UncheckedIOException(ioe);
 135         }
 136     }
 137 
 138     private static void createUtf8File(File file, String content) throws IOException {
 139         try (OutputStream fout = new FileOutputStream(file);
 140              Writer output = new OutputStreamWriter(fout, "UTF-8")) {
 141             output.write(content);
 142         }
 143     }
 144 
 145 
 146     //it is static for the sake of sharing with "installer" bundlers
 147     // that may skip calls to validate/bundle in this class!
 148     public static File getRootDir(File outDir, Map<String, ? super Object> p) {
 149         return new File(outDir, APP_FS_NAME.fetchFrom(p));
 150     }
 151 
 152     public static String getLauncherName(Map<String, ? super Object> p) {
 153         return APP_FS_NAME.fetchFrom(p);
 154     }
 155 
 156     public static String getLauncherCfgName(Map<String, ? super Object> p) {
 157         return "app/" + APP_FS_NAME.fetchFrom(p) + ".cfg";
 158     }
 159 
 160     @Override
 161     public InputStream getResourceAsStream(String name) {
 162         return LinuxResources.class.getResourceAsStream(name);
 163     }
 164 
 165     @Override
 166     public void prepareApplicationFiles() throws IOException {
 167         Map<String, ? super Object> originalParams = new HashMap<>(params);
 168 
 169         try {
 170             // create the primary launcher
 171             createLauncherForEntryPoint(params, root);
 172 
 173             // Copy library to the launcher folder
 174             writeEntry(LinuxResources.class.getResourceAsStream(LIBRARY_NAME), root.resolve(LIBRARY_NAME));
 175 
 176             // create the secondary launchers, if any
 177             List<Map<String, ? super Object>> entryPoints = StandardBundlerParam.SECONDARY_LAUNCHERS.fetchFrom(params);
 178             for (Map<String, ? super Object> entryPoint : entryPoints) {
 179                 Map<String, ? super Object> tmp = new HashMap<>(originalParams);
 180                 tmp.putAll(entryPoint);
 181                 // remove name.fs that was calculated for main launcher.
 182                 // otherwise, wrong launcher name will be selected.
 183                 tmp.remove(APP_FS_NAME.getID());
 184                 createLauncherForEntryPoint(tmp, root);
 185             }
 186 
 187             // Copy class path entries to Java folder
 188             copyApplication();
 189 
 190             // Copy icon to Resources folder
 191             copyIcon();
 192 
 193         } catch (IOException ex) {
 194             Log.info("Exception: " + ex);
 195             Log.debug(ex);
 196         }
 197     }
 198 
 199     private void createLauncherForEntryPoint(Map<String, ? super Object> p, Path rootDir) throws IOException {
 200         // Copy executable to Linux folder
 201         Path executableFile = root.resolve(getLauncherName(p));
 202 
 203         writeEntry(LinuxResources.class.getResourceAsStream(EXECUTABLE_NAME), executableFile);
 204 
 205         executableFile.toFile().setExecutable(true, false);
 206         executableFile.toFile().setWritable(true, true);
 207 
 208         writeCfgFile(p, root.resolve(getLauncherCfgName(p)).toFile(), "$APPDIR/runtime");
 209     }
 210 
 211     private void copyIcon() throws IOException {
 212         File icon = ICON_PNG.fetchFrom(params);
 213         File iconTarget = new File(resourcesDir.toFile(), APP_FS_NAME.fetchFrom(params) + ".png");
 214         IOUtils.copyFile(icon, iconTarget);
 215     }
 216 
 217     private void copyApplication() throws IOException {
 218         List<RelativeFileSet> appResourcesList = APP_RESOURCES_LIST.fetchFrom(params);
 219         if (appResourcesList == null) {
 220             throw new RuntimeException("Null app resources?");
 221         }
 222         for (RelativeFileSet appResources : appResourcesList) {
 223             if (appResources == null) {
 224                 throw new RuntimeException("Null app resources?");
 225             }
 226             File srcdir = appResources.getBaseDirectory();
 227             for (String fname : appResources.getIncludedFiles()) {
 228                 writeEntry(
 229                         new FileInputStream(new File(srcdir, fname)),
 230                         new File(appDir.toFile(), fname).toPath()
 231                 );
 232             }
 233         }
 234     }
 235 
 236     @Override
 237     protected String getCacheLocation(Map<String, ? super Object> params) {
 238         return "$CACHEDIR/";
 239     }
 240 
 241 }