-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractTemplatedLauncher.java
More file actions
330 lines (275 loc) · 14.1 KB
/
AbstractTemplatedLauncher.java
File metadata and controls
330 lines (275 loc) · 14.1 KB
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
package build.spawn.application;
/*-
* #%L
* Spawn Application
* %%
* Copyright (C) 2026 Workday, Inc.
* %%
* Licensed 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.
* #L%
*/
import build.base.commandline.CommandLine;
import build.base.configuration.Configuration;
import build.base.configuration.ConfigurationBuilder;
import build.base.foundation.Introspection;
import build.base.logging.Logger;
import build.base.naming.UniqueNameGenerator;
import build.base.option.TemporaryDirectory;
import build.base.option.WorkingDirectory;
import build.base.table.Table;
import build.base.table.Tabular;
import build.base.table.option.CellSeparator;
import build.base.table.option.RowComparator;
import build.base.table.option.TableName;
import build.codemodel.foundation.usage.GenericTypeUsage;
import build.codemodel.foundation.usage.NamedTypeUsage;
import build.codemodel.injection.Binding;
import build.codemodel.injection.Context;
import build.codemodel.injection.Dependency;
import build.codemodel.injection.Resolver;
import build.codemodel.injection.ValueBinding;
import build.spawn.application.facet.Facet;
import build.spawn.application.facet.Faceted;
import build.spawn.application.option.Argument;
import build.spawn.application.option.DiagnosticName;
import build.spawn.application.option.DiagnosticNameProvider;
import build.spawn.application.option.Executable;
import build.spawn.application.option.Name;
import jakarta.inject.Inject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* An abstract {@link TemplatedLauncher}.
*
* @param <A> the type of {@link Application} that will be launched
* @param <P> the type of {@link Platform} on which the {@link Application} will be launched
* @param <N> the type of {@link java.lang.Process} representing managing the {@link Application} when it's launched
* @author graeme.campbell
* @since Apr-2019
*/
public abstract class AbstractTemplatedLauncher<A extends Application, P extends Platform, N extends Process>
implements TemplatedLauncher<A, P, N> {
/**
* The {@link Logger}.
*/
private static final Logger LOGGER = Logger.get(AbstractTemplatedLauncher.class);
/**
* A {@link UniqueNameGenerator} to generate unique {@link Application} names.
*/
@Inject
protected UniqueNameGenerator uniqueNameGenerator;
/**
* The {@link Table} used to log diagnostic information when launching and closing an {@link Application}.
*/
@Inject
protected Table diagnostics;
/**
* The {@link Platform} supplied dependency injection {@link Context}.
*/
@Inject
protected Context platformContext;
@Override
public Name getName(final ConfigurationBuilder options) {
return getExecutable(options)
.map(Executable::get)
.map(Name::of)
.orElseGet(() -> Name.of(this.uniqueNameGenerator.next()
.toLowerCase()
.replace(' ', '.')));
}
@Override
@SuppressWarnings("unchecked")
public A launch(final P platform,
final Class<? extends A> applicationClass,
final Configuration configuration) {
Objects.requireNonNull(platform, "The Platform must not be null");
Objects.requireNonNull(applicationClass, "The Application Class must not be null");
Objects.requireNonNull(configuration, "The Configuration must not be null");
// establish a dependency injection context for launching
final var launchContext = this.platformContext.newContext();
// establish a ConfigurationBuilder capturing the launch Options
final var launchOptions = ConfigurationBuilder.create()
.include(configuration);
// establish a table to capture launch diagnostics information
this.diagnostics.options().add(RowComparator.orderByColumn(0));
this.diagnostics.options().add(CellSeparator.of(" : "));
this.diagnostics.addRow("Platform", platform.name());
// discover the Application "Implementation" class
final Class<? extends Application> implementationClass = Application
.getImplementationClass(applicationClass);
this.diagnostics.addRow("Application Class", applicationClass.getCanonicalName());
this.diagnostics.addRow("Application Implementation", implementationClass.getCanonicalName());
// TODO: complete for Java-based Debugging (this should be part of the JDKApplication)
// // automatically enable remote debugging for launched application when the current JVM is in debug mode
// launchOptions.addIfNotPresent(Debugging.class, Debugging::autoDetect);
// determine the initial customizers to prepare the application
// (we start with those that have been specified in the OptionsByType,
// but more may be added as the Application is prepared)
final LinkedHashSet<Customizer<A>> customizersToPrepare = launchOptions
.stream(Customizer.class)
.map(customizer -> (Customizer<A>) customizer)
.collect(Collectors.toCollection(LinkedHashSet::new));
// the customizers that have been used to prepare the application
final LinkedHashSet<Customizer<A>> customizers = new LinkedHashSet<>();
// allow each discovered customizer to prepare the application,
// and allow newly introduced customizers introduced during preparation to prepare as well!
while (!customizersToPrepare.isEmpty()) {
// remove the next customizer
final Iterator<Customizer<A>> iterator = customizersToPrepare.iterator();
final Customizer<A> customizer = iterator.next();
iterator.remove();
// notify the customizer to prepare the application (if it hasn't done so already)
if (!customizers.contains(customizer)) {
customizer.onPreparing(platform, applicationClass, launchOptions);
customizers.add(customizer);
}
// look for newly introduced customizers that may have been added to the OptionsByType
launchOptions
.stream(Customizer.class)
.filter(c -> !customizers.contains(c))
.forEach(customizersToPrepare::add);
}
// notify the customizers we're about to launch the application
customizers.forEach(customizer -> customizer.onLaunching(platform, applicationClass, launchOptions));
// convert any CommandLine options to arguments and add them
launchOptions.stream(CommandLine.class)
.flatMap(CommandLine::arguments)
.map(Argument::of)
.forEach(launchOptions::add);
// establish a Name for the Application
launchOptions.computeIfNotPresent(Name.class, () -> getName(launchOptions));
final var name = launchOptions.get(Name.class);
// establish a DiagnosticName for the Application given the launch options
final DiagnosticName diagnosticName = launchOptions
.get(DiagnosticNameProvider.class)
.create(launchOptions, name);
launchOptions.add(diagnosticName);
// determine the Executable to launch
getExecutable(launchOptions)
.ifPresent(executable -> launchOptions.addIfNotPresent(Executable.class, executable));
// establish the WorkingDirectory (when defined)
launchOptions.computeIfNotPresent(
WorkingDirectory.class,
() -> platform.configuration().get(WorkingDirectory.class));
// establish the TemporaryDirectory
launchOptions.computeIfNotPresent(
TemporaryDirectory.class,
() -> platform.configuration().get(TemporaryDirectory.class));
// --- establish the diagnostics table for the Tabular Options ---
// establish the map of tables, keyed by type of Tabular Option
final HashMap<Class<? extends Tabular>, Table> tables = new HashMap<>();
// establish tables for each of the types of Tabular Options
// (those that don't supply a table, will use the diagnostics table)
// and tabularize each of the Tabular Options into their respective tables
launchOptions.stream(Tabular.class)
.filter(Tabular::hasTabularContent)
.sequential()
.peek(tabular ->
tables.computeIfAbsent(tabular.getClass(),
tabularClass -> tabular.getTableSupplier().orElse(() -> this.diagnostics).get()))
.forEach(tabular -> tabular.tabularize(tables.get(tabular.getClass())));
// add the non-diagnostic tables, into the diagnostics table (using their respective TableName)
tables.entrySet().stream()
.filter(entry -> entry.getValue() != this.diagnostics)
.forEach(entry -> {
final Class<? extends Tabular> tabularClass = entry.getKey();
final Table table = entry.getValue();
table.options()
.computeIfNotPresent(
TableName.class,
() -> TableName.of(tabularClass.getSimpleName()));
final TableName tableName = table.options().get(TableName.class);
this.diagnostics.addRow(tableName.get(), table.toString());
});
// allow the launch Configuration to be injected
final var launchConfiguration = launchOptions.build();
launchContext.bind(Configuration.class).to(launchConfiguration);
// create the process for the Application
final N process = createProcess(platform, launchOptions);
// allow the process interfaces to be used for injection
launchContext.bind((Class) process.getClass()).to(process);
Introspection.getAll(process.getClass(), Class::getInterfaces)
.filter(i -> !i.equals(Addressable.class))
.forEach(i -> launchContext.bind((Class) i).to(process));
// instantiate individual facets
final Set<Facet<?>> facets = launchOptions.stream(Facet.class)
.map(facet -> (Facet<?>) facet)
.map(facet -> {
final Object implementation = facet.getFactory().apply(launchContext);
// allow injection of facets
launchContext.bind((Class<Object>) facet.getInterface()).to(implementation);
// create a synthetic Facet that always resolves to the same implementation
return Facet.of(facet.getInterface(), _ -> facet.getInterface().cast(implementation));
})
.collect(Collectors.toSet());
// allow Iterable<T> to be resolved for injection where T is implemented by zero or more Facets.
launchContext.addResolver(new Resolver<Iterable<Object>>() {
@Override
public Optional<? extends Binding<Iterable<Object>>> resolve(final Dependency dependency) {
if (dependency.typeUsage() instanceof GenericTypeUsage genericTypeUsage
&& genericTypeUsage.typeName().canonicalName().equals(Iterable.class.getCanonicalName())
&& genericTypeUsage.parameters().count() == 1) {
final var parameterTypeUsage = genericTypeUsage.parameters()
.findFirst()
.orElseThrow();
if (parameterTypeUsage instanceof NamedTypeUsage namedTypeUsage) {
try {
final var parameterClass = this.getClass()
.getClassLoader()
.loadClass(namedTypeUsage.typeName().canonicalName());
// find the Facets that implement T
final var list = facets.stream()
.map(facet -> parameterClass.cast(facet.getFactory().apply(launchContext)))
.filter(parameterClass::isInstance)
.toList();
return Optional.of(new ValueBinding<Iterable<Object>>() {
@Override
@SuppressWarnings("unchecked")
public Iterable<Object> value() {
return (Iterable<Object>) list;
}
@Override
public Dependency dependency() {
return dependency;
}
});
}
catch (final ClassNotFoundException e) {
LOGGER.debug("Could not load class [{0}] for Iterable injection resolution",
namedTypeUsage.typeName().canonicalName(), e);
}
}
}
return Optional.empty();
}
});
// --- create the application ---
final Facet<A> applicationFacet = Facet.of(
(Class<A>) applicationClass,
(Class<? extends A>) implementationClass);
final Facet<?>[] allFacets = Stream.concat(
Stream.of(applicationFacet),
facets.stream())
.toArray(Facet[]::new);
// --- create the faceted wrapper around all facets ---
final A implementation = (A) Faceted.create(launchContext, allFacets);
customizers.forEach(customizer -> customizer.onLaunched(platform, applicationClass, implementation));
return implementation;
}
}