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; 026import java.util.function.Supplier; 027 028/** 029 * A simple session data storage backed by a thread-safe map. 030 */ 031public final class DefaultSessionData 032 implements SessionData 033{ 034 035 private final ConcurrentMap<Object, Object> data; 036 037 public DefaultSessionData() 038 { 039 data = new ConcurrentHashMap<>(); 040 } 041 042 public void set( Object key, Object value ) 043 { 044 requireNonNull( key, "key cannot be null" ); 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 requireNonNull( key, "key cannot be null" ); 059 060 if ( newValue != null ) 061 { 062 if ( oldValue == null ) 063 { 064 return data.putIfAbsent( key, newValue ) == null; 065 } 066 return data.replace( key, oldValue, newValue ); 067 } 068 else 069 { 070 if ( oldValue == null ) 071 { 072 return !data.containsKey( key ); 073 } 074 return data.remove( key, oldValue ); 075 } 076 } 077 078 public Object get( Object key ) 079 { 080 requireNonNull( key, "key cannot be null" ); 081 082 return data.get( key ); 083 } 084 085 public Object computeIfAbsent( Object key, Supplier<Object> supplier ) 086 { 087 return data.computeIfAbsent( key, k -> supplier.get() ); 088 } 089}