All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonarsource.sonarlint.core.plugin.cache.PluginHashes Maven / Gradle / Ivy

/*
 * SonarLint Core - Implementation
 * Copyright (C) 2016-2021 SonarSource SA
 * mailto:info AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.sonarsource.sonarlint.core.plugin.cache;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;

/**
 * Hashes used to store files in the cache directory.
 */
public class PluginHashes {

  private static final int STREAM_BUFFER_LENGTH = 1024;

  public String of(Path file) {
    try {
      return of(Files.newInputStream(file));
    } catch (IOException e) {
      throw new IllegalStateException("Fail to compute hash of: " + file, e);
    }
  }

  /**
   * Computes the hash of given stream. The stream is closed by this method.
   */
  public String of(InputStream input) {
    try (InputStream is = input) {
      MessageDigest digest = MessageDigest.getInstance("MD5");
      byte[] hash = digest(is, digest);
      return toHex(hash);
    } catch (Exception e) {
      throw new IllegalStateException("Fail to compute hash", e);
    }
  }

  private static byte[] digest(InputStream input, MessageDigest digest) throws IOException {
    final byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
    int read = input.read(buffer, 0, STREAM_BUFFER_LENGTH);
    while (read > -1) {
      digest.update(buffer, 0, read);
      read = input.read(buffer, 0, STREAM_BUFFER_LENGTH);
    }
    return digest.digest();
  }

  static String toHex(byte[] bytes) {
    BigInteger bi = new BigInteger(1, bytes);
    return String.format("%0" + (bytes.length << 1) + "x", bi);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy