You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LongObjectIdTestUtils.java 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (C) 2015, Matthias Sohn <matthias.sohn@sap.com> and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.lfs.test;
  11. import static java.nio.charset.StandardCharsets.UTF_8;
  12. import java.io.BufferedInputStream;
  13. import java.io.FileNotFoundException;
  14. import java.io.IOException;
  15. import java.io.InputStream;
  16. import java.nio.file.Files;
  17. import java.nio.file.Path;
  18. import java.security.MessageDigest;
  19. import org.eclipse.jgit.lfs.lib.Constants;
  20. import org.eclipse.jgit.lfs.lib.LongObjectId;
  21. public class LongObjectIdTestUtils {
  22. /**
  23. * Create id as hash of the given string.
  24. *
  25. * @param s
  26. * the string to hash
  27. * @return id calculated by hashing string
  28. */
  29. public static LongObjectId hash(String s) {
  30. MessageDigest md = Constants.newMessageDigest();
  31. md.update(s.getBytes(UTF_8));
  32. return LongObjectId.fromRaw(md.digest());
  33. }
  34. /**
  35. * Create id as hash of a file content
  36. *
  37. * @param file
  38. * the file to hash
  39. * @return id calculated by hashing file content
  40. * @throws FileNotFoundException
  41. * if file doesn't exist
  42. * @throws IOException
  43. */
  44. public static LongObjectId hash(Path file)
  45. throws FileNotFoundException, IOException {
  46. MessageDigest md = Constants.newMessageDigest();
  47. try (InputStream is = new BufferedInputStream(
  48. Files.newInputStream(file))) {
  49. final byte[] buffer = new byte[4096];
  50. for (int read = 0; (read = is.read(buffer)) != -1;) {
  51. md.update(buffer, 0, read);
  52. }
  53. }
  54. return LongObjectId.fromRaw(md.digest());
  55. }
  56. }