@SuppressWarnings("rawtypes") static String locationOf(final Class clazz) { return Optional.ofNullable(clazz.getResource(clazz.getSimpleName() + ".class")) .map(url -> Try.apply(() -> { String path = url.getPath(); int i = path.indexOf("!"); if (i > 0) { // jar url String jar = path.substring(0, i); return jar.substring(Math.max(jar.lastIndexOf('/'), -1) + 1); } String cfile = clazz.getName().replace(".", "/") + ".class"; String relativePath = path.replace(cfile, ""); return new File(System.getProperty("user.dir")) .toPath() .relativize(Paths.get(relativePath).toFile().getCanonicalFile().toPath()) .toString(); }).orElse("~unknown")) .orElse("~unknown"); }
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); } }
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")); }
@SuppressWarnings("rawtypes") static String locationOf(final Class clazz) { return Optional.ofNullable(clazz.getResource(clazz.getSimpleName() + ".class")) .map(url -> Try.apply(() -> { String path = url.getPath(); int i = path.indexOf("!"); if (i > 0) { // jar url String jar = path.substring(0, i); return jar.substring(Math.max(jar.lastIndexOf('/'), -1) + 1); } String cfile = clazz.getName().replace(".", "/") + ".class"; String relativePath = path.replace(cfile, ""); return new File(System.getProperty("user.dir")) .toPath() .relativize(Paths.get(relativePath).toFile().getCanonicalFile().toPath()) .toString(); }).orElse("~unknown")) .orElse("~unknown"); }
@Override public void configure(final Env env, final Config conf, final Binder binder) { String name = conf.getString("application.name"); Logger log = LoggerFactory.getLogger(name); String v = conf.getString("application.version"); String text = this.text.orElse(name); Provider<String> ascii = () -> Try .apply(() -> CharMatcher.whitespace() .trimTrailingFrom(convertOneLine(String.format(FONT, font), text))) .orElse(text); binder.bind(Key.get(String.class, Names.named("application.banner"))).toProvider(ascii); env.onStart(() -> { log.info("\n{} v{}\n", ascii.get(), v); }); }
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")); }
@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))); }
buckets.forEach(n -> Try.apply(() -> r.require(n, Bucket.class).close()) .onFailure(x -> log.debug("bucket {} close operation resulted in exception", n, x)) .orElse(false)); Try.run(cluster::disconnect) .onFailure(x -> log.debug("disconnect operation resulted in exception", x));
.orElse(System.getProperty("java.io.tmpdir")));
routeResponse.status(ImmutableMap.of(status, Try.apply(() -> Status.valueOf(status.intValue()).reason()) .orElse(status.toString())));
private void onChange(final Kind<?> kind, final Path path) { File outputdir = workdir.toFile(); String filename = Route .normalize(Try.apply(() -> path.subpath(1, path.getNameCount()).toString()) .orElse(path.toString())); try { if (kind == StandardWatchEventKinds.ENTRY_DELETE) { errors.remove(filename); } else { if (Files.isDirectory(path)) { errors.clear(); compiler.build("dev", outputdir); } else { compiler.buildOne(filename, outputdir); errors.remove(filename); } } } catch (AssetException ex) { String localname = ex.getProblems().stream() .findFirst() .map(AssetProblem::getFilename) .orElse(filename); errors.put(localname, rewrite(ex)); } catch (Exception ex) { AssetException assetEx = rewrite(new AssetException("compiler", new AssetProblem(filename, -1, -1, ex.getMessage(), null), ex)); errors.put(filename, assetEx); } }
}).orElse(new Source(Paths.get(filename), Collections.emptyList()));
@Override public <T> Observable<List<T>> query(final N1qlQuery query) { return bucket.query(query) .flatMap(aqr -> Observable.zip(aqr.rows().toList(), aqr.errors().toList(), aqr.finalSuccess().singleOrDefault(Boolean.FALSE), (rows, errors, finalSuccess) -> { if (!finalSuccess) { throw new QueryExecutionException( "execution of query resulted in exception: ", Try.apply(() -> errors.get(0)).orElse(null)); } List<T> value = new ArrayList<>(); for (AsyncN1qlQueryRow row : rows) { try { T v = converter.fromBytes(row.byteValue()); value.add(v); } catch (IOException ex) { throw new QueryExecutionException( "execution of query resulted in exception", null, ex); } } return value; })); }
@Override public void configure(final Env env, final Config conf, final Binder binder) { Config $base = flyway(conf.getConfig("flyway")); Config $flyway = Try.apply(() -> flyway(conf.getConfig(name)).withFallback($base)) .orElse($base); Flyway flyway = new Flyway(); Properties props = props($flyway); flyway.configure(props); if (!props.containsKey("flyway.url")) { Key<DataSource> dskey = Key.get(DataSource.class, Names.named(name)); DataSource dataSource = env.get(dskey) .orElseThrow(() -> new NoSuchElementException("DataSource missing: " + dskey)); flyway.setDataSource(dataSource); } // bind env.serviceKey() .generate(Flyway.class, name, key -> binder.bind(key).toInstance(flyway)); // commands: Iterable<Command> cmds = commands(conf); // eager initialization cmds.forEach(cmd -> cmd.run(flyway)); }
private Integer statusCodeFor(MethodInsnNode node) { if (node.name.equals("noContent")) { return 204; } if (node.name.equals("with")) { AbstractInsnNode previous = node.getPrevious(); if (previous instanceof IntInsnNode) { return ((IntInsnNode) previous).operand; } if (previous instanceof FieldInsnNode) { String owner = ((FieldInsnNode) previous).owner.replace("/", "."); if (owner.equals(Status.class.getName())) { String statusName = ((FieldInsnNode) previous).name; return Try.apply(() -> Status.class.getDeclaredField(statusName).get(null)) .map(it -> ((Status) it).value()) .orElse(null); } } } return null; }
@Override public void configure(final Env env, final Config conf, final Binder binder) { String name = conf.getString("application.name"); Logger log = LoggerFactory.getLogger(name); String v = conf.getString("application.version"); String text = this.text.orElse(name); Provider<String> ascii = () -> Try .apply(() -> CharMatcher.whitespace() .trimTrailingFrom(convertOneLine(String.format(FONT, font), text))) .orElse(text); binder.bind(Key.get(String.class, Names.named("application.banner"))).toProvider(ascii); env.onStart(() -> { log.info("\n{} v{}\n", ascii.get(), v); }); }
private Class type(final String cname, final Class deftype) { return Try.apply(() -> getClass().getClassLoader().loadClass(cname)).orElse(deftype); }
@Override public long getLastModified(final Path handle) { return Try.apply(() -> Files.getLastModifiedTime(handle).toMillis()).orElse(-1L); }
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()); }
@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))); }