001 /* 002 * Sonar, open source software quality management tool. 003 * Copyright (C) 2008-2011 SonarSource 004 * mailto:contact AT sonarsource DOT com 005 * 006 * Sonar is free software; you can redistribute it and/or 007 * modify it under the terms of the GNU Lesser General Public 008 * License as published by the Free Software Foundation; either 009 * version 3 of the License, or (at your option) any later version. 010 * 011 * Sonar is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 014 * Lesser General Public License for more details. 015 * 016 * You should have received a copy of the GNU Lesser General Public 017 * License along with Sonar; if not, write to the Free Software 018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 019 */ 020 package org.sonar.duplications.index; 021 022 import java.io.Serializable; 023 import java.util.Collection; 024 import java.util.Comparator; 025 026 import org.sonar.duplications.block.Block; 027 import org.sonar.duplications.block.ByteArray; 028 029 import com.google.common.collect.HashMultimap; 030 import com.google.common.collect.TreeMultimap; 031 032 public class MemoryCloneIndex implements CloneIndex { 033 034 private final TreeMultimap<String, Block> filenameIndex; 035 private final HashMultimap<ByteArray, Block> sequenceHashIndex; 036 037 private static final class ValueComparator implements Comparator<Block>, Serializable { 038 039 private static final long serialVersionUID = 6048010242032502222L; 040 041 public int compare(Block o1, Block o2) { 042 if (o2.getResourceId().equals(o1.getResourceId())) { 043 return o1.getIndexInFile() - o2.getIndexInFile(); 044 } 045 return o1.getResourceId().compareTo(o2.getResourceId()); 046 } 047 } 048 049 private static final class KeyComparator implements Comparator<String>, Serializable { 050 051 private static final long serialVersionUID = 8705841881237170539L; 052 053 public int compare(String o1, String o2) { 054 return o1.compareTo(o2); 055 } 056 } 057 058 public MemoryCloneIndex() { 059 filenameIndex = TreeMultimap.create(new KeyComparator(), new ValueComparator()); 060 sequenceHashIndex = HashMultimap.create(); 061 } 062 063 public Collection<String> getAllUniqueResourceId() { 064 return filenameIndex.keySet(); 065 } 066 067 public boolean containsResourceId(String resourceId) { 068 return filenameIndex.containsKey(resourceId); 069 } 070 071 public Collection<Block> getByResourceId(String fileName) { 072 return filenameIndex.get(fileName); 073 } 074 075 public Collection<Block> getBySequenceHash(ByteArray sequenceHash) { 076 return sequenceHashIndex.get(sequenceHash); 077 } 078 079 public void insert(Block tuple) { 080 filenameIndex.put(tuple.getResourceId(), tuple); 081 sequenceHashIndex.put(tuple.getBlockHash(), tuple); 082 } 083 084 }