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:io.takari.jdkget.OracleWebsiteTransport.java

@Override
public boolean validate(Arch arch, JdkVersion jdkVersion, File jdkImage, IOutput output) throws IOException {
    if (isApple(arch, jdkVersion)) {
        return jdkImage.length() == 66724162L;
    } else {/*from w w  w.j a  va 2 s.com*/
        JdkBinary bin = binary(arch, jdkVersion);

        int checks = 0;
        int failed = 0;

        if (bin.getSha256() != null) {
            checks++;
            String fileHash = hash(jdkImage, Hashing.sha256());
            if (!bin.getSha256().equals(fileHash)) {
                failed++;
                output.error("File sha256 `" + fileHash + "` differs from `" + bin.getSha256() + "`");
            }
        }
        if (bin.getMd5() != null) {
            checks++;
            String fileHash = hash(jdkImage, Hashing.md5());
            if (!bin.getMd5().equals(fileHash)) {
                failed++;
                output.error("File md5 `" + fileHash + "` differs from `" + bin.getMd5() + "`");
            }
        }
        if (bin.getSize() != -1) {
            checks++;
            if (bin.getSize() != jdkImage.length()) {
                failed++;
                output.error("File size `" + jdkImage.length() + "` differs from `" + bin.getSize() + "`");
            }
        }

        if (checks != 0 && failed > 0) {
            return false;
        }
    }
    return true;
}

From source file:com.google.cloud.hadoop.gcsio.testing.InMemoryObjectEntry.java

public InMemoryObjectEntry(String bucketName, String objectName, long createTimeMillis, String contentType,
        Map<String, byte[]> metadata) {
    // Override close() to commit its completed byte array into completedContents to reflect
    // the behavior that any readable contents are only well-defined if the writeStream is closed.
    writeStream = new ByteArrayOutputStream() {
        @Override/*w  w  w  .  jav a 2s. c  om*/
        public synchronized void close() throws IOException {
            synchronized (InMemoryObjectEntry.this) {
                completedContents = toByteArray();
                HashCode md5 = Hashing.md5().hashBytes(completedContents);
                HashCode crc32c = Hashing.crc32c().hashBytes(completedContents);
                writeStream = null;
                writeChannel = null;
                info = new GoogleCloudStorageItemInfo(info.getResourceId(), info.getCreationTime(),
                        completedContents.length, null, null, info.getContentType(), info.getMetadata(),
                        info.getContentGeneration(), 0L,
                        new VerificationAttributes(md5.asBytes(), Ints.toByteArray(crc32c.asInt())));
            }
        }
    };

    // We have to delegate because we can't extend from the inner class returned by,
    // Channels.newChannel, and the default version doesn't enforce ClosedChannelException
    // when trying to write to a closed channel; probably because it relies on the underlying
    // output stream throwing when closed. The ByteArrayOutputStream doesn't enforce throwing
    // when closed, so we have to manually do it.
    WritableByteChannel delegateWriteChannel = Channels.newChannel(writeStream);
    writeChannel = new WritableByteChannelImpl(delegateWriteChannel);

    // Size 0 initially because this object exists, but contains no data.
    info = new GoogleCloudStorageItemInfo(new StorageResourceId(bucketName, objectName), createTimeMillis, 0,
            null, null, contentType, ImmutableMap.copyOf(metadata), createTimeMillis, 0L);
}

From source file:de.cinovo.cloudconductor.agent.executors.FileExecutor.java

private HashCode getChecksum(File content) {
    try {//from   w  w  w .  j a  va  2s.  co  m
        return Files.hash(content, Hashing.md5());
    } catch (IOException e) {
        // should never happen, if it does-> leave checksum empty
        return null;
    }
}

From source file:org.codehaus.httpcache4j.auth.digest.RequestDigest.java

private String hash(Algorithm algorithm, String input, final String charset) {
    switch (algorithm) {
    case MD5:/* w  ww .j a  va 2s . c  o m*/
    case MD5_SESSION:
        try {
            return Hashing.md5().hashBytes(input.getBytes(charset)).toString();
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }
    case TOKEN:
    default:
        throw new IllegalArgumentException("No such algorithm");
    }
}

From source file:org.graylog.plugins.collector.configurations.rest.resources.CollectorConfigurationResource.java

@GET
@Path("/{collectorId}")
@Produces(MediaType.APPLICATION_JSON)//w ww . ja  v a 2s  . co  m
@ApiOperation(value = "Get a single collector configuration")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Collector not found."),
        @ApiResponse(code = 400, message = "Invalid ObjectId."),
        @ApiResponse(code = 304, message = "Configuration didn't update.") })
public Response getConfiguration(@Context Request request, @Context HttpHeaders httpHeaders,
        @ApiParam(name = "collectorId", required = true) @PathParam("collectorId") String collectorId,
        @ApiParam(name = "tags") @QueryParam("tags") String queryTags) throws NotFoundException {

    List tags = parseQueryTags(queryTags);
    CollectorConfiguration collectorConfiguration;

    String ifNoneMatch = httpHeaders.getHeaderString("If-None-Match");
    Boolean etagCached = false;

    Response.ResponseBuilder builder = Response.noContent();

    // check if client is up to date with a known valid etag
    if (ifNoneMatch != null) {
        EntityTag etag = new EntityTag(ifNoneMatch.replaceAll("\"", ""));
        etagCached = validEtags.contains(etag.toString());
        if (etagCached) {
            etagCached = true;
            builder = Response.notModified();
            builder.tag(etag);
        }
    }

    // fetch configuration from database if client is outdated
    if (tags != null && !etagCached) {
        List<CollectorConfiguration> collectorConfigurationList = collectorConfigurationService
                .findByTags(tags);
        collectorConfiguration = collectorConfigurationService.merge(collectorConfigurationList);
        String hashCode;
        if (collectorConfiguration != null) {
            collectorConfiguration.tags().addAll(tags);

            // add new etag to cache
            hashCode = Hashing.md5().hashInt(collectorConfiguration.hashCode()) // avoid negative values
                    .toString();

            EntityTag collectorConfigurationEtag = new EntityTag(hashCode);
            builder = Response.ok(collectorConfiguration);
            builder.tag(collectorConfigurationEtag);
            if (!validEtags.contains(collectorConfigurationEtag.toString())) {
                validEtags.add(collectorConfigurationEtag.toString());
            }
        }
    }

    // set cache control
    CacheControl cacheControl = new CacheControl();
    cacheControl.setNoTransform(true);
    cacheControl.setPrivate(true);
    builder.cacheControl(cacheControl);

    return builder.build();
}

From source file:com.dangdang.ddframe.job.cloud.scheduler.state.failover.FailoverService.java

private List<Integer> getAssignedShardingItems(final String jobName, final List<String> taskIdList,
        final Set<HashCode> assignedTasks) {
    List<Integer> result = new ArrayList<>(taskIdList.size());
    for (String each : taskIdList) {
        TaskContext.MetaInfo metaInfo = TaskContext.MetaInfo.from(each);
        if (assignedTasks
                .add(Hashing.md5().newHasher().putString(jobName, Charsets.UTF_8)
                        .putInt(metaInfo.getShardingItems().get(0)).hash())
                && !runningService.isTaskRunning(metaInfo)) {
            result.add(metaInfo.getShardingItems().get(0));
        }/*from  w  w  w . ja  v  a  2s  .  co m*/
    }
    return result;
}

From source file:com.google.gerrit.httpd.raw.HostPageServlet.java

@Inject
HostPageServlet(final Provider<CurrentUser> cu, final Provider<WebSession> w, final SitePaths sp,
        final ThemeFactory themeFactory, final GerritConfig gc, final ServletContext servletContext,
        final DynamicSet<WebUiPlugin> webUiPlugins, @GerritServerConfig final Config cfg)
        throws IOException, ServletException {
    currentUser = cu;/*w  w w.  j a v a2 s. com*/
    session = w;
    config = gc;
    plugins = webUiPlugins;
    signedOutTheme = themeFactory.getSignedOutTheme();
    signedInTheme = themeFactory.getSignedInTheme();
    site = sp;
    refreshHeaderFooter = cfg.getBoolean("site", "refreshHeaderFooter", true);
    boolean checkUserAgent = cfg.getBoolean("site", "checkUserAgent", true);

    final String pageName = "HostPage.html";
    template = HtmlDomUtil.parseFile(getClass(), pageName);
    if (template == null) {
        throw new FileNotFoundException("No " + pageName + " in webapp");
    }

    if (HtmlDomUtil.find(template, "gerrit_module") == null) {
        throw new ServletException("No gerrit_module in " + pageName);
    }
    if (HtmlDomUtil.find(template, HPD_ID) == null) {
        throw new ServletException("No " + HPD_ID + " in " + pageName);
    }

    String src = "gerrit_ui/gerrit_ui.nocache.js";
    if (!IS_DEV) {
        Element devmode = HtmlDomUtil.find(template, "gwtdevmode");
        if (devmode != null) {
            devmode.getParentNode().removeChild(devmode);
        }

        InputStream in = servletContext.getResourceAsStream("/" + src);
        if (in != null) {
            Hasher md = Hashing.md5().newHasher();
            try {
                try {
                    final byte[] buf = new byte[1024];
                    int n;
                    while ((n = in.read(buf)) > 0) {
                        md.putBytes(buf, 0, n);
                    }
                } finally {
                    in.close();
                }
            } catch (IOException e) {
                throw new IOException("Failed reading " + src, e);
            }
            src += "?content=" + md.hash().toString();
        } else {
            log.debug("No " + src + " in webapp root; keeping noncache.js URL");
        }
    }

    noCacheName = src;
    selector = new PermutationSelector("gerrit_ui");
    if (checkUserAgent && !IS_DEV) {
        selector.init(servletContext);
    }
    page = new Page();
}

From source file:com.google.appinventor.buildserver.DexExecTask.java

private String getHashFor(File inputFile) {
    String retval = alreadyChecked.get(inputFile.getAbsolutePath());
    if (retval != null)
        return retval;
    // add a hash of the original file path
    try {/*from w  w w  .j a  v  a 2 s  .  c o  m*/
        HashFunction hashFunction = Hashing.md5();
        HashCode hashCode = hashFunction.hashBytes(Files.readAllBytes(inputFile.toPath()));
        retval = hashCode.toString();
        alreadyChecked.put(inputFile.getAbsolutePath(), retval);
        return retval;
    } catch (IOException e) {
        e.printStackTrace();
        return "ERROR";
    }
}

From source file:net.jamcraft.chowtime.remote.RemoteMain.java

public static void HashCTD() {
    try {//from w w w .j a  va  2 s  .  co m
        HashFunction hasher = Hashing.md5();

        FileReader fis = new FileReader(ModConstants.DYN_LOC + "/local.ctd");
        BufferedReader br = new BufferedReader(fis);

        String line = br.readLine();
        String file = "";
        while (line != null) {
            file += line;
            line = br.readLine();
        }

        HashCode hash = hasher.hashString(file, Charset.defaultCharset());

        ChowTime.logger.info("Local.ctd hash digest(in hex format):: " + hash.toString());
        localHash = hash.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.opendaylight.md.controller.topology.lldp.utils.LLDPDiscoveryUtils.java

/**
 * @param nodeConnectorId/*from   w  ww.  j  a  v a2  s  .c  om*/
 * @return extra authenticator for lldp security
 * @throws NoSuchAlgorithmException
 */
public static byte[] getValueForLLDPPacketIntegrityEnsuring(final NodeConnectorId nodeConnectorId)
        throws NoSuchAlgorithmException {
    final String pureValue = nodeConnectorId + ManagementFactory.getRuntimeMXBean().getName();
    final byte[] pureBytes = pureValue.getBytes();
    HashFunction hashFunction = Hashing.md5();
    Hasher hasher = hashFunction.newHasher();
    HashCode hashedValue = hasher.putBytes(pureBytes).hash();
    return hashedValue.asBytes();
}