001/*
002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 */
019package org.nuxeo.ecm.core.event.impl;
020
021import java.util.HashMap;
022import java.util.HashSet;
023import java.util.Map;
024import java.util.Set;
025
026/**
027 * A map used to track duplicates.
028 * <p>
029 * This class is not synchronized on read; this means you need to populate the map before using it.
030 *
031 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
032 */
033public class AssocMap {
034
035    protected final Map<String, Set<String>> peers = new HashMap<String, Set<String>>();
036
037    public synchronized void put(String x, String y) {
038        Set<String> px = peers.get(x);
039        Set<String> py = peers.get(y);
040        if (px == py) {
041            return; // already associated
042        }
043        if (px == null) {
044            py.add(x);
045            peers.put(x, py);
046        } else if (py == null) {
047            px.add(y);
048            peers.put(y, px);
049        } else { // both members are already in relation with other members
050            Set<String> set = new HashSet<String>();
051            set.addAll(px);
052            set.addAll(py);
053            for (String key : set.toArray(new String[set.size()])) {
054                peers.put(key, set);
055            }
056        }
057    }
058
059    public boolean isPeerOf(String x, String y) {
060        Set<String> set = peers.get(x);
061        return set != null && set.contains(y);
062    }
063
064}