org.jooby.Env类的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(12.4k)|赞(0)|评价(0)|浏览(125)

本文整理了Java中org.jooby.Env类的一些代码示例,展示了Env类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Env类的具体详情如下:
包路径:org.jooby.Env
类名称:Env

Env介绍

[英]Allows to optimize, customize or apply defaults values for application services.

A env is represented by it's name. For example: dev, prod, etc... A dev env is special and a module provider could do some special configuration for development, like turning off a cache, reloading of resources, etc.

Same is true for not dev environments. For example, a module provider might create a high performance connection pool, caches, etc.

By default env is set to dev, but you can change it by setting the application.env property to anything else.
[中]允许优化、自定义或应用应用程序服务的默认值。
环境由其名称表示。例如:devprod等。。。dev env是特殊的,模块提供者可以为开发做一些特殊的配置,比如关闭缓存、重新加载资源等等。
对于非开发环境也是如此。例如,模块提供程序可能会创建高性能连接池、缓存等。
默认情况下,env设置为dev,但您可以通过将application.env属性设置为任何其他属性来更改它。

代码示例

代码示例来源:origin: jooby-project/jooby

DataSource ds = env.get(dskey)
  .orElseThrow(() -> new NoSuchElementException("DataSource missing: " + dskey));
env.onStart(ebean::start);
env.onStop(ebean::stop);
ServiceKey keys = env.serviceKey();
keys.generate(EbeanServer.class, name, provider);
env.onStart(runEnhancer());

代码示例来源:origin: jooby-project/jooby

@Override
public void configure(final Env env, final Config conf, final Binder binder) {
 // empty metric & checks
 MapBinder.newMapBinder(binder, String.class, Metric.class);
 MapBinder.newMapBinder(binder, String.class, HealthCheck.class);
 Router routes = env.router();
 MetricHandler mhandler = new MetricHandler();
 routes.use("GET", this.pattern + "/metrics", mhandler);
 routes.use("GET", this.pattern + "/metrics/:type", mhandler);
 routes.use("GET", this.pattern + "/healthcheck", new HealthCheckHandler());
 Multibinder<Reporter> reporters = Multibinder.newSetBinder(binder, Reporter.class);
 binder.bind(MetricRegistry.class).toInstance(metricRegistry);
 this.reporters.forEach(it -> reporters.addBinding().toInstance(it.apply(metricRegistry, conf)));
 binder.bind(MetricRegistryInitializer.class).asEagerSingleton();
 env.onStop(app -> app.require(MetricRegistryInitializer.class).close());
 binder.bind(HealthCheckRegistry.class).toInstance(healthCheckRegistry);
 binder.bind(HealthCheckRegistryInitializer.class).asEagerSingleton();
 bindings.forEach(it -> it.bind(binder, routes, conf));
 this.routes.forEach(it -> it.accept(routes));
}

代码示例来源:origin: jooby-project/jooby

@Override
public void configure(final Env env, final Config conf, final Binder binder) {
 boolean whoops = conf.hasPath("whoops.enabled")
   ? conf.getBoolean("whoops.enabled")
   : "dev".equals(env.name());
 if (whoops) {
  ClassLoader loader = env.router().getClass().getClassLoader();
  Handler handler = prettyPage(loader, SourceLocator.local(), maxFrameSize, log);
  env.router().err(tryPage(handler, log));
 }
}

代码示例来源:origin: jooby-project/jooby

@Override
 public void configure(final Env env, final Config config, final Binder binder) {
  Key<DataSource> dskey = Key.get(DataSource.class, Names.named(name));
  DataSource ds = env.get(dskey)
    .orElseThrow(() -> new NoSuchElementException("DataSource missing: " + dskey));
  Database db = Database.fromDataSource(ds);

  env.serviceKey().generate(Database.class, name, k -> binder.bind(k).toInstance(db));

  // close on shutdown
  env.onStop(db::close);
 }
}

代码示例来源:origin: jooby-project/jooby

private static List<Object> processEnvDep(final Set<Object> src, final Env env) {
 List<Object> result = new ArrayList<>();
 List<Object> bag = new ArrayList<>(src);
 bag.forEach(it -> {
  if (it instanceof EnvDep) {
   EnvDep envdep = (EnvDep) it;
   if (envdep.predicate.test(env.name())) {
    int from = src.size();
    envdep.callback.accept(env.config());
    int to = src.size();
    result.addAll(new ArrayList<>(src).subList(from, to));
   }
  } else {
   result.add(it);
  }
 });
 return result;
}

代码示例来源:origin: jooby-project/jooby

@SuppressWarnings({"unchecked", "rawtypes" })
@Override
public void configure(final Env env, final Config conf, final Binder binder) throws Throwable {
 String db = database(conf, this.db);
 Properties props = props(neo4j(conf, this.db));
 ServiceKey keys = env.serviceKey();
 IDBAccess dbaccess = dbaccess(conf, this.db, db, props, keys, binder);
 Arrays.asList(props.getProperty(SERVER_ROOT_URI), props.getProperty(DATABASE_DIR))
   .stream()
   .filter(Objects::nonNull)
   .findFirst()
   .ifPresent(it -> log.info("Starting neo4j: {}", it));
 Class dbaccessType = dbaccess.getClass();
 keys.generate(IDBAccess.class, this.db, k -> binder.bind(k).toInstance(dbaccess));
 keys.generate(dbaccessType, this.db, k -> binder.bind(k).toInstance(dbaccess));
 env.onStop(dbaccess::close);
}

代码示例来源:origin: jooby-project/jooby

@Override
public void configure(final Env env, final Config conf, final Binder binder) {
 Key<DataSource> dskey = Key.get(DataSource.class, Names.named(name));
 DataSource ds = env.get(dskey)
   .orElseThrow(() -> new NoSuchElementException("DataSource missing: " + dskey));
 String dbtype = env.get(Key.get(String.class, Names.named(name + ".dbtype")))
   .orElse("unknown");
 SQLTemplates templates = this.templates.apply(dbtype);
 Configuration querydslconf = new Configuration(templates);
 if (callback != null) {
  callback.accept(querydslconf, conf);
 }
 SQLQueryFactory sqfp = new SQLQueryFactory(querydslconf, ds);
 ServiceKey serviceKey = env.serviceKey();
 serviceKey.generate(SQLTemplates.class, name, k -> binder.bind(k).toInstance(templates));
 serviceKey.generate(Configuration.class, name, k -> binder.bind(k).toInstance(querydslconf));
 serviceKey.generate(SQLQueryFactory.class, name, k -> binder.bind(k).toInstance(sqfp));
}

代码示例来源:origin: jooby-project/jooby

@Override
public void configure(final Env env, final Config config, final Binder binder) {
 /**
  * Pool
  */
 GenericObjectPoolConfig poolConfig = poolConfig(config, name);
 int timeout = (int) config.getDuration("jedis.timeout", TimeUnit.MILLISECONDS);
 URI uri = URI.create(config.getString(name));
 JedisPool pool = new JedisPool(poolConfig, uri, timeout);
 RedisProvider provider = new RedisProvider(pool, uri, poolConfig);
 env.onStart(provider::start);
 env.onStop(provider::stop);
 Provider<Jedis> jedis = (Provider<Jedis>) () -> pool.getResource();
 ServiceKey serviceKey = env.serviceKey();
 serviceKey.generate(JedisPool.class, name, k -> binder.bind(k).toInstance(pool));
 serviceKey.generate(Jedis.class, name,
   k -> binder.bind(k).toProvider(jedis));
}

代码示例来源:origin: jooby-project/jooby

.filter(it -> !env.get(Key.get(DataSource.class, Names.named(it))).isPresent())
  .collect(Collectors.toSet());
if (names.size() == 0) {
names.forEach(it -> env.serviceKey().generate(DataSource.class, it, k -> {
   binder.bind(k).toInstance(ds);
   env.set(k, ds);
   dskeys.add(k);
  })
env.set(Key.get(String.class, Names.named(dbkey + ".url")), url);
env.set(Key.get(String.class, Names.named(dbkey + ".dbtype")), dbtype.orElse("unknown"));
env.onStarted(() -> dskeys.forEach(env::unset));
env.onStop(ds::close);

代码示例来源:origin: jooby-project/jooby

env.onStop(consul::destroy);
env.serviceKey().generate(Consul.class, name, k -> binder.bind(k).toInstance(consul));
  env.router().get(checkConfig.getString("path"), () -> response);
 env.onStarted(() -> agentClient.register(registration));
 env.onStop(() -> agentClient.deregister(registration.getId()));

代码示例来源:origin: jooby-project/jooby

@Override public void configure(Env env, Config conf, Binder binder) {
  EventBus eventbus = factory.apply(conf);
  binder.bind(EventBus.class).toInstance(eventbus);

  List<Object> subscribers = new ArrayList<>(initialSubscribers.size());
  /** Register subscribers: */
  env.onStart(registry -> {
   initialSubscribers.forEach(candidate -> {
      Object subscriber = candidate;
      if (subscriber instanceof Class) {
       subscriber = registry.require((Class) subscriber);
      }
      subscribers.add(subscriber);
      eventbus.register(subscriber);
     }
   );
   // free initial subscribers
   initialSubscribers.clear();
  });
  /** Unregister subscribers: */
  env.onStop(() -> subscribers.forEach(eventbus::unregister));
 }
}

代码示例来源:origin: jooby-project/jooby

@Override public void configure(Env env, Config conf, Binder binder) throws Throwable {
 Key<DataSource> dskey = Key.get(DataSource.class, Names.named(name));
 DataSource dataSource = env.get(dskey)
   .orElseThrow(() -> new NoSuchElementException("DataSource missing: " + dskey));
 Jdbi jdbi = Jdbi.create(dataSource);
  callback.accept(jdbi, conf);
 env.serviceKey().generate(Jdbi.class, name, key -> binder.bind(key).toInstance(jdbi));
    .in(RequestScoped.class);
  AtomicReference<Registry> registry = new AtomicReference<>();
  env.onStart(registry::set);
  });
  env.router()
    .use(it.method(), it.pattern(), new OpenHandle(jdbi, it))
    .name("transactionPerRequest");

代码示例来源:origin: jooby-project/jooby

@Inject
public FileMonitor(final Injector injector, final Env env,
  final WatchService watcher, final Set<FileEventOptions> optionList) {
 this.injector = injector;
 this.watcher = watcher;
 this.optionList = optionList;
 // start monitor:
 ExecutorService monitor = Executors.newSingleThreadExecutor(task -> {
  Thread thread = new Thread(task, "file-watcher");
  thread.setDaemon(true);
  return thread;
 });
 env.onStop(monitor::shutdown);
 monitor.execute(this);
}

代码示例来源:origin: jooby-project/jooby

@Override
public void configure(final Env env, final Config config, final Binder binder) throws Throwable {
 String envname = env.name();
 boolean dev = "dev".equals(envname);
 ClassLoader loader = getClass().getClassLoader();
 AssetCompiler compiler = new AssetCompiler(assetClassLoader, conf);
 Router routes = env.router();
 List<String> dist = dev ? ImmutableList.of("dev") : ImmutableList.of(envname, "dist");
 String prefix = dist.stream()
   compiler.setProgressBar(progressBar);
   Future<Map<String, List<File>>> future = liveCompiler.sync();
   env.onStarted(() -> {
    Logger log = LoggerFactory.getLogger(AssetCompiler.class);
    if (!future.isDone()) {
  } else {
   env.onStarted(liveCompiler::watch);
  env.onStop(liveCompiler::stop);
 } else {
  handler = new AssetHandler("/");
 env.onStop(compiler::stop);

代码示例来源:origin: jooby-project/jooby

.orElseGet(() -> ConnectionString.parse(conf.getString(db)));
ServiceKey serviceKey = env.serviceKey();
});
env.router()
  .map(new CassandraMapper());
env.onStop(() -> {
 log.debug("Stopping {}", cstr);
 Try.run(session::close)

代码示例来源:origin: jooby-project/jooby

@Override
public void configure(final Env env, final Config conf, final Binder binder) {
 Key<DataSource> dskey = Key.get(DataSource.class, Names.named(name));
 DataSource dataSource = env.get(dskey)
   .orElseThrow(() -> new NoSuchElementException("DataSource missing: " + dskey));
 Object newStore = store.apply(configuration);
 ServiceKey keys = env.serviceKey();
 Consumer bind = k -> binder.bind((Key) k).toInstance(newStore);
 keys.generate(storeType, model.getName(), bind);
 env.onStart(registry -> {
  schema(conf, schema, schema -> new SchemaModifier(dataSource, model).createTables(schema));
  states

代码示例来源:origin: jooby-project/jooby

@Override
public void configure(final Env env, final Config conf, final Binder binder) {
 String baseurl = this.baseurl.orElseGet(() -> {
  if (conf.hasPath(SITEMAP_BASEURL)) {
   return conf.getString(SITEMAP_BASEURL);
  } else {
   Config $ = conf.getConfig("application");
   return "http://" + $.getString("host") + ":" + $.getString("port") + $.getString("path");
  }
 });
 wpp.accept(binder);
 env.router().get(path, new SitemapHandler(path, NOT_ME.and(filter), gen(baseurl)));
}

代码示例来源:origin: jooby-project/jooby

@Override
public void configure(final Env env, final Config conf, final Binder binder) {
 configure(env, conf, binder, (uri, client) -> {
  String db = uri.getDatabase();
  Mapper mapper = new Mapper();
  Morphia morphia = new Morphia(mapper);
  if (this.morphiaCbck != null) {
   this.morphiaCbck.accept(morphia, conf);
  }
  Datastore datastore = morphia.createDatastore(client, mapper, db);
  if (gen != null) {
   mapper.addInterceptor(new AutoIncID(datastore, gen));
  }
  if (callback != null) {
   callback.accept(datastore);
  }
  ServiceKey serviceKey = env.serviceKey();
  serviceKey.generate(Morphia.class, db,
    k -> binder.bind(k).toInstance(morphia));
  serviceKey.generate(Datastore.class, db,
    k -> binder.bind(k).toInstance(datastore));
  env.onStart(registry -> new GuiceObjectFactory(registry, morphia));
 });
}

代码示例来源:origin: jooby-project/jooby

/**
 * 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.
 */
@Nonnull
default <T> Optional<T> ifMode(final String name, final Supplier<T> fn) {
 if (name().equals(name)) {
  return Optional.of(fn.get());
 }
 return Optional.empty();
}

代码示例来源:origin: jooby-project/jooby

@Override
public void configure(@Nonnull final Env env, @Nonnull final Config conf, @Nonnull final Binder binder) {
 ActorSystem sys = ActorSystem.create(name, conf);
 env.serviceKey().generate(ActorSystem.class, name, syskey -> binder.bind(syskey).toInstance(sys));
}

相关文章