Java Code Examples for com.google.common.hash.Hasher#hash()

The following examples show how to use com.google.common.hash.Hasher#hash() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultInferredElementFragmentProvider.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Computes a hash code for the given {@link #getEClass(EObject) EClass} and {@link #getQualifiedName(EObject) qualified name}.
 *
 * @param eClass
 *          EClass to base hash on, must not be {@code null}
 * @param name
 *          qualified name of inferred model element, can be {@code null}
 * @return hash code, never {@code null}
 */
protected HashCode computeHash(final EClass eClass, final QualifiedName name) {
  byte[] eClassUriBytes = eClassToUriBytesMap.get(eClass);
  if (eClassUriBytes == null) {
    eClassUriBytes = EcoreUtil.getURI(eClass).toString().getBytes(Charsets.UTF_8);
    eClassToUriBytesMap.put(eClass, eClassUriBytes);
  }

  Hasher hasher = hashFunction.newHasher(HASHER_CAPACITY);
  hasher.putBytes(eClassUriBytes);

  if (name != null) {
    hasher.putChar('/');

    for (int j = 0; j < name.getSegmentCount(); j++) {
      hasher.putUnencodedChars(name.getSegment(j)).putChar('.');
    }
  }

  return hasher.hash();
}
 
Example 2
Source File: HeaderSearchPaths.java    From buck with Apache License 2.0 6 votes vote down vote up
private HashCode getHeaderSymlinkTreeHashCode(
    ImmutableSortedMap<Path, Path> contents,
    boolean shouldCreateHeadersSymlinks,
    boolean shouldCreateHeaderMap) {
  Hasher hasher = Hashing.sha1().newHasher();
  hasher.putBytes(ruleKeyConfiguration.getCoreKey().getBytes(Charsets.UTF_8));
  String symlinkState = shouldCreateHeadersSymlinks ? "symlinks-enabled" : "symlinks-disabled";
  byte[] symlinkStateValue = symlinkState.getBytes(Charsets.UTF_8);
  hasher.putInt(symlinkStateValue.length);
  hasher.putBytes(symlinkStateValue);
  String hmapState = shouldCreateHeaderMap ? "hmap-enabled" : "hmap-disabled";
  byte[] hmapStateValue = hmapState.getBytes(Charsets.UTF_8);
  hasher.putInt(hmapStateValue.length);
  hasher.putBytes(hmapStateValue);
  hasher.putInt(0);
  for (Map.Entry<Path, Path> entry : contents.entrySet()) {
    byte[] key = entry.getKey().toString().getBytes(Charsets.UTF_8);
    byte[] value = entry.getValue().toString().getBytes(Charsets.UTF_8);
    hasher.putInt(key.length);
    hasher.putBytes(key);
    hasher.putInt(value.length);
    hasher.putBytes(value);
  }
  return hasher.hash();
}
 
Example 3
Source File: EventTraceDataSourceFactory.java    From shardingsphere-elasticjob-lite with Apache License 2.0 6 votes vote down vote up
/**
 * Create event trace data source.
 * 
 * @param driverClassName database driver class name
 * @param url database URL
 * @param username database username
 * @param password database password
 * @return event trace data source
 */
public static EventTraceDataSource createEventTraceDataSource(final String driverClassName, final String url, final String username, final String password) {
    Hasher hasher = Hashing.md5().newHasher().putString(driverClassName, Charsets.UTF_8).putString(url, Charsets.UTF_8);
    if (!Strings.isNullOrEmpty(username)) {
        hasher.putString(username, Charsets.UTF_8);
    }
    if (null != password) {
        hasher.putString(password, Charsets.UTF_8);
    }
    HashCode hashCode = hasher.hash();
    EventTraceDataSource result = DATA_SOURCE_REGISTRY.get(hashCode);
    if (null != result) {
        return result;
    }
    EventTraceDataSourceConfiguration eventTraceDataSourceConfiguration = new EventTraceDataSourceConfiguration(driverClassName, url, username);
    if (null != password) {
        eventTraceDataSourceConfiguration.setPassword(password);
    }
    result = new EventTraceDataSource(eventTraceDataSourceConfiguration);
    result.init();
    DATA_SOURCE_REGISTRY.put(hashCode, result);
    return result;
}
 
Example 4
Source File: Manifest.java    From buck with Apache License 2.0 6 votes vote down vote up
/** Hash the files pointed to by the source paths. */
@VisibleForTesting
static HashCode hashSourcePathGroup(
    FileHashLoader fileHashLoader,
    SourcePathResolverAdapter resolver,
    ImmutableList<SourcePath> paths)
    throws IOException {
  if (paths.size() == 1) {
    return hashSourcePath(paths.get(0), fileHashLoader, resolver);
  }
  Hasher hasher = Hashing.md5().newHasher();
  for (SourcePath path : paths) {
    hasher.putBytes(hashSourcePath(path, fileHashLoader, resolver).asBytes());
  }
  return hasher.hash();
}
 
Example 5
Source File: ItemController.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
MemoizedPrices(ItemPrice[] prices)
{
	this.prices = prices;

	Hasher hasher = Hashing.sha256().newHasher();
	for (ItemPrice itemPrice : prices)
	{
		hasher.putInt(itemPrice.getId()).putInt(itemPrice.getPrice());
	}
	HashCode code = hasher.hash();
	hash = code.toString();
}
 
Example 6
Source File: Bugs231.java    From boon with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Hasher hasher = md5().newHasher();
    hasher.putString("heisann", Charset.defaultCharset());
    HashCode hash = hasher.hash();
    String actualJson = toJson(hash);

    ok = actualJson.equals("\"86c7c929d73e1d91c268c9f18d121212\"") || die(actualJson);

    puts(actualJson);
}
 
Example 7
Source File: ByteSource.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Hashes the contents of this byte source using the given hash function.
 *
 * @throws IOException if an I/O error occurs in the process of reading from this source
 */


public HashCode hash(HashFunction hashFunction) throws IOException {
  Hasher hasher = hashFunction.newHasher();
  copyTo(Funnels.asOutputStream(hasher));
  return hasher.hash();
}
 
Example 8
Source File: ByteSource.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Hashes the contents of this byte source using the given hash function.
 *
 * @throws IOException if an I/O error occurs in the process of reading from this source
 */


public HashCode hash(HashFunction hashFunction) throws IOException {
  Hasher hasher = hashFunction.newHasher();
  copyTo(Funnels.asOutputStream(hasher));
  return hasher.hash();
}
 
Example 9
Source File: ByteSource.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Hashes the contents of this byte source using the given hash function.
 *
 * @throws IOException if an I/O error occurs in the process of reading from this source
 */


public HashCode hash(HashFunction hashFunction) throws IOException {
  Hasher hasher = hashFunction.newHasher();
  copyTo(Funnels.asOutputStream(hasher));
  return hasher.hash();
}
 
Example 10
Source File: FeedController.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
MemoizedFeed(FeedResult feedResult)
{
	this.feedResult = feedResult;

	Hasher hasher = Hashing.sha256().newHasher();
	for (FeedItem itemPrice : feedResult.getItems())
	{
		hasher.putBytes(itemPrice.getTitle().getBytes()).putBytes(itemPrice.getContent().getBytes());
	}
	HashCode code = hasher.hash();
	hash = code.toString();
}
 
Example 11
Source File: SslContextStore.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static HashCode hashTrustAndKeyStore(final @NotNull Tls tls) throws IOException {
    final Hasher hasher = Hashing.md5().newHasher();
    final File keyStore = new File(tls.getKeystorePath());
    hashStore(keyStore, hasher);

    if (tls.getTruststorePath() != null && !StringUtils.isBlank(tls.getTruststorePath())) {
        final File trustStore = new File(tls.getTruststorePath());
        hashStore(trustStore, hasher);

    }
    return hasher.hash();
}
 
Example 12
Source File: BuildInfoRecorder.java    From buck with Apache License 2.0 5 votes vote down vote up
public HashCode getOutputHash(FileHashLoader fileHashLoader) throws IOException {
  Hasher hasher = Hashing.md5().newHasher();
  for (Path path : getRecordedPaths()) {
    hasher.putBytes(fileHashLoader.get(projectFilesystem.resolve(path)).asBytes());
  }
  return hasher.hash();
}
 
Example 13
Source File: VerifyPayloadHandlingComponentTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
/**
 * @return The MD5 hash of the given payload. This can be used to verify correctness when sending payloads across the wire.
 */
private static String getHashForPayload(byte[] payloadBytes) {
    Hasher hasher = hashFunction.newHasher();

    hasher = hasher.putBytes(payloadBytes);

    HashCode hc = hasher.hash();
    return hc.toString();
}
 
Example 14
Source File: SerializableSaltedHasher.java    From CuckooFilter4J with Apache License 2.0 5 votes vote down vote up
/**
 * hashes the object with an additional salt. For purpose of the cuckoo
 * filter, this is used when the hash generated for an item is all zeros.
 * All zeros is the same as an empty bucket, so obviously it's not a valid
 * tag. 
 */
HashCode hashObjWithSalt(T object, int moreSalt) {
	Hasher hashInst = hasher.newHasher();
	hashInst.putObject(object, funnel);
	hashInst.putLong(seedNSalt);
	hashInst.putInt(moreSalt);
	return hashInst.hash();
}
 
Example 15
Source File: Launcher.java    From launcher with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static byte[] download(String path, String hash, IntConsumer progress) throws IOException, VerificationException
{
	HashFunction hashFunction = Hashing.sha256();
	Hasher hasher = hashFunction.newHasher();
	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

	URL url = new URL(path);
	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	conn.setRequestProperty("User-Agent", USER_AGENT);
	conn.getResponseCode();

	InputStream err = conn.getErrorStream();
	if (err != null)
	{
		err.close();
		throw new IOException("Unable to download " + path + " - " + conn.getResponseMessage());
	}

	int downloaded = 0;
	try (InputStream in = conn.getInputStream())
	{
		int i;
		byte[] buffer = new byte[1024 * 1024];
		while ((i = in.read(buffer)) != -1)
		{
			byteArrayOutputStream.write(buffer, 0, i);
			hasher.putBytes(buffer, 0, i);
			downloaded += i;
			progress.accept(downloaded);
		}
	}

	HashCode hashCode = hasher.hash();
	if (!hash.equals(hashCode.toString()))
	{
		throw new VerificationException("Unable to verify resource " + path + " - expected " + hash + " got " + hashCode.toString());
	}

	return byteArrayOutputStream.toByteArray();
}
 
Example 16
Source File: RegistryCenterFactory.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
/**
 * 创建注册中心.
 *
 * @param zookeeperProperties the zookeeper properties
 *
 * @return 注册中心对象 coordinator registry center
 */
public static CoordinatorRegistryCenter createCoordinatorRegistryCenter(ZookeeperProperties zookeeperProperties) {
	Hasher hasher = Hashing.md5().newHasher().putString(zookeeperProperties.getZkAddressList(), Charsets.UTF_8);
	HashCode hashCode = hasher.hash();
	CoordinatorRegistryCenter result = REG_CENTER_REGISTRY.get(hashCode);
	if (null != result) {
		return result;
	}
	result = new ZookeeperRegistryCenter(zookeeperProperties);
	result.init();
	REG_CENTER_REGISTRY.put(hashCode, result);
	return result;
}
 
Example 17
Source File: PersistentTestRunner.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static HashCode getCombinedHashForFiles(Set<File> files) {
  List<HashCode> hashesAsBytes =
      files.stream()
          .parallel()
          .map(file -> getFileHash(file))
          .filter(Objects::nonNull)
          .collect(toList());

  // Update the hasher separately because Hasher.putBytes() is not safe for parallel operations
  Hasher hasher = Hashing.sha256().newHasher();
  for (HashCode hash : hashesAsBytes) {
    hasher.putBytes(hash.asBytes());
  }
  return hasher.hash();
}
 
Example 18
Source File: DefaultResolver.java    From emodb with Apache License 2.0 4 votes vote down vote up
private HashCode hash(HashCode previous, UUID next) {
    Hasher hasher = HASH_FUNCTION.newHasher();
    hasher.putBytes(previous.asBytes());
    hasher.putBytes(UUIDs.asByteArray(next));
    return hasher.hash();
}
 
Example 19
Source File: SerializableSaltedHasher.java    From CuckooFilter4J with Apache License 2.0 4 votes vote down vote up
HashCode hashObj(T object) {
	Hasher hashInst = hasher.newHasher();
	hashInst.putObject(object, funnel);
	hashInst.putLong(seedNSalt);
	return hashInst.hash();
}
 
Example 20
Source File: ByteSource.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Hashes the contents of this byte source using the given hash function.
 *
 * @throws IOException if an I/O error occurs in the process of reading from this source
 */
public HashCode hash(HashFunction hashFunction) throws IOException {
  Hasher hasher = hashFunction.newHasher();
  copyTo(Funnels.asOutputStream(hasher));
  return hasher.hash();
}