001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2017-2022 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.util.events;
020
021import java.util.Collections;
022import java.util.HashMap;
023import java.util.HashSet;
024import java.util.Map;
025import java.util.Optional;
026import java.util.Set;
027import java.util.concurrent.ConcurrentHashMap;
028import java.util.stream.Collectors;
029import org.jgrapes.core.Event;
030import org.jgrapes.core.Manager;
031import org.jgrapes.util.ConfigurationStore;
032
033/**
034 * An event to indicate that configuration information has been
035 * updated.
036 * 
037 * Configuration information provided by this event is organized
038 * by paths and associated key/value pairs. The path information
039 * should be used by components to select the information important
040 * to them. Often, a component simply matches the path from the event
041 * with its own path in the component hierarchy 
042 * (see {@link Manager#componentPath()}). But paths can also be used
043 * to structure information in a way that is completely independent of
044 * the implementation's structure as the filtering is completely up
045 * to the component.
046 */
047@SuppressWarnings("PMD.AvoidSynchronizedStatement")
048public class ConfigurationUpdate extends Event<Void> {
049
050    @SuppressWarnings("PMD.UseConcurrentHashMap")
051    private final Map<String, Map<String, Object>> structuredValues
052        = new HashMap<>();
053    private final Map<String, Map<String, Object>> flattenedCache
054        = new ConcurrentHashMap<>();
055
056    /**
057     * Return all paths affected by this event.
058     * 
059     * @return the paths
060     */
061    public Set<String> paths() {
062        synchronized (structuredValues) {
063            return new HashSet<>(structuredValues.keySet());
064        }
065    }
066
067    private Optional<Map<String, Object>> flattened(String path) {
068        return Optional.ofNullable(flattenedCache.computeIfAbsent(path,
069            p -> ConfigurationStore.flatten(structuredValues.get(path))));
070    }
071
072    /**
073     * Return the properties for a given path if any exist.
074     * If a property has a structured value (list or collection),
075     * the values are returned as several entries as described in
076     * {@link ConfigurationStore#flatten(Map)}. All values are
077     * converted to their string representation.
078     * 
079     * @param path the path
080     * @return the updated values or `null` if the path has been
081     * removed (implies the removal of all values for that path).
082     */
083    public Optional<Map<String, String>> values(String path) {
084        if (structuredValues.get(path) == null) {
085            return Optional.empty();
086        }
087        Map<String, Object> result = flattened(path).get();
088        return Optional.of(result).map(o -> o.entrySet().stream()
089            .collect(
090                Collectors.toMap(Map.Entry::getKey, e -> ConfigurationStore
091                    .as(e.getValue(), String.class).orElse(null))));
092    }
093
094    /**
095     * Return the value with the given path and key if it exists
096     * and is of or can be converted to the requested type.
097     *
098     * @param <T> the generic type
099     * @param path the path
100     * @param key the key
101     * @param as the as
102     * @return the optional
103     */
104    @SuppressWarnings("PMD.ShortVariable")
105    public <T> Optional<T> value(String path, String key, Class<T> as) {
106        return flattened(path)
107            .flatMap(map -> ConfigurationStore.as(map.get(key), as));
108    }
109
110    /**
111     * Return the value with the given path and key if it exists as string.
112     * 
113     * @param path the path
114     * @param key the key
115     * @return the value
116     */
117    public Optional<String> value(String path, String key) {
118        return value(path, key, String.class);
119    }
120
121    /**
122     * Return the properties for a given path if they exists as
123     * a map with (possibly) structured values (see 
124     * {@link ConfigurationStore#structured(String)}). The type
125     * of the value depends on the configuration store used.
126     * Some configuration stores support types other than string,
127     * some don't. Too avoid any problems, it is strongly recommended
128     * to call {@link ConfigurationStore#as(Object, Class)} for any
129     * value obtained from the result of this method.
130     * 
131     * @param path the path
132     * @return the updated values or `null` if the path has been
133     * removed (implies the removal of all values for that path).
134     */
135    public Optional<Map<String, Object>> structured(String path) {
136        if (structuredValues.get(path) == null) {
137            return Optional.empty();
138        }
139        return Optional
140            .of(Collections.unmodifiableMap(structuredValues.get(path)));
141    }
142
143    /**
144     * Set new (updated), possibly structured configuration values (see
145     * {@link ConfigurationStore#structure(Map)} for the given path.
146     * Any information associated with the path before the invocation
147     * of this method is replaced.  
148     * 
149     * @param path the value's path
150     * @return the event for easy chaining
151     */
152    @SuppressWarnings("unchecked")
153    public ConfigurationUpdate set(String path, Map<String, ?> values) {
154        if (path == null || !path.startsWith("/")) {
155            throw new IllegalArgumentException("Path must start with \"/\".");
156        }
157        structuredValues.put(path, (Map<String, Object>) values);
158        return this;
159    }
160
161    /**
162     * Add a new (or updated) configuration value for the given path
163     * and key.
164     * 
165     * @param path the value's path
166     * @param selector the key or the path within the structured value
167     * @param value the value
168     * @return the event for easy chaining
169     */
170    public ConfigurationUpdate add(String path, String selector, Object value) {
171        if (path == null || !path.startsWith("/")) {
172            throw new IllegalArgumentException("Path must start with \"/\".");
173        }
174        synchronized (structuredValues) {
175            Map<String, Object> scoped = structuredValues
176                .computeIfAbsent(path, newKey -> new HashMap<>());
177            ConfigurationStore.mergeValue(scoped, selector, value);
178            flattenedCache.remove(path);
179        }
180        return this;
181    }
182
183    /**
184     * Associate the given path with `null`. This signals to handlers 
185     * that the path has been removed from the configuration.
186     * 
187     * @param path the path that has been removed
188     * @return the event for easy chaining
189     */
190    public ConfigurationUpdate removePath(String path) {
191        if (path == null || !path.startsWith("/")) {
192            throw new IllegalArgumentException("Path must start with \"/\".");
193        }
194        structuredValues.put(path, null);
195        return this;
196    }
197
198}