01 /*
02 * SPDX-License-Identifier: Apache-2.0
03 *
04 * Copyright 2008-2017 the original author or authors.
05 *
06 * Licensed under the Apache License, Version 2.0 (the "License");
07 * you may not use this file except in compliance with the License.
08 * You may obtain a copy of the License at
09 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package org.codehaus.griffon.runtime.core.storage;
19
20 import griffon.core.storage.ObjectStorage;
21
22 import javax.annotation.Nonnull;
23 import javax.annotation.Nullable;
24 import java.util.Collection;
25 import java.util.LinkedHashSet;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.concurrent.ConcurrentHashMap;
29
30 import static griffon.util.GriffonNameUtils.isBlank;
31 import static java.util.Collections.unmodifiableSet;
32 import static java.util.Objects.requireNonNull;
33
34 /**
35 * @author Andres Almiray
36 * @since 2.0.0
37 */
38 public class DefaultObjectStorage<T> implements ObjectStorage<T> {
39 private static final String DEFAULT_KEY = "default";
40 private final Map<String, T> instances = new ConcurrentHashMap<>();
41
42 @Nonnull
43 @Override
44 public String[] getKeys() {
45 Set<String> keys = instances.keySet();
46 return keys.toArray(new String[keys.size()]);
47 }
48
49 @Nonnull
50 @Override
51 public Collection<T> getValues() {
52 Set<T> values = new LinkedHashSet<>();
53 values.addAll(instances.values());
54 return unmodifiableSet(values);
55 }
56
57 @Nullable
58 @Override
59 public T get(@Nonnull String key) {
60 return instances.get(resolveKey(key));
61 }
62
63 @Nullable
64 @Override
65 public T remove(@Nonnull String key) {
66 return instances.remove(resolveKey(key));
67 }
68
69 @Override
70 public void set(@Nonnull String key, @Nonnull T instance) {
71 instances.put(resolveKey(key), requireNonNull(instance, "Argument 'instance' must not be null"));
72 }
73
74 @Override
75 public boolean contains(@Nonnull String key) {
76 return instances.containsKey(resolveKey(key));
77 }
78
79 @Nonnull
80 private String resolveKey(@Nonnull String key) {
81 return isBlank(key) ? DEFAULT_KEY : key.trim();
82 }
83 }
|