summaryrefslogtreecommitdiffstats
path: root/sca-java-2.x/tags/2.0.1-RC1/modules/launcher/src/main/java/org/apache/tuscany/sca/launcher/LauncherMain.java
blob: 275e0a75c7ea74debddcb44e91269f22fd00f47b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */

package org.apache.tuscany.sca.launcher;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

public class LauncherMain {
    
    private static final String DEFAULT_PROPERTY_FILENAME = "default.config";
    private static final String CONFIG_CLASSPATH = "classpath";
    private static final String CONFIG_MAIN_CLASS = "mainClass";
    private static final String CONFIG_ARG_JAR_MAIN = "[firstArgJarManifestMainClass]";
    private static final String LAUNCHER_ARGS = "launcherArgs";

    public static void main(String[] args) throws SecurityException, IllegalArgumentException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, URISyntaxException, IOException {
        Properties launcherProperties = getLauncherProperties(args);
        setSystemProperties(launcherProperties);
        ClassLoader classLoader = getClassLoader(launcherProperties);
        String mainClassName = getMainClass(launcherProperties, classLoader);
        String[] mainArgs = getMainArgs(launcherProperties);
        invokeMainMethod(mainClassName, classLoader, mainArgs);
    }

    private static void setSystemProperties(Properties launcherProperties) throws URISyntaxException {
        for (Enumeration<?> e = launcherProperties.propertyNames(); e.hasMoreElements();) {
            String pn = (String) e.nextElement();
            if (pn.startsWith("-D")) {
                System.setProperty(pn.substring(2), keywordExpand(launcherProperties.getProperty(pn)));
            }
        }
    }

    private static String keywordExpand(String property) throws URISyntaxException {
        if (property.contains("{TUSCANY_HOME}")) {
            property = property.replace("{TUSCANY_HOME}", getLauncherFolder().getParentFile().getAbsolutePath());
        }
        return property;
    }

    private static String[] getMainArgs(Properties launcherProperties) {
        String[] mainArgs = (String[])launcherProperties.get(LAUNCHER_ARGS);
        if (mainArgs == null) {
            mainArgs = new String[0];
        }
        return mainArgs;
    }

    private static String getMainClass(Properties launcherProperties, ClassLoader classLoader) {
        String mainClassName;
        String[] args = getMainArgs(launcherProperties);
        if (args.length > 0) {
            try {
                Class.forName(args[0], true, classLoader);
                mainClassName = args[0];
                String[] args2 = new String[args.length-1];
                System.arraycopy(args, 1, args2, 0, args.length-1);
                launcherProperties.put(LAUNCHER_ARGS, args2);
            } catch (ClassNotFoundException e) {
                mainClassName = launcherProperties.getProperty(CONFIG_MAIN_CLASS);
            }
        } else {
            mainClassName = launcherProperties.getProperty(CONFIG_MAIN_CLASS);
        }

        if (mainClassName.startsWith(CONFIG_ARG_JAR_MAIN + "|")) {
            mainClassName = mainClassName.substring(CONFIG_ARG_JAR_MAIN.length()+1);
        }
        
        return mainClassName;
    }

    private static void invokeMainMethod(String className, ClassLoader classLoader, String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        try {

            Thread.currentThread().setContextClassLoader(classLoader);
            Class mainClass = Class.forName(className, true, classLoader);
            Method m = mainClass.getMethod("main", new Class[]{ args.getClass() });

            m.invoke(null, new Object[]{args});
            
        } finally {
            Thread.currentThread().setContextClassLoader(tccl);
        }
    }

    private static ClassLoader getClassLoader(Properties launcherProperties) throws URISyntaxException, IOException {
        Set<URL> jarURLs = new HashSet<URL>(); 
        for (Enumeration<?> e = launcherProperties.propertyNames(); e.hasMoreElements();) {
            String pn = (String) e.nextElement();
            if (pn.startsWith(CONFIG_CLASSPATH)) {
                jarURLs.addAll(getJARs(launcherProperties.getProperty(pn), launcherProperties));
            } else if (pn.equals(CONFIG_MAIN_CLASS) && launcherProperties.getProperty(pn).startsWith(CONFIG_ARG_JAR_MAIN)) {
                if (firstArgJarHasManifestMainClass(launcherProperties)) {
                    jarURLs.add(firstArgJarManifestMainClass(launcherProperties));
                }
            }
        }
        ClassLoader parentCL = Thread.currentThread().getContextClassLoader();
        if (parentCL == null) {
            parentCL = LauncherMain.class.getClassLoader();
        }
        return new URLClassLoader(jarURLs.toArray(new URL[]{}), parentCL);
    }

    private static void argJars(Set<URL> jarURLs, Properties launcherProperties) throws IOException {
        String[] args = (String[])launcherProperties.get(LAUNCHER_ARGS);
        if (args != null && args.length > 0) {
            for (String a : args) {
                File f = new File(a);
                if (!f.exists()) {
                    throw new FileNotFoundException(args[0]);
                }
                jarURLs.add(f.toURI().toURL());
            }
        }
        launcherProperties.put(LAUNCHER_ARGS, new String[]{});
    }

    private static URL firstArgJarManifestMainClass(Properties launcherProperties) throws IOException {
        String[] args = (String[])launcherProperties.get(LAUNCHER_ARGS);
        if (args.length < 1) {
            throw new IllegalArgumentException("must specifiy a jar file");
        }
        File f = new File(args[0]);
        if (!f.exists()) {
            throw new FileNotFoundException(args[0]);
        }
        JarFile jar = new JarFile(f);
        String mfc = jar.getManifest().getMainAttributes().getValue("Main-Class");
        if (mfc == null || mfc.length() < 1) {
            throw new IllegalArgumentException("first jar file missing manifest Main-Class attribute");
        }
        launcherProperties.setProperty(CONFIG_MAIN_CLASS, mfc);
        
        return f.toURL();
    }

    private static boolean firstArgJarHasManifestMainClass(Properties launcherProperties) throws IOException {
        String[] args = (String[])launcherProperties.get(LAUNCHER_ARGS);
        if (args.length < 1) {
            return false;
        }
        File f = new File(args[0]);
        if (!f.exists() || f.isDirectory()) {
            return false;
        }
        JarFile jar = new JarFile(f);
        Manifest mf = jar.getManifest();
        if (mf != null) {
            String mfc = jar.getManifest().getMainAttributes().getValue("Main-Class");
            return mfc != null && mfc.length() > 0;
        } else {
            return false;
        }
    }
    /**
     * Gets the jars matching a config classpath property
     * property values may be an explicit jar name or use an asterix wildcard for
     * all jars in a folder, or a double asterix '**' for all jars in a folder and its subfolders
     * @throws URISyntaxException 
     */
    private static Set<URL> getJARs(String classpathValue, Properties launcherProperties) throws URISyntaxException {
        Set<URL> jarURLs = new HashSet<URL>();
        
        if (classpathValue.endsWith("**")) {
            File folder = new File(classpathValue.substring(0, classpathValue.length()-2));
            if (!folder.isAbsolute()) {
                folder = new File(getLauncherFolder().getParent(), folder.getName());
            }
            jarURLs.addAll(getFolderJars(folder));
            jarURLs.addAll(getSubFolderJars(folder));
        } else if (classpathValue.endsWith("*")) {
            File folder = new File(classpathValue.substring(0, classpathValue.length()-1));
            if (!folder.isAbsolute()) {
                folder = new File(getLauncherFolder(), folder.getName());
            }
            jarURLs.addAll(getFolderJars(folder));
        } else {
            File f = new File(classpathValue);
            if (!f.isAbsolute()) {
                f = new File(getLauncherFolder(), classpathValue);
            }
            try {
                jarURLs.add(f.toURI().toURL());
            } catch (MalformedURLException e) {
                throw new RuntimeException("Exception getting JAR URL", e);
            }
        }
        return jarURLs;
    }

    /**
     * Gets all the jars in a folder
     */
    private static Set<URL> getFolderJars(File folder) {
        Set<URL> jarURLs = new HashSet<URL>(); 
        if (folder.exists() && folder.isDirectory()) {
            File[] files = folder.listFiles(new FilenameFilter(){
                public boolean accept(File dir, String name) {
                    return name.endsWith(".jar");
                }});
            for (File f : files) {
                try {
                    jarURLs.add(f.toURI().toURL());
                } catch (MalformedURLException e) {
                    throw new RuntimeException("Exception getting JAR URL", e);
                }
            }
        }
        return jarURLs;
    }

    /**
     * Recursively gets all the jars in a folder and its subfolders
     */
    private static Set<URL> getSubFolderJars(File folder) {
        Set<URL> jarURLs = new HashSet<URL>(); 
        if (folder.exists() && folder.isDirectory()) {
            File[] files = folder.listFiles(new FileFilter(){
                public boolean accept(File pathname) {
                    return pathname.isDirectory();
                }});
            for (File f : files) {
                jarURLs.addAll(getFolderJars(f));
                jarURLs.addAll(getSubFolderJars(f));
            }
        }
        return jarURLs;
    }

    /**
     * Read the config properties for this launcher invocation
     * (Either default.config or the 1st cmd line argument suffixed with ".config" if that file exists 
     */
    private static Properties getLauncherProperties(String[] args) throws URISyntaxException, FileNotFoundException {

        Properties properties = new Properties();
        
        File f;
        if (args.length > 0) {
            f = new File(getLauncherFolder(), args[0] + ".config");
            if (f.exists()) {
                String[] args2 = new String[args.length-1];
                System.arraycopy(args, 1, args2, 0, args.length-1);
                args = args2;
            } else {
                f = new File(getLauncherFolder(), DEFAULT_PROPERTY_FILENAME);
            }
        } else {
            f = new File(getLauncherFolder(), DEFAULT_PROPERTY_FILENAME);
        }
        
        if (!f.exists()) {
//            throw new FileNotFoundException(f.getName());
            if (args.length > 0 && "client".equals(args[0])) {
                properties.put("mainClass", "org.apache.tuscany.sca.client.javascript.TuscanyShell");
                String[] args2 = new String[args.length-1];
                System.arraycopy(args, 1, args2, 0, args.length-1);
                args = args2;
            } else {
                properties.put("mainClass", "[firstArgJarManifestMainClass]|org.apache.tuscany.sca.domain.node.DomainNodeMain");
            }
        } else {
            try {
                FileInputStream fis = new FileInputStream(f);
                properties.load(fis);
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        properties.put(LAUNCHER_ARGS, args);
        
        return properties;
    }

    /**
     * Find the folder that contains the launcher jar
     */
    private static File getLauncherFolder() throws URISyntaxException {

        File folder = null;

        String resource = LauncherMain.class.getName().replace('.', '/') + ".class"; 
        URL url = LauncherMain.class.getClassLoader().getResource(resource);
        if (url != null) {
            URI uri = url.toURI();
            String scheme = uri.getScheme();
            if (uri.getScheme().equals("jar")) {
                String path = uri.toString().substring(4);
                int i = path.indexOf("!/");
                if (i != -1) {
                    path = path.substring(0, i);
                    uri = URI.create(path);
                }
        
                File file = new File(uri);
                if (file.exists()) {
                    File jarDirectory = file.getParentFile();
                    if (jarDirectory != null && jarDirectory.exists()) {
                        folder = file;
                    }
                }
            }
        }
        folder = folder.getParentFile();
        return folder;
    }
}