Example usage for com.google.common.hash HashCode fromString

List of usage examples for com.google.common.hash HashCode fromString

Introduction

In this page you can find the example usage for com.google.common.hash HashCode fromString.

Prototype

@CheckReturnValue
public static HashCode fromString(String string) 

Source Link

Document

Creates a HashCode from a hexadecimal ( base 16 ) encoded string.

Usage

From source file:uk.org.ngo.squeezer.model.Player.java

private Player(Parcel source) {
    setId(source.readString());//from w w w .  j a v a2s .c o m
    mIp = source.readString();
    mName = source.readString();
    mModel = source.readString();
    mCanPowerOff = (source.readByte() == 1);
    mConnected = (source.readByte() == 1);
    mHashCode = HashCode.fromString(source.readString());
}

From source file:com.attribyte.relay.wp.PostMeta.java

/**
 * Creates an instance from previously stored bytes.
 * @param bytes The stored bytes.//w  w  w  .j  av a 2s  .  c  om
 * @return The metadata.
 * @throws IOException on invalid format.
 */
public static PostMeta fromBytes(final ByteString bytes) throws IOException {

    String[] components = bytes.toStringUtf8().split(",");
    if (components.length < 2) {
        throw new IOException(String.format("Invalid state: '%s'", bytes.toStringUtf8()));
    }

    Long id = Longs.tryParse(components[0].trim());
    if (id == null) {
        throw new IOException(String.format("Invalid state: '%s'", bytes.toStringUtf8()));
    }

    Long lastModifiedMillis = Longs.tryParse(components[1].trim());
    if (lastModifiedMillis == null) {
        throw new IOException(String.format("Invalid state: '%s'", bytes.toStringUtf8()));
    }

    if (components.length >= 3) {
        return new PostMeta(id, lastModifiedMillis, HashCode.fromString(components[2].trim()));
    } else {
        return new PostMeta(id, lastModifiedMillis);
    }
}

From source file:com.facebook.buck.util.sha1.Sha1HashCode.java

/**
 * <strong>This method should be used sparingly as we are trying to favor {@link Sha1HashCode}
 * over {@link HashCode}, where appropriate.</strong> Currently, the {@code FileHashCache} API is
 * written in terms of {@code HashCode}, so conversions are common. As we migrate it to use
 * {@link Sha1HashCode}, this method should become unnecessary.
 * @return a {@link HashCode} with an equivalent value
 *//*  ww  w  .  j  ava  2 s .  co m*/
public HashCode asHashCode() {
    return HashCode.fromString(getHash());
}

From source file:org.openqa.selenium.BuckBuild.java

private void downloadBuckPexIfNecessary(ImmutableList.Builder<String> builder) throws IOException {
    Path projectRoot = InProject.locate("Rakefile").getParentFile().toPath();
    String buckVersion = new String(Files.readAllBytes(projectRoot.resolve(".buckversion"))).trim();

    Path pex = projectRoot.resolve("buck-out/crazy-fun/" + buckVersion + "/buck.pex");

    String expectedHash = new String(Files.readAllBytes(projectRoot.resolve(".buckhash"))).trim();
    HashCode md5 = Files.exists(pex) ? Hashing.md5().hashBytes(Files.readAllBytes(pex))
            : HashCode.fromString("aa"); // So we have a non-null value

    if (!Files.exists(pex) || !expectedHash.equals(md5.toString())) {
        log.warning("Downloading PEX");

        if (!Files.exists(pex.getParent())) {
            Files.createDirectories(pex.getParent());
        }/*from  w w  w.j  a  va2s .c o m*/

        URL url = new URL(String.format(
                "https://github.com/SeleniumHQ/buck/releases/download/buck-release-%s/buck.pex", buckVersion));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setInstanceFollowRedirects(true);
        Files.copy(connection.getInputStream(), pex, REPLACE_EXISTING);
        // Do our best to make this executable
        pex.toFile().setExecutable(true);
    }

    md5 = Hashing.md5().hashBytes(Files.readAllBytes(pex));
    if (!expectedHash.equals(md5.toString())) {
        throw new WebDriverException("Unable to confirm that download is valid");
    }

    if (Platform.getCurrent().is(WINDOWS)) {
        String python = CommandLine.find("python2");
        if (python == null) {
            python = CommandLine.find("python");
        }
        Preconditions.checkNotNull(python, "Unable to find python executable");
        builder.add(python);
    }

    builder.add(pex.toAbsolutePath().toString());
}

From source file:de.siegmar.securetransfer.controller.SendController.java

/**
 * Process the send form./*from w  w  w.j a  v a  2  s  .c o  m*/
 */
@PostMapping
public ModelAndView create(final HttpServletRequest req, final RedirectAttributes redirectAttributes)
        throws IOException, FileUploadException {

    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new IllegalStateException("No multipart request!");
    }

    // Create encryptionKey and initialization vector (IV) to encrypt data
    final KeyIv encryptionKey = messageService.newEncryptionKey();

    // secret shared with receiver using the link - not stored in database
    final String linkSecret = messageService.newRandomId();

    final DataBinder binder = initBinder();

    final List<SecretFile> tmpFiles = handleStream(req, encryptionKey, binder);

    final EncryptMessageCommand command = (EncryptMessageCommand) binder.getTarget();
    final BindingResult errors = binder.getBindingResult();

    if (!errors.hasErrors() && command.getMessage() == null && (tmpFiles == null || tmpFiles.isEmpty())) {
        errors.reject(null, "Neither message nor files submitted");
    }

    if (errors.hasErrors()) {
        return new ModelAndView(FORM_SEND_MSG, binder.getBindingResult().getModel());
    }

    final String senderId = messageService.storeMessage(command.getMessage(), tmpFiles, encryptionKey,
            HashCode.fromString(linkSecret).asBytes(), command.getPassword(),
            Instant.now().plus(command.getExpirationDays(), ChronoUnit.DAYS));

    redirectAttributes.addFlashAttribute("messageSent", true).addFlashAttribute("message",
            command.getMessage());

    return new ModelAndView("redirect:/send/" + senderId).addObject("linkSecret", linkSecret);
}

From source file:org.sonatype.nexus.repository.storage.Asset.java

/**
 * Extract checksums of asset blob if checksums are present in asset attributes.
 *//* ww  w  .j a  v  a 2 s.  c  o m*/
public Map<HashAlgorithm, HashCode> getChecksums(final Iterable<HashAlgorithm> hashAlgorithms) {
    final NestedAttributesMap checksumAttributes = attributes().child(CHECKSUM);
    final Map<HashAlgorithm, HashCode> hashCodes = Maps.newHashMap();
    for (HashAlgorithm algorithm : hashAlgorithms) {
        final HashCode hashCode = HashCode
                .fromString(checksumAttributes.require(algorithm.name(), String.class));
        hashCodes.put(algorithm, hashCode);
    }
    return hashCodes;
}

From source file:com.facebook.buck.java.AccumulateClassNames.java

/**
 * Sets both {@link #classNames} and {@link #abiKey}.
 *//*  www.  j  a v a 2s  .c o m*/
@Override
protected void initializeFromDisk(OnDiskBuildInfo onDiskBuildInfo) {
    // Read the output file, which should now be in place because this rule was downloaded from
    // cache.
    List<String> lines;
    try {
        lines = onDiskBuildInfo.getOutputFileContentsByLine(this);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // Use the contents of the file to create the ImmutableSortedMap<String, HashCode>.
    ImmutableSortedMap.Builder<String, HashCode> classNamesBuilder = ImmutableSortedMap.naturalOrder();
    for (String line : lines) {
        List<String> parts = CLASS_NAME_AND_HASH_SPLITTER.splitToList(line);
        Preconditions.checkState(parts.size() == 2);
        String key = parts.get(0);
        HashCode value = HashCode.fromString(parts.get(1));
        classNamesBuilder.put(key, value);
    }
    this.classNames = Suppliers.ofInstance(classNamesBuilder.build());
    this.abiKey = onDiskBuildInfo.getHash(AbiRule.ABI_KEY_ON_DISK_METADATA).get();
}

From source file:com.facebook.buck.java.AccumulateClassNamesStep.java

/**
 * @param lines that were written in the same format output by {@link #execute(ExecutionContext)}.
 *//*w  w w  . j  a va 2  s  . c o  m*/
public static ImmutableSortedMap<String, HashCode> parseClassHashes(List<String> lines) {
    ImmutableSortedMap.Builder<String, HashCode> classNamesBuilder = ImmutableSortedMap.naturalOrder();

    for (String line : lines) {
        List<String> parts = CLASS_NAME_AND_HASH_SPLITTER.splitToList(line);
        Preconditions.checkState(parts.size() == 2);
        String key = parts.get(0);
        HashCode value = HashCode.fromString(parts.get(1));
        classNamesBuilder.put(key, value);
    }

    return classNamesBuilder.build();
}

From source file:org.sonatype.nexus.repository.storage.Asset.java

/**
 * Extract checksum of asset blob if checksum is present in asset attributes.
 *///from  www . ja  v a 2s  .c  om
@Nullable
public HashCode getChecksum(final HashAlgorithm hashAlgorithm) {
    String hashCode = attributes().child(CHECKSUM).get(hashAlgorithm.name(), String.class);
    if (hashCode != null) {
        return HashCode.fromString(hashCode);
    }
    return null;
}

From source file:com.facebook.buck.jvm.java.AccumulateClassNamesStep.java

/**
 * @param lines that were written in the same format output by {@link #execute(ExecutionContext)}.
 *///from w  w w.ja v  a  2  s .c  o  m
public static ImmutableSortedMap<String, HashCode> parseClassHashes(List<String> lines) {
    final Map<String, HashCode> classNames = new HashMap<>();

    for (String line : lines) {
        List<String> parts = CLASS_NAME_AND_HASH_SPLITTER.splitToList(line);
        Preconditions.checkState(parts.size() == 2);
        String key = parts.get(0);
        HashCode value = HashCode.fromString(parts.get(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());
}