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
3518 lines (3298 loc) · 105 KB
/
Copy pathJooby.java
File metadata and controls
3518 lines (3298 loc) · 105 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
/**
* 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.
*/
/**
* This copy of Woodstox XML processor is licensed under the
* Apache (Software) License, version 2.0 ("the License").
* See the License for details about distribution rights, and the
* specific rights regarding derivate works.
*
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing Woodstox, in file "ASL2.0", under the same directory
* as this file.
*/
/**
o * 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.jooby;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.typesafe.config.ConfigValueFactory.fromAnyRef;
import static java.util.Objects.requireNonNull;
import java.io.File;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.TimeZone;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import javax.inject.Singleton;
import javax.net.ssl.SSLContext;
import org.jooby.Route.Definition;
import org.jooby.Session.Store;
import org.jooby.handlers.AssetHandler;
import org.jooby.internal.AppPrinter;
import org.jooby.internal.AssetProxy;
import org.jooby.internal.BuiltinParser;
import org.jooby.internal.BuiltinRenderer;
import org.jooby.internal.DefaulErrRenderer;
import org.jooby.internal.HttpHandlerImpl;
import org.jooby.internal.JvmInfo;
import org.jooby.internal.LifecycleProcessor;
import org.jooby.internal.LocaleUtils;
import org.jooby.internal.RequestScope;
import org.jooby.internal.RouteMetadata;
import org.jooby.internal.ServerLookup;
import org.jooby.internal.SessionManager;
import org.jooby.internal.TypeConverters;
import org.jooby.internal.handlers.HeadHandler;
import org.jooby.internal.handlers.OptionsHandler;
import org.jooby.internal.handlers.TraceHandler;
import org.jooby.internal.js.JsJooby;
import org.jooby.internal.mvc.MvcRoutes;
import org.jooby.internal.parser.BeanParser;
import org.jooby.internal.parser.DateParser;
import org.jooby.internal.parser.LocalDateParser;
import org.jooby.internal.parser.LocaleParser;
import org.jooby.internal.parser.ParserExecutor;
import org.jooby.internal.parser.StaticMethodParser;
import org.jooby.internal.parser.StringConstructorParser;
import org.jooby.internal.ssl.SslContextProvider;
import org.jooby.reflect.ParameterNameProvider;
import org.jooby.scope.RequestScoped;
import org.jooby.spi.HttpHandler;
import org.jooby.spi.Server;
import org.jooby.util.Providers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Stage;
import com.google.inject.matcher.Matchers;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
import com.google.inject.util.Types;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigObject;
import com.typesafe.config.ConfigValue;
import com.typesafe.config.ConfigValueFactory;
/**
* <h1>Getting Started:</h1>
* <p>
* A new application must extends Jooby, register one ore more {@link Renderer} and some
* {@link Route routes}. It sounds like a lot of work to do, but it isn't.
* </p>
*
* <pre>
* public class MyApp extends Jooby {
*
* {
* renderer(new Json()); // 1. JSON serializer.
*
* // 2. Define a route
* get("/", (req, rsp) {@literal ->} {
* Map{@literal <}String, Object{@literal >} model = ...;
* rsp.send(model);
* }
* }
*
* public static void main(String[] args) throws Exception {
* new MyApp().start(); // 3. Done!
* }
* }
* </pre>
*
* <h1>Properties files</h1>
* <p>
* Jooby delegate configuration management to <a
* href="https://github.com/typesafehub/config">TypeSafe Config</a>. If you are unfamiliar with <a
* href="https://github.com/typesafehub/config">TypeSafe Config</a> please take a few minutes to
* discover what <a href="https://github.com/typesafehub/config">TypeSafe Config</a> can do for you.
* </p>
*
* <p>
* By default Jooby looks for an <code>application.conf</code> file at the root of the classpath. If
* you want to specify a different file or location, you can do it with {@link #use(Config)}.
* </p>
*
* <p>
* <a href="https://github.com/typesafehub/config">TypeSafe Config</a> uses a hierarchical model to
* define and override properties.
* </p>
* <p>
* A {@link Jooby.Module} might provides his own set of properties through the
* {@link Jooby.Module#config()} method. By default, this method returns an empty config object.
* </p>
* For example:
*
* <pre>
* use(new M1());
* use(new M2());
* use(new M3());
* </pre>
*
* Previous example had the following order (first-listed are higher priority):
* <ul>
* <li>System properties</li>
* <li>application.conf</li>
* <li>M3 properties</li>
* <li>M2 properties</li>
* <li>M1 properties</li>
* </ul>
* <p>
* System properties takes precedence over any application specific property.
* </p>
*
* <h1>env</h1>
* <p>
* Jooby defines two modes: <strong>dev</strong> or something else. In Jooby, <strong>dev</strong>
* is special and some modules could apply special settings while running in <strong>dev</strong>.
* Any other env is usually considered a <code>prod</code> like env. But that depends on module
* implementor.
* </p>
* <p>
* A env can be defined in your <code>application.conf</code> file using the
* <code>application.env</code> property. If missing, Jooby set the env for you to
* <strong>dev</strong>.
* </p>
* <p>
* There is more at {@link Env} so take a few minutes to discover what a {@link Env} can do for you.
* </p>
*
* <h1>Modules</h1>
* <p>
* {@link Jooby.Module Modules} are quite similar to a Guice modules except that the configure
* callback has been complementing with {@link Env} and {@link Config}.
* </p>
*
* <pre>
* public class MyModule implements Jooby.Module {
* public void configure(env env, Config config, Binder binder) {
* }
* }
* </pre>
*
* From the configure callback you can bind your services as you usually do in a Guice app.
* <p>
* There is more at {@link Jooby.Module} so take a few minutes to discover what a
* {@link Jooby.Module} can do for you.
* </p>
*
* <h1>Path Patterns</h1>
* <p>
* Jooby supports Ant-style path patterns:
* </p>
* <p>
* Some examples:
* </p>
* <ul>
* <li>{@code com/t?st.html} - matches {@code com/test.html} but also {@code com/tast.html} or
* {@code com/txst.html}</li>
* <li>{@code com/*.html} - matches all {@code .html} files in the {@code com} directory</li>
* <li><code>com/{@literal **}/test.html</code> - matches all {@code test.html} files underneath the
* {@code com} path</li>
* <li>{@code **}/{@code *} - matches any path at any level.</li>
* <li>{@code *} - matches any path at any level, shorthand for {@code **}/{@code *}.</li>
* </ul>
*
* <h2>Variables</h2>
* <p>
* Jooby supports path parameters too:
* </p>
* <p>
* Some examples:
* </p>
* <ul>
* <li><code> /user/{id}</code> - /user/* and give you access to the <code>id</code> var.</li>
* <li><code> /user/:id</code> - /user/* and give you access to the <code>id</code> var.</li>
* <li><code> /user/{id:\\d+}</code> - /user/[digits] and give you access to the numeric
* <code>id</code> var.</li>
* </ul>
*
* <h1>Routes</h1>
* <p>
* Routes perform actions in response to a server HTTP request. There are two types of routes
* callback: {@link Route.Handler} and {@link Route.Filter}.
* </p>
* <p>
* Routes are executed in the order they are defined, for example:
*
* <pre>
* get("/", (req, rsp) {@literal ->} {
* log.info("first"); // start here and go to second
* });
*
* get("/", (req, rsp) {@literal ->} {
* log.info("second"); // execute after first and go to final
* });
*
* get("/", (req, rsp) {@literal ->} {
* rsp.send("final"); // done!
* });
* </pre>
*
* Please note first and second routes are converted to a filter, so previous example is the same
* as:
*
* <pre>
* get("/", (req, rsp, chain) {@literal ->} {
* log.info("first"); // start here and go to second
* chain.next(req, rsp);
* });
*
* get("/", (req, rsp, chain) {@literal ->} {
* log.info("second"); // execute after first and go to final
* chain.next(req, rsp);
* });
*
* get("/", (req, rsp) {@literal ->} {
* rsp.send("final"); // done!
* });
* </pre>
*
* Due to the use of lambdas a route is a singleton and you should NOT use global variables. For
* example this is a bad practice:
*
* <pre>
* List{@literal <}String{@literal >} names = new ArrayList{@literal <}{@literal >}(); // names produces side effects
* get("/", (req, rsp) {@literal ->} {
* names.add(req.param("name").value();
* // response will be different between calls.
* rsp.send(names);
* });
* </pre>
*
* <h2>Mvc Route</h2>
* <p>
* A Mvc route use annotations to define routes:
* </p>
*
* <pre>
* use(MyRoute.class);
* ...
* // MyRoute.java
* {@literal @}Path("/")
* public class MyRoute {
*
* {@literal @}GET
* public String hello() {
* return "Hello Jooby";
* }
* }
* </pre>
* <p>
* Programming model is quite similar to JAX-RS/Jersey with some minor differences and/or
* simplifications.
* </p>
*
* <p>
* To learn more about Mvc Routes, please check {@link org.jooby.mvc.Path},
* {@link org.jooby.mvc.Produces} {@link org.jooby.mvc.Consumes} .
* </p>
*
* <h1>Static Files</h1>
* <p>
* Static files, like: *.js, *.css, ..., etc... can be served with:
* </p>
*
* <pre>
* assets("assets/**");
* </pre>
* <p>
* Classpath resources under the <code>/assets</code> folder will be accessible from client/browser.
* </p>
* <h1>Bootstrap</h1>
* <p>
* The bootstrap process is defined as follows:
* </p>
* <h2>1. Configuration files are loaded in this order:</h2>
* <ol>
* <li>System properties</li>
* <li>Application properties: {@code application.conf} or custom, see {@link #use(Config)}</li>
* <li>Configuration properties from {@link Jooby.Module modules}</li>
* </ol>
*
* <h2>2. Dependency Injection and {@link Jooby.Module modules}</h2>
* <ol>
* <li>An {@link Injector Guice Injector} is created.</li>
* <li>It configures each registered {@link Jooby.Module module}</li>
* <li>At this point Guice is ready and all the services has been binded.</li>
* <li>The {@link Jooby.Module#start() start method} is invoked.</li>
* <li>Finally, Jooby starts the web server</li>
* </ol>
*
* @author edgar
* @since 0.1.0
* @see Jooby.Module
*/
public class Jooby {
/**
* A module can publish or produces: {@link Route.Definition routes}, {@link Parser},
* {@link Renderer}, and any other application specific service or contract of your choice.
* <p>
* It is similar to {@link com.google.inject.Module} except for the callback method receives a
* {@link Env}, {@link Config} and {@link Binder}.
* </p>
*
* <p>
* A module can provide his own set of properties through the {@link #config()} method. By
* default, this method returns an empty config object.
* </p>
* For example:
*
* <pre>
* use(new M1());
* use(new M2());
* use(new M3());
* </pre>
*
* Previous example had the following order (first-listed are higher priority):
* <ul>
* <li>System properties</li>
* <li>application.conf</li>
* <li>M3 properties</li>
* <li>M2 properties</li>
* <li>M1 properties</li>
* </ul>
*
* <p>
* A module can provide start/stop methods in order to start or close resources.
* </p>
*
* @author edgar
* @since 0.1.0
* @see Jooby#use(Jooby.Module)
*/
public interface Module {
/**
* @return Produces a module config object (when need it). By default a module doesn't produce
* any configuration object.
*/
default Config config() {
return ConfigFactory.empty();
}
/**
* Configure and produces bindings for the underlying application. A module can optimize or
* customize a service by checking current the {@link Env application env} and/or the current
* application properties available from {@link Config}.
*
* @param env The current application's env. Not null.
* @param conf The current config object. Not null.
* @param binder A guice binder. Not null.
*/
void configure(Env env, Config conf, Binder binder);
}
private static class RouteClass {
Class<?> routeClass;
String path;
public RouteClass(final Class<?> routeClass, final String path) {
this.routeClass = routeClass;
this.path = path;
}
}
static {
// set pid as system property
String pid = System.getProperty("pid", JvmInfo.pid() + "");
System.setProperty("pid", pid);
// Avoid warning message from logback when multiples files are present
String logback = System.getProperty("logback.configurationFile", "logback.xml");
System.setProperty("logback.configurationFile", logback);
}
/** The logging system. */
private final Logger log = LoggerFactory.getLogger(getClass());
/**
* Keep track of routes.
*/
private final Set<Object> bag = new LinkedHashSet<>();
/**
* Keep track of modules.
*/
private final Set<Jooby.Module> modules = new LinkedHashSet<>();
/**
* Env callback.
*/
private final Multimap<Predicate<String>, Consumer<Config>> envcallbacks = ArrayListMultimap
.create();
/**
* The override config. Optional.
*/
private Config source;
/** Keep the global injector instance. */
private Injector injector;
/** Session store. */
private Session.Definition session = new Session.Definition(Session.Mem.class);
/** Env builder. */
private Env.Builder env = Env.DEFAULT;
/** Route's prefix. */
private String prefix;
public Jooby() {
this(null);
}
/**
* Creates a new application and prefix all the names of the routes with the given prefix. Useful,
* for dynamic/advanced routing. See {@link Route.Chain#next(String, Request, Response)}.
*
* @param prefix Route name prefix.
*/
public Jooby(final String prefix) {
this.prefix = prefix;
use(new ServerLookup());
}
/**
* Import ALL the direct routes from the given app.
*
* <p>
* PLEASE NOTE: that ONLY routes are imported.
* </p>
*
* @param app Routes provider.
* @return This jooby instance.
*/
public Jooby use(final Jooby app) {
return use(Optional.empty(), app);
}
/**
* Import ALL the direct routes from the given app, under the given path.
*
* <p>
* PLEASE NOTE: that ONLY routes are imported.
* </p>
*
* @param path Path to mount the given app.
* @param app Routes provider.
* @return This jooby instance.
*/
public Jooby use(final String path, final Jooby app) {
return use(Optional.of(path), app);
}
/**
* Import ALL the direct routes from the given app.
*
* <p>
* PLEASE NOTE: that ONLY routes are imported.
* </p>
*
* @param app Routes provider.
* @return This jooby instance.
*/
private Jooby use(final Optional<String> path, final Jooby app) {
requireNonNull(app, "App is required.");
Function<Route.Definition, Route.Definition> rewrite = r -> {
return path.map(p -> {
Route.Definition result = new Route.Definition(r.method(), p + r.pattern(), r.filter());
result.consumes(r.consumes());
result.produces(r.produces());
result.excludes(r.excludes());
return result;
}).orElse(r);
};
app.bag.forEach(it -> {
if (it instanceof Route.Definition) {
this.bag.add(rewrite.apply((Definition) it));
} else if (it instanceof Route.Group) {
((Route.Group) it).routes().forEach(r -> this.bag.add(rewrite.apply(r)));
} else if (it instanceof RouteClass) {
Object routes = path.<Object> map(p -> new RouteClass(((RouteClass) it).routeClass, p))
.orElse(it);
this.bag.add(routes);
}
});
this.envcallbacks.putAll(app.envcallbacks);
return this;
}
/**
* Define one or more routes under the same namespace:
*
* <pre>
* {
* use("/pets")
* .get("/{id}", req {@literal ->} db.get(req.param("id").value()))
* .get(() {@literal ->} db.values());
* }
* </pre>
*
* @param pattern Global pattern to use.
* @return A route namespace.
*/
public Route.Group use(final String pattern) {
Route.Group group = new Route.Group(pattern, prefix);
this.bag.add(group);
return group;
}
/**
* Set a custom {@link Env.Builder} to use.
*
* @param env A custom env builder.
* @return This jooby instance.
*/
public Jooby env(final Env.Builder env) {
this.env = requireNonNull(env, "Env builder is required.");
return this;
}
/**
* Run the given callback if and only if, app runs in the given enviroment.
*
* <pre>
* {
* on("dev", () {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* @param env Environment where we want to run the callback.
* @param callback An env callback.
* @return This jooby instance.
*/
public Jooby on(final String env, final Runnable callback) {
requireNonNull(env, "Env is required.");
return on(envpredicate(env), callback);
}
/**
* Run the given callback if and only if, app runs in the given enviroment.
*
* <pre>
* {
* on("dev", () {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* @param env Environment where we want to run the callback.
* @param callback An env callback.
* @return This jooby instance.
*/
public Jooby on(final String env, final Consumer<Config> callback) {
requireNonNull(env, "Env is required.");
return on(envpredicate(env), callback);
}
/**
* Run the given callback if and only if, app runs in the given enviroment.
*
* <pre>
* {
* on("dev", "test", () {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* @param predicate Predicate to check the environment.
* @param callback An env callback.
* @return This jooby instance.
*/
public Jooby on(final Predicate<String> predicate, final Runnable callback) {
requireNonNull(predicate, "Predicate is required.");
requireNonNull(callback, "Callback is required.");
return on(predicate, conf -> callback.run());
}
/**
* Run the given callback if and only if, app runs in the given enviroment.
*
* <pre>
* {
* on("dev", "test", () {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* @param predicate Predicate to check the environment.
* @param callback An env callback.
* @return This jooby instance.
*/
public Jooby on(final Predicate<String> predicate, final Consumer<Config> callback) {
requireNonNull(predicate, "Predicate is required.");
requireNonNull(callback, "Callback is required.");
envcallbacks.put(predicate, callback);
return this;
}
/**
* Run the given callback if and only if, app runs in the given enviroment.
*
* <pre>
* {
* on("dev", "test", "mock", () {@literal ->} {
* use(new DevModule());
* });
* }
* </pre>
*
* @param env1 Environment where we want to run the callback.
* @param env2 Environment where we want to run the callback.
* @param env3 Environment where we want to run the callback.
* @param callback An env callback.
* @return This jooby instance.
*/
public Jooby on(final String env1, final String env2, final String env3,
final Runnable callback) {
on(env1, callback);
on(env2, callback);
on(env3, callback);
return this;
}
/**
* Ask Guice for the given type.
*
* @param type A service type.
* @param <T> Service type.
* @return A ready to use object.
*/
public <T> T require(final Class<T> type) {
checkState(injector != null, "App didn't start yet");
return injector.getInstance(type);
}
/**
* Produces a deferred response, useful for async request processing.
*
* <h2>usage</h2>
*
* <pre>
* {
* ExecutorService executor = ...;
*
* get("/async", promise(deferred {@literal ->} {
* executor.execute(() {@literal ->} {
* try {
* deferred.resolve(...); // success value
* } catch (Exception ex) {
* deferred.reject(ex); // error value
* }
* });
* }));
* }
* </pre>
*
* <p>
* Or with automatic error handler:
* </p>
*
* <pre>
* {
* ExecutorService executor = ...;
*
* get("/async", promise(deferred {@literal ->} {
* executor.execute(() {@literal ->} {
* deferred.resolve(() {@literal ->} {
* Object value = ...
* return value;
* }); // success value
* });
* }));
* }
* </pre>
*
* <p>
* Or as {@link Runnable} with automatic error handler:
* </p>
*
* <pre>
* {
* ExecutorService executor = ...;
*
* get("/async", promise(deferred {@literal ->} {
* executor.execute(deferred.run(() {@literal ->} {
* Object value = ...
* return value;
* }); // success value
* }));
* }
* </pre>
*
* @param initializer Deferred initializer.
* @return A new deferred handler.
* @see Deferred
*/
public Route.OneArgHandler promise(final Deferred.Initializer initializer) {
return req -> {
return new Deferred(req, initializer);
};
}
/**
* Produces a deferred response, useful for async request processing.
*
* <h2>usage</h2>
*
* <pre>
* {
* ExecutorService executor = ...;
*
* get("/async", promise(deferred {@literal ->} {
* executor.execute(() {@literal ->} {
* try {
* deferred.resolve(...); // success value
* } catch (Exception ex) {
* deferred.reject(ex); // error value
* }
* });
* }));
* }
* </pre>
*
* <p>
* Or with automatic error handler:
* </p>
*
* <pre>
* {
* ExecutorService executor = ...;
*
* get("/async", promise(deferred {@literal ->} {
* executor.execute(() {@literal ->} {
* deferred.resolve(() {@literal ->} {
* Object value = ...
* return value;
* }); // success value
* });
* }));
* }
* </pre>
*
* <p>
* Or as {@link Runnable} with automatic error handler:
* </p>
*
* <pre>
* {
* ExecutorService executor = ...;
*
* get("/async", promise(deferred {@literal ->} {
* executor.execute(deferred.run(() {@literal ->} {
* Object value = ...
* return value;
* }); // success value
* }));
* }
* </pre>
*
* @param initializer Deferred initializer.
* @return A new deferred handler.
* @see Deferred
*/
public Route.OneArgHandler promise(final Deferred.Initializer0 initializer) {
return req -> {
return new Deferred(initializer);
};
}
/**
* Setup a session store to use. Useful if you want/need to persist sessions between shutdowns.
* Sessions are not persisted by defaults.
*
* @param store A session store.
* @return A session store definition.
*/
public Session.Definition session(final Class<? extends Session.Store> store) {
this.session = new Session.Definition(requireNonNull(store, "A session store is required."));
return this.session;
}
/**
* Setup a session store to use. Useful if you want/need to persist sessions between shutdowns.
* Sessions are not persisted by defaults.
*
* @param store A session store.
* @return A session store definition.
*/
public Session.Definition session(final Session.Store store) {
this.session = new Session.Definition(requireNonNull(store, "A session store is required."));
return this.session;
}
/**
* Register a new param converter. See {@link Parser} for more details.
*
* @param parser A parser.
* @return This jooby instance.
*/
public Jooby parser(final Parser parser) {
bag.add(requireNonNull(parser, "A parser is required."));
return this;
}
/**
* Append a response {@link Renderer} for write HTTP messages.
*
* @param renderer A renderer renderer.
* @return This jooby instance.
*/
public Jooby renderer(final Renderer renderer) {
this.bag.add(requireNonNull(renderer, "A renderer is required."));
return this;
}
/**
* Append a new filter that matches any method under the given path.
*
* @param path A path pattern.
* @param filter A filter to execute.
* @return A new route definition.
*/
public Route.Definition use(final String path,
final Route.Filter filter) {
return appendDefinition(new Route.Definition("*", path, filter));
}
/**
* Append a new filter that matches any method under the given path.
*
* @param verb A HTTP verb.
* @param path A path pattern.
* @param filter A filter to execute.
* @return A new route definition.
*/
public Route.Definition use(final String verb, final String path,
final Route.Filter filter) {
return appendDefinition(new Route.Definition(verb, path, filter));
}
/**
* Append a new route handler that matches any method under the given path.
*
* @param verb A HTTP verb.
* @param path A path pattern.
* @param handler A handler to execute.
* @return A new route definition.
*/
public Route.Definition use(final String verb, final String path,
final Route.Handler handler) {
return appendDefinition(new Route.Definition(verb, path, handler));
}
/**
* Append a new route handler that matches any method under the given path.
*
* @param path A path pattern.
* @param handler A handler to execute.
* @return A new route definition.
*/
public Route.Definition use(final String path,
final Route.Handler handler) {
return appendDefinition(new Route.Definition("*", path, handler));
}
/**
* Append a new route handler that matches any method under the given path.
*
* @param path A path pattern.
* @param handler A handler to execute.
* @return A new route definition.
*/
public Route.Definition use(final String path,
final Route.OneArgHandler handler) {
return appendDefinition(new Route.Definition("*", path, handler));
}
/**
* Append a route that supports HTTP GET method:
*
* <pre>
* get("/", (req, rsp) {@literal ->} {
* rsp.send(something);
* });
* </pre>
*
* This is a singleton route so make sure you don't share or use global variables.
*
* @param path A path pattern.
* @param handler A handler to execute.
* @return A new route definition.
*/
public Route.Definition get(final String path,