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.statement; 021 022 import java.util.List; 023 024 import org.sonar.duplications.token.Token; 025 026 public class Statement { 027 028 private final int startLine; 029 private final int endLine; 030 private final String value; 031 032 /** 033 * Cache for hash code. 034 */ 035 private int hash; 036 037 public Statement(int startLine, int endLine, String value) { 038 this.startLine = startLine; 039 this.endLine = endLine; 040 this.value = value; 041 } 042 043 public Statement(List<Token> tokens) { 044 if (tokens == null || tokens.isEmpty()) { 045 throw new IllegalArgumentException("A statement can't be initialized with an empty list of tokens"); 046 } 047 StringBuilder sb = new StringBuilder(); 048 for (Token token : tokens) { 049 sb.append(token.getValue()); 050 } 051 this.value = sb.toString(); 052 this.startLine = tokens.get(0).getLine(); 053 this.endLine = tokens.get(tokens.size() - 1).getLine(); 054 } 055 056 public int getStartLine() { 057 return startLine; 058 } 059 060 public int getEndLine() { 061 return endLine; 062 } 063 064 public String getValue() { 065 return value; 066 } 067 068 @Override 069 public int hashCode() { 070 int h = hash; 071 if (h == 0) { 072 h = value.hashCode(); 073 h = 31 * h + startLine; 074 h = 31 * h + endLine; 075 hash = h; 076 } 077 return h; 078 } 079 080 @Override 081 public boolean equals(Object obj) { 082 if (!(obj instanceof Statement)) { 083 return false; 084 } 085 Statement other = (Statement) obj; 086 return startLine == other.startLine 087 && endLine == other.endLine 088 && value.equals(other.value); 089 } 090 091 @Override 092 public String toString() { 093 return "[" + getStartLine() + "-" + getEndLine() + "] [" + getValue() + "]"; 094 } 095 096 }