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.home.cache;
021
022import java.io.File;
023import java.io.FileInputStream;
024import java.io.IOException;
025import java.io.InputStream;
026import java.math.BigInteger;
027import java.security.MessageDigest;
028
029/**
030 * Hashes used to store files in the cache directory.
031 *
032 * @since 3.5
033 */
034public class FileHashes {
035
036  private static final int STREAM_BUFFER_LENGTH = 1024;
037
038  public String of(File file) {
039    try {
040      return of(new FileInputStream(file));
041    } catch (IOException e) {
042      throw new IllegalStateException("Fail to compute hash of: " + file.getAbsolutePath(), e);
043    }
044  }
045
046  /**
047   * Computes the hash of given stream. The stream is closed by this method.
048   */
049  public String of(InputStream input) {
050    try(InputStream is = input) {
051      MessageDigest digest = MessageDigest.getInstance("MD5");
052      byte[] hash = digest(is, digest);
053      return toHex(hash);
054    } catch (Exception e) {
055      throw new IllegalStateException("Fail to compute hash", e);
056    }
057  }
058
059  private static byte[] digest(InputStream input, MessageDigest digest) throws IOException {
060    final byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
061    int read = input.read(buffer, 0, STREAM_BUFFER_LENGTH);
062    while (read > -1) {
063      digest.update(buffer, 0, read);
064      read = input.read(buffer, 0, STREAM_BUFFER_LENGTH);
065    }
066    return digest.digest();
067  }
068
069  static String toHex(byte[] bytes) {
070    BigInteger bi = new BigInteger(1, bytes);
071    return String.format("%0" + (bytes.length << 1) + "x", bi);
072  }
073}