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