private ClassNode loadClass(String name) { return Try.apply(() -> { String cname = name.replace("/", "."); ClassNode node = cache.get(cname); if (node == null) { String rname = cname.replace(".", "/") + ".class"; try (InputStream in = loader.getResourceAsStream(rname)) { if (in == null) { throw new FileNotFoundException(rname + " using " + loader); } ClassReader reader = new ClassReader(ByteStreams.toByteArray(in)); node = new ClassNode(); reader.accept(node, 0); cache.put(cname, node); if (log.isDebugEnabled()) { log.info("Source: {}; Class: {}", node.sourceFile, node.name); reader.accept( new TraceClassVisitor(null, new ASMifier(), new PrintWriter(writer(log, name))), 0); } } } return node; }).get(); }
public static List<CrashFSDriver> parse(final ClassLoader loader, final List<CrashPredicate> paths) { List<CrashFSDriver> drivers = new ArrayList<>(); boolean loginFound = false; for (CrashPredicate path : paths) { for (URI uri : expandPath(loader, path.name)) { // classpath first CrashFSDriver driver = Try .apply(() -> FileSystems.newFileSystem(uri, Collections.emptyMap())) .map(it -> Try.apply(() -> new CrashFSDriver(uri, it, path)).get()) // file system fallback .recover(x -> Try.apply(() -> new CrashFSDriver(uri, Paths.get(uri), path)).get()) .get(); // HACK to make sure login.groovy takes precedence over default one driver.log.debug("driver created: {}", driver); if (loginFound) { driver.filter = FLOGIN.negate().and(driver.filter); } else if (driver.exists(FLOGIN)) { driver.log.debug(" login.groovy found: {}", driver); loginFound = true; } drivers.add(driver); } } return drivers; }
Provider<Sse> sse = () -> Try.apply(() -> request.upgrade(Sse.class)).get(); scope.put(SSE, sse);
.orElseGet(() -> new ConnectionString(conf.getString(db)));
routeResponse.status(ImmutableMap.of(status, Try.apply(() -> Status.valueOf(status.intValue()).reason()) .orElse(status.toString())));
public void configure(final Env env, final Config conf, final Binder binder) { ConnectionString cstr = Try.apply(() -> ConnectionString.parse(db)) .orElseGet(() -> ConnectionString.parse(conf.getString(db)));
}).orElse(new Source(Paths.get(filename), Collections.emptyList()));
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); } }
private ClassNode loadClass(String name) { return Try.apply(() -> { String cname = name.replace("/", "."); ClassNode node = cache.get(cname); if (node == null) { String rname = cname.replace(".", "/") + ".class"; try (InputStream in = loader.getResourceAsStream(rname)) { if (in == null) { throw new FileNotFoundException(rname + " using " + loader); } ClassReader reader = new ClassReader(ByteStreams.toByteArray(in)); node = new ClassNode(); reader.accept(node, 0); cache.put(cname, node); if (log.isDebugEnabled()) { log.info("Source: {}; Class: {}", node.sourceFile, node.name); reader.accept( new TraceClassVisitor(null, new ASMifier(), new PrintWriter(writer(log, name))), 0); } } } return node; }).get(); }
@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)); }
@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"); }
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; }
@SuppressWarnings("unchecked") public static Class<? extends CommonProfile> typeOf(final Class<?> client) { Type genericType = client.getGenericSuperclass(); if (genericType instanceof ParameterizedType) { Type[] types = ((ParameterizedType) genericType).getActualTypeArguments(); for (Type type : types) { if (type instanceof Class) { if (CommonProfile.class.isAssignableFrom((Class<?>) type)) { return (Class<? extends CommonProfile>) type; } } } } if (client.getSimpleName().equals("OidcClient")) { return Try.apply(() -> (Class<? extends CommonProfile>) client.getClassLoader() .loadClass("org.pac4j.oidc.profile.OidcProfile")).get(); } return CommonProfile.class; }
/** * Flat map the success value. * * @param mapper Mapper. * @param <T> New type. * @return A new try value for success or failure. */ public <T> Value<T> flatMap(Throwing.Function<V, Value<T>> mapper) { if (isFailure()) { return (Value<T>) this; } try { return mapper.apply(get()); } catch (Throwable x) { return new Failure<>(x); } }
@Override public SSLContext get() { return Try.apply(() -> { String tmpdir = conf.getString("application.tmpdir"); File keyStoreCert = toFile(conf.getString("ssl.keystore.cert"), tmpdir); File keyStoreKey = toFile(conf.getString("ssl.keystore.key"), tmpdir); String keyStorePass = conf.hasPath("ssl.keystore.password") ? conf.getString("ssl.keystore.password") : null; File trustCert = conf.hasPath("ssl.trust.cert") ? toFile(conf.getString("ssl.trust.cert"), tmpdir) : null; return SslContext .newServerContextInternal(trustCert, keyStoreCert, keyStoreKey, keyStorePass, conf.getLong("ssl.session.cacheSize"), conf.getLong("ssl.session.timeout")) .context(); }).get(); }
@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); }); }
/** * Always run the given action, works like a finally clause. Exception and value might be null. * Exception will be null in case of success. * * @param action Finally action. * @return This try result. */ public Value<V> onComplete(final Throwing.Consumer2<V, Throwable> action) { try { V value = isSuccess() ? get() : null; action.accept(value, getCause().orElse(null)); return this; } catch (Throwable x) { return (Value<V>) failure(x); } }
/** * Parse value as {@link Duration}. If the value is already a number then it uses as seconds. * Otherwise, it parse expressions like: 8m, 1h, 365d, etc... * * @param maxAge Set the cache header max-age value in seconds. * @return This handler. */ public AssetHandler maxAge(final String maxAge) { Try.apply(() -> Long.parseLong(maxAge)) .recover(x -> ConfigFactory.empty() .withValue("v", ConfigValueFactory.fromAnyRef(maxAge)) .getDuration("v") .getSeconds()) .onSuccess(this::maxAge); return this; }
public static final String objToStr(final Object value) { if (value instanceof CharSequence || Primitives.isWrapperType(value.getClass())) { return value.toString(); } return Try.apply(() -> { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream stream = new ObjectOutputStream(bytes); stream.writeObject(value); stream.flush(); return PREFIX + BaseEncoding.base64().encode(bytes.toByteArray()); }) .wrap(x -> new IllegalArgumentException("Can't serialize value " + value, x)) .get(); }