List of usage examples for com.google.common.hash HashCode equals
@Override public final boolean equals(@Nullable Object object)
From source file:io.takari.watcher.DirectoryWatcherJdk.java
public void processEventsJdk() throws IOException { for (;;) {// w w w .jav a2s . c om if (listener.stopWatching()) { return; } // wait for key to be signalled WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == OVERFLOW) { continue; } // Context for directory entry event is the file name of entry WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = keyRoots.containsKey(key) ? keyRoots.get(key).resolve(name) : directory.resolve(name); // if directory is created, and watching recursively, then register it and its sub-directories if (kind == ENTRY_CREATE) { if (Files.isDirectory(child, NOFOLLOW_LINKS)) { registerAll(child); } else { pathHashes.put(child, hash(child)); listener.onCreate(child); } } else if (kind == ENTRY_MODIFY) { HashCode existingHash = pathHashes.get(child); HashCode newHash = hash(child); // newHash can be null when using File#delete() on windows - it generates MODIFY and DELETE in succession // in this case the MODIFY event can be safely ignored if (existingHash != null && newHash != null && !existingHash.equals(newHash)) { pathHashes.put(child, newHash); listener.onModify(child); } } else if (kind == ENTRY_DELETE) { pathHashes.remove(child); listener.onDelete(child); } } boolean valid = key.reset(); if (!valid) { break; } } }
From source file:org.rf.ide.core.executor.ArgumentsFile.java
File writeToTemporaryOrUseAlreadyExisting() throws IOException { final String content = generateContent(); // it's deprecated although we don't need security here, so md5 is fine @SuppressWarnings("deprecation") final HashFunction md5Hasher = Hashing.md5(); final HashCode hash = md5Hasher.hashString(content, Charsets.UTF_8); final String fileName = "args_" + Strings.padStart(Integer.toHexString(hash.asInt()), 8, '0') + ".arg"; final Path dir = RobotRuntimeEnvironment.createTemporaryDirectory(); for (final File existingArgFile : dir.toFile().listFiles((d, name) -> name.equals(fileName))) { final HashCode candidateHash = md5Hasher .hashString(Files.asCharSource(existingArgFile, Charsets.UTF_8).read(), Charsets.UTF_8); if (hash.equals(candidateHash)) { return existingArgFile; }/*w w w . jav a2 s .c om*/ } final File filePath = dir.resolve(fileName).toFile(); writeTo(filePath); return filePath; }
From source file:com.google.idea.blaze.base.wizard2.ui.BlazeEditProjectViewControl.java
public void update(BlazeNewProjectBuilder builder) { BlazeSelectWorkspaceOption workspaceOption = builder.getWorkspaceOption(); BlazeSelectProjectViewOption projectViewOption = builder.getProjectViewOption(); String workspaceName = workspaceOption.getWorkspaceName(); WorkspaceRoot workspaceRoot = workspaceOption.getWorkspaceRoot(); WorkspacePath workspacePath = projectViewOption.getSharedProjectView(); String initialProjectViewText = projectViewOption.getInitialProjectViewText(); boolean allowAddDefaultValues = projectViewOption.allowAddDefaultProjectViewValues() && allowAddprojectViewDefaultValues.getValue(); WorkspacePathResolver workspacePathResolver = workspaceOption.getWorkspacePathResolver(); HashCode hashCode = Hashing.md5().newHasher().putUnencodedChars(workspaceName) .putUnencodedChars(workspaceRoot.toString()) .putUnencodedChars(workspacePath != null ? workspacePath.toString() : "") .putUnencodedChars(initialProjectViewText != null ? initialProjectViewText : "") .putBoolean(allowAddDefaultValues).hash(); // If any params have changed, reinit the control if (!hashCode.equals(paramsHash)) { this.paramsHash = hashCode; init(workspaceName, workspaceRoot, workspacePathResolver, workspacePath, initialProjectViewText, allowAddDefaultValues);/*from www .j av a 2s . com*/ } }
From source file:co.cask.cdap.internal.app.runtime.adapter.AdapterService.java
private ApplicationTemplateInfo getTemplateInfo(File jarFile) throws InterruptedException, ExecutionException, TimeoutException, IOException { ApplicationTemplateInfo existing = fileToTemplateMap.get().get(jarFile.getAbsoluteFile()); HashCode fileHash = Files.hash(jarFile, Hashing.md5()); // if the file is the same, just return if (existing != null && fileHash.equals(existing.getFileHash())) { return existing; }/* w ww . j a va 2 s . c o m*/ // instantiate the template application and call configure() on it to determine it's specification InMemoryConfigurator configurator = new InMemoryConfigurator( new LocalLocationFactory().create(jarFile.toURI()), null); ListenableFuture<ConfigResponse> result = configurator.config(); ConfigResponse response = result.get(2, TimeUnit.MINUTES); InputSupplier<? extends Reader> configSupplier = response.get(); if (response.getExitCode() != 0 || configSupplier == null) { throw new IllegalArgumentException("Failed to get template info"); } ApplicationSpecification spec; try (Reader configReader = configSupplier.getInput()) { spec = GSON.fromJson(configReader, ApplicationSpecification.class); } // verify that the name is ok Id.Application.from(Constants.DEFAULT_NAMESPACE_ID, spec.getName()); // determine the program type of the template ProgramType programType; int numWorkflows = spec.getWorkflows().size(); int numWorkers = spec.getWorkers().size(); if (numWorkers == 0 && numWorkflows == 1) { programType = ProgramType.WORKFLOW; } else if (numWorkers == 1 && numWorkflows == 0) { programType = ProgramType.WORKER; } else { throw new IllegalArgumentException( "An application template must contain exactly one worker or one workflow."); } return new ApplicationTemplateInfo(jarFile, spec.getName(), spec.getDescription(), programType, fileHash); }
From source file:com.facebook.buck.rules.CachingBuildRuleBuilder.java
private boolean verifyRecordedPathHashes(BuildTarget target, ProjectFilesystem filesystem, ImmutableMap<String, String> recordedPathHashes) throws IOException { // Create a new `DefaultFileHashCache` to prevent caching from interfering with verification. ProjectFileHashCache fileHashCache = DefaultFileHashCache.createDefaultFileHashCache(filesystem, fileHashCacheMode);// w w w . j av a 2 s . c om // Verify each path from the recorded path hashes entry matches the actual on-disk version. for (Map.Entry<String, String> ent : recordedPathHashes.entrySet()) { Path path = filesystem.getPath(ent.getKey()); HashCode cachedHashCode = HashCode.fromString(ent.getValue()); HashCode realHashCode = fileHashCache.get(path); if (!realHashCode.equals(cachedHashCode)) { LOG.debug("%s: recorded hash for \"%s\" doesn't match actual hash: %s (cached) != %s (real).", target, path, cachedHashCode, realHashCode); return false; } } return true; }
From source file:com.facebook.buck.rules.HttpArtifactCache.java
@Override public CacheResult fetch(RuleKey ruleKey, File file) { String url = String.format(URL_TEMPLATE_FETCH, hostname, port, ruleKey.toString()); HttpURLConnection connection; try {/* w w w. j av a 2s.c o m*/ connection = getConnection(url); connection.setConnectTimeout(1000 * timeoutSeconds); } catch (MalformedURLException e) { logger.error(e, "fetch(%s): malformed URL: %s", ruleKey, url); return CacheResult.MISS; } catch (IOException e) { logger.warn(e, "fetch(%s): [init] IOException: %s", ruleKey, e.getMessage()); return CacheResult.MISS; } int responseCode; try { responseCode = connection.getResponseCode(); } catch (IOException e) { reportConnectionFailure(String.format("fetch(%s)", ruleKey), e); return CacheResult.MISS; } switch (responseCode) { case HttpURLConnection.HTTP_OK: try (InputStream input = connection.getInputStream()) { // Setup an object input stream to deserialize the hash code. try (ObjectInputStream objectStream = new ObjectInputStream(input)) { // First, extract the hash code from the beginning of the request data. HashCode expectedHashCode; try { expectedHashCode = (HashCode) objectStream.readObject(); } catch (ClassNotFoundException | ClassCastException e) { logger.warn("fetch(%s): could not deserialize artifact checksum", ruleKey); return CacheResult.MISS; } // Setup a temporary file, which sits next to the destination, to write to and // make sure all parent dirs exist. Path path = file.toPath(); projectFilesystem.createParentDirs(path); Path temp = projectFilesystem.createTempFile(path.getParent(), path.getFileName().toString(), ".tmp"); // Write the remaining response data to the temp file. projectFilesystem.copyToPath(input, temp, StandardCopyOption.REPLACE_EXISTING); // Now form the checksum on the file we got and compare it to the checksum form the // the HTTP header. If it's incorrect, log this and return a miss. HashCode actualHashCode = fileHashCache.get(temp); if (!expectedHashCode.equals(actualHashCode)) { logger.warn("fetch(%s): artifact had invalid checksum", ruleKey); projectFilesystem.deleteFileAtPath(temp); return CacheResult.MISS; } // Finally, move the temp file into it's final place. projectFilesystem.move(temp, path, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException e) { logger.warn(e, "fetch(%s): [write] IOException: %s", ruleKey, e.getMessage()); return CacheResult.MISS; } logger.info("fetch(%s): cache hit", ruleKey); return CacheResult.HTTP_HIT; case HttpURLConnection.HTTP_NOT_FOUND: logger.info("fetch(%s): cache miss", ruleKey); return CacheResult.MISS; default: logger.warn("fetch(%s): unexpected response: %d", ruleKey, responseCode); return CacheResult.MISS; } }