com.typesafe.config.ConfigObject Java Examples

The following examples show how to use com.typesafe.config.ConfigObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VcapServicesStringParser.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private static ConfigObject getAsConfigObject(final ConfigList configList) {
    final Map<String, ConfigValue> flattenedConfigValues = new HashMap<>(configList.size());

    for (int i = 0; i < configList.size(); i++) {
        final ConfigValue configValue = configList.get(i);
        final String configPath;
        if (ConfigValueType.OBJECT == configValue.valueType()) {
            configPath = getName((ConfigObject) configValue);
        } else {
            configPath = String.valueOf(i);
        }
        flattenedConfigValues.put(configPath, configValue);
    }

    return ConfigValueFactory.fromMap(flattenedConfigValues);
}
 
Example #2
Source File: TestRangeRowRule.java    From envelope with Apache License 2.0 6 votes vote down vote up
@Test
public void testRangeDataTypes() throws Exception {
  Config config = ConfigUtils.configFromResource("/dq/dq-range-rules.conf").getConfig("steps");
  StructType schema = new StructType(new StructField[] {
    new StructField("fa", DataTypes.LongType, false, Metadata.empty()),
    new StructField("fi", DataTypes.IntegerType, false, Metadata.empty()),
    new StructField("fl", DataTypes.LongType, false, Metadata.empty()),
    new StructField("ff", DataTypes.FloatType, false, Metadata.empty()),
    new StructField("fe", DataTypes.DoubleType, false, Metadata.empty()),
    new StructField("fd", DataTypes.createDecimalType(), false, Metadata.empty())
  });
  Row row = new RowWithSchema(schema, new Long(2), 2, new Long(2), new Float(2.0), 2.0, new BigDecimal("2.0"));
    
  ConfigObject rro =  config.getObject("dq1.deriver.rules") ;
  for ( String rulename : rro.keySet() ) {
    Config rrc = rro.toConfig().getConfig(rulename);
    RangeRowRule rrr = new RangeRowRule() ;
    rrr.configure(rrc);
    rrr.configureName(rulename);
    assertTrue("Row should pass rule " + rulename, rrr.check(row));
  }
}
 
Example #3
Source File: DispatcherActor.java    From Nickle-Scheduler with Apache License 2.0 6 votes vote down vote up
/**
 * 执行注册
 *
 * @param clientRegisterEvent
 */
private void execRegister(ClientRegisterEvent clientRegisterEvent) throws InterruptedException {
    Config config = getContext().getSystem().settings().config();
    //一直注册直到服务器返回数据
    if (!ObjectUtils.isEmpty(masterList)) {
        if (registerSuccess) {
            log.info("已注册成功");
            return;
        }
        ConfigObject configObject = config.getObject("akka.remote.netty.tcp");
        String hostname = configObject.get("hostname").unwrapped().toString();
        String portStr = configObject.get("port").unwrapped().toString();
        Integer port = Integer.valueOf(portStr);
        registerEvent = new RegisterEvent(hostname, port, clientRegisterEvent.getJobDataList(), clientRegisterEvent.getTriggerDataList());
        masterRouter.route(registerEvent, getSelf());
        //睡眠1s后注册,避免频繁注册
        Thread.sleep(1000);
        this.getSelf().tell(clientRegisterEvent, getSelf());
    } else {
        log.error("master地址为空,将不继续注册");
        ClientUtils.exit(getContext());
    }
}
 
Example #4
Source File: HBaseColumnsValidation.java    From envelope with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(Config config) {
  if (config.hasPath(HBaseUtils.COLUMNS_PROPERTY)) {
    ConfigObject columnConfig = config.getConfig(HBaseUtils.COLUMNS_PROPERTY).root();
    Set<String> columns = columnConfig.keySet();
    for (String column : columns) {
      if (!config.hasPath(HBaseUtils.COLUMNS_PROPERTY + "." + column + ".col")) {
        return new ValidationResult(this, Validity.INVALID, "'col' not specified in column " + column);
      }
      if (!config.hasPath(HBaseUtils.COLUMNS_PROPERTY + "." + column + ".type")) {
        return new ValidationResult(this, Validity.INVALID, "'type' not specified in column " + column);
      }
      if (!config.hasPath(HBaseUtils.COLUMNS_PROPERTY + "." + column + ".cf")) {
        return new ValidationResult(this, Validity.INVALID, "'cf' not specified in column " + column);
      }
    }
  }
  
  return new ValidationResult(this, Validity.VALID, "HBase column entries are all valid");
}
 
Example #5
Source File: HoconTreeTraversingParser.java    From jackson-dataformat-hocon with Apache License 2.0 6 votes vote down vote up
public HoconTreeTraversingParser(ConfigObject n, ObjectCodec codec)
{
    super(0);
    _rootObject = n;
    _objectCodec = codec;
    if (n.valueType() == ConfigValueType.LIST) {
        _nextToken = JsonToken.START_ARRAY;
        _nodeCursor = new HoconNodeCursor.Array(n, null);
    } else if (n.valueType() == ConfigValueType.OBJECT) {
        if (HoconNodeCursor.isNumericallyIndexed(n)) {
            _nextToken = JsonToken.START_ARRAY;
            _nodeCursor = new HoconNodeCursor.NumericallyIndexedObjectBackedArray(n, null);
        } else {
            _nextToken = JsonToken.START_OBJECT;
            _nodeCursor = new HoconNodeCursor.Object(n, null);
        }
    } else { // value node
        _nodeCursor = new HoconNodeCursor.RootValue(n, null);
    }
}
 
Example #6
Source File: Args.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static TriggerConfig createTriggerConfig(ConfigObject triggerObject) {
    if (Objects.isNull(triggerObject)) {
        return null;
    }

    TriggerConfig triggerConfig = new TriggerConfig();

    String triggerName = triggerObject.get("triggerName").unwrapped().toString();
    triggerConfig.setTriggerName(triggerName);

    String enabled = triggerObject.get("enable").unwrapped().toString();
    triggerConfig.setEnabled("true".equalsIgnoreCase(enabled) ? true : false);

    String topic = triggerObject.get("topic").unwrapped().toString();
    triggerConfig.setTopic(topic);

    return triggerConfig;
}
 
Example #7
Source File: ConfigModule.java    From proteus with Apache License 2.0 6 votes vote down vote up
private static void traverse(final Binder binder, final String nextPath, final ConfigObject rootConfig)
{
    rootConfig.forEach(
            (key, value) -> {
                if (value instanceof ConfigObject) {
                    try {

                        ConfigObject child = (ConfigObject) value;
                        String path = nextPath + key;

                        Named named = Names.named(path);

                        binder.bind(Config.class).annotatedWith(named).toInstance(child.toConfig());

                        traverse(binder, path + ".", child);

                    } catch (Exception e) {
                        log.error("Error binding " + value, e);
                    }
                }
            });
}
 
Example #8
Source File: Rules.java    From Stargraph with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<Language, List<QueryPlanPatterns>> loadQueryPlanPatterns(Config config) {
    Map<Language, List<QueryPlanPatterns>> rulesByLang = new LinkedHashMap<>();
    ConfigObject configObject = config.getObject("rules.planner-pattern");

    configObject.keySet().forEach(strLang -> {
        Language language = Language.valueOf(strLang.toUpperCase());
        List<QueryPlanPatterns> plans = new ArrayList<>();

        List<? extends ConfigObject> innerCfg = configObject.toConfig().getObjectList(strLang);
        innerCfg.forEach(e -> {
            Map<String, Object> plan = e.unwrapped();
            String planId = plan.keySet().toArray(new String[1])[0];
            List<String> triplePatterns = (List<String>)plan.values().toArray()[0];
            plans.add(new QueryPlanPatterns(planId,
                    triplePatterns.stream().map(TriplePattern::new).collect(Collectors.toList())));
        });

        rulesByLang.put(language, plans);
    });

    return rulesByLang;
}
 
Example #9
Source File: Rules.java    From Stargraph with MIT License 6 votes vote down vote up
private Map<Language, List<Pattern>> loadStopPatterns(Config config) {
    Map<Language, List<Pattern>> rulesByLang = new LinkedHashMap<>();
    ConfigObject configObject = config.getObject("rules.stop-pattern");

    configObject.keySet().forEach(strLang -> {
        Language language = Language.valueOf(strLang.toUpperCase());
        List<String> patternStr = configObject.toConfig().getStringList(strLang);

        rulesByLang.compute(language,
                (lang, pattern) -> patternStr.stream().map(Pattern::compile).collect(Collectors.toList()));

        logger.info(marker, "Loaded {} Stop patterns for '{}'", rulesByLang.get(language).size(), language);

    });

    return rulesByLang;
}
 
Example #10
Source File: Args.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static Account createAccount(final ConfigObject asset) {
    final Account account = new Account();
    account.setAccountName(asset.get("accountName").unwrapped().toString());
    account.setAccountType(asset.get("accountType").unwrapped().toString());
    account.setAddress(Wallet.decodeFromBase58Check(asset.get("address").unwrapped().toString()));
    account.setBalance(asset.get("balance").unwrapped().toString());
    return account;
}
 
Example #11
Source File: DefaultScopedConfig.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<? extends ConfigObject> getObjectList(final String path) {
    try {
        return config.getObjectList(path);
    } catch (final ConfigException.Missing | ConfigException.WrongType e) {
        final String msgPattern = "Failed to get List of ConfigObjects for path <{0}>!";
        throw new DittoConfigError(MessageFormat.format(msgPattern, appendToConfigPath(path)), e);
    }
}
 
Example #12
Source File: Args.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static Witness createWitness(final ConfigObject witnessAccount) {
    final Witness witness = new Witness();
    witness.setAddress(
            Wallet.decodeFromBase58Check(witnessAccount.get("address").unwrapped().toString()));
    witness.setUrl(witnessAccount.get("url").unwrapped().toString());
    witness.setVoteCount(witnessAccount.toConfig().getLong("voteCount"));
    return witness;
}
 
Example #13
Source File: Rules.java    From Stargraph with MIT License 5 votes vote down vote up
private Map<Language, List<QueryTypePatterns>> loadQueryTypePatterns(Config config) {
    Map<Language, List<QueryTypePatterns>> rulesByLang = new HashMap<>();
    ConfigObject configObject = config.getObject("rules.query-pattern");

    configObject.keySet().forEach(strLang -> {
        Language language = Language.valueOf(strLang.toUpperCase());

        ConfigObject innerCfg = configObject.toConfig().getObject(strLang);

        List<QueryTypePatterns> patterns = new ArrayList<>();

        rulesByLang.compute(language, (l, q) -> {
            innerCfg.keySet().forEach(key -> {
                QueryType queryType = QueryType.valueOf(key);
                List<String> patternStr = innerCfg.toConfig().getStringList(key);
                patterns.add(new QueryTypePatterns(queryType,
                        patternStr.stream().map(Pattern::compile).collect(Collectors.toList())));
            });

            logger.info(marker, "Loaded {} Query Type patterns for '{}'", patterns.size(), language);
            return patterns;
        });

    });

    return rulesByLang;
}
 
Example #14
Source File: Rules.java    From Stargraph with MIT License 5 votes vote down vote up
private Map<Language, List<DataModelTypePattern>> loadDataModelTypePatterns(Config config) {
    Map<Language, List<DataModelTypePattern>> rulesByLang = new HashMap<>();
    ConfigObject configObject = config.getObject("rules.syntatic-pattern");

    configObject.keySet().forEach(strLang -> {
        Language language = Language.valueOf(strLang.toUpperCase());

        rulesByLang.compute(language, (l, r) -> {

            List<DataModelTypePattern> rules = new ArrayList<>();
            List<? extends Config> patternCfg = configObject.toConfig().getConfigList(strLang);

            for (Config cfg : patternCfg) {
                Map.Entry<String, ConfigValue> entry = cfg.entrySet().stream().findFirst().orElse(null);
                String modelStr = entry.getKey();
                @SuppressWarnings("unchecked")
                List<String> patternList = (List<String>) entry.getValue().unwrapped();
                rules.addAll(patternList.stream()
                        .map(p -> new DataModelTypePattern(p, DataModelType.valueOf(modelStr)))
                        .collect(Collectors.toList()));
            }

            logger.info(marker, "Loaded {} Data Model Type patterns for '{}'", rules.size(), l);

            return rules;
        });
    });


    return rulesByLang;
}
 
Example #15
Source File: Instruments.java    From parity with Apache License 2.0 5 votes vote down vote up
/**
 * Get the instruments from a configuration object.
 *
 * @param config a configuration object
 * @param path the path expression
 * @return the instruments
 * @throws ConfigException if a configuration error occurs
 */
public static Instruments fromConfig(Config config, String path) {
    ConfigObject root = config.getObject(path);

    Config rootConfig = root.toConfig();

    int priceIntegerDigits = getInt(rootConfig, "price-integer-digits", 1);
    int sizeIntegerDigits  = getInt(rootConfig, "size-integer-digits",  1);

    Set<String> instruments = root.keySet();

    instruments.remove("price-integer-digits");
    instruments.remove("size-integer-digits");

    Instrument[] values = instruments.stream()
            .map(instrument -> Instrument.fromConfig(rootConfig, instrument))
            .toArray(Instrument[]::new);

    int maxPriceFractionDigits = max(values, Instrument::getPriceFractionDigits);
    int maxSizeFractionDigits  = max(values, Instrument::getSizeFractionDigits);

    for (Instrument value : values) {
        value.setPriceFormat(priceIntegerDigits, maxPriceFractionDigits);
        value.setSizeFormat(sizeIntegerDigits, maxSizeFractionDigits);
    }

    return new Instruments(values, priceIntegerDigits, maxPriceFractionDigits,
            sizeIntegerDigits, maxSizeFractionDigits);
}
 
Example #16
Source File: HeartBeatActor.java    From Nickle-Scheduler with Apache License 2.0 5 votes vote down vote up
public HeartBeatActor(Router masterRouter, ActorRef dispatcherActor) {
    Config config = getContext().getSystem().settings().config();
    ConfigObject configObject = config.getObject("akka.remote.netty.tcp");
    localHostName = configObject.get("hostname").unwrapped().toString();
    localPort = Integer.valueOf(configObject.get("port").unwrapped().toString());
    this.masterRouter = masterRouter;
    this.dispatcherActor = dispatcherActor;
}
 
Example #17
Source File: HoconNodeCursor.java    From jackson-dataformat-hocon with Apache License 2.0 5 votes vote down vote up
@Override
public boolean currentHasChildren() {
	if(currentNode() instanceof ConfigList) {
		return !((ConfigList)currentNode()).isEmpty();
	} else if (currentNode() instanceof ConfigObject) {
		return !((ConfigObject)currentNode()).isEmpty();
	} else {
		return false;
	}
}
 
Example #18
Source File: HoconNodeCursor.java    From jackson-dataformat-hocon with Apache License 2.0 5 votes vote down vote up
@Override
public boolean currentHasChildren() {
	if(currentNode() instanceof ConfigList) {
		return !((ConfigList)currentNode()).isEmpty();
	} else if (currentNode() instanceof ConfigObject) {
		return !((ConfigObject)currentNode()).isEmpty();
	} else {
		return false;
	}
}
 
Example #19
Source File: AccountStore.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void setAccount(com.typesafe.config.Config config) {
    List list = config.getObjectList("genesis.block.assets");
    for (int i = 0; i < list.size(); i++) {
        ConfigObject obj = (ConfigObject) list.get(i);
        String accountName = obj.get("accountName").unwrapped().toString();
        byte[] address = Wallet.decodeFromBase58Check(obj.get("address").unwrapped().toString());
        assertsAddress.put(accountName, address);
    }
}
 
Example #20
Source File: SecurityConfig.java    From para with Apache License 2.0 5 votes vote down vote up
private void parseProtectedResources(HttpSecurity http, ConfigObject protectedResources) throws Exception {
	for (ConfigValue cv : protectedResources.values()) {
		LinkedList<String> patterns = new LinkedList<>();
		LinkedList<String> roles = new LinkedList<>();
		HashSet<HttpMethod> methods = new HashSet<>();

		for (ConfigValue configValue : (ConfigList) cv) {
			try {
				if (configValue instanceof ConfigList) {
					for (ConfigValue role : (ConfigList) configValue) {
						String r = ((String) role.unwrapped()).toUpperCase().trim();
						// check if any HTTP methods appear here
						HttpMethod m = HttpMethod.resolve(r);
						if (m != null) {
							methods.add(m);
						} else {
							roles.add(r);
						}
					}
				} else {
					patterns.add((String) configValue.unwrapped());
				}
			} catch (Exception e) {
				logger.error("Invalid config syntax for protected resource: {}.", configValue.render(), e);
			}
		}
		String[] rolz = (roles.isEmpty()) ? DEFAULT_ROLES : roles.toArray(new String[0]);
		String[] patternz = patterns.toArray(new String[0]);
		if (methods.isEmpty()) {
			http.authorizeRequests().antMatchers(patternz).hasAnyRole(rolz);
		} else {
			for (HttpMethod method : methods) {
				http.authorizeRequests().antMatchers(method, patternz).hasAnyRole(rolz);
			}
		}
	}
}
 
Example #21
Source File: ConfigToProperties.java    From oryx with Apache License 2.0 5 votes vote down vote up
private static void add(ConfigObject config, String prefix, Map<String,String> values) {
  config.forEach((key, value) -> {
    String nextPrefix = prefix + '.' + key;
    switch (value.valueType()) {
      case OBJECT:
        add((ConfigObject) value, nextPrefix, values);
        break;
      case NULL:
        // do nothing
        break;
      default:
        values.put(nextPrefix, String.valueOf(value.unwrapped()));
    }
  });
}
 
Example #22
Source File: VcapServicesStringToConfigTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getConfigForVcapServicesStringReturnsExpected() {
    final VcapServicesStringToConfig underTest = VcapServicesStringToConfig.getInstance();

    final Config actual = underTest.apply(vcapServicesString);

    assertThat(actual.hasPath(VcapServicesStringToConfig.VCAP_CONFIG_PATH)).isTrue();
    assertThat(actual.getValue(VcapServicesStringToConfig.VCAP_CONFIG_PATH)).satisfies(vcapConfig -> {
        assertThat(vcapConfig.valueType()).isEqualTo(ConfigValueType.OBJECT);
        assertThat((ConfigObject) vcapConfig).containsOnlyKeys("MongoDB-Service", "mongodb", "permissions-service",
                "permissions", "usage-server", "usage");
    });
}
 
Example #23
Source File: SimpleHoconConfigTest.java    From kite with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromMap() { // test access based on key
  final Map<String, String> map = Maps.newHashMap();
  map.put(TIKA_CONFIG_LOCATION, "src/test/resources/tika-config.xml");
  String key = "collection1.testcoll.solr.home";
  map.put(key, "target/test-classes/solr/collection1");
  ConfigObject config = ConfigValueFactory.fromMap(map);
  String filePath = config.get(TIKA_CONFIG_LOCATION).unwrapped().toString();
  assertEquals(map.get(TIKA_CONFIG_LOCATION), filePath);
  assertEquals(map.get(key), config.get(key).unwrapped().toString());
}
 
Example #24
Source File: SwiftConfig.java    From swift-k with Apache License 2.0 5 votes vote down vote up
@Override
public ConfigObject include(ConfigIncludeContext context, String what) {
    int b = what.indexOf("${");
    while (b != -1) {
        int e = what.indexOf("}", b);
        String var = what.substring(b + 2, e);
        what = what.substring(0, b) + resolve(var) + what.substring(e + 1);
        b = what.indexOf("${");
    }
    loadedFiles.add(new File(what).getAbsolutePath());
    loadedFileIndices.add(String.valueOf(++index));
    return ConfigFactory.parseFile(new File(what)).root();
}
 
Example #25
Source File: TypesafeConfigModule.java    From typesafeconfig-guice with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private Object getConfigValue(Class<?> paramClass, Type paramType, String path) {
	Optional<Object> extractedValue = ConfigExtractors.extractConfigValue(config, paramClass, path);
	if (extractedValue.isPresent()) {
		return extractedValue.get();
	}

	ConfigValue configValue = config.getValue(path);
	ConfigValueType valueType = configValue.valueType();
	if (valueType.equals(ConfigValueType.OBJECT) && Map.class.isAssignableFrom(paramClass)) {
		ConfigObject object = config.getObject(path);
           return object.unwrapped();
	} else if (valueType.equals(ConfigValueType.OBJECT)) {
		Object bean = ConfigBeanFactory.create(config.getConfig(path), paramClass);
		return bean;
	} else if (valueType.equals(ConfigValueType.LIST) && List.class.isAssignableFrom(paramClass)) {
		Type listType = ((ParameterizedType) paramType).getActualTypeArguments()[0];
		
		Optional<List<?>> extractedListValue = 
			ListExtractors.extractConfigListValue(config, listType, path);
		
		if (extractedListValue.isPresent()) {
			return extractedListValue.get();
		} else {
			List<? extends Config> configList = config.getConfigList(path);
			return configList.stream()
				.map(cfg -> {
					Object created = ConfigBeanFactory.create(cfg, (Class) listType);
					return created;
				})
				.collect(Collectors.toList());
		}
	}
	
	throw new RuntimeException("Cannot obtain config value for " + paramType + " at path: " + path);
}
 
Example #26
Source File: ConfigBeanImpl.java    From mpush with Apache License 2.0 5 votes vote down vote up
private static Object getListValue(Class<?> beanClass, Type parameterType, Class<?> parameterClass, Config config, String configPropName) {
    Type elementType = ((ParameterizedType) parameterType).getActualTypeArguments()[0];

    if (elementType == Boolean.class) {
        return config.getBooleanList(configPropName);
    } else if (elementType == Integer.class) {
        return config.getIntList(configPropName);
    } else if (elementType == Double.class) {
        return config.getDoubleList(configPropName);
    } else if (elementType == Long.class) {
        return config.getLongList(configPropName);
    } else if (elementType == String.class) {
        return config.getStringList(configPropName);
    } else if (elementType == Duration.class) {
        return config.getDurationList(configPropName);
    } else if (elementType == ConfigMemorySize.class) {
        return config.getMemorySizeList(configPropName);
    } else if (elementType == Object.class) {
        return config.getAnyRefList(configPropName);
    } else if (elementType == Config.class) {
        return config.getConfigList(configPropName);
    } else if (elementType == ConfigObject.class) {
        return config.getObjectList(configPropName);
    } else if (elementType == ConfigValue.class) {
        return config.getList(configPropName);
    } else {
        throw new ConfigException.BadBean("Bean property '" + configPropName + "' of class " + beanClass.getName() + " has unsupported list element type " + elementType);
    }
}
 
Example #27
Source File: ConfigBeanImpl.java    From mpush with Apache License 2.0 5 votes vote down vote up
private static ConfigValueType getValueTypeOrNull(Class<?> parameterClass) {
    if (parameterClass == Boolean.class || parameterClass == boolean.class) {
        return ConfigValueType.BOOLEAN;
    } else if (parameterClass == Integer.class || parameterClass == int.class) {
        return ConfigValueType.NUMBER;
    } else if (parameterClass == Double.class || parameterClass == double.class) {
        return ConfigValueType.NUMBER;
    } else if (parameterClass == Long.class || parameterClass == long.class) {
        return ConfigValueType.NUMBER;
    } else if (parameterClass == String.class) {
        return ConfigValueType.STRING;
    } else if (parameterClass == Duration.class) {
        return null;
    } else if (parameterClass == ConfigMemorySize.class) {
        return null;
    } else if (parameterClass == List.class) {
        return ConfigValueType.LIST;
    } else if (parameterClass == Map.class) {
        return ConfigValueType.OBJECT;
    } else if (parameterClass == Config.class) {
        return ConfigValueType.OBJECT;
    } else if (parameterClass == ConfigObject.class) {
        return ConfigValueType.OBJECT;
    } else if (parameterClass == ConfigList.class) {
        return ConfigValueType.LIST;
    } else {
        return null;
    }
}
 
Example #28
Source File: ConfigCenterTest.java    From mpush with Apache License 2.0 5 votes vote down vote up
public static void print2(String s, ConfigValue configValue, String p, int level) {
    int l = level + 1;
    switch (configValue.valueType()) {
        case OBJECT:
            printTab(level);
            System.out.printf("interface %s {%n", s.replace('-', '_'));
            printTab(level);
            System.out.printf("    Config cfg = %s.cfg.getObject(\"%s\").toConfig();%n%n", p, s);
            ((ConfigObject) configValue).forEach((s1, configValue2) -> print2(s1, configValue2, s, l));
            printTab(level);
            System.out.printf("}%n%n");
            break;
        case STRING:
            printTab(level);
            System.out.printf("  String %s = cfg.getString(\"%s\");%n%n", s.replace('-', '_'), s);
            break;
        case NUMBER:
            printTab(level);
            System.out.printf("  Number %s = cfg.getNumber(\"%s\");%n%n", s.replace('-', '_'), s);
            break;
        case BOOLEAN:
            printTab(level);
            System.out.printf("  Boolean %s = cfg.getBoolean(\"%s\");%n%n", s.replace('-', '_'), s);
            break;
        case LIST:
            printTab(level);
            System.out.printf("  List<Object> %s = cfg.getList(\"%s\").unwrapped();%n%n", s.replace('-', '_'), s);
            break;
    }
}
 
Example #29
Source File: Runner.java    From envelope with Apache License 2.0 5 votes vote down vote up
private Map<Config, EventHandler> getEventHandlers(Config config, boolean configure) {
  Map<Config, EventHandler> handlers = Maps.newHashMap();
  Set<String> nonConfiguredDefaultHandlerAliases = Sets.newHashSet(
      new LogEventHandler().getAlias()
  );

  if (ConfigUtils.getApplicationConfig(config).hasPath(EVENT_HANDLERS_CONFIG)) {
    List<? extends ConfigObject> handlerConfigObjects;
    try {
      handlerConfigObjects =
          ConfigUtils.getApplicationConfig(config).getObjectList(EVENT_HANDLERS_CONFIG);
    }
    catch (ConfigException.WrongType e) {
      throw new RuntimeException("Event handler configuration must be a list of event handler objects");
    }

    for (ConfigObject handlerConfigObject : handlerConfigObjects) {
      Config handlerConfig = handlerConfigObject.toConfig();
      EventHandler handler = ComponentFactory.create(EventHandler.class, handlerConfig, configure);
      handlers.put(handlerConfig, handler);

      // If this handler is a default handler then because it was configured we remove it from the
      // non-configured set. If this handler is not a default handler then this will be a no-op.
      nonConfiguredDefaultHandlerAliases.remove(handlerConfig.getString(ComponentFactory.TYPE_CONFIG_NAME));
    }
  }

  // Create the default handlers that were not already created above. These are created with
  // no configurations, so default handlers must only use optional configurations.
  for (String defaultHandlerAlias : nonConfiguredDefaultHandlerAliases) {
    Config defaultHandlerConfig = ConfigFactory.empty().withValue(
        ComponentFactory.TYPE_CONFIG_NAME, ConfigValueFactory.fromAnyRef(defaultHandlerAlias));
    EventHandler defaultHandler = ComponentFactory.create(EventHandler.class, defaultHandlerConfig, configure);
    handlers.put(defaultHandlerConfig, defaultHandler);
  }

  return handlers;
}
 
Example #30
Source File: Runner.java    From envelope with Apache License 2.0 5 votes vote down vote up
void initializeUDFs(Config config) {
  if (!config.hasPath(UDFS_SECTION_CONFIG)) return;

  ConfigList udfList = config.getList(UDFS_SECTION_CONFIG);

  for (ConfigValue udfValue : udfList) {
    ConfigValueType udfValueType = udfValue.valueType();
    if (!udfValueType.equals(ConfigValueType.OBJECT)) {
      throw new RuntimeException("UDF list must contain UDF objects");
    }

    Config udfConfig = ((ConfigObject)udfValue).toConfig();

    for (String path : Lists.newArrayList(UDFS_NAME, UDFS_CLASS)) {
      if (!udfConfig.hasPath(path)) {
        throw new RuntimeException("UDF entries must provide '" + path + "'");
      }
    }

    String name = udfConfig.getString(UDFS_NAME);
    String className = udfConfig.getString(UDFS_CLASS);

    // null third argument means that registerJava will infer the return type
    Contexts.getSparkSession().udf().registerJava(name, className, null);

    LOG.info("Registered Spark SQL UDF: " + name);
  }
}