001/*
002 * SonarQube
003 * Copyright (C) 2009-2017 SonarSource SA
004 * mailto:info AT sonarsource DOT com
005 *
006 * This program 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 * This program 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 License
017 * along with this program; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019 */
020package org.sonar.api.batch.fs.internal.charhandler;
021
022import java.nio.ByteBuffer;
023import java.nio.CharBuffer;
024import java.nio.charset.CharacterCodingException;
025import java.nio.charset.CharsetEncoder;
026import java.nio.charset.CodingErrorAction;
027import java.nio.charset.StandardCharsets;
028import java.security.MessageDigest;
029
030import javax.annotation.CheckForNull;
031
032import org.apache.commons.codec.binary.Hex;
033import org.apache.commons.codec.digest.DigestUtils;
034
035public class FileHashComputer extends CharHandler {
036  private static final char LINE_FEED = '\n';
037
038  
039  private MessageDigest globalMd5Digest = DigestUtils.getMd5Digest();
040  private StringBuilder sb = new StringBuilder();
041  private final CharsetEncoder encoder;
042  private final String filePath;
043
044  public FileHashComputer(String filePath) {
045    encoder = StandardCharsets.UTF_8.newEncoder()
046      .onMalformedInput(CodingErrorAction.REPLACE)
047      .onUnmappableCharacter(CodingErrorAction.REPLACE);
048    this.filePath = filePath;
049  }
050
051  @Override
052  public void handleIgnoreEoL(char c) {
053    sb.append(c);
054  }
055
056  @Override
057  public void newLine() {
058    sb.append(LINE_FEED);
059    processBuffer();
060    sb.setLength(0);
061  }
062
063  @Override
064  public void eof() {
065    if (sb.length() > 0) {
066      processBuffer();
067    }
068  }
069
070  private void processBuffer() {
071    try {
072      if (sb.length() > 0) {
073        ByteBuffer encoded = encoder.encode(CharBuffer.wrap(sb));
074        globalMd5Digest.update(encoded.array(), 0, encoded.limit());
075      }
076    } catch (CharacterCodingException e) {
077      throw new IllegalStateException("Error encoding line hash in file: " + filePath, e);
078    }
079  }
080
081  @CheckForNull
082  public String getHash() {
083    return Hex.encodeHexString(globalMd5Digest.digest());
084  }
085}