View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.eclipse.aether;
20  
21  import java.util.concurrent.ConcurrentHashMap;
22  import java.util.concurrent.ConcurrentMap;
23  import java.util.function.Supplier;
24  
25  import static java.util.Objects.requireNonNull;
26  
27  /**
28   * A simple session data storage backed by a thread-safe map.
29   */
30  public final class DefaultSessionData implements SessionData {
31  
32      private final ConcurrentMap<Object, Object> data;
33  
34      public DefaultSessionData() {
35          data = new ConcurrentHashMap<>();
36      }
37  
38      public void set(Object key, Object value) {
39          requireNonNull(key, "key cannot be null");
40  
41          if (value != null) {
42              data.put(key, value);
43          } else {
44              data.remove(key);
45          }
46      }
47  
48      public boolean set(Object key, Object oldValue, Object newValue) {
49          requireNonNull(key, "key cannot be null");
50  
51          if (newValue != null) {
52              if (oldValue == null) {
53                  return data.putIfAbsent(key, newValue) == null;
54              }
55              return data.replace(key, oldValue, newValue);
56          } else {
57              if (oldValue == null) {
58                  return !data.containsKey(key);
59              }
60              return data.remove(key, oldValue);
61          }
62      }
63  
64      public Object get(Object key) {
65          requireNonNull(key, "key cannot be null");
66  
67          return data.get(key);
68      }
69  
70      public Object computeIfAbsent(Object key, Supplier<Object> supplier) {
71          return data.computeIfAbsent(key, k -> supplier.get());
72      }
73  }