Example usage for com.google.common.hash Hashing md5

List of usage examples for com.google.common.hash Hashing md5

Introduction

In this page you can find the example usage for com.google.common.hash Hashing md5.

Prototype

public static HashFunction md5() 

Source Link

Document

Returns a hash function implementing the MD5 hash algorithm (128 hash bits) by delegating to the MD5 MessageDigest .

Usage

From source file:com.google.jenkins.plugins.dsl.YamlProjectFactory.java

/** {@inheritDoc} */
@Override/*from   ww  w  .  jav a 2s  .  c om*/
public YamlProject<T> newInstance(final Branch branch) {
    try {
        // If the branch name contains '/' then use its MD5 hash
        // as the project name, but otherwise use the branch name
        // for backwards compatibility.
        final String hashedName = UnsignedLongs
                .toString(Hashing.md5().hashString(branch.getName(), Charsets.UTF_8).asLong(), 16);
        final String projectName = branch.getName().indexOf('/') == -1 ? branch.getName() : hashedName;
        final YamlProject<T> project = new YamlProject<T>((YamlMultiBranchProject<T>) getOwner(), projectName,
                null /* module */);

        // Set the display name so that it is always the branch name.
        project.setDisplayName(branch.getName());

        project.setBranch(branch);

        return decorate(project);
    } catch (IOException e) {
        logger.log(SEVERE, e.getMessage(), e);
        return null;
    }
}

From source file:uk.ac.horizon.artcodes.server.utils.ExperienceItems.java

private static ExperienceItems create(JsonElement element, String experienceID) throws HTTPException {
    final ExperienceEntry wrapper = gson.fromJson(element, ExperienceEntry.class);
    wrapper.setCreated(new Date());
    wrapper.setId(experienceID);/*from  ww  w . j  a  v a  2s.c o  m*/

    final JsonObject experienceObject = verifyExperience(element);
    final String fullID = wrapper.getPublicID();
    if (experienceObject.has("id")) {
        String existing = experienceObject.get("id").getAsString();
        if ((existing.startsWith("http://") || existing.startsWith("https://")) && !fullID.equals(existing)) {
            experienceObject.add("originalID", experienceObject.get("id"));
        }
    }
    experienceObject.addProperty("id", fullID);

    final JsonArray actionArray = experienceObject.getAsJsonArray("actions");
    for (JsonElement actionElement : actionArray) {
        JsonObject action = actionElement.getAsJsonObject();
        if (action != null) {
            if (action.has("owner")) {
                String owner = action.get("owner").getAsString();
                if (owner != null && owner.equals("this")) {
                    action.addProperty("owner", fullID);
                }
            }
        }
    }

    final String experienceJson = gson.toJson(experienceObject);
    wrapper.setJson(experienceJson);
    wrapper.setEtag(Hashing.md5().hashString(experienceJson, Charset.forName("UTF-8")).toString());

    final ExperienceItems items = new ExperienceItems();
    items.entry = wrapper;

    JsonArray availabilityArray = experienceObject.getAsJsonArray("availabilities");
    if (availabilityArray != null) {
        for (JsonElement availElement : availabilityArray) {
            ExperienceAvailability availability = gson.fromJson(availElement, ExperienceAvailability.class);
            availability.setUri(wrapper.getPublicID());
            items.availabilities.add(availability);
        }
    }

    return items;
}

From source file:org.obiba.mica.file.service.TempFileService.java

@NotNull
public TempFile addTempFile(@NotNull TempFile tempFile, @NotNull InputStream uploadedInputStream)
        throws IOException {
    TempFile savedTempFile;/*from   w ww  .  j a  v a 2  s . c  o  m*/
    if (tempFile.getId() != null) {
        savedTempFile = tempFileRepository.findOne(tempFile.getId());
        if (savedTempFile == null) {
            savedTempFile = tempFileRepository.save(tempFile);
        }
    } else {
        savedTempFile = tempFileRepository.save(tempFile);
    }

    File file = getFile(savedTempFile.getId());
    OutputStream fileOut = new FileOutputStream(file);
    ByteStreams.copy(uploadedInputStream, fileOut);
    fileOut.close();
    savedTempFile.setSize(file.length());
    savedTempFile.setMd5(Files.hash(file, Hashing.md5()).toString());
    tempFileRepository.save(savedTempFile);
    return savedTempFile;
}

From source file:co.cask.cdap.internal.app.runtime.flow.FlowUtils.java

/**
 * Generates a queue consumer groupId for the given flowlet in the given program id.
 *///from   ww w .j  a  v  a2  s  . c  o m
public static long generateConsumerGroupId(Id.Program program, String flowletId) {
    // Use 'developer' in place of a program's namespace for programs in the 'default' namespace
    // to support backwards compatibility for queues and streams.
    String namespace = program.getNamespaceId();
    String backwardsCompatibleNamespace = Constants.DEFAULT_NAMESPACE.equals(namespace)
            ? Constants.DEVELOPER_ACCOUNT
            : namespace;
    return Hashing.md5().newHasher().putString(backwardsCompatibleNamespace)
            .putString(program.getApplicationId()).putString(program.getId()).putString(flowletId).hash()
            .asLong();
}

From source file:org.codehaus.httpcache4j.cache.FileManager.java

public synchronized File resolve(Key key) {
    File uriFolder = resolve(key.getURI());
    String vary;/*from  w w w  . j  a va  2  s  .  co m*/
    if (key.getVary().isEmpty()) {
        vary = "default";
    } else {
        vary = Hashing.md5().hashString(key.getVary().toString(), Charsets.UTF_8).toString().trim();
    }
    return new File(uriFolder, vary);
}

From source file:org.apache.accumulo.core.client.sample.AbstractHashSampler.java

/**
 * Subclasses with options should override this method and call {@code super.init(config)}.
 *//*from   w  w  w.  j  av  a  2  s. co  m*/
@SuppressFBWarnings(value = "UNSAFE_HASH_EQUALS", justification = "these hashes don't protect any secrets, just used for binning")
@Override
public void init(SamplerConfiguration config) {
    String hasherOpt = config.getOptions().get("hasher");
    String modulusOpt = config.getOptions().get("modulus");

    requireNonNull(hasherOpt, "Hasher not specified");
    requireNonNull(modulusOpt, "Modulus not specified");

    for (String option : config.getOptions().keySet()) {
        checkArgument(isValidOption(option), "Unknown option : %s", option);
    }

    switch (hasherOpt) {
    case "murmur3_32":
        hashFunction = Hashing.murmur3_32();
        break;
    case "md5":
        @SuppressWarnings("deprecation")
        HashFunction deprecatedMd5 = Hashing.md5();
        hashFunction = deprecatedMd5;
        break;
    case "sha1":
        @SuppressWarnings("deprecation")
        HashFunction deprecatedSha1 = Hashing.sha1();
        hashFunction = deprecatedSha1;
        break;
    default:
        throw new IllegalArgumentException("Unknown hahser " + hasherOpt);
    }

    modulus = Integer.parseInt(modulusOpt);
}

From source file:org.jclouds.karaf.commands.blobstore.BlobWriteCommand.java

@Override
protected Object doExecute() throws Exception {
    BlobStore blobStore = getBlobStore();

    BlobBuilder builder = blobStore.blobBuilder(blobName);
    if (stringPayload) {
        builder = builder.payload(payload.getBytes()); // use default Charset
    } else if (urlPayload) {
        InputStream input = new URL(payload).openStream();
        try {//www  .  j av  a  2 s . com
            builder = builder.payload(ByteStreams.toByteArray(input));
        } finally {
            input.close();
        }
    } else {
        ByteSource byteSource = Files.asByteSource(new File(payload));
        BlobBuilder.PayloadBlobBuilder payloadBuilder = builder.payload(byteSource)
                .contentLength(byteSource.size());
        if (!multipartUpload) {
            payloadBuilder = payloadBuilder.contentMD5(byteSource.hash(Hashing.md5()).asBytes());
        }
        builder = payloadBuilder;
    }

    PutOptions options = multipartUpload ? new PutOptions().multipart(true) : PutOptions.NONE;

    write(blobStore, containerName, blobName, builder.build(), options, signedRequest);

    cacheProvider.getProviderCacheForType("container").put(blobStore.getContext().unwrap().getId(),
            containerName);
    cacheProvider.getProviderCacheForType("blob").put(blobStore.getContext().unwrap().getId(), blobName);

    return null;
}

From source file:edu.cmu.lti.oaqa.ecd.phase.ProcessingStepUtils.java

/**
 * Execution hash is computed from JCas currentExperimentId, trace and sequenceId
 * @return MD5 hash corresponding to the above mentioned elements
 */// w  w  w.  j av  a 2  s .  c  o  m
public static String getExecutionIdHash(String experimentId, Trace trace, String sequenceId) {
    HashFunction hf = Hashing.md5();
    Hasher hasher = hf.newHasher();
    hasher.putString(experimentId, StandardCharsets.UTF_8);
    hasher.putString(trace.getTrace(), StandardCharsets.UTF_8);
    hasher.putString(String.valueOf(sequenceId), StandardCharsets.UTF_8);
    HashCode hash = hasher.hash();
    final String traceHash = hash.toString();
    return traceHash;
}

From source file:cosmos.sql.impl.LogicVisitor.java

@Override
public Iterable<MultimapRecord> apply(ChildVisitor input) {

    HashFunction hf = Hashing.md5();
    HashCode hc = hf.newHasher().putObject(input, input).hash();

    Entry<Cosmos, Store> entry = tempTableCache.getIfPresent(hc.toString());

    if (null != entry) {

        try {//from ww w  . j  a v  a2s. co  m
            return entry.getKey().fetch(entry.getValue());
        } catch (TableNotFoundException e) {
            log.error("Could not fetch results", e);
        } catch (UnexpectedStateException e) {
            log.error("Could not fetch results", e);
        }
    }

    Iterable<MultimapRecord> iter = Collections.emptyList();
    if (input instanceof FieldEquality) {
        FieldEquality equality = (FieldEquality) input;
        iter = apply(equality);
    } else if (input instanceof AndOperator) {
        AndOperator andOp = (AndOperator) input;
        iter = apply(andOp);

    } else if (input instanceof OrOperator) {
        OrOperator orOp = (OrOperator) input;

        iter = apply(orOp);
    }

    return iter;
}

From source file:com.cloudera.gertrude.space.LayerBuilder.java

Layer build(Map<Integer, Segment> finalSegments) {
    ImmutableMap.Builder<Integer, NavigableMap<Integer, Set<Segment>>> b = ImmutableMap.builder();
    Set<Integer> allSegmentIds = Sets.newHashSet();
    for (Map.Entry<Integer, Map<Integer, Integer>> e : allocatedBucketsByDiversion.entrySet()) {
        int diversionId = e.getKey();
        NavigableMap<Integer, Set<Segment>> bucketToSegment = Maps.newTreeMap();
        for (Map.Entry<Integer, Integer> ee : e.getValue().entrySet()) {
            int bucketId = ee.getKey();
            int segmentId = ee.getValue();
            Segment segment = experiments.get(segmentId);
            if (segment == null) {
                segment = parent.getDomain(domains.get(segmentId), finalSegments);
            } else {
                allSegmentIds.add(segmentId);
            }/*w  w w .j  a  v  a2s .c  o  m*/
            Set<Segment> segments = bucketToSegment.get(bucketId);
            if (segments == null) {
                segments = Sets.newHashSet();
                bucketToSegment.put(bucketId, segments);
            }
            segments.add(segment);
            finalSegments.put(segmentId, segment);
        }
        b.put(diversionId, bucketToSegment);
    }
    // TODO: check the collision properties of faster impls (e.g., MurmurHash3)
    return new LayerImpl(info, Hashing.md5(), allSegmentIds, b.build(), parent.getRandom());
}