Search in sources :

Example 31 with ConfigValue

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);
    }
}
Also used : ConfigValue(com.typesafe.config.ConfigValue) HashMap(java.util.HashMap) BeanInfo(java.beans.BeanInfo) IntrospectionException(java.beans.IntrospectionException) ArrayList(java.util.ArrayList) ConfigException(com.typesafe.config.ConfigException) ConfigValueType(com.typesafe.config.ConfigValueType) PropertyDescriptor(java.beans.PropertyDescriptor) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) ConfigValueType(com.typesafe.config.ConfigValueType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) ConfigObject(com.typesafe.config.ConfigObject) HashMap(java.util.HashMap) Map(java.util.Map)

Example 32 with ConfigValue

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);
    }
}
Also used : ConfigValue(com.typesafe.config.ConfigValue) ConfigException(com.typesafe.config.ConfigException)

Example 33 with ConfigValue

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";
}
Also used : ConfigValue(com.typesafe.config.ConfigValue) Pager(com.erudika.para.core.utils.Pager) Sysprop(com.erudika.para.core.Sysprop) ParaObject(com.erudika.para.core.ParaObject) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) LinkedHashMap(java.util.LinkedHashMap) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 34 with ConfigValue

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;
}
Also used : ConfigValue(com.typesafe.config.ConfigValue) Map(java.util.Map) ConfigList(com.typesafe.config.ConfigList)

Example 35 with ConfigValue

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;
}
Also used : ConfigValue(com.typesafe.config.ConfigValue) HashMap(java.util.HashMap) Config(com.typesafe.config.Config) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

ConfigValue (com.typesafe.config.ConfigValue)37 Map (java.util.Map)20 Config (com.typesafe.config.Config)11 ConfigException (com.typesafe.config.ConfigException)10 ArrayList (java.util.ArrayList)8 HashMap (java.util.HashMap)6 ConfigList (com.typesafe.config.ConfigList)5 ConfigObject (com.typesafe.config.ConfigObject)5 ImmutableMap (com.google.common.collect.ImmutableMap)4 Configuration (org.apache.hadoop.conf.Configuration)4 IOException (java.io.IOException)3 BigInteger (java.math.BigInteger)3 FileSystem (org.apache.hadoop.fs.FileSystem)3 Properties (java.util.Properties)2 ParaObject (com.erudika.para.core.ParaObject)1 Sysprop (com.erudika.para.core.Sysprop)1 Pager (com.erudika.para.core.utils.Pager)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Gson (com.google.gson.Gson)1 ConfigOrigin (com.typesafe.config.ConfigOrigin)1