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 java.util.concurrent.ConcurrentHashMap;
023import java.util.concurrent.ConcurrentMap;
024
025/**
026 * A simple session data storage backed by a thread-safe map.
027 */
028public final class DefaultSessionData
029    implements SessionData
030{
031
032    private final ConcurrentMap<Object, Object> data;
033
034    public DefaultSessionData()
035    {
036        data = new ConcurrentHashMap<Object, Object>();
037    }
038
039    public void set( Object key, Object value )
040    {
041        if ( key == null )
042        {
043            throw new IllegalArgumentException( "key must not be null" );
044        }
045
046        if ( value != null )
047        {
048            data.put( key, value );
049        }
050        else
051        {
052            data.remove( key );
053        }
054    }
055
056    public boolean set( Object key, Object oldValue, Object newValue )
057    {
058        if ( key == null )
059        {
060            throw new IllegalArgumentException( "key must not be null" );
061        }
062
063        if ( newValue != null )
064        {
065            if ( oldValue == null )
066            {
067                return data.putIfAbsent( key, newValue ) == null;
068            }
069            return data.replace( key, oldValue, newValue );
070        }
071        else
072        {
073            if ( oldValue == null )
074            {
075                return !data.containsKey( key );
076            }
077            return data.remove( key, oldValue );
078        }
079    }
080
081    public Object get( Object key )
082    {
083        if ( key == null )
084        {
085            throw new IllegalArgumentException( "key must not be null" );
086        }
087
088        return data.get( key );
089    }
090
091}