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

The following examples show how to use com.google.common.hash.HashCode#equals() . 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: MapDefinition.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
public boolean shouldReload() {
    if(context == null) return true;
    if(!configuration.autoReload()) return false;
    if(context.loadedFiles().isEmpty()) return configuration.reloadWhenError();

    try {
        for(Map.Entry<Path, HashCode> loaded : context.loadedFiles().entrySet()) {
            HashCode latest = Files.hash(loaded.getKey().toFile(), Hashing.sha256());
            if(!latest.equals(loaded.getValue())) return true;
        }

        return false;
    } catch (IOException e) {
        return true;
    }
}
 
Example 2
Source File: AccumulateClassNamesStep.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * @param lines that were written in the same format output by {@link #execute(ExecutionContext)}.
 */
public static ImmutableSortedMap<String, HashCode> parseClassHashes(List<String> lines) {
  Map<String, HashCode> classNames = new HashMap<>();

  for (String line : lines) {
    int lastSeparator = line.lastIndexOf(CLASS_NAME_HASH_CODE_SEPARATOR);
    String key = line.substring(0, lastSeparator);
    HashCode value = HashCode.fromString(line.substring(lastSeparator + 1));
    HashCode existing = classNames.putIfAbsent(key, value);
    if (existing != null && !existing.equals(value)) {
      throw new IllegalArgumentException(
          String.format(
              "Multiple entries with same key but differing values: %1$s=%2$s and %1$s=%3$s",
              key, value, existing));
    }
  }

  return ImmutableSortedMap.copyOf(classNames, Ordering.natural());
}
 
Example 3
Source File: Manifest.java    From buck with Apache License 2.0 6 votes vote down vote up
private boolean hashesMatch(
    FileHashLoader fileHashLoader,
    SourcePathResolverAdapter resolver,
    ImmutableListMultimap<String, SourcePath> universe,
    int[] hashIndices)
    throws IOException {
  for (int hashIndex : hashIndices) {
    Pair<Integer, HashCode> hashEntry = hashes.get(hashIndex);
    String input = inputs.get(hashEntry.getFirst());
    ImmutableList<SourcePath> candidates = universe.get(input);
    if (candidates.isEmpty()) {
      return false;
    }
    HashCode onDiskHeaderHash;
    try {
      onDiskHeaderHash = hashSourcePathGroup(fileHashLoader, resolver, candidates);
    } catch (NoSuchFileException e) {
      return false;
    }
    HashCode inputHash = hashEntry.getSecond();
    if (!inputHash.equals(onDiskHeaderHash)) {
      return false;
    }
  }
  return true;
}
 
Example 4
Source File: PathUtils.java    From bazel-tools with Apache License 2.0 5 votes vote down vote up
private static void syncRegularFile(final Path sourceFile, final Path targetFile)
    throws IOException {
  if (Files.exists(targetFile)) {
    final HashCode sourceHash = sha256(sourceFile);
    final HashCode targetHash = sha256(targetFile);

    if (sourceHash.equals(targetHash)) {
      return;
    }
  }

  Files.copy(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING);
}
 
Example 5
Source File: AbstractStreamingFingerprintComputer.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public String computeFingerprint(final EObject object) {
  if (object == null) {
    return null;
  }
  Hasher hasher = HASH_FUNCTION.newHasher();
  fingerprint(object, hasher);
  HashCode export = hasher.hash();
  if (export.equals(NO_EXPORT)) {
    return null;
  }
  return export.toString();
}
 
Example 6
Source File: BlazeEditProjectViewControl.java    From intellij with Apache License 2.0 5 votes vote down vote up
public void update(BlazeNewProjectBuilder builder) {
  this.workspaceData = builder.getWorkspaceData();
  this.projectViewOption = builder.getProjectViewOption();
  WorkspaceRoot workspaceRoot = workspaceData.workspaceRoot();
  WorkspacePath workspacePath = projectViewOption.getSharedProjectView();
  String initialProjectViewText = projectViewOption.getInitialProjectViewText();
  boolean allowAddDefaultValues =
      projectViewOption.allowAddDefaultProjectViewValues()
          && allowAddprojectViewDefaultValues.getValue();
  WorkspacePathResolver workspacePathResolver = workspaceData.workspacePathResolver();

  HashCode hashCode =
      Hashing.md5()
          .newHasher()
          .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;
    this.isInitialising = true;
    init(
        workspaceData.buildSystem(),
        workspacePathResolver,
        workspacePath,
        initialProjectViewText,
        allowAddDefaultValues);
    this.isInitialising = false;
  }
}
 
Example 7
Source File: Murmur3HashedFrameDecoder.java    From xio with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
  HashCode sentHash = HashCode.fromInt(msg.readInt());
  HashCode hash =
      Hashing.murmur3_32().hashBytes(msg.array(), msg.readerIndex(), msg.readableBytes());

  out.add(msg);

  if (sentHash.equals(hash)) {
    System.out.println("Hashes matches");
  } else {
    System.out.println("Hashes no matches");
  }
}
 
Example 8
Source File: WorkerFactory.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** The worker is considered to be valid when its files have not changed on disk. */
@Override
public boolean validateObject(WorkerKey key, PooledObject<Worker> p) {
  Worker worker = p.getObject();
  boolean hashMatches =
      key.getWorkerFilesCombinedHash().equals(worker.getWorkerFilesCombinedHash());

  if (workerOptions.workerVerbose && reporter != null && !hashMatches) {
    StringBuilder msg = new StringBuilder();
    msg.append(
        String.format(
            "%s %s (id %d) can no longer be used, because its files have changed on disk:",
            key.getMnemonic(),
            WorkerKey.makeWorkerTypeName(key.getProxied()),
            worker.getWorkerId()));
    TreeSet<PathFragment> files = new TreeSet<>();
    files.addAll(key.getWorkerFilesWithHashes().keySet());
    files.addAll(worker.getWorkerFilesWithHashes().keySet());
    for (PathFragment file : files) {
      HashCode oldHash = worker.getWorkerFilesWithHashes().get(file);
      HashCode newHash = key.getWorkerFilesWithHashes().get(file);
      if (!oldHash.equals(newHash)) {
        msg.append("\n")
            .append(file.getPathString())
            .append(": ")
            .append(oldHash != null ? oldHash : "<none>")
            .append(" -> ")
            .append(newHash != null ? newHash : "<none>");
      }
    }

    reporter.handle(Event.warn(msg.toString()));
  }

  return hashMatches;
}
 
Example 9
Source File: GoogleFormatterMojo.java    From googleformatter-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() throws MojoExecutionException {

  if ("pom".equals(project.getPackaging())) {
    getLog().info("Project packaging is POM, skipping...");
    return;
  }

  if (skip) {
    getLog().info("Skipping source reformatting due to plugin configuration.");
    return;
  }

  try {
    Set<File> sourceFiles = new HashSet<>();

    if (formatMain) {
      sourceFiles.addAll(findFilesToReformat(sourceDirectory, outputDirectory));
    }
    if (formatTest) {
      sourceFiles.addAll(findFilesToReformat(testSourceDirectory, testOutputDirectory));
    }

    Set<File> sourceFilesToProcess = filterModified ? filterUnchangedFiles(sourceFiles) : sourceFiles;

    JavaFormatterOptions options = getJavaFormatterOptions();

    for (File file : sourceFilesToProcess) {
      String source = CharStreams.toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));

      Formatter formatter = new Formatter(options);
      String formattedSource = fixImports ? formatter.formatSourceAndFixImports(source) : formatter.formatSource(source);

      HashCode sourceHash = Hashing.sha256().hashString(source, StandardCharsets.UTF_8);
      HashCode formattedHash = Hashing.sha256().hashString(formattedSource, StandardCharsets.UTF_8);

      if (!formattedHash.equals(sourceHash)) {
        // overwrite existing file
        Files.write(file.toPath(), formattedSource.getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

        getLog().info(String.format("Reformatted file %s", file.getPath()));
      }
    }
  } catch (Exception e) {
    throw new MojoExecutionException(e.getMessage(), e);
  }
}
 
Example 10
Source File: JdbcGenericRecordWriter.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public List<OnRecordErrorException> write(Iterator<Record> recordIterator, boolean perRecord) throws StageException {
  List<OnRecordErrorException> errorRecords = new LinkedList<>();

  try (Connection connection = getDataSource().getConnection()){
    int prevOpCode = -1;
    HashCode prevColumnHash = null;
    LinkedList<Pair<Record, Map<String, String>>> queue = new LinkedList<>();

    while (recordIterator.hasNext()) {
      Record record = recordIterator.next();
      int opCode = getOperationCode(record, errorRecords);

      Map<String, String> columnsToParameters = recordReader.getColumnsToParameters(
          record,
          opCode,
          getColumnsToParameters(),
          opCode == OperationType.UPDATE_CODE ? getColumnsToFieldNoPK() : getColumnsToFields(),
          sortedColumns
      );

      // Need to consider the number of columns in query. If different, process saved records in queue.
      HashCode columnHash = columnHashFunction.newHasher().putObject(columnsToParameters, stringMapFunnel).hash();

      boolean opCodeValid = opCode > 0;
      boolean opCodeUnchanged = opCode == prevOpCode;
      boolean supportedOpCode = opCode == DELETE_CODE || opCode == INSERT_CODE && columnHash.equals(prevColumnHash);
      boolean canEnqueue = opCodeValid && opCodeUnchanged && supportedOpCode;

      if (canEnqueue) {
        queue.add(Pair.of(record, columnsToParameters));
      }

      if (!opCodeValid || canEnqueue) {
        continue;
      }

      // Process enqueued records.
      processQueue(queue, errorRecords, connection, prevOpCode, perRecord);

      if (!queue.isEmpty()) {
        throw new IllegalStateException("Queue processed, but was not empty upon completion.");
      }

      queue.add(Pair.of(record, columnsToParameters));
      prevOpCode = opCode;
      prevColumnHash = columnHash;
    }


    // Check if any records are left in queue unprocessed
    processQueue(queue, errorRecords, connection, prevOpCode, perRecord);
    try(Timer.Context t = commitTimer.time()) {
      connection.commit();
    }
  } catch (SQLException e) {
    handleSqlException(e);
  }

  return errorRecords;
}
 
Example 11
Source File: AccumulateClassNamesStep.java    From buck with Apache License 2.0 4 votes vote down vote up
/** @return an Optional that will be absent if there was an error. */
public static Optional<ImmutableSortedMap<String, HashCode>> calculateClassHashes(
    ExecutionContext context, ProjectFilesystem filesystem, Path path) {
  Map<String, HashCode> classNames = new HashMap<>();

  ClasspathTraversal traversal =
      new ClasspathTraversal(Collections.singleton(path), filesystem) {
        @Override
        public void visit(FileLike fileLike) throws IOException {
          // When traversing a JAR file, it may have resources or directory entries that do not
          // end in .class, which should be ignored.
          if (!FileLikes.isClassFile(fileLike)) {
            return;
          }

          String key = FileLikes.getFileNameWithoutClassSuffix(fileLike);
          ByteSource input =
              new ByteSource() {
                @Override
                public InputStream openStream() throws IOException {
                  return fileLike.getInput();
                }
              };
          HashCode value = input.hash(Hashing.sha1());
          HashCode existing = classNames.putIfAbsent(key, value);
          if (existing != null && !existing.equals(value)) {
            throw new IllegalArgumentException(
                String.format(
                    "Multiple entries with same key but differing values: %1$s=%2$s and %1$s=%3$s",
                    key, value, existing));
          }
        }
      };

  try {
    new DefaultClasspathTraverser().traverse(traversal);
  } catch (IOException e) {
    context.logError(e, "Error accumulating class names for %s.", path);
    return Optional.empty();
  }

  return Optional.of(ImmutableSortedMap.copyOf(classNames, Ordering.natural()));
}
 
Example 12
Source File: ConanHashVerifier.java    From nexus-repository-conan with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Verifies that the hashes match when both hashes are supplied
 * @param me
 * @param you
 * @return
 */
public boolean verify(final HashCode me, final HashCode you) {
  return me == null || you == null || me.equals(you);
}