com.networknt.config.Config类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(12.7k)|赞(0)|评价(0)|浏览(300)

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

Config介绍

[英]A injectable singleton config that has default implementation based on FileSystem json files. It can be extended to other sources (database, distributed cache etc.) by providing another jar in the classpath to replace the default implementation.

Config files are loaded in the following sequence: 1. resource/config folder for the default 2. externalized directory specified by light-4j-config-dir

In docker, the config files should be in volume and any update will be picked up the next day morning.
[中]可注入的单例配置,具有基于文件系统json文件的默认实现。通过在类路径中提供另一个jar来替换默认实现,可以将其扩展到其他源(数据库、分布式缓存等)。
配置文件按以下顺序加载:1。默认2的资源/配置文件夹。light-4j-config-dir指定的外部化目录
在docker中,配置文件应该在卷中,任何更新都将在第二天早上获取。

代码示例

代码示例来源:origin: networknt/light-4j

private static TokenResponse handleResponse(String responseBody) {
  TokenResponse tokenResponse = null;
  try {
    if (responseBody != null && responseBody.length() > 0) {
      tokenResponse = Config.getInstance().getMapper().readValue(responseBody, TokenResponse.class);
    } else {
      logger.error("Error in token retrieval, response = " + responseBody);
    }
  } catch (IOException | RuntimeException e) {
    logger.error("Error in token retrieval", e);
  }
  return tokenResponse;
}

代码示例来源:origin: networknt/light-4j

@Override
  public void register() {
    ModuleRegistry.registerModule(LimitHandler.class.getName(), Config.getInstance().getJsonMapConfigNoCache(CONFIG_NAME), null);
  }
}

代码示例来源:origin: networknt/light-4j

private static KeyStore loadKeyStore() {
  String name = config.getKeystoreName();
  try (InputStream stream = Config.getInstance().getInputStreamFromFile(name)) {
    KeyStore loadedKeystore = KeyStore.getInstance("JKS");
    loadedKeystore.load(stream, ((String) secret.get(SecretConstants.SERVER_KEYSTORE_PASS)).toCharArray());
    return loadedKeystore;
  } catch (Exception e) {
    logger.error("Unable to load keystore " + name, e);
    throw new RuntimeException("Unable to load keystore " + name, e);
  }
}

代码示例来源:origin: networknt/light-4j

public KeyRequest(String kid) {
  Map<String, Object> clientConfig = Config.getInstance().getJsonMapConfig(Http2Client.CONFIG_NAME);
  // client_secret is in secret.yml instead of client.yml
  if(clientConfig != null) {
    Map<String, Object> oauthConfig = (Map<String, Object>)clientConfig.get(OAUTH);
    if(oauthConfig != null) {
      Map<String, Object> keyConfig = (Map<String, Object>)oauthConfig.get(KEY);
      if(keyConfig != null) {
        setServerUrl((String)keyConfig.get(SERVER_URL));
        Object object = keyConfig.get(ENABLE_HTTP2);
        setEnableHttp2(object != null && (Boolean) object);
        setUri(keyConfig.get(URI) + "/" + kid);
        setClientId((String)keyConfig.get(CLIENT_ID));
        setClientSecret((String)secret.get(SecretConstants.KEY_CLIENT_SECRET));
      }
    }
  }
}

代码示例来源:origin: networknt/light-4j

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
  ServerInfoConfig config = (ServerInfoConfig)Config.getInstance().getJsonObjectConfig(CONFIG_NAME, ServerInfoConfig.class);
  if(config.isEnableServerInfo()) {
    Map<String, Object> infoMap = new LinkedHashMap<>();
    infoMap.put("deployment", getDeployment());
    infoMap.put("environment", getEnvironment(exchange));
    infoMap.put("security", getSecurity());
    infoMap.put("specification", Config.getInstance().getJsonMapConfigNoCache("swagger"));
    infoMap.put("component", ModuleRegistry.getRegistry());
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(infoMap));
  } else {
    setExchangeStatus(exchange, STATUS_SERVER_INFO_DISABLED);
  }
}

代码示例来源:origin: networknt/light-4j

static void setConfig(String configName) throws Exception {
    Handler.configName = configName;
    config = (HandlerConfig) Config.getInstance().getJsonObjectConfig(configName, HandlerConfig.class);
    initHandlers();
    initPaths();
  }
}

代码示例来源:origin: networknt/light-4j

/**
   * We can get it from server module but we don't want mutual dependency. So
   * get it from config and keystore directly
   *
   * @return String TLS server certificate finger print
   */
  private String getServerTlsFingerPrint() {
    String fingerPrint = null;
    Map<String, Object> serverConfig = Config.getInstance().getJsonMapConfigNoCache("server");
    Map<String, Object> secretConfig = Config.getInstance().getJsonMapConfigNoCache("secret");
    // load keystore here based on server config and secret config
    String keystoreName = (String)serverConfig.get("keystoreName");
    String serverKeystorePass = (String)secretConfig.get("serverKeystorePass");
    if(keystoreName != null) {
      try (InputStream stream = Config.getInstance().getInputStreamFromFile(keystoreName)) {
        KeyStore loadedKeystore = KeyStore.getInstance("JKS");
        loadedKeystore.load(stream, serverKeystorePass.toCharArray());
        X509Certificate cert = (X509Certificate)loadedKeystore.getCertificate("server");
        if(cert != null) {
          fingerPrint = FingerPrintUtil.getCertFingerPrint(cert);
        } else {
          logger.error("Unable to find the certificate with alias name as server in the keystore");
        }
      } catch (Exception e) {
        logger.error("Unable to load server keystore ", e);
      }
    }
    return fingerPrint;
  }
}

代码示例来源:origin: networknt/light-oauth2

if(logger.isDebugEnabled()) logger.debug("keyId = " + keyId);
Map<String, Object> config = Config.getInstance().getJsonMapConfig(CONFIG_SECURITY);
Map<String, Object> jwtConfig = (Map<String, Object>)config.get(CONFIG_JWT);
Map<String, Object> certificateConfig = (Map<String, Object>)jwtConfig.get(CONFIG_CERTIFICATE);
    String content = Config.getInstance().getStringFromFile(filename);
    if(logger.isDebugEnabled()) logger.debug("certificate = " + content);
    if(content != null) {

代码示例来源:origin: networknt/light-example-4j

@Override
  public GraphQLSchema getSchema() {
    Config config = Config.getInstance();
    TypeDefinitionRegistry typeDefinitionRegistry = new SchemaParser().parse(config.getStringFromFile("subscription-schema.graphqls"));
    RuntimeWiring wiring = buildRuntimeWiring();
    return new SchemaGenerator().makeExecutableSchema(typeDefinitionRegistry, wiring);
  }
}

代码示例来源:origin: networknt/light-4j

public DerefRequest(String token) {
  Map<String, Object> clientConfig = Config.getInstance().getJsonMapConfig(Http2Client.CONFIG_NAME);
  // client_secret is in secret.yml instead of client.yml
  if(clientConfig != null) {
    Map<String, Object> oauthConfig = (Map<String, Object>)clientConfig.get(OAUTH);
    if(oauthConfig != null) {
      Map<String, Object> derefConfig = (Map<String, Object>)oauthConfig.get(DEREF);
      if(derefConfig != null) {
        setServerUrl((String)derefConfig.get(SERVER_URL));
        Object object = derefConfig.get(ENABLE_HTTP2);
        setEnableHttp2(object != null && (Boolean) object);
        setUri(derefConfig.get(URI) + "/" + token);
        setClientId((String)derefConfig.get(CLIENT_ID));
        setClientSecret((String)secret.get(SecretConstants.DEREF_CLIENT_SECRET));
      }
    }
  }
}

代码示例来源:origin: networknt/light-4j

public VirtualHostHandler() {
  VirtualHostConfig config = (VirtualHostConfig)Config.getInstance().getJsonObjectConfig(VirtualHostConfig.CONFIG_NAME, VirtualHostConfig.class);
  virtualHostHandler = new NameVirtualHostHandler();
  for(VirtualHost host: config.hosts) {
    virtualHostHandler.addHost(host.domain, new PathHandler().addPrefixPath(host.getPath(), new ResourceHandler((new PathResourceManager(Paths.get(host.getBase()), host.getTransferMinSize()))).setDirectoryListingEnabled(host.isDirectoryListingEnabled())));
  }
}

代码示例来源:origin: networknt/light-4j

@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
  exchange.getResponseHeaders().put(
      Headers.CONTENT_TYPE, "application/json");
  Map<String, Object> resMap = new HashMap<>();
  resMap.put("access_token", JwtIssuer.getJwt(mockClaims()));
  resMap.put("token_type", "bearer");
  resMap.put("expires_in", 600);
  exchange.getResponseSender().send(ByteBuffer.wrap(
      Config.getInstance().getMapper().writeValueAsBytes(
          resMap)));
}

代码示例来源:origin: networknt/light-4j

@Override
public void register() {
  ModuleRegistry.registerModule(MetricsHandler.class.getName(), Config.getInstance().getJsonMapConfigNoCache(CONFIG_NAME), null);
}

代码示例来源:origin: networknt/light-4j

protected HikariDataSource createDataSource() {
  // get the configured datasources
  Map<String, Object> dataSourceMap = Config.getInstance().getJsonMapConfig(DATASOURCE);
  // get the decrypted secret file
  Map<String, Object> secret = DecryptUtil.decryptMap(Config.getInstance().getJsonMapConfig(SECRET));
  // get the requested datasource
  Map<String, Object> mainParams = (Map<String, Object>) dataSourceMap.get(getDsName());
  Map<String, String> configParams = (Map<String, String>)mainParams.get("parameters");
  // create the DataSource
  ds = new HikariDataSource();
  ds.setJdbcUrl((String)mainParams.get("jdbcUrl"));
  ds.setUsername((String)mainParams.get("username"));
  // use encrypted password
  ds.setPassword((String)secret.get(getDbPassKey()));
  // set datasource paramters
  ds.setMaximumPoolSize((Integer)mainParams.get("maximumPoolSize"));
  ds.setConnectionTimeout((Integer)mainParams.get("connectionTimeout"));
  // add datasource specific connection parameters
  if(configParams != null) configParams.forEach((k, v) -> ds.addDataSourceProperty(k, v));
  return ds;
}

代码示例来源:origin: networknt/light-4j

protected static KeyStore loadTrustStore() {
  String name = config.getTruststoreName();
  try (InputStream stream = Config.getInstance().getInputStreamFromFile(name)) {
    KeyStore loadedKeystore = KeyStore.getInstance("JKS");
    loadedKeystore.load(stream, ((String) secret.get(SecretConstants.SERVER_TRUSTSTORE_PASS)).toCharArray());
    return loadedKeystore;
  } catch (Exception e) {
    logger.error("Unable to load truststore " + name, e);
    throw new RuntimeException("Unable to load truststore " + name, e);
  }
}

代码示例来源:origin: networknt/light-4j

public PathResourceHandler() {
  PathResourceConfig config = (PathResourceConfig)Config.getInstance().getJsonObjectConfig(PathResourceConfig.CONFIG_NAME, PathResourceConfig.class);
  if(config.isPrefix()) {
    pathHandler = new PathHandler()
        .addPrefixPath(config.getPath(), new ResourceHandler(new PathResourceManager(Paths.get(config.getBase()), config.getTransferMinSize()))
            .setDirectoryListingEnabled(config.isDirectoryListingEnabled()));
  } else {
    pathHandler = new PathHandler()
        .addExactPath(config.getPath(), new ResourceHandler(new PathResourceManager(Paths.get(config.getBase()), config.getTransferMinSize()))
            .setDirectoryListingEnabled(config.isDirectoryListingEnabled()));
  }
}

代码示例来源:origin: networknt/light-4j

public static String maskJson(DocumentContext ctx, String key) {
  Map<String, Object> jsonConfig = (Map<String, Object>) config.get(MASK_TYPE_JSON);
  if (jsonConfig != null) {
    Map<String, Object> patternMap = (Map<String, Object>) jsonConfig.get(key);
    if (patternMap != null) {
      JsonNode configNode = Config.getInstance().getMapper().valueToTree(patternMap);
      Iterator<Map.Entry<String, JsonNode>> iterator = configNode.fields();
      while (iterator.hasNext()) {
        Map.Entry<String, JsonNode> entry = iterator.next();
        applyMask(entry, ctx);
      }
      return ctx.jsonString();
    } else {
      logger.warn("mask.json doesn't contain the key {} ", Encode.forJava(key));
    }
  }
  return ctx.jsonString();
}

代码示例来源:origin: networknt/light-4j

@Override
public void register() {
  ModuleRegistry.registerModule(SanitizerHandler.class.getName(), Config.getInstance().getJsonMapConfigNoCache(CONFIG_NAME), null);
}

代码示例来源:origin: networknt/light-4j

public RefreshTokenRequest() {
  setGrantType(REFRESH_TOKEN);
  Map<String, Object> clientConfig = Config.getInstance().getJsonMapConfig(Http2Client.CONFIG_NAME);
  // client_secret is in secret.yml instead of client.yml
  if(clientConfig != null) {
    Map<String, Object> oauthConfig = (Map<String, Object>)clientConfig.get(OAUTH);
    if(oauthConfig != null) {
      Map<String, Object> tokenConfig = (Map<String, Object>)oauthConfig.get(TOKEN);
      if(tokenConfig != null) {
        setServerUrl((String)tokenConfig.get(SERVER_URL));
        Object object = tokenConfig.get(ENABLE_HTTP2);
        setEnableHttp2(object != null && (Boolean) object);
        Map<String, Object> rtConfig = (Map<String, Object>) tokenConfig.get(REFRESH_TOKEN);
        if(rtConfig != null) {
          setClientId((String)rtConfig.get(CLIENT_ID));
          setClientSecret((String)secret.get(SecretConstants.REFRESH_TOKEN_CLIENT_SECRET));
          setUri((String)rtConfig.get(URI));
          setScope((List<String>)rtConfig.get(SCOPE));
        }
      }
    }
  }
}

代码示例来源:origin: networknt/light-4j

private static KeyStore loadKeyStore(final String name, final char[] password) throws IOException {
  final InputStream stream = Config.getInstance().getInputStreamFromFile(name);
  if(stream == null) {
    throw new RuntimeException("Could not load keystore");
  }
  try {
    KeyStore loadedKeystore = KeyStore.getInstance("JKS");
    loadedKeystore.load(stream, password);
    return loadedKeystore;
  } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) {
    throw new IOException(String.format("Unable to load KeyStore %s", name), e);
  } finally {
    IoUtils.safeClose(stream);
  }
}

相关文章