/
ProjectLauncherImpl.java
333 lines (286 loc) · 10.4 KB
/
ProjectLauncherImpl.java
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
package aQute.launcher.plugin;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aQute.bnd.build.Project;
import aQute.bnd.build.ProjectLauncher;
import aQute.bnd.osgi.Builder;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.EmbeddedResource;
import aQute.bnd.osgi.FileResource;
import aQute.bnd.osgi.Instructions;
import aQute.bnd.osgi.Jar;
import aQute.bnd.osgi.Processor;
import aQute.bnd.osgi.Resource;
import aQute.launcher.constants.LauncherConstants;
import aQute.launcher.pre.EmbeddedLauncher;
import aQute.lib.strings.Strings;
import aQute.lib.utf8properties.UTF8Properties;
public class ProjectLauncherImpl extends ProjectLauncher {
private final static Logger logger = LoggerFactory.getLogger(ProjectLauncherImpl.class);
private static final String EMBEDDED_LAUNCHER_FQN = "aQute.launcher.pre.EmbeddedLauncher";
private static final String EMBEDDED_LAUNCHER = "aQute/launcher/pre/EmbeddedLauncher.class";
final private File launchPropertiesFile;
boolean prepared;
DatagramSocket listenerComms;
public ProjectLauncherImpl(Project project) throws Exception {
super(project);
logger.debug("created a aQute launcher plugin");
launchPropertiesFile = File.createTempFile("launch", ".properties", project.getTarget());
logger.debug("launcher plugin using temp launch file {}", launchPropertiesFile.getAbsolutePath());
addRunVM("-D" + LauncherConstants.LAUNCHER_PROPERTIES + "=\"" + launchPropertiesFile.getAbsolutePath() + "\"");
if (project.getRunProperties().get("noframework") != null) {
setRunFramework(NONE);
project.warning(
"The noframework property in -runproperties is replaced by a project setting: '-runframework: none'");
}
super.addDefault(Constants.DEFAULT_LAUNCHER_BSN);
}
//
// Initialize the main class for a local launch start
//
protected int invoke(Class< ? > main, String args[]) throws Exception {
LauncherConstants lc = getConstants(getRunBundles(), false);
Method mainMethod = main.getMethod("main", args.getClass(), Properties.class);
Object o = mainMethod.invoke(null, args, lc.getProperties(new UTF8Properties()));
if (o == null)
return 0;
return (Integer) o;
}
/**
* Cleanup the properties file. Is called after the process terminates.
*/
@Override
public void cleanup() {
launchPropertiesFile.delete();
if (listenerComms != null) {
listenerComms.close();
listenerComms = null;
}
prepared = false;
logger.debug("Deleted {}", launchPropertiesFile.getAbsolutePath());
super.cleanup();
}
@Override
public String getMainTypeName() {
return "aQute.launcher.Launcher";
}
@Override
public void update() throws Exception {
updateFromProject();
writeProperties();
}
@Override
public int launch() throws Exception {
prepare();
return super.launch();
}
@Override
public void prepare() throws Exception {
if (prepared)
return;
prepared = true;
writeProperties();
}
void writeProperties() throws Exception {
LauncherConstants lc = getConstants(getRunBundles(), false);
try (OutputStream out = Files.newOutputStream(launchPropertiesFile.toPath())) {
lc.getProperties(new UTF8Properties()).store(out, "Launching " + getProject());
}
}
/**
* @throws Exception
* @throws FileNotFoundException
* @throws IOException
*/
private LauncherConstants getConstants(Collection<String> runbundles, boolean exported)
throws Exception, FileNotFoundException, IOException {
logger.debug("preparing the aQute launcher plugin");
LauncherConstants lc = new LauncherConstants();
lc.noreferences = getProject().is(Constants.RUNNOREFERENCES);
lc.runProperties = getRunProperties();
lc.storageDir = getStorageDir();
lc.keep = isKeep();
lc.runbundles.addAll(runbundles);
lc.trace = getTrace();
lc.timeout = getTimeout();
lc.services = super.getRunFramework() == SERVICES ? true : false;
lc.activators.addAll(getActivators());
lc.name = getProject().getName();
if (!exported && !getNotificationListeners().isEmpty()) {
if (listenerComms == null) {
listenerComms = new DatagramSocket(new InetSocketAddress(InetAddress.getByName(null), 0));
new Thread(new Runnable() {
public void run() {
DatagramSocket socket = listenerComms;
DatagramPacket packet = new DatagramPacket(new byte[65536], 65536);
while (!socket.isClosed()) {
try {
socket.receive(packet);
DataInputStream dai = new DataInputStream(new ByteArrayInputStream(packet.getData(),
packet.getOffset(), packet.getLength()));
NotificationType type = NotificationType.values()[dai.readInt()];
String message = dai.readUTF();
for (NotificationListener listener : getNotificationListeners()) {
listener.notify(type, message);
}
} catch (IOException e) {}
}
}
}).start();
}
lc.notificationPort = listenerComms.getLocalPort();
} else {
lc.notificationPort = -1;
}
try {
// If the workspace contains a newer version of biz.aQute.launcher
// than the version of bnd(tools) used
// then this could throw NoSuchMethodError. For now just ignore it.
Map<String, ? extends Map<String,String>> systemPkgs = getSystemPackages();
if (systemPkgs != null && !systemPkgs.isEmpty())
lc.systemPackages = Processor.printClauses(systemPkgs);
} catch (Throwable e) {}
try {
// If the workspace contains a newer version of biz.aQute.launcher
// than the version of bnd(tools) used
// then this could throw NoSuchMethodError. For now just ignore it.
String systemCaps = getSystemCapabilities();
if (systemCaps != null) {
systemCaps = systemCaps.trim();
if (systemCaps.length() > 0)
lc.systemCapabilities = systemCaps;
}
} catch (Throwable e) {}
return lc;
}
/**
* Create a standalone executable. All entries on the runpath are rolled out
* into the JAR and the runbundles are copied to a directory in the jar. The
* launcher will see that it starts in embedded mode and will automatically
* detect that it should load the bundles from inside. This is drive by the
* launcher.embedded flag.
*
* @throws Exception
*/
@Override
public Jar executable() throws Exception {
Jar jar = new Jar(getProject().getName());
Builder b = new Builder();
getProject().addClose(b);
if (!getProject().getIncludeResource().isEmpty()) {
b.setIncludeResource(getProject().getIncludeResource().toString());
b.setProperty(Constants.RESOURCEONLY, "true");
b.build();
if (b.isOk()) {
jar.addAll(b.getJar());
}
getProject().getInfo(b);
}
List<String> runpath = getRunpath();
Set<String> runpathShas = new LinkedHashSet<String>();
Set<String> runbundleShas = new LinkedHashSet<String>();
List<String> classpath = new ArrayList<String>();
for (String path : runpath) {
logger.debug("embedding runpath {}", path);
File file = new File(path);
if (file.isFile()) {
String newPath = nonCollidingPath(file, jar);
jar.putResource(newPath, new FileResource(file));
classpath.add(newPath);
}
}
// Copy the bundles to the JAR
List<String> runbundles = (List<String>) getRunBundles();
List<String> actualPaths = new ArrayList<String>();
for (String path : runbundles) {
logger.debug("embedding run bundles {}", path);
File file = new File(path);
if (!file.isFile())
getProject().error("Invalid entry in -runbundles %s", file);
else {
String newPath = nonCollidingPath(file, jar);
jar.putResource(newPath, new FileResource(file));
actualPaths.add(newPath);
}
}
LauncherConstants lc = getConstants(actualPaths, true);
lc.embedded = true;
final Properties p = lc.getProperties(new UTF8Properties());
ByteArrayOutputStream bout = new ByteArrayOutputStream();
p.store(bout, "");
jar.putResource(LauncherConstants.DEFAULT_LAUNCHER_PROPERTIES, new EmbeddedResource(bout.toByteArray(), 0L));
Manifest m = new Manifest();
Attributes main = m.getMainAttributes();
for (Entry<Object,Object> e : getProject().getFlattenedProperties().entrySet()) {
String key = (String) e.getKey();
if (key.length() > 0 && Character.isUpperCase(key.charAt(0)))
main.putValue(key, (String) e.getValue());
}
Instructions instructions = new Instructions(getProject().getProperty(Constants.REMOVEHEADERS));
Collection<Object> result = instructions.select(main.keySet(), false);
main.keySet().removeAll(result);
logger.debug("Use Embedded launcher");
m.getMainAttributes().putValue("Main-Class", EMBEDDED_LAUNCHER_FQN);
m.getMainAttributes().putValue(EmbeddedLauncher.EMBEDDED_RUNPATH, Processor.join(classpath));
Resource embeddedLauncher = Resource.fromURL(this.getClass().getResource("/" + EMBEDDED_LAUNCHER));
jar.putResource(EMBEDDED_LAUNCHER, embeddedLauncher);
doStart(jar, EMBEDDED_LAUNCHER_FQN);
if (getProject().getProperty(Constants.DIGESTS) != null)
jar.setDigestAlgorithms(getProject().getProperty(Constants.DIGESTS).trim().split("\\s*,\\s*"));
else
jar.setDigestAlgorithms(new String[] {
"SHA-1", "MD-5"
});
jar.setManifest(m);
cleanup();
return jar;
}
String nonCollidingPath(File file, Jar jar) {
String fileName = file.getName();
String path = "jar/" + fileName;
String[] parts = Strings.extension(fileName);
if (parts == null) {
parts = new String[] {
fileName, ""
};
}
int i = 1;
while (jar.exists(path)) {
path = String.format("jar/%s[%d].%s", parts[0], i++, parts[1]);
}
return path;
}
/*
* Useful for when exported as folder or unzipped
*/
void doStart(Jar jar, String fqn) throws UnsupportedEncodingException {
String nix = "#!/bin/sh\njava -cp . " + fqn + "\n";
String pc = "java -cp . " + fqn + "\r\n";
jar.putResource("start", new EmbeddedResource(nix, 0));
jar.putResource("start.bat", new EmbeddedResource(pc, 0));
}
}