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