package fi.vtt.simantics.procore.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.simantics.db.Disposable; import org.simantics.db.Resource; import org.simantics.db.impl.internal.RandomAccessValueSupport; import org.simantics.db.impl.internal.ResourceData; import org.simantics.utils.datastructures.Pair; /** * A simple implementation of {@link RandomAccessValueSupport}. * * @author Tuukka Lehtonen */ public class RandomAccessValueSupportImpl implements RandomAccessValueSupport { private final static boolean DEBUG = false; /** * The map of services maintained by the workbench window. These services * are initialized during workbench window during the * {@link #configureShell(Shell)}. This value is null until * a service is registered. */ private Map values = new HashMap(); /** * Constructs a new random access value registry. */ public RandomAccessValueSupportImpl() { } @Override public ResourceData get(Resource resource) { synchronized (this) { return values.get(resource); } } /** * Registers a service with this locator. If there is an existing service * matching the same api and it implements * {@link Disposable}, it will be disposed. * * @param api * This is the interface that the service implements. Must not be * null. * @param service * The service to register. This must be some implementation of * api. This value must not be null. */ public void put(final Resource resource, final ResourceData data) { synchronized (this) { final ResourceData current = values.get(resource); if (current != null) throw new IllegalStateException( "Value already registered for resource " + resource + ": " + current + ". Tried to register " + data); if (DEBUG) System.out.println(this + ": register " + resource + " -> " + data); values.put(resource, data); } } @Override public Collection> entries() { synchronized (this) { if (values.isEmpty()) return Collections.emptyList(); Collection> result = new ArrayList>( values.size() ); for (Map.Entry entry : values.entrySet()) { result.add( Pair.make( entry.getKey(), entry.getValue() ) ); } return result; } } @Override public Collection> removeAll() { synchronized (this) { if (values.isEmpty()) return Collections.emptyList(); if (DEBUG) System.out.println(this + ": remove " + values.size() + " registrations"); Collection> result = new ArrayList>( values.size() ); for (Map.Entry entry : values.entrySet()) { result.add( Pair.make( entry.getKey(), entry.getValue() ) ); } values.clear(); return result; } } }