public boolean exists(final Predicate<Path> filter) { try (Stream<Path> walk = Try.apply(() -> Files.walk(root)).orElse(Stream.empty())) { return walk .skip(1) .anyMatch(filter); } }
/** * Decode a path by delegating to {@link URLDecoder#decode(String, String)}. * * @param path Path to decoded. * @return Decode a path by delegating to {@link URLDecoder#decode(String, String)}. */ static String decode(String path) { return Try.apply(() -> URLDecoder.decode(path, "UTF-8")).get(); }
static final Object strToObject(final String value) { if (value == null || !value.startsWith(PREFIX)) { return value; } return Try.apply(() -> { byte[] bytes = base64().decode(value.substring(PREFIX.length())); // TODO: sanitization of arguments return new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject(); }).get(); }
@Override public long getLastModified(final Path handle) { return Try.apply(() -> Files.getLastModifiedTime(handle).toMillis()).orElse(-1L); }
private static List<URI> expandPath(final ClassLoader loader, final String pattern) { List<URI> result = new ArrayList<>(); File file = new File(pattern); if (file.exists()) { result.add(file.toURI()); } Try.run(() -> Collections.list(loader.getResources(pattern)) .stream() .map(it -> Try.apply(it::toURI).get()) .forEach(result::add)); return result; }
public static final Object strToObject(final String value) { if (value == null || !value.startsWith(PREFIX)) { return value; } return Try.apply(() -> { byte[] bytes = BaseEncoding.base64().decode(value.substring(PREFIX.length())); // TODO: sanitization of arguments return new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject(); }) .wrap(x -> new IllegalArgumentException("Can't de-serialize value " + value, x)) .get(); }
static final String objToStr(final Object value) { if (value instanceof CharSequence || Primitives.isWrapperType(value.getClass())) { return value.toString(); } return PREFIX + Try.apply(() -> { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream stream = new ObjectOutputStream(bytes); stream.writeObject(value); stream.flush(); return base64().encode(bytes.toByteArray()); }).get(); } }
@Override public Locale locale(final BiFunction<List<LanguageRange>, List<Locale>, Locale> filter) { Supplier<Locale> def = () -> filter.apply(ImmutableList.of(), locales); // don't fail on bad Accept-Language header, just fallback to default locale. return lang.map(h -> Try.apply(() -> filter.apply(LocaleUtils.range(h), locales)).orElseGet(def)) .orElseGet(def); }
static Config dbconf(final String db, final Config conf) { Function<String, Config> ifconf = path -> { if (Try.apply(() -> conf.hasPath(path)).orElse(Boolean.FALSE)) { return conf.getConfig(path); } return ConfigFactory.empty(); }; // mongdo.db.* < mongo.* return ifconf.apply("mongo." + db) .withFallback(ifconf.apply("mongo")); }
private File extra(final List<Artifact> artifacts, final String name) { return Try.apply(() -> { for (Artifact artifact : artifacts) { for (String tail : artifact.getDependencyTrail()) { if (tail.contains(name)) { return artifact.getFile(); } } } throw new FileNotFoundException(name); }).get(); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Override public Object exec(final List arguments) throws TemplateModelException { List<String> args = (List<String>) arguments.stream() .map(it -> Try.apply(() -> ((TemplateScalarModel) it).getAsString()).get()) .collect(Collectors.toList()); String[] xss = args.subList(1, args.size()) .toArray(new String[arguments.size() - 1]); return env.xss(xss).apply(args.get(0)); }
private <T> Optional<T> get(final String name, final Function<String, T> provider) { return Try.apply(() -> Optional.of(register(v8, provider.apply(name)))) .orElse(Optional.empty()); }
private static Field field(final Object bean) { return Try.apply(() -> CACHE.getUnchecked(bean.getClass())) .unwrap(UncheckedExecutionException.class) .get(); }
/** * Prepare and startup a {@link Jooby} application. * * @param app Application supplier. * @param args Application arguments. */ public static void run(final Class<? extends Jooby> app, final String... args) { run(() -> Try.apply(() -> app.newInstance()).get(), args); }
private Map<String, Object> md(final Executable exec) { return Try.apply(() -> cache.getUnchecked(exec.getDeclaringClass())) .unwrap(UncheckedExecutionException.class) .get(); }
private Object value(final RequestParam param, final Request req, final Response rsp, final Route.Chain chain) throws Throwable { return Try.apply(() -> param.value(req, rsp, chain)) .recover(x -> recoverMissing.apply(x).get()) .get(); }
private CompletableFuture<Optional<Object>> send(final Event event) { List<MediaType> produces = event.type().<List<MediaType>>map(ImmutableList::of) .orElse(this.produces); SseRenderer ctx = new SseRenderer(renderers, produces, StandardCharsets.UTF_8, locale, locals); return Try.apply(() -> { byte[] bytes = ctx.format(event); return send(event.id(), bytes); }).recover(x -> { CompletableFuture<Optional<Object>> future = new CompletableFuture<>(); future.completeExceptionally(x); return future; }) .get(); }
@Override public void handle(final Request req, final Response rsp, final Chain chain) throws Throwable { Object input = supplier.apply(req, rsp, chain); Object output = Try .apply(() -> mapper.map(input)) .recover(ClassCastException.class, input) .get(); rsp.send(output); chain.next(req, rsp); }
@Override public void handle(final Request req, final Response rsp, final Err ex) throws Throwable { log.error("execution of: {}{} resulted in exception\nRoute:\n{}\n\nStacktrace:", req.method(), req.path(), req.route().print(6), ex); Config conf = req.require(Config.class); boolean stackstrace = Try.apply(() -> conf.getBoolean("err.stacktrace")) .orElse(req.require(Env.class).name().equals("dev")); rsp.send( Results .when(MediaType.html, () -> Results.html(VIEW).put("err", ex.toMap(stackstrace))) .when(MediaType.all, () -> ex.toMap(stackstrace))); }