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