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