use of com.typesafe.config.ConfigValue in project config by typesafehub.
the class ConfigBeanImpl method createInternal.
/**
* This is public ONLY for use by the "config" package, DO NOT USE this ABI
* may change.
* @param <T> type of the bean
* @param config config to use
* @param clazz class of the bean
* @return the bean instance
*/
public static <T> T createInternal(Config config, Class<T> clazz) {
if (((SimpleConfig) config).root().resolveStatus() != ResolveStatus.RESOLVED)
throw new ConfigException.NotResolved("need to Config#resolve() a config before using it to initialize a bean, see the API docs for Config#resolve()");
Map<String, AbstractConfigValue> configProps = new HashMap<String, AbstractConfigValue>();
Map<String, String> originalNames = new HashMap<String, String>();
for (Map.Entry<String, ConfigValue> configProp : config.root().entrySet()) {
String originalName = configProp.getKey();
String camelName = ConfigImplUtil.toCamelCase(originalName);
// the camel one wins
if (originalNames.containsKey(camelName) && !originalName.equals(camelName)) {
// if we aren't a camel name to start with, we lose.
// if we are or we are the first matching key, we win.
} else {
configProps.put(camelName, (AbstractConfigValue) configProp.getValue());
originalNames.put(camelName, originalName);
}
}
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(clazz);
} catch (IntrospectionException e) {
throw new ConfigException.BadBean("Could not get bean information for class " + clazz.getName(), e);
}
try {
List<PropertyDescriptor> beanProps = new ArrayList<PropertyDescriptor>();
for (PropertyDescriptor beanProp : beanInfo.getPropertyDescriptors()) {
if (beanProp.getReadMethod() == null || beanProp.getWriteMethod() == null) {
continue;
}
beanProps.add(beanProp);
}
// Try to throw all validation issues at once (this does not comprehensively
// find every issue, but it should find common ones).
List<ConfigException.ValidationProblem> problems = new ArrayList<ConfigException.ValidationProblem>();
for (PropertyDescriptor beanProp : beanProps) {
Method setter = beanProp.getWriteMethod();
Class<?> parameterClass = setter.getParameterTypes()[0];
ConfigValueType expectedType = getValueTypeOrNull(parameterClass);
if (expectedType != null) {
String name = originalNames.get(beanProp.getName());
if (name == null)
name = beanProp.getName();
Path path = Path.newKey(name);
AbstractConfigValue configValue = configProps.get(beanProp.getName());
if (configValue != null) {
SimpleConfig.checkValid(path, expectedType, configValue, problems);
} else {
if (!isOptionalProperty(clazz, beanProp)) {
SimpleConfig.addMissing(problems, expectedType, path, config.origin());
}
}
}
}
if (!problems.isEmpty()) {
throw new ConfigException.ValidationFailed(problems);
}
// Fill in the bean instance
T bean = clazz.newInstance();
for (PropertyDescriptor beanProp : beanProps) {
Method setter = beanProp.getWriteMethod();
Type parameterType = setter.getGenericParameterTypes()[0];
Class<?> parameterClass = setter.getParameterTypes()[0];
String configPropName = originalNames.get(beanProp.getName());
// Is the property key missing in the config?
if (configPropName == null) {
// If so, continue if the field is marked as @{link Optional}
if (isOptionalProperty(clazz, beanProp)) {
continue;
}
// Otherwise, raise a {@link Missing} exception right here
throw new ConfigException.Missing(beanProp.getName());
}
Object unwrapped = getValue(clazz, parameterType, parameterClass, config, configPropName);
setter.invoke(bean, unwrapped);
}
return bean;
} catch (InstantiationException e) {
throw new ConfigException.BadBean(clazz.getName() + " needs a public no-args constructor to be used as a bean", e);
} catch (IllegalAccessException e) {
throw new ConfigException.BadBean(clazz.getName() + " getters and setters are not accessible, they must be for use as a bean", e);
} catch (InvocationTargetException e) {
throw new ConfigException.BadBean("Calling bean method on " + clazz.getName() + " caused an exception", e);
}
}
use of com.typesafe.config.ConfigValue in project config by typesafehub.
the class ConfigReference method resolveSubstitutions.
// ConfigReference should be a firewall against NotPossibleToResolve going
// further up the stack; it should convert everything to ConfigException.
// This way it's impossible for NotPossibleToResolve to "escape" since
// any failure to resolve has to start with a ConfigReference.
@Override
ResolveResult<? extends AbstractConfigValue> resolveSubstitutions(ResolveContext context, ResolveSource source) {
ResolveContext newContext = context.addCycleMarker(this);
AbstractConfigValue v;
try {
ResolveSource.ResultWithPath resultWithPath = source.lookupSubst(newContext, expr, prefixLength);
newContext = resultWithPath.result.context;
if (resultWithPath.result.value != null) {
if (ConfigImpl.traceSubstitutionsEnabled())
ConfigImpl.trace(newContext.depth(), "recursively resolving " + resultWithPath + " which was the resolution of " + expr + " against " + source);
ResolveSource recursiveResolveSource = (new ResolveSource((AbstractConfigObject) resultWithPath.pathFromRoot.last(), resultWithPath.pathFromRoot));
if (ConfigImpl.traceSubstitutionsEnabled())
ConfigImpl.trace(newContext.depth(), "will recursively resolve against " + recursiveResolveSource);
ResolveResult<? extends AbstractConfigValue> result = newContext.resolve(resultWithPath.result.value, recursiveResolveSource);
v = result.value;
newContext = result.context;
} else {
ConfigValue fallback = context.options().getResolver().lookup(expr.path().render());
v = (AbstractConfigValue) fallback;
}
} catch (NotPossibleToResolve e) {
if (ConfigImpl.traceSubstitutionsEnabled())
ConfigImpl.trace(newContext.depth(), "not possible to resolve " + expr + ", cycle involved: " + e.traceString());
if (expr.optional())
v = null;
else
throw new ConfigException.UnresolvedSubstitution(origin(), expr + " was part of a cycle of substitutions involving " + e.traceString(), e);
}
if (v == null && !expr.optional()) {
if (newContext.options().getAllowUnresolved())
return ResolveResult.make(newContext.removeCycleMarker(this), this);
else
throw new ConfigException.UnresolvedSubstitution(origin(), expr.toString());
} else {
return ResolveResult.make(newContext.removeCycleMarker(this), v);
}
}
use of com.typesafe.config.ConfigValue in project scoold by Erudika.
the class AdminController method get.
@GetMapping
public String get(HttpServletRequest req, Model model) {
if (utils.isAuthenticated(req) && !utils.isAdmin(utils.getAuthUser(req))) {
return "redirect:" + HOMEPAGE;
} else if (!utils.isAuthenticated(req)) {
return "redirect:" + SIGNINLINK + "?returnto=" + ADMINLINK;
}
Map<String, Object> configMap = new LinkedHashMap<String, Object>();
for (Map.Entry<String, ConfigValue> entry : Config.getConfig().entrySet()) {
ConfigValue value = entry.getValue();
configMap.put(entry.getKey(), value != null ? value.unwrapped() : "-");
}
Pager itemcount = utils.getPager("page", req);
Pager itemcount1 = utils.getPager("page1", req);
itemcount.setLimit(40);
model.addAttribute("path", "admin.vm");
model.addAttribute("title", utils.getLang(req).get("administration.title"));
model.addAttribute("configMap", configMap);
model.addAttribute("version", pc.getServerVersion());
model.addAttribute("endpoint", Config.getConfigParam("security.redirect_uri", pc.getEndpoint()));
model.addAttribute("paraapp", Config.getConfigParam("access_key", "x"));
model.addAttribute("spaces", pc.findQuery("scooldspace", "*", itemcount));
model.addAttribute("webhooks", pc.findQuery(Utils.type(Webhook.class), "*", itemcount1));
model.addAttribute("scooldimports", pc.findQuery("scooldimport", "*", new Pager(7)));
model.addAttribute("coreScooldTypes", utils.getCoreScooldTypes());
model.addAttribute("customHookEvents", utils.getCustomHookEvents());
model.addAttribute("apiKeys", utils.getApiKeys());
model.addAttribute("apiKeysExpirations", utils.getApiKeysExpirations());
model.addAttribute("itemcount", itemcount);
model.addAttribute("itemcount1", itemcount1);
model.addAttribute("isDefaultSpacePublic", utils.isDefaultSpacePublic());
model.addAttribute("scooldVersion", Optional.ofNullable(scooldVersion).orElse("unknown"));
String importedCount = req.getParameter("imported");
if (importedCount != null) {
if (req.getParameter("success") != null) {
model.addAttribute("infoStripMsg", "Successfully imported " + importedCount + " objects from archive.");
} else {
model.addAttribute("infoStripMsg", "Imported operation failed!" + ("0".equals(importedCount) ? "" : " Partially imported " + importedCount + " objects from archive."));
}
}
Sysprop theme = utils.getCustomTheme();
String themeCSS = (String) theme.getProperty("theme");
model.addAttribute("selectedTheme", theme.getName());
model.addAttribute("customTheme", StringUtils.isBlank(themeCSS) ? utils.getDefaultTheme() : themeCSS);
return "base";
}
use of com.typesafe.config.ConfigValue in project drill by apache.
the class ClusterDef method getCluster.
/**
* Deserialize a node tier from the configuration file.
*
* @param n
* @return
*/
public static ClusterGroup getCluster(Config config, int n) {
int index = n + 1;
ConfigList tiers = config.getList(DrillOnYarnConfig.CLUSTERS);
ConfigValue value = tiers.get(n);
if (value == null) {
throw new IllegalArgumentException("If cluster group is provided, it cannot be null: group " + index);
}
@SuppressWarnings("unchecked") Map<String, Object> tier = (Map<String, Object>) value.unwrapped();
String type;
try {
type = tier.get(GROUP_TYPE).toString();
} catch (NullPointerException e) {
throw new IllegalArgumentException("Pool type is required for cluster group " + index);
}
GroupType groupType = GroupType.toEnum(type);
if (groupType == null) {
throw new IllegalArgumentException("Undefined type for cluster group " + index + ": " + type);
}
ClusterGroup tierDef;
switch(groupType) {
case BASIC:
tierDef = new BasicGroup(tier, index);
break;
case LABELED:
tierDef = new LabeledGroup(tier, index);
break;
default:
assert false;
throw new IllegalStateException("Undefined cluster group type: " + groupType);
}
return tierDef;
}
use of com.typesafe.config.ConfigValue in project incubator-gobblin by apache.
the class ReplicationMetaData method buildMetaData.
public static ReplicationMetaData buildMetaData(Config config) {
if (!config.hasPath(ReplicationConfiguration.METADATA)) {
return new ReplicationMetaData(Optional.<Map<String, String>>absent());
}
Config metaDataConfig = config.getConfig(ReplicationConfiguration.METADATA);
Map<String, String> metaDataValues = new HashMap<>();
Set<Map.Entry<String, ConfigValue>> meataDataEntry = metaDataConfig.entrySet();
for (Map.Entry<String, ConfigValue> entry : meataDataEntry) {
metaDataValues.put(entry.getKey(), metaDataConfig.getString(entry.getKey()));
}
ReplicationMetaData metaData = new ReplicationMetaData(Optional.of(metaDataValues));
return metaData;
}
Aggregations