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