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 public DefaultSessionData() { 035 data = new ConcurrentHashMap<>(); 036 } 037 038 public void set(Object key, Object value) { 039 requireNonNull(key, "key cannot be null"); 040 041 if (value != null) { 042 data.put(key, value); 043 } else { 044 data.remove(key); 045 } 046 } 047 048 public boolean set(Object key, Object oldValue, Object newValue) { 049 requireNonNull(key, "key cannot be null"); 050 051 if (newValue != null) { 052 if (oldValue == null) { 053 return data.putIfAbsent(key, newValue) == null; 054 } 055 return data.replace(key, oldValue, newValue); 056 } else { 057 if (oldValue == null) { 058 return !data.containsKey(key); 059 } 060 return data.remove(key, oldValue); 061 } 062 } 063 064 public Object get(Object key) { 065 requireNonNull(key, "key cannot be null"); 066 067 return data.get(key); 068 } 069 070 public Object computeIfAbsent(Object key, Supplier<Object> supplier) { 071 return data.computeIfAbsent(key, k -> supplier.get()); 072 } 073}