001package org.eclipse.aether;
002
003/*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements.  See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership.  The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License.  You may obtain a copy of the License at
011 * 
012 *  http://www.apache.org/licenses/LICENSE-2.0
013 * 
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied.  See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022import static java.util.Objects.requireNonNull;
023
024import java.util.concurrent.ConcurrentHashMap;
025import java.util.concurrent.ConcurrentMap;
026
027/**
028 * A simple session data storage backed by a thread-safe map.
029 */
030public final class DefaultSessionData
031    implements SessionData
032{
033
034    private final ConcurrentMap<Object, Object> data;
035
036    public DefaultSessionData()
037    {
038        data = new ConcurrentHashMap<>();
039    }
040
041    public void set( Object key, Object value )
042    {
043        requireNonNull( key, "key cannot be null" );
044
045        if ( value != null )
046        {
047            data.put( key, value );
048        }
049        else
050        {
051            data.remove( key );
052        }
053    }
054
055    public boolean set( Object key, Object oldValue, Object newValue )
056    {
057        requireNonNull( key, "key cannot be null" );
058
059        if ( newValue != null )
060        {
061            if ( oldValue == null )
062            {
063                return data.putIfAbsent( key, newValue ) == null;
064            }
065            return data.replace( key, oldValue, newValue );
066        }
067        else
068        {
069            if ( oldValue == null )
070            {
071                return !data.containsKey( key );
072            }
073            return data.remove( key, oldValue );
074        }
075    }
076
077    public Object get( Object key )
078    {
079        requireNonNull( key, "key cannot be null" );
080
081        return data.get( key );
082    }
083
084}