01 /*
02 * Copyright 2008-2014 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.Map;
23 import java.util.Set;
24 import java.util.concurrent.ConcurrentHashMap;
25
26 import static griffon.util.GriffonNameUtils.isBlank;
27 import static java.util.Objects.requireNonNull;
28
29 /**
30 * @author Andres Almiray
31 * @since 2.0.0
32 */
33 public class DefaultObjectStorage<T> implements ObjectStorage<T> {
34 private final Map<String, T> instances = new ConcurrentHashMap<>();
35 private static final String DEFAULT_KEY = "default";
36
37 @Nonnull
38 @Override
39 public String[] getKeys() {
40 Set<String> keys = instances.keySet();
41 return keys.toArray(new String[keys.size()]);
42 }
43
44 @Nullable
45 @Override
46 public T get(@Nonnull String key) {
47 return instances.get(resolveKey(key));
48 }
49
50 @Nullable
51 @Override
52 public T remove(@Nonnull String key) {
53 return instances.remove(resolveKey(key));
54 }
55
56 @Override
57 public void set(@Nonnull String key, @Nonnull T instance) {
58 instances.put(resolveKey(key), requireNonNull(instance, "Argument 'instance' must not be null"));
59 }
60
61 @Override
62 public boolean contains(@Nonnull String key) {
63 return instances.containsKey(resolveKey(key));
64 }
65
66 @Nonnull
67 private String resolveKey(@Nonnull String key) {
68 return isBlank(key) ? DEFAULT_KEY : key.trim();
69 }
70 }
|