View Javadoc
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  
12  import static java.nio.charset.StandardCharsets.UTF_8;
13  
14  import java.io.BufferedInputStream;
15  import java.io.FileNotFoundException;
16  import java.io.IOException;
17  import java.io.InputStream;
18  import java.nio.file.Files;
19  import java.nio.file.Path;
20  import java.security.MessageDigest;
21  
22  import org.eclipse.jgit.lfs.lib.Constants;
23  import org.eclipse.jgit.lfs.lib.LongObjectId;
24  
25  public class LongObjectIdTestUtils {
26  
27  	/**
28  	 * Create id as hash of the given string.
29  	 *
30  	 * @param s
31  	 *            the string to hash
32  	 * @return id calculated by hashing string
33  	 */
34  	public static LongObjectId hash(String s) {
35  		MessageDigest md = Constants.newMessageDigest();
36  		md.update(s.getBytes(UTF_8));
37  		return LongObjectId.fromRaw(md.digest());
38  	}
39  
40  	/**
41  	 * Create id as hash of a file content
42  	 *
43  	 * @param file
44  	 *            the file to hash
45  	 * @return id calculated by hashing file content
46  	 * @throws FileNotFoundException
47  	 *             if file doesn't exist
48  	 * @throws IOException
49  	 */
50  	public static LongObjectId hash(Path file)
51  			throws FileNotFoundException, IOException {
52  		MessageDigest md = Constants.newMessageDigest();
53  		try (InputStream is = new BufferedInputStream(
54  				Files.newInputStream(file))) {
55  			final byte[] buffer = new byte[4096];
56  			for (int read = 0; (read = is.read(buffer)) != -1;) {
57  				md.update(buffer, 0, read);
58  			}
59  		}
60  		return LongObjectId.fromRaw(md.digest());
61  	}
62  }