forked from jooby-project/jooby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJooby.java
More file actions
1330 lines (1163 loc) · 37.4 KB
/
Jooby.java
File metadata and controls
1330 lines (1163 loc) · 37.4 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import static java.util.Spliterators.spliteratorUnknownSize;
import static java.util.stream.StreamSupport.stream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.Spliterator;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.typesafe.config.Config;
import io.jooby.exception.RegistryException;
import io.jooby.exception.StartupException;
import io.jooby.internal.LocaleUtils;
import io.jooby.internal.RegistryRef;
import io.jooby.internal.RouterImpl;
/**
* <h1>Welcome to Jooby!</h1>
*
* <p>Hello World!</p>
* <pre>{@code
*
* public class App extends Jooby {
*
* {
* get("/", ctx -> "Hello World!");
* }
*
* public static void main(String[] args) {
* runApp(args, App::new);
* }
* }
*
* }</pre>
*
* More documentation at <a href="https://jooby.io">jooby.io</a>
*
* @since 2.0.0
* @author edgar
*/
public class Jooby implements Router, Registry {
static final String BASE_PACKAGE = "application.package";
static final String APP_NAME = "___app_name__";
private static final String JOOBY_RUN_HOOK = "___jooby_run_hook__";
private final transient AtomicBoolean started = new AtomicBoolean(true);
private static transient Jooby owner;
private RouterImpl router;
private ExecutionMode mode;
private Path tmpdir;
private List<SneakyThrows.Runnable> readyCallbacks;
private List<SneakyThrows.Runnable> startingCallbacks;
private LinkedList<AutoCloseable> stopCallbacks;
private List<Extension> lateExtensions;
private Environment env;
private RegistryRef registry = new RegistryRef();
private ServerOptions serverOptions;
private EnvironmentOptions environmentOptions;
private List<Locale> locales;
private boolean lateInit;
private String name;
private String version;
/**
* Creates a new Jooby instance.
*/
public Jooby() {
if (owner == null) {
ClassLoader classLoader = getClass().getClassLoader();
environmentOptions = new EnvironmentOptions().setClassLoader(classLoader);
router = new RouterImpl(classLoader);
stopCallbacks = new LinkedList<>();
startingCallbacks = new ArrayList<>();
readyCallbacks = new ArrayList<>();
lateExtensions = new ArrayList<>();
} else {
copyState(owner, this);
}
}
/**
* Server options or <code>null</code>.
*
* @return Server options or <code>null</code>.
*/
public @Nullable ServerOptions getServerOptions() {
return serverOptions;
}
/**
* Set server options.
*
* @param serverOptions Server options.
* @return This application.
*/
public @Nonnull Jooby setServerOptions(@Nonnull ServerOptions serverOptions) {
this.serverOptions = serverOptions;
return this;
}
@Nonnull @Override public Set<RouterOption> getRouterOptions() {
return router.getRouterOptions();
}
@Nonnull @Override public Jooby setRouterOptions(@Nonnull RouterOption... options) {
router.setRouterOptions(options);
return this;
}
/**
* Application environment. If none was set, environment is initialized
* using {@link Environment#loadEnvironment(EnvironmentOptions)}.
*
* @return Application environment.
*/
public @Nonnull Environment getEnvironment() {
if (env == null) {
env = Environment.loadEnvironment(environmentOptions);
}
return env;
}
/**
* Returns the list of supported locales, or
* {@code null} if none set.
*
* @return The supported locales.
*/
@Nullable @Override public List<Locale> getLocales() {
return locales;
}
/**
* Sets the supported locales.
*
* @param locales The supported locales.
* @return This router.
*/
public Router setLocales(@Nonnull List<Locale> locales) {
this.locales = requireNonNull(locales);
return this;
}
/**
* Sets the supported locales.
*
* @param locales The supported locales.
* @return This router.
*/
public Router setLocales(Locale... locales) {
return setLocales(Arrays.asList(locales));
}
/**
* Application class loader.
*
* @return Application class loader.
*/
public @Nonnull ClassLoader getClassLoader() {
return env == null ? environmentOptions.getClassLoader() : env.getClassLoader();
}
/**
* Application configuration. It is a shortcut for {@link Environment#getConfig()}.
*
* @return Application config.
*/
public @Nonnull Config getConfig() {
return getEnvironment().getConfig();
}
/**
* Set application environment.
*
* @param environment Application environment.
* @return This application.
*/
public @Nonnull Jooby setEnvironment(@Nonnull Environment environment) {
this.env = environment;
return this;
}
/**
* Set environment options and initialize/overrides the environment.
*
* @param options Environment options.
* @return New environment.
*/
public @Nonnull Environment setEnvironmentOptions(@Nonnull EnvironmentOptions options) {
this.environmentOptions = options;
this.env = Environment.loadEnvironment(
options.setClassLoader(options.getClassLoader(getClass().getClassLoader())));
return this.env;
}
/**
* Event fired before starting router and web-server. Non-lateinit extension are installed at
* this stage.
*
* @param body Start body.
* @return This application.
*/
public @Nonnull Jooby onStarting(@Nonnull SneakyThrows.Runnable body) {
startingCallbacks.add(body);
return this;
}
/**
* Event is fire once all components has been initialized, for example router and web-server
* are up and running, extension installed, etc...
*
* @param body Start body.
* @return This application.
*/
public @Nonnull Jooby onStarted(@Nonnull SneakyThrows.Runnable body) {
readyCallbacks.add(body);
return this;
}
/**
* Stop event is fire at application shutdown time. Useful to execute cleanup task, free
* resources, etc...
*
* @param body Stop body.
* @return This application.
*/
public @Nonnull Jooby onStop(@Nonnull AutoCloseable body) {
stopCallbacks.addFirst(body);
return this;
}
@Nonnull @Override public Jooby setContextPath(@Nonnull String basePath) {
router.setContextPath(basePath);
return this;
}
@Nonnull @Override public String getContextPath() {
return router.getContextPath();
}
/**
* Installs/imports a full application into this one. Applications share services, registry,
* callbacks, etc.
*
* Applications must be instantiated/created lazily via a supplier/factory. This is required due
* to the way an application is usually initialized (constructor initializer).
*
* Working example:
*
* <pre>{@code
*
* install(SubApp::new);
*
* }</pre>
*
* Lazy creation configures and setup <code>SubApp</code> correctly, the next example
* won't work:
*
* <pre>{@code
*
* SubApp app = new SubApp();
* install(app); // WONT WORK
*
* }</pre>
*
* Note: you must take care of application services across the applications. For example make sure
* you don't configure the same service twice or more in the main and imported applications too.
*
* @param factory Application factory.
* @return This application.
*/
@Nonnull public Jooby install(@Nonnull SneakyThrows.Supplier<Jooby> factory) {
return install("/", factory);
}
/**
* Installs/imports a full application into this one. Applications share services, registry,
* callbacks, etc.
*
* Application must be instantiated/created lazily via a supplier/factory. This is required due
* to the way an application is usually initialized (constructor initializer).
*
* Working example:
*
* <pre>{@code
*
* install("/subapp", SubApp::new);
*
* }</pre>
*
* Lazy creation allows to configure and setup <code>SubApp</code> correctly, the next example
* won't work:
*
* <pre>{@code
*
* SubApp app = new SubApp();
* install("/subapp", app); // WONT WORK
*
* }</pre>
*
* Note: you must take care of application services across the applications. For example make sure
* you don't configure the same service twice or more in the main and imported applications too.
*
* @param path Path prefix.
* @param factory Application factory.
* @return This application.
*/
@Nonnull
public Jooby install(@Nonnull String path, @Nonnull SneakyThrows.Supplier<Jooby> factory) {
try {
owner = this;
path(path, () -> factory.get());
return this;
} finally {
owner = null;
}
}
/**
* The underlying router.
*
* @return The underlying router.
*/
public @Nonnull Router getRouter() {
return router;
}
@Override public boolean isTrustProxy() {
return router.isTrustProxy();
}
@Nonnull @Override public Jooby setTrustProxy(boolean trustProxy) {
this.router.setTrustProxy(trustProxy);
return this;
}
@Nonnull @Override public Router domain(@Nonnull String domain, @Nonnull Router subrouter) {
this.router.domain(domain, subrouter);
return this;
}
@Nonnull @Override public RouteSet domain(@Nonnull String domain, @Nonnull Runnable body) {
return router.domain(domain, body);
}
@Nonnull @Override
public RouteSet mount(@Nonnull Predicate<Context> predicate, @Nonnull Runnable body) {
return router.mount(predicate, body);
}
@Nonnull @Override
public Jooby mount(@Nonnull Predicate<Context> predicate, @Nonnull Router subrouter) {
this.router.mount(predicate, subrouter);
return this;
}
@Nonnull @Override public Jooby mount(@Nonnull String path, @Nonnull Router router) {
this.router.mount(path, router);
if (router instanceof Jooby) {
Jooby child = (Jooby) router;
child.registry = this.registry;
}
return this;
}
@Nonnull @Override
public Jooby mount(@Nonnull Router router) {
return mount("/", router);
}
@Nonnull @Override public Jooby mvc(@Nonnull Object router) {
Provider provider = () -> router;
return mvc(router.getClass(), provider);
}
@Nonnull @Override public Jooby mvc(@Nonnull Class router) {
return mvc(router, () -> require(router));
}
@Nonnull @Override
public <T> Jooby mvc(@Nonnull Class<T> router, @Nonnull Provider<T> provider) {
try {
ServiceLoader<MvcFactory> modules = ServiceLoader.load(MvcFactory.class);
MvcFactory module = stream(modules.spliterator(), false)
.filter(it -> it.supports(router))
.findFirst()
.orElseGet(() ->
/** Make happy IDE incremental build: */
mvcReflectionFallback(router, getClassLoader())
.orElseThrow(() -> Usage.mvcRouterNotFound(router))
);
Extension extension = module.create(provider);
extension.install(this);
return this;
} catch (Exception x) {
throw SneakyThrows.propagate(x);
}
}
@Nonnull @Override
public Route ws(@Nonnull String pattern, @Nonnull WebSocket.Initializer handler) {
return router.ws(pattern, handler);
}
@Nonnull @Override
public Route sse(@Nonnull String pattern, @Nonnull ServerSentEmitter.Handler handler) {
return router.sse(pattern, handler);
}
@Nonnull @Override public List<Route> getRoutes() {
return router.getRoutes();
}
@Nonnull @Override public Jooby error(@Nonnull ErrorHandler handler) {
router.error(handler);
return this;
}
@Nonnull @Override public Jooby decorator(@Nonnull Route.Decorator decorator) {
router.decorator(decorator);
return this;
}
@Nonnull @Override public Jooby before(@Nonnull Route.Before before) {
router.before(before);
return this;
}
@Nonnull @Override public Jooby after(@Nonnull Route.After after) {
router.after(after);
return this;
}
@Nonnull @Override public Jooby encoder(@Nonnull MessageEncoder encoder) {
router.encoder(encoder);
return this;
}
@Nonnull @Override public Jooby decoder(@Nonnull MediaType contentType, @Nonnull
MessageDecoder decoder) {
router.decoder(contentType, decoder);
return this;
}
@Nonnull @Override
public Jooby encoder(@Nonnull MediaType contentType, @Nonnull MessageEncoder encoder) {
router.encoder(contentType, encoder);
return this;
}
/**
* Install extension module.
*
* @param extension Extension module.
* @return This application.
*/
@Nonnull public Jooby install(@Nonnull Extension extension) {
if (lateInit || extension.lateinit()) {
lateExtensions.add(extension);
} else {
try {
extension.install(this);
} catch (Exception x) {
throw SneakyThrows.propagate(x);
}
}
return this;
}
@Nonnull @Override public Jooby dispatch(@Nonnull Runnable body) {
router.dispatch(body);
return this;
}
@Nonnull @Override public Jooby dispatch(@Nonnull Executor executor, @Nonnull Runnable action) {
router.dispatch(executor, action);
return this;
}
@Nonnull @Override public RouteSet path(@Nonnull String pattern, @Nonnull Runnable action) {
return router.path(pattern, action);
}
@Nonnull @Override public RouteSet routes(@Nonnull Runnable action) {
return router.routes(action);
}
@Nonnull @Override
public Route route(@Nonnull String method, @Nonnull String pattern,
@Nonnull Route.Handler handler) {
return router.route(method, pattern, handler);
}
@Nonnull @Override public Match match(@Nonnull Context ctx) {
return router.match(ctx);
}
@Override public boolean match(@Nonnull String pattern, @Nonnull String path) {
return router.match(pattern, path);
}
@Nonnull @Override
public Jooby errorCode(@Nonnull Class<? extends Throwable> type,
@Nonnull StatusCode statusCode) {
router.errorCode(type, statusCode);
return this;
}
@Nonnull @Override public StatusCode errorCode(@Nonnull Throwable cause) {
return router.errorCode(cause);
}
@Nonnull @Override public Executor getWorker() {
return router.getWorker();
}
@Nonnull @Override public Jooby setWorker(@Nonnull Executor worker) {
this.router.setWorker(worker);
if (worker instanceof ExecutorService) {
onStop(((ExecutorService) worker)::shutdown);
}
return this;
}
@Nonnull @Override public Jooby setDefaultWorker(@Nonnull Executor worker) {
this.router.setDefaultWorker(worker);
return this;
}
@Nonnull @Override public Logger getLog() {
return LoggerFactory.getLogger(getClass());
}
@Nonnull @Override public Jooby responseHandler(ResponseHandler handler) {
router.responseHandler(handler);
return this;
}
@Nonnull @Override public ErrorHandler getErrorHandler() {
return router.getErrorHandler();
}
@Nonnull @Override public Path getTmpdir() {
if (tmpdir == null) {
tmpdir = Paths.get(getEnvironment().getConfig().getString("application.tmpdir"))
.toAbsolutePath();
}
return tmpdir;
}
/**
* Set application temporary directory.
*
* @param tmpdir Temp directory.
* @return This application.
*/
public @Nonnull Jooby setTmpdir(@Nonnull Path tmpdir) {
this.tmpdir = tmpdir;
return this;
}
/**
* Application execution mode.
*
* @return Application execution mode.
*/
public @Nonnull ExecutionMode getExecutionMode() {
return mode == null ? ExecutionMode.DEFAULT : mode;
}
/**
* Set application execution mode.
*
* @param mode Application execution mode.
* @return This application.
*/
public @Nonnull Jooby setExecutionMode(@Nonnull ExecutionMode mode) {
this.mode = mode;
return this;
}
@Nonnull @Override public Map<String, Object> getAttributes() {
return router.getAttributes();
}
@Nonnull @Override public Jooby attribute(@Nonnull String key, @Nonnull Object value) {
router.attribute(key, value);
return this;
}
@Nonnull @Override public <T> T attribute(@Nonnull String key) {
return router.attribute(key);
}
@Nonnull @Override public <T> T require(@Nonnull Class<T> type, @Nonnull String name) {
return require(ServiceKey.key(type, name));
}
@Nonnull @Override public <T> T require(@Nonnull Class<T> type) {
return require(ServiceKey.key(type));
}
@Override public @Nonnull <T> T require(@Nonnull ServiceKey<T> key) {
ServiceRegistry services = getServices();
T service = services.getOrNull(key);
if (service == null) {
if (!registry.isSet()) {
throw new RegistryException("Service not found: " + key);
}
String name = key.getName();
return name == null ? registry.get().require(key.getType()) : registry.get().require(key.getType(), name);
}
return service;
}
/**
* Set application registry.
*
* @param registry Application registry.
* @return This application.
*/
@Nonnull public Jooby registry(@Nonnull Registry registry) {
this.registry.set(registry);
return this;
}
@Nonnull @Override public ServiceRegistry getServices() {
return this.router.getServices();
}
/**
* Get base application package. This is the package from where application was initialized
* or the package of a Jooby application sub-class.
*
* @return Base application package.
*/
public @Nullable String getBasePackage() {
return System.getProperty(BASE_PACKAGE,
Optional.ofNullable(getClass().getPackage()).map(Package::getName).orElse(null));
}
@Nonnull @Override public SessionStore getSessionStore() {
return router.getSessionStore();
}
@Nonnull @Override public Jooby setSessionStore(@Nonnull SessionStore store) {
router.setSessionStore(store);
return this;
}
@Nonnull @Override public Jooby executor(@Nonnull String name, @Nonnull Executor executor) {
if (executor instanceof ExecutorService) {
onStop(((ExecutorService) executor)::shutdown);
}
router.executor(name, executor);
return this;
}
@Deprecated @Nonnull @Override public Jooby setFlashCookie(@Nonnull String name) {
router.setFlashCookie(name);
return this;
}
@Nonnull @Override public Cookie getFlashCookie() {
return router.getFlashCookie();
}
@Nonnull @Override public Jooby setFlashCookie(@Nonnull Cookie flashCookie) {
router.setFlashCookie(flashCookie);
return this;
}
@Nonnull @Override public Jooby converter(@Nonnull ValueConverter converter) {
router.converter(converter);
return this;
}
@Nonnull @Override public Jooby converter(@Nonnull BeanConverter converter) {
router.converter(converter);
return this;
}
@Nonnull @Override public List<ValueConverter> getConverters() {
return router.getConverters();
}
@Nonnull @Override public List<BeanConverter> getBeanConverters() {
return router.getBeanConverters();
}
@Nonnull @Override public Jooby setHiddenMethod(
@Nonnull Function<Context, Optional<String>> provider) {
router.setHiddenMethod(provider);
return this;
}
@Nonnull @Override public Jooby setCurrentUser(
@Nonnull Function<Context, Object> provider) {
router.setCurrentUser(provider);
return this;
}
@Nonnull @Override public Jooby setContextAsService(boolean contextAsService) {
router.setContextAsService(contextAsService);
return this;
}
@Nonnull @Override public Jooby setHiddenMethod(@Nonnull String parameterName) {
router.setHiddenMethod(parameterName);
return this;
}
/**
* Start application, find a web server, deploy application, start router, extension modules,
* etc..
*
* @return Server.
*/
public @Nonnull Server start() {
List<Server> servers = stream(
spliteratorUnknownSize(
ServiceLoader.load(Server.class).iterator(),
Spliterator.ORDERED),
false)
.collect(Collectors.toList());
if (servers.size() == 0) {
throw new IllegalStateException("Server not found.");
}
if (servers.size() > 1) {
List<String> names = servers.stream()
.map(it -> it.getClass().getSimpleName().toLowerCase())
.collect(Collectors.toList());
getLog().warn("Multiple servers found {}. Using: {}", names, names.get(0));
}
Server server = servers.get(0);
try {
if (serverOptions == null) {
serverOptions = ServerOptions.from(getEnvironment().getConfig()).orElse(null);
}
if (serverOptions != null) {
serverOptions.setServer(server.getClass().getSimpleName().toLowerCase());
server.setOptions(serverOptions);
}
return server.start(this);
} catch (Throwable x) {
Logger log = getLog();
log.error("Application startup resulted in exception", x);
try {
server.stop();
} catch (Throwable stopx) {
log.info("Server stop resulted in exception", stopx);
}
// rethrow
throw x instanceof StartupException
? (StartupException) x
: new StartupException("Application startup resulted in exception", x);
}
}
/**
* Call back method that indicates application was deploy it in the given server.
*
* @param server Server.
* @return This application.
*/
public @Nonnull Jooby start(@Nonnull Server server) {
Path tmpdir = getTmpdir();
ensureTmpdir(tmpdir);
if (mode == null) {
mode = ExecutionMode.DEFAULT;
}
if (locales == null) {
String path = "application.lang";
locales = Optional.of(getConfig())
.filter(c -> c.hasPath(path))
.map(c -> c.getString(path))
.map(
v -> LocaleUtils.parseLocales(v).orElseThrow(() -> new RuntimeException(String.format(
"Invalid value for configuration property '%s'; check the documentation of %s#parse(): %s",
path, Locale.LanguageRange.class.getName(), v))))
.orElseGet(() -> singletonList(Locale.getDefault()));
}
ServiceRegistry services = getServices();
services.put(Environment.class, getEnvironment());
services.put(Config.class, getConfig());
joobyRunHook(getClass().getClassLoader(), server);
for (Extension extension : lateExtensions) {
try {
extension.install(this);
} catch (Throwable e) {
throw SneakyThrows.propagate(e);
}
}
this.lateExtensions.clear();
this.lateExtensions = null;
this.startingCallbacks = fire(this.startingCallbacks);
router.start(this);
return this;
}
/**
* Callback method that indicates application was successfully started it and listening for
* connections.
*
* @param server Server.
* @return This application.
*/
public @Nonnull Jooby ready(@Nonnull Server server) {
Logger log = getLog();
this.serverOptions = server.getOptions();
log.info("{} started with:", getName());
log.info(" PID: {}", System.getProperty("PID"));
log.info(" {}", server.getOptions());
if (log.isDebugEnabled()) {
log.debug(" env: {}", env);
} else {
log.info(" env: {}", env.getActiveNames());
}
log.info(" execution mode: {}", mode.name().toLowerCase());
log.info(" user: {}", System.getProperty("user.name"));
log.info(" app dir: {}", System.getProperty("user.dir"));
log.info(" tmp dir: {}", tmpdir);
StringBuilder buff = new StringBuilder();
buff.append("routes: \n\n{}\n\nlistening on:\n");
ServerOptions options = server.getOptions();
String host = options.getHost().replace("0.0.0.0", "localhost");
List<Object> args = new ArrayList<>();
args.add(router);
args.add(host);
args.add(options.getPort());
args.add(router.getContextPath());
buff.append(" http://{}:{}{}\n");
if (options.isSSLEnabled()) {
args.add(host);
args.add(options.getSecurePort());
args.add(router.getContextPath());
buff.append(" https://{}:{}{}\n");
}
log.info(buff.toString(), args.toArray(new Object[0]));
this.readyCallbacks = fire(this.readyCallbacks);
return this;
}
/**
* Stop application, fire the stop event to cleanup resources.
*
* This method is usually invoked by {@link Server#stop()} using a shutdown hook.
*
* The next example shows how to successfully stop the web server and application:
*
* <pre>{@code
* Jooby app = new Jooby();
*
* Server server = app.start();
*
* ...
*
* server.stop();
* }</pre>
*
* @return This application.
*/
public @Nonnull Jooby stop() {
if (started.compareAndSet(true, false)) {
Logger log = getLog();
log.debug("Stopping {}", System.getProperty(APP_NAME, getClass().getSimpleName()));
router.destroy();
fireStop();
log.info("Stopped {}", System.getProperty(APP_NAME, getClass().getSimpleName()));
}
return this;
}
/**
* Force all module to be initialized lazily at application startup time (not at
* creation/instantiation time).
*
* This option is present mostly for unit-test where you need to instantiated a Jooby instance
* without running extensions.
*
* @param lateInit True for late init.
* @return This application.
*/
public Jooby setLateInit(boolean lateInit) {
this.lateInit = lateInit;
return this;
}
/**
* Get application's name. If none set:
*
* - Try to get from {@link Package#getImplementationTitle()}.
* - Otherwise fallback to class name.
*
* @return Application's name.
*/
public @Nonnull String getName() {
if (name == null) {
name = System.getProperty(APP_NAME);
if (name == null) {
name = Optional.ofNullable(getClass().getPackage())
.map(Package::getImplementationTitle)
.filter(Objects::nonNull)
.orElse(getClass().getSimpleName());
}
}
return name;
}
/**
* Set application name.
*
* @param name Application's name.
* @return This application.
*/
public @Nonnull Jooby setName(@Nonnull String name) {
this.name = name;
return this;
}
/**