JAL-3691 patch toUpper/toLower to use Locale.ROOT for 2.11.2 getdown - needs rebuild...
[jalview.git] / getdown / src / getdown / core / src / main / java / com / threerings / getdown / data / EnvConfig.java
1 //
2 // Getdown - application installer, patcher and launcher
3 // Copyright (C) 2004-2018 Getdown authors
4 // https://github.com/threerings/getdown/blob/master/LICENSE
5
6 package com.threerings.getdown.data;
7
8 import java.io.File;
9 import java.io.FileInputStream;
10 import java.net.MalformedURLException;
11 import java.net.URL;
12 import java.security.cert.Certificate;
13 import java.security.cert.CertificateFactory;
14 import java.security.cert.X509Certificate;
15 import java.util.*;
16
17 import com.threerings.getdown.util.StringUtil;
18 import com.threerings.getdown.data.Application;
19
20 /** Configuration that comes from our "environment" (command line args, sys props, etc.). */
21 public final class EnvConfig {
22
23     /** Used to report problems or feedback by {@link #create}. */
24     public static final class Note {
25         public static enum Level { INFO, WARN, ERROR };
26         public static Note info (String msg) { return new Note(Level.INFO, msg); }
27         public static Note warn (String msg) { return new Note(Level.WARN, msg); }
28         public static Note error (String msg) { return new Note(Level.ERROR, msg); }
29         public final Level level;
30         public final String message;
31         public Note (Level level, String message) {
32             this.level = level;
33             this.message = message;
34         }
35     }
36
37     /**
38      * Creates an environment config, obtaining information (in order) from the following sources:
39      *
40      * <ul>
41      * <li> A {@code bootstrap.properties} file bundled with the jar. </li>
42      * <li> System properties supplied to the JVM. </li>
43      * <li> The supplied command line arguments ({@code argv}). </li>
44      * </ul>
45      *
46      * If a later source supplies a configuration already provided by a prior source, a warning
47      * message will be logged to indicate the conflict, and the prior source will be used.
48      *
49      * @param notes a list into which notes are added, to be logged after the logging system has
50      * been initialized (which cannot happen until the appdir is known). If any {@code ERROR} notes
51      * are included, the app should terminate after reporting them.
52      * @return an env config instance, or {@code null} if no appdir could be located via any
53      * configuration source.
54      */
55     public static EnvConfig create (String[] argv, List<Note> notes) {
56         String appDir = null, appDirProv = null;
57         String appId = null, appIdProv = null;
58         String appBase = null, appBaseProv = null;
59
60         // start with bootstrap.properties config, if avaialble
61         try {
62             ResourceBundle bundle = ResourceBundle.getBundle("bootstrap");
63             if (bundle.containsKey("appdir")) {
64                 appDir = bundle.getString("appdir");
65                 appDir = appDir.replace(USER_HOME_KEY, System.getProperty("user.home"));
66                 appDirProv = "bootstrap.properties";
67             }
68             if (bundle.containsKey("appid")) {
69                 appId = bundle.getString("appid");
70                 appIdProv = "bootstrap.properties";
71             }
72             if (bundle.containsKey("appbase")) {
73                 appBase = bundle.getString("appbase");
74                 appBaseProv = "bootstrap.properties";
75             }
76             // if any system properties are specified (keys prefixed with sys.), set those up
77             for (String key : bundle.keySet()) {
78                 if (key.startsWith("sys.")) {
79                     String skey = key.substring(4);
80                     String svalue = bundle.getString(key);
81                     notes.add(Note.info("Setting system property from bundle: " +
82                                         skey + "='" + svalue + "'"));
83                     System.setProperty(skey, svalue);
84                 }
85             }
86
87         } catch (MissingResourceException e) {
88             // bootstrap.properties is optional; no need for a warning
89         }
90
91         // next seek config from system properties
92         String spropsAppDir = SysProps.appDir();
93         if (!StringUtil.isBlank(spropsAppDir)) {
94             if (appDir == null) {
95                 appDir = spropsAppDir;
96                 appDirProv = "system property";
97             } else {
98                 notes.add(Note.warn("Ignoring 'appdir' system property, have appdir via '" +
99                                     appDirProv + "'"));
100             }
101         }
102         String spropsAppId = SysProps.appId();
103         if (!StringUtil.isBlank(spropsAppId)) {
104             if (appId == null) {
105                 appId = spropsAppId;
106                 appIdProv = "system property";
107             } else {
108                 notes.add(Note.warn("Ignoring 'appid' system property, have appid via '" +
109                                     appIdProv + "'"));
110             }
111         }
112         String spropsAppBase = SysProps.appBase();
113         if (!StringUtil.isBlank(spropsAppBase)) {
114             if (appBase == null) {
115                 appBase = spropsAppBase;
116                 appBaseProv = "system property";
117             } else {
118                 notes.add(Note.warn("Ignoring 'appbase' system property, have appbase via '" +
119                                     appBaseProv + "'"));
120             }
121         }
122
123         // finally obtain config from command line arguments
124         String argvAppDir = argv.length > 0 ? argv[0] : null;
125         if (!StringUtil.isBlank(argvAppDir)) {
126             if (appDir == null) {
127                 appDir = argvAppDir;
128                 appDirProv = "command line";
129             } else {
130                 notes.add(Note.warn("Ignoring 'appdir' command line arg, have appdir via '" +
131                                     appDirProv + "'"));
132             }
133         }
134         String argvAppId = argv.length > 1 ? argv[1] : null;
135         if (!StringUtil.isBlank(argvAppId)) {
136             if (appId == null) {
137                 appId = argvAppId;
138                 appIdProv = "command line";
139             } else {
140                 notes.add(Note.warn("Ignoring 'appid' command line arg, have appid via '" +
141                                     appIdProv + "'"));
142             }
143         }
144         
145         int skipArgs = 2;
146         // Look for locator file, pass to Application and remove from appArgs
147         String argvLocatorFilename = argv.length > 2 ? argv[2] : null;
148         if (
149                 !StringUtil.isBlank(argvLocatorFilename)
150                 && argvLocatorFilename.toLowerCase(Locale.ROOT).endsWith("."+Application.LOCATOR_FILE_EXTENSION)
151                 ) {
152           notes.add(Note.info("locatorFilename in args: '"+argv[2]+"'"));
153           Application.setLocatorFile(argvLocatorFilename);
154           
155           skipArgs++;
156         }
157
158         // ensure that we were able to find an app dir
159         if (appDir == null) {
160             return null; // caller will report problem to user
161         }
162
163         notes.add(Note.info("Using appdir from " + appDirProv + ": " + appDir));
164         if (appId != null) notes.add(Note.info("Using appid from " + appIdProv + ": " + appId));
165         if (appBase != null) notes.add(
166             Note.info("Using appbase from " + appBaseProv + ": " + appBase));
167
168         // ensure that the appdir refers to a directory that exists
169         File appDirFile = new File(appDir);
170         if (!appDirFile.exists()) {
171             // if we have a bootstrap URL then we auto-create the app dir; this enables an
172             // installer to simply place a getdown.jar file somewhere and create an OS shortcut
173             // that runs getdown with an appdir and appbase specified, and have getdown create the
174             // appdir and download the app into it
175             if (!StringUtil.isBlank(appBase)) {
176                 if (appDirFile.mkdirs()) {
177                     notes.add(Note.info("Auto-created app directory '" + appDir + "'"));
178                 } else {
179                     notes.add(Note.warn("Unable to auto-create app dir: '" + appDir + "'"));
180                 }
181             } else {
182                 notes.add(Note.error("Invalid appdir '" + appDir + "': directory does not exist"));
183                 return null;
184             }
185         } else if (!appDirFile.isDirectory()) {
186             notes.add(Note.error("Invalid appdir '" + appDir + "': refers to non-directory"));
187             return null;
188         }
189
190         // pass along anything after the first two (or three) args as extra app args
191         List<String> appArgs = argv.length > skipArgs ?
192             Arrays.asList(argv).subList(skipArgs, argv.length) :
193             Collections.<String>emptyList();
194
195         // load X.509 certificate if it exists
196         File crtFile = new File(appDirFile, Digest.digestFile(Digest.VERSION) + ".crt");
197         List<Certificate> certs = new ArrayList<>();
198         if (crtFile.exists()) {
199             try (FileInputStream fis = new FileInputStream(crtFile)) {
200                 X509Certificate certificate = (X509Certificate)
201                     CertificateFactory.getInstance("X.509").generateCertificate(fis);
202                 certs.add(certificate);
203             } catch (Exception e) {
204                 notes.add(Note.error("Certificate error: " + e.getMessage()));
205             }
206         }
207
208         return new EnvConfig(appDirFile, appId, appBase, certs, appArgs);
209     }
210
211     /** The directory in which the application and metadata is stored. */
212     public final File appDir;
213
214     /** Either {@code null} or an identifier for a secondary application that should be
215       * launched. That app will use {@code appid.class} and {@code appid.apparg} to configure
216       * itself but all other parameters will be the same as the primary app. */
217     public final String appId;
218
219     /** Either {@code null} or fallback {@code appbase} to use if one cannot be read from a
220       * {@code getdown.txt} file during startup. */
221     public final String appBase;
222
223     /** Zero or more signing certificates used to verify the digest file. */
224     public final List<Certificate> certs;
225
226     /** Additional arguments to pass on to launched application. These will be added after the
227       * args in the getdown.txt file. */
228     public final List<String> appArgs;
229
230     public EnvConfig (File appDir) {
231         this(appDir, null, null, Collections.<Certificate>emptyList(),
232              Collections.<String>emptyList());
233     }
234
235     private EnvConfig (File appDir, String appId, String appBase, List<Certificate> certs,
236                        List<String> appArgs) {
237         this.appDir = appDir;
238         this.appId = appId;
239         this.appBase = appBase;
240         this.certs = certs;
241         this.appArgs = appArgs;
242     }
243
244     private static final String USER_HOME_KEY = "${user.home}";
245 }