Repository navigation
Expand file tree
/
Copy pathEnv.java
More file actions
484 lines (435 loc) · 14.9 KB
/
Copy pathEnv.java
File metadata and controls
484 lines (435 loc) · 14.9 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
/**
* 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 java.util.Objects.requireNonNull;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.inject.Key;
import com.google.inject.name.Names;
import com.typesafe.config.Config;
import javaslang.API;
import javaslang.control.Option;
import javaslang.control.Try.CheckedConsumer;
/**
* Allows to optimize, customize or apply defaults values for services.
*
* <p>
* A env is represented by it's name. For example: <code>dev</code>, <code>prod</code>, etc... A
* <strong>dev</strong> env is special and a module provider could do some special configuration for
* development, like turning off a cache, reloading of resources, etc.
* </p>
* <p>
* Same is true for not <strong>dev</strong> environments. For example, a module provider might
* create a high performance connection pool, caches, etc.
* </p>
* <p>
* By default env is set to dev, but you can change it by setting the <code>application.env</code>
* property to anything else.
* </p>
*
* @author edgar
* @since 0.1.0
*/
public interface Env extends LifeCycle {
/**
* Utility class for generating {@link Key} for named services.
*
* @author edgar
*/
class ServiceKey {
private Map<Object, Integer> instances = new HashMap<>();
/**
* Generate at least one named key for the provided type. If this is the first call for the
* provided type then it generates an unnamed key.
*
* @param type Service type.
* @param name Service name.
* @param keys Key callback. Invoked once with a named key, and optionally again with an unamed
* key.
* @param <T> Service type.
*/
public <T> void generate(final Class<T> type, final String name, final Consumer<Key<T>> keys) {
Integer c = instances.put(type, instances.getOrDefault(type, 0) + 1);
if (c == null) {
// def key
keys.accept(Key.get(type));
}
keys.accept(Key.get(type, Names.named(name)));
}
}
/**
* Build an jooby environment.
*
* @author edgar
*/
interface Builder {
/**
* Build a new environment from a {@link Config} object. The environment is created from the
* <code>application.env</code> property. If such property is missing, env's name must be:
* <code>dev</code>.
*
* Please note an environment created with this method won't have a {@link Env#routes()}.
*
* @param config A config instance.
* @return A new environment.
*/
default Env build(final Config config) {
return build(config, null, Locale.getDefault());
}
/**
* Build a new environment from a {@link Config} object. The environment is created from the
* <code>application.env</code> property. If such property is missing, env's name must be:
* <code>dev</code>.
*
* @param config A config instance.
* @param router Application router.
* @param locale App locale.
* @return A new environment.
*/
Env build(Config config, Routes router, Locale locale);
}
/**
* Default builder.
*/
Env.Builder DEFAULT = (config, router, locale) -> {
requireNonNull(config, "Config required.");
String name = config.hasPath("application.env") ? config.getString("application.env") : "dev";
return new Env() {
private ImmutableList.Builder<CheckedConsumer<Registry>> start = ImmutableList.builder();
private ImmutableList.Builder<CheckedConsumer<Registry>> shutdown = ImmutableList.builder();
private Map<String, Function<String, String>> xss = new HashMap<>();
private ServiceKey key = new ServiceKey();
@Override
public String name() {
return name;
}
@Override
public ServiceKey serviceKey() {
return key;
}
@Override
public Routes routes() {
if (router == null) {
throw new UnsupportedOperationException();
}
return router;
}
@Override
public Config config() {
return config;
}
@Override
public Locale locale() {
return locale;
}
@Override
public String toString() {
return name();
}
@Override
public List<CheckedConsumer<Registry>> stopTasks() {
return shutdown.build();
}
@Override
public Env onStop(final CheckedConsumer<Registry> task) {
this.shutdown.add(task);
return this;
}
@Override
public Env onStart(final CheckedConsumer<Registry> task) {
this.start.add(task);
return this;
}
@Override
public List<CheckedConsumer<Registry>> startTasks() {
return this.start.build();
}
@Override
public Map<String, Function<String, String>> xss() {
return Collections.unmodifiableMap(xss);
}
@Override
public Env xss(final String name, final Function<String, String> escaper) {
xss.put(requireNonNull(name, "Name required."),
requireNonNull(escaper, "Function required."));
return this;
}
};
};
/**
* @return Env's name.
*/
String name();
/**
* Application router.
*
* @return Available {@link Routes}.
* @throws UnsupportedOperationException if router isn't available.
*/
Routes routes() throws UnsupportedOperationException;
/**
* @return environment properties.
*/
Config config();
/**
* @return Default locale from <code>application.lang</code>.
*/
Locale locale();
/**
* @return Utility method for generating keys for named services.
*/
default ServiceKey serviceKey() {
return new ServiceKey();
}
/**
* Returns a string with all substitutions (the <code>${foo.bar}</code> syntax,
* see <a href="https://github.com/typesafehub/config/blob/master/HOCON.md">the
* spec</a>) resolved. Substitutions are looked up using the {@link #config()} as the root object,
* that is, a substitution <code>${foo.bar}</code> will be replaced with
* the result of <code>getValue("foo.bar")</code>.
*
* @param text Text to process.
* @return A processed string.
*/
default String resolve(final String text) {
return resolve(text, config());
}
/**
* Returns a string with all substitutions (the <code>${foo.bar}</code> syntax,
* see <a href="https://github.com/typesafehub/config/blob/master/HOCON.md">the
* spec</a>) resolved. Substitutions are looked up using the {@link #config()} as the root object,
* that is, a substitution <code>${foo.bar}</code> will be replaced with
* the result of <code>getValue("foo.bar")</code>.
*
* @param text Text to process.
* @param startDelimiter Start delimiter.
* @param endDelimiter End delimiter.
* @return A processed string.
*/
default String resolve(final String text, final String startDelimiter,
final String endDelimiter) {
return resolve(text, config(), startDelimiter, endDelimiter);
}
/**
* Returns a string with all substitutions (the <code>${foo.bar}</code> syntax,
* see <a href="https://github.com/typesafehub/config/blob/master/HOCON.md">the
* spec</a>) resolved. Substitutions are looked up using the <code>source</code> param as the
* root object, that is, a substitution <code>${foo.bar}</code> will be replaced with
* the result of <code>getValue("foo.bar")</code>.
*
* @param text Text to process.
* @param source The source config to use.
* @return A processed string.
*/
default String resolve(final String text, final Config source) {
return resolve(text, source, "${", "}");
}
/**
* Returns a string with all substitutions (the <code>${foo.bar}</code> syntax,
* see <a href="https://github.com/typesafehub/config/blob/master/HOCON.md">the
* spec</a>) resolved. Substitutions are looked up using the <code>source</code> param as the
* root object, that is, a substitution <code>${foo.bar}</code> will be replaced with
* the result of <code>getValue("foo.bar")</code>.
*
* @param text Text to process.
* @param source The source config to use
* @param startDelimiter Start delimiter.
* @param endDelimiter End delimiter.
* @return A processed string.
*/
default String resolve(final String text, final Config source,
final String startDelimiter, final String endDelimiter) {
requireNonNull(text, "Text is required.");
requireNonNull(source, "Config source is required.");
checkArgument(!Strings.isNullOrEmpty(startDelimiter), "Start delimiter is required.");
checkArgument(!Strings.isNullOrEmpty(endDelimiter), "End delimiter is required.");
if (text.length() == 0) {
return "";
}
BiFunction<Integer, BiFunction<Integer, Integer, RuntimeException>, RuntimeException> err = (
start, ex) -> {
String snapshot = text.substring(0, start);
int line = Splitter.on('\n').splitToList(snapshot).size();
int column = start - snapshot.lastIndexOf('\n');
return ex.apply(line, column);
};
StringBuilder buffer = new StringBuilder();
int offset = 0;
int start = text.indexOf(startDelimiter);
while (start >= 0) {
int end = text.indexOf(endDelimiter, start + startDelimiter.length());
if (end == -1) {
throw err.apply(start, (line, column) -> new IllegalArgumentException(
"found '" + startDelimiter + "' expecting '" + endDelimiter + "' at " + line + ":"
+ column));
}
buffer.append(text.substring(offset, start));
String key = text.substring(start + startDelimiter.length(), end);
if (!source.hasPath(key)) {
throw err.apply(start, (line, column) -> new NoSuchElementException(
"No configuration setting found for key '" + key + "' at " + line + ":" + column));
}
buffer.append(source.getAnyRef(key));
offset = end + endDelimiter.length();
start = text.indexOf(startDelimiter, offset);
}
if (buffer.length() == 0) {
return text;
}
if (offset < text.length()) {
buffer.append(text.substring(offset));
}
return buffer.toString();
}
/**
* Runs the callback function if the current env matches the given name.
*
* @param name A name to test for.
* @param fn A callback function.
* @param <T> A resulting type.
* @return A resulting object.
*/
default <T> Optional<T> ifMode(final String name, final Supplier<T> fn) {
if (name().equals(name)) {
return Optional.of(fn.get());
}
return Optional.empty();
}
/**
* Produces a {@link API.Match} of the current {@link Env}.
*
* <pre>
* String accessKey = env.match()"dev", () {@literal ->} "1234")
* .when("stage", () {@literal ->} "4321")
* .when("prod", () {@literal ->} "abc")
* .get();
* </pre>
*
* @return A new matcher.
*/
default API.Match<String> match() {
return API.Match(name());
}
/**
* Produces a {@link API.Match} of the current {@link Env}.
*
* <pre>
* String accessKey = env.when("dev", () {@literal ->} "1234")
* .when("stage", () {@literal ->} "4321")
* .when("prod", () {@literal ->} "abc")
* .get();
* </pre>
*
* @param name A name to test for.
* @param fn A callback function.
* @param <T> A resulting type.
* @return A new matcher.
*/
default <T> Option<T> when(final String name, final Supplier<T> fn) {
return match().option(API.Case(API.$(name), fn));
}
/**
* Produces a {@link API.Match} of the current {@link Env}.
*
* <pre>
* String accessKey = env.when("dev", "1234")
* .when("stage", "4321")
* .when("prod", "abc")
* .get();
* </pre>
*
* @param name A name to test for.
* @param result A constant value to return.
* @param <T> A resulting type.
* @return A new matcher.
*/
default <T> Option<T> when(final String name, final T result) {
return match().option(API.Case(API.$(name), result));
}
/**
* Produces a {@link API.Match} of the current {@link Env}.
*
* <pre>
* String accessKey = env.when("dev", () {@literal ->} "1234")
* .when("stage", () {@literal ->} "4321")
* .when("prod", () {@literal ->} "abc")
* .get();
* </pre>
*
* @param predicate A predicate to use.
* @param result A constant value to return.
* @param <T> A resulting type.
* @return A new matcher.
*/
default <T> Option<T> when(final Predicate<String> predicate, final T result) {
return match().option(API.Case(predicate, result));
}
/**
* @return XSS escape functions.
*/
Map<String, Function<String, String>> xss();
/**
* Get or chain the required xss functions.
*
* @param xss XSS to combine.
* @return Chain of required xss functions.
*/
default Function<String, String> xss(final String... xss) {
Map<String, Function<String, String>> fn = xss();
BinaryOperator<Function<String, String>> reduce = Function::andThen;
return Arrays.asList(xss)
.stream()
.map(fn::get)
.filter(Objects::nonNull)
.reduce(Function.identity(), reduce);
}
/**
* Set/override a XSS escape function.
*
* @param name Escape's name.
* @param escaper Escape function.
* @return This environment.
*/
Env xss(String name, Function<String, String> escaper);
/**
* @return List of start tasks.
*/
List<CheckedConsumer<Registry>> startTasks();
/**
* @return List of stop tasks.
*/
List<CheckedConsumer<Registry>> stopTasks();
}