Search in sources :

Example 1 with ConfigurationMetadataProperty

use of org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty in project cas by apereo.

the class AddPropertiesToConfigurationCommand method add.

/**
 * Add properties to configuration.
 *
 * @param file  the file
 * @param group the group
 * @throws Exception the exception
 */
@CliCommand(value = "add-properties", help = "Add properties associated with a CAS group/module to a Properties/Yaml configuration file.")
public void add(@CliOption(key = { "file" }, help = "Path to the CAS configuration file", unspecifiedDefaultValue = "/etc/cas/config/cas.properties", specifiedDefaultValue = "/etc/cas/config/cas.properties", optionContext = "Path to the CAS configuration file") final String file, @CliOption(key = { "group" }, specifiedDefaultValue = "", unspecifiedDefaultValue = "", help = "Group/module whose associated settings should be added to the CAS configuration file", optionContext = "Group/module whose associated settings should be added to the CAS configuration file", mandatory = true) final String group) throws Exception {
    if (StringUtils.isBlank(file)) {
        LOGGER.warn("Configuration file must be specified");
        return;
    }
    final File filePath = new File(file);
    if (filePath.exists() && (filePath.isDirectory() || !filePath.canRead() || !filePath.canWrite())) {
        LOGGER.warn("Configuration file [{}] is not readable/writable or is not a path to a file", filePath.getCanonicalPath());
        return;
    }
    final Map<String, ConfigurationMetadataProperty> results = findProperties(group);
    LOGGER.info("Located [{}] properties matching [{}]", results.size(), group);
    switch(FilenameUtils.getExtension(filePath.getName()).toLowerCase()) {
        case "properties":
            createConfigurationFileIfNeeded(filePath);
            final Properties props = loadPropertiesFromConfigurationFile(filePath);
            writeConfigurationPropertiesToFile(filePath, results, props);
            break;
        case "yml":
            createConfigurationFileIfNeeded(filePath);
            final Properties yamlProps = loadYamlPropertiesFromConfigurationFile(filePath);
            writeYamlConfigurationPropertiesToFile(filePath, results, yamlProps);
            break;
        default:
            LOGGER.warn("Configuration file format [{}] is not recognized", filePath.getCanonicalPath());
    }
}
Also used : ConfigurationMetadataProperty(org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty) Properties(java.util.Properties) File(java.io.File) CliCommand(org.springframework.shell.core.annotation.CliCommand)

Example 2 with ConfigurationMetadataProperty

use of org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty in project cas by apereo.

the class ConfigurationMetadataGenerator method processHints.

private Set<ConfigurationMetadataHint> processHints(final Collection<ConfigurationMetadataProperty> props, final Collection<ConfigurationMetadataProperty> groups) {
    final Set<ConfigurationMetadataHint> hints = new LinkedHashSet<>();
    for (final ConfigurationMetadataProperty entry : props) {
        try {
            final String propName = StringUtils.substringAfterLast(entry.getName(), ".");
            final String groupName = StringUtils.substringBeforeLast(entry.getName(), ".");
            final ConfigurationMetadataProperty grp = groups.stream().filter(g -> g.getName().equalsIgnoreCase(groupName)).findFirst().orElseThrow(() -> new IllegalArgumentException("Cant locate group " + groupName));
            final Matcher matcher = PATTERN_GENERICS.matcher(grp.getType());
            final String className = matcher.find() ? matcher.group(1) : grp.getType();
            final Class clazz = ClassUtils.getClass(className);
            final ConfigurationMetadataHint hint = new ConfigurationMetadataHint();
            hint.setName(entry.getName());
            if (clazz.isAnnotationPresent(RequiresModule.class)) {
                final RequiresModule annotation = Arrays.stream(clazz.getAnnotations()).filter(a -> a.annotationType().equals(RequiresModule.class)).findFirst().map(RequiresModule.class::cast).get();
                final ValueHint valueHint = new ValueHint();
                valueHint.setValue(Stream.of(RequiresModule.class.getName(), annotation.automated()).collect(Collectors.toList()));
                valueHint.setDescription(annotation.name());
                hint.getValues().add(valueHint);
            }
            final boolean foundRequiredProperty = StreamSupport.stream(RelaxedNames.forCamelCase(propName).spliterator(), false).map(n -> ReflectionUtils.findField(clazz, n)).anyMatch(f -> f != null && f.isAnnotationPresent(RequiredProperty.class));
            if (foundRequiredProperty) {
                final ValueHint valueHint = new ValueHint();
                valueHint.setValue(RequiredProperty.class.getName());
                hint.getValues().add(valueHint);
            }
            if (!hint.getValues().isEmpty()) {
                hints.add(hint);
            }
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    return hints;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) Arrays(java.util.Arrays) SneakyThrows(lombok.SneakyThrows) VoidVisitorAdapter(com.github.javaparser.ast.visitor.VoidVisitorAdapter) Reflections(org.reflections.Reflections) StringUtils(org.apache.commons.lang3.StringUtils) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) LiteralStringValueExpr(com.github.javaparser.ast.expr.LiteralStringValueExpr) ClassUtils(org.apache.commons.lang3.ClassUtils) QueryType(org.apereo.services.persondir.support.QueryType) Matcher(java.util.regex.Matcher) Map(java.util.Map) Expression(com.github.javaparser.ast.expr.Expression) CompilationUnit(com.github.javaparser.ast.CompilationUnit) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Resource(org.springframework.core.io.Resource) ValueHint(org.springframework.boot.configurationmetadata.ValueHint) Unchecked(org.jooq.lambda.Unchecked) Collection(java.util.Collection) Set(java.util.Set) AbstractLdapProperties(org.apereo.cas.configuration.model.support.ldap.AbstractLdapProperties) ConfigurationMetadataProperty(org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty) Collectors(java.util.stream.Collectors) PasswordPolicyProperties(org.apereo.cas.configuration.model.core.authentication.PasswordPolicyProperties) ClasspathHelper(org.reflections.util.ClasspathHelper) Modifier(com.github.javaparser.ast.Modifier) Serializable(java.io.Serializable) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Stream(java.util.stream.Stream) Predicate(com.google.common.base.Predicate) Pattern(java.util.regex.Pattern) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) TypeElementsScanner(org.reflections.scanners.TypeElementsScanner) RequiresModule(org.apereo.cas.configuration.support.RequiresModule) HashMap(java.util.HashMap) PrincipalTransformationProperties(org.apereo.cas.configuration.model.core.authentication.PrincipalTransformationProperties) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) HashSet(java.util.HashSet) DefaultPrettyPrinter(com.fasterxml.jackson.core.util.DefaultPrettyPrinter) StreamSupport(java.util.stream.StreamSupport) ConfigurationBuilder(org.reflections.util.ConfigurationBuilder) LinkedHashSet(java.util.LinkedHashSet) RelaxedNames(org.springframework.boot.bind.RelaxedNames) BooleanLiteralExpr(com.github.javaparser.ast.expr.BooleanLiteralExpr) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileInputStream(java.io.FileInputStream) RequiredProperty(org.apereo.cas.configuration.support.RequiredProperty) CaseCanonicalizationMode(org.apereo.services.persondir.util.CaseCanonicalizationMode) File(java.io.File) SubTypesScanner(org.reflections.scanners.SubTypesScanner) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) ReflectionUtils(org.springframework.util.ReflectionUtils) LdapSearchEntryHandlersProperties(org.apereo.cas.configuration.model.support.ldap.LdapSearchEntryHandlersProperties) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) PrettyPrinter(com.fasterxml.jackson.core.PrettyPrinter) JavaParser(com.github.javaparser.JavaParser) InputStream(java.io.InputStream) RequiresModule(org.apereo.cas.configuration.support.RequiresModule) Matcher(java.util.regex.Matcher) ValueHint(org.springframework.boot.configurationmetadata.ValueHint) ConfigurationMetadataProperty(org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty) RequiredProperty(org.apereo.cas.configuration.support.RequiredProperty)

Example 3 with ConfigurationMetadataProperty

use of org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty in project cas by apereo.

the class ConfigurationMetadataGenerator method execute.

/**
 * Execute.
 *
 * @throws Exception the exception
 */
public void execute() throws Exception {
    final File jsonFile = new File(buildDir, "classes/java/main/META-INF/spring-configuration-metadata.json");
    final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    final TypeReference<Map<String, Set<ConfigurationMetadataProperty>>> values = new TypeReference<Map<String, Set<ConfigurationMetadataProperty>>>() {
    };
    final Map<String, Set> jsonMap = mapper.readValue(jsonFile, values);
    final Set<ConfigurationMetadataProperty> properties = jsonMap.get("properties");
    final Set<ConfigurationMetadataProperty> groups = jsonMap.get("groups");
    final Set<ConfigurationMetadataProperty> collectedProps = new HashSet<>();
    final Set<ConfigurationMetadataProperty> collectedGroups = new HashSet<>();
    properties.stream().filter(p -> NESTED_TYPE_PATTERN.matcher(p.getType()).matches()).forEach(Unchecked.consumer(p -> {
        final Matcher matcher = NESTED_TYPE_PATTERN.matcher(p.getType());
        final boolean indexBrackets = matcher.matches();
        final String typeName = matcher.group(1);
        final String typePath = buildTypeSourcePath(typeName);
        parseCompilationUnit(collectedProps, collectedGroups, p, typePath, typeName, indexBrackets);
    }));
    properties.addAll(collectedProps);
    groups.addAll(collectedGroups);
    final Set<ConfigurationMetadataHint> hints = processHints(properties, groups);
    jsonMap.put("properties", properties);
    jsonMap.put("groups", groups);
    jsonMap.put("hints", hints);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    final PrettyPrinter pp = new DefaultPrettyPrinter();
    mapper.writer(pp).writeValue(jsonFile, jsonMap);
}
Also used : ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) Arrays(java.util.Arrays) SneakyThrows(lombok.SneakyThrows) VoidVisitorAdapter(com.github.javaparser.ast.visitor.VoidVisitorAdapter) Reflections(org.reflections.Reflections) StringUtils(org.apache.commons.lang3.StringUtils) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) LiteralStringValueExpr(com.github.javaparser.ast.expr.LiteralStringValueExpr) ClassUtils(org.apache.commons.lang3.ClassUtils) QueryType(org.apereo.services.persondir.support.QueryType) Matcher(java.util.regex.Matcher) Map(java.util.Map) Expression(com.github.javaparser.ast.expr.Expression) CompilationUnit(com.github.javaparser.ast.CompilationUnit) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Resource(org.springframework.core.io.Resource) ValueHint(org.springframework.boot.configurationmetadata.ValueHint) Unchecked(org.jooq.lambda.Unchecked) Collection(java.util.Collection) Set(java.util.Set) AbstractLdapProperties(org.apereo.cas.configuration.model.support.ldap.AbstractLdapProperties) ConfigurationMetadataProperty(org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty) Collectors(java.util.stream.Collectors) PasswordPolicyProperties(org.apereo.cas.configuration.model.core.authentication.PasswordPolicyProperties) ClasspathHelper(org.reflections.util.ClasspathHelper) Modifier(com.github.javaparser.ast.Modifier) Serializable(java.io.Serializable) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Stream(java.util.stream.Stream) Predicate(com.google.common.base.Predicate) Pattern(java.util.regex.Pattern) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) TypeElementsScanner(org.reflections.scanners.TypeElementsScanner) RequiresModule(org.apereo.cas.configuration.support.RequiresModule) HashMap(java.util.HashMap) PrincipalTransformationProperties(org.apereo.cas.configuration.model.core.authentication.PrincipalTransformationProperties) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) HashSet(java.util.HashSet) DefaultPrettyPrinter(com.fasterxml.jackson.core.util.DefaultPrettyPrinter) StreamSupport(java.util.stream.StreamSupport) ConfigurationBuilder(org.reflections.util.ConfigurationBuilder) LinkedHashSet(java.util.LinkedHashSet) RelaxedNames(org.springframework.boot.bind.RelaxedNames) BooleanLiteralExpr(com.github.javaparser.ast.expr.BooleanLiteralExpr) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileInputStream(java.io.FileInputStream) RequiredProperty(org.apereo.cas.configuration.support.RequiredProperty) CaseCanonicalizationMode(org.apereo.services.persondir.util.CaseCanonicalizationMode) File(java.io.File) SubTypesScanner(org.reflections.scanners.SubTypesScanner) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) ReflectionUtils(org.springframework.util.ReflectionUtils) LdapSearchEntryHandlersProperties(org.apereo.cas.configuration.model.support.ldap.LdapSearchEntryHandlersProperties) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) PrettyPrinter(com.fasterxml.jackson.core.PrettyPrinter) JavaParser(com.github.javaparser.JavaParser) InputStream(java.io.InputStream) DefaultPrettyPrinter(com.fasterxml.jackson.core.util.DefaultPrettyPrinter) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Matcher(java.util.regex.Matcher) DefaultPrettyPrinter(com.fasterxml.jackson.core.util.DefaultPrettyPrinter) PrettyPrinter(com.fasterxml.jackson.core.PrettyPrinter) ConfigurationMetadataProperty(org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty) TypeReference(com.fasterxml.jackson.core.type.TypeReference) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 4 with ConfigurationMetadataProperty

use of org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty in project cas by apereo.

the class CasConfigurationMetadataServerController method search.

/**
 * Search for property.
 *
 * @param name the name
 * @return the response entity
 */
@GetMapping(path = "/search")
public ResponseEntity<List<ConfigurationMetadataSearchResult>> search(@RequestParam(value = "name", required = false) final String name) {
    List results = new ArrayList<>();
    final Map<String, ConfigurationMetadataProperty> allProps = repository.getRepository().getAllProperties();
    if (StringUtils.isNotBlank(name) && RegexUtils.isValidRegex(name)) {
        final String names = StreamSupport.stream(RelaxedNames.forCamelCase(name).spliterator(), false).map(Object::toString).collect(Collectors.joining("|"));
        final Pattern pattern = RegexUtils.createPattern(names);
        results = allProps.entrySet().stream().filter(propEntry -> RegexUtils.find(pattern, propEntry.getKey())).map(propEntry -> new ConfigurationMetadataSearchResult(propEntry.getValue(), repository)).collect(Collectors.toList());
        Collections.sort(results);
    }
    return ResponseEntity.ok(results);
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) RelaxedNames(org.springframework.boot.bind.RelaxedNames) RequestParam(org.springframework.web.bind.annotation.RequestParam) BaseCasMvcEndpoint(org.apereo.cas.web.BaseCasMvcEndpoint) HttpServletResponse(javax.servlet.http.HttpServletResponse) StringUtils(org.apache.commons.lang3.StringUtils) ConfigurationMetadataProperty(org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty) Collectors(java.util.stream.Collectors) RegexUtils(org.apereo.cas.util.RegexUtils) ArrayList(java.util.ArrayList) CasConfigurationMetadataRepository(org.apereo.cas.metadata.CasConfigurationMetadataRepository) ModelAndView(org.springframework.web.servlet.ModelAndView) Slf4j(lombok.extern.slf4j.Slf4j) HttpServletRequest(javax.servlet.http.HttpServletRequest) List(java.util.List) Map(java.util.Map) GetMapping(org.springframework.web.bind.annotation.GetMapping) ResponseEntity(org.springframework.http.ResponseEntity) StreamSupport(java.util.stream.StreamSupport) Pattern(java.util.regex.Pattern) ConfigurationMetadataGroup(org.springframework.boot.configurationmetadata.ConfigurationMetadataGroup) Collections(java.util.Collections) Pattern(java.util.regex.Pattern) ConfigurationMetadataProperty(org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 5 with ConfigurationMetadataProperty

use of org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty in project cas by apereo.

the class FindPropertiesCommand method find.

/**
 * Find.
 *
 * @param strict          the strict
 * @param propertyPattern the property pattern
 * @return the map
 */
public Map<String, ConfigurationMetadataProperty> find(final boolean strict, final Pattern propertyPattern) {
    final Map<String, ConfigurationMetadataProperty> results = new LinkedHashMap<>();
    final CasConfigurationMetadataRepository repository = new CasConfigurationMetadataRepository();
    final Map<String, ConfigurationMetadataProperty> props = repository.getRepository().getAllProperties();
    props.forEach((k, v) -> {
        final boolean matched = StreamSupport.stream(RelaxedNames.forCamelCase(k).spliterator(), false).map(Object::toString).anyMatch(name -> strict ? RegexUtils.matches(propertyPattern, name) : RegexUtils.find(propertyPattern, name));
        if (matched) {
            results.put(k, v);
        }
    });
    return results;
}
Also used : ConfigurationMetadataProperty(org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty) CasConfigurationMetadataRepository(org.apereo.cas.metadata.CasConfigurationMetadataRepository) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

ConfigurationMetadataProperty (org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty)6 Map (java.util.Map)4 Slf4j (lombok.extern.slf4j.Slf4j)4 File (java.io.File)3 List (java.util.List)3 Pattern (java.util.regex.Pattern)3 Collectors (java.util.stream.Collectors)3 StreamSupport (java.util.stream.StreamSupport)3 StringUtils (org.apache.commons.lang3.StringUtils)3 CasConfigurationMetadataRepository (org.apereo.cas.metadata.CasConfigurationMetadataRepository)3 JsonInclude (com.fasterxml.jackson.annotation.JsonInclude)2 PrettyPrinter (com.fasterxml.jackson.core.PrettyPrinter)2 TypeReference (com.fasterxml.jackson.core.type.TypeReference)2 DefaultPrettyPrinter (com.fasterxml.jackson.core.util.DefaultPrettyPrinter)2 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 JavaParser (com.github.javaparser.JavaParser)2 CompilationUnit (com.github.javaparser.ast.CompilationUnit)2 Modifier (com.github.javaparser.ast.Modifier)2 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)2