001 /* 002 * Sonar, open source software quality management tool. 003 * Copyright (C) 2008-2012 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.plugins.core.timemachine; 021 022 import org.sonar.plugins.core.timemachine.tracking.HashedSequence; 023 import org.sonar.plugins.core.timemachine.tracking.HashedSequenceComparator; 024 import org.sonar.plugins.core.timemachine.tracking.StringText; 025 import org.sonar.plugins.core.timemachine.tracking.StringTextComparator; 026 027 public class ViolationTrackingBlocksRecognizer { 028 029 private final HashedSequence<StringText> a; 030 private final HashedSequence<StringText> b; 031 private final HashedSequenceComparator<StringText> cmp; 032 033 public ViolationTrackingBlocksRecognizer(String referenceSource, String source) { 034 this(new StringText(referenceSource), new StringText(source), StringTextComparator.IGNORE_WHITESPACE); 035 } 036 037 private ViolationTrackingBlocksRecognizer(StringText a, StringText b, StringTextComparator cmp) { 038 this.a = HashedSequence.wrap(a, cmp); 039 this.b = HashedSequence.wrap(b, cmp); 040 this.cmp = new HashedSequenceComparator<StringText>(cmp); 041 } 042 043 /** 044 * @param startA number of line from first version of text (numbering starts from 0) 045 * @param startB number of line from second version of text (numbering starts from 0) 046 */ 047 public int computeLengthOfMaximalBlock(int startA, int startB) { 048 if (!cmp.equals(a, startA, b, startB)) { 049 return 0; 050 } 051 int length = 0; 052 int ai = startA; 053 int bi = startB; 054 while (ai < a.length() && bi < b.length() && cmp.equals(a, ai, b, bi)) { 055 ai++; 056 bi++; 057 length++; 058 } 059 ai = startA; 060 bi = startB; 061 while (ai >= 0 && bi >= 0 && cmp.equals(a, ai, b, bi)) { 062 ai--; 063 bi--; 064 length++; 065 } 066 // Note that position (startA, startB) was counted twice 067 return length - 1; 068 } 069 070 }