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:org.dllearner.reasoning.MaterializableFastInstanceChecker.java

private void loadOrDematerialize() {
    if (useCaching) {
        File cacheDir = new File("cache");
        cacheDir.mkdirs();//from w w w  . j  a v  a  2 s.  co  m
        HashFunction hf = Hashing.md5();
        Hasher hasher = hf.newHasher();
        hasher.putBoolean(materializeExistentialRestrictions);
        hasher.putBoolean(handlePunning);
        for (OWLOntology ont : rc.getOWLAPIOntologies()) {
            hasher.putInt(ont.getLogicalAxioms().hashCode());
            hasher.putInt(ont.getAxioms().hashCode());
        }
        String filename = hasher.hash().toString() + ".obj";

        File cacheFile = new File(cacheDir, filename);
        if (cacheFile.exists()) {
            logger.debug("Loading materialization from disk...");
            try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(cacheFile))) {
                Materialization mat = (Materialization) ois.readObject();
                classInstancesPos = mat.classInstancesPos;
                classInstancesNeg = mat.classInstancesNeg;
                opPos = mat.opPos;
                dpPos = mat.dpPos;
                bdPos = mat.bdPos;
                bdNeg = mat.bdNeg;
                dd = mat.dd;
                id = mat.id;
                sd = mat.sd;
            } catch (ClassNotFoundException | IOException e) {
                e.printStackTrace();
            }
            logger.debug("done.");
        } else {
            dematerialize();
            Materialization mat = new Materialization();
            mat.classInstancesPos = classInstancesPos;
            mat.classInstancesNeg = classInstancesNeg;
            mat.opPos = opPos;
            mat.dpPos = dpPos;
            mat.bdPos = bdPos;
            mat.bdNeg = bdNeg;
            mat.dd = dd;
            mat.id = id;
            mat.sd = sd;
            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(cacheFile))) {
                oos.writeObject(mat);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } else {
        dematerialize();
    }
}

From source file:org.dllearner.reasoning.FastInstanceChecker.java

private void loadOrDematerialize() {
    if (useCaching) {
        File cacheDir = new File("cache");
        cacheDir.mkdirs();/*  ww w.j  a  va  2 s .c om*/
        HashFunction hf = Hashing.md5();
        Hasher hasher = hf.newHasher();
        hasher.putBoolean(materializeExistentialRestrictions);
        hasher.putBoolean(handlePunning);
        for (OWLOntology ont : rc.getOWLAPIOntologies()) {
            hasher.putInt(ont.getLogicalAxioms().hashCode());
            hasher.putInt(ont.getAxioms().hashCode());
        }
        String filename = hasher.hash().toString() + ".obj";

        File cacheFile = new File(cacheDir, filename);
        if (cacheFile.exists()) {
            logger.debug("Loading materialization from disk...");
            try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(cacheFile))) {
                Materialization mat = (Materialization) ois.readObject();
                classInstancesPos = mat.classInstancesPos;
                classInstancesNeg = mat.classInstancesNeg;
                opPos = mat.opPos;
                dpPos = mat.dpPos;
                bdPos = mat.bdPos;
                bdNeg = mat.bdNeg;
                dd = mat.dd;
                id = mat.id;
                sd = mat.sd;
            } catch (ClassNotFoundException | IOException e) {
                e.printStackTrace();
            }
            logger.debug("done.");
        } else {
            materialize();
            Materialization mat = new Materialization();
            mat.classInstancesPos = classInstancesPos;
            mat.classInstancesNeg = classInstancesNeg;
            mat.opPos = opPos;
            mat.dpPos = dpPos;
            mat.bdPos = bdPos;
            mat.bdNeg = bdNeg;
            mat.dd = dd;
            mat.id = id;
            mat.sd = sd;
            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(cacheFile))) {
                oos.writeObject(mat);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } else {
        materialize();
    }
}

From source file:com.infinities.keystone4j.utils.Cms.java

public String hashToken(String tokenid, Algorithm mode)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, DecoderException {
    if (mode == null) {
        mode = Algorithm.md5;/*  ww w.  ja va  2s .co m*/
    }

    if (Strings.isNullOrEmpty(tokenid)) {
        throw new NullPointerException("invalid tokenid");
    }

    if (isAsn1Token(tokenid) || isPkiz(tokenid)) {
        HashFunction hf = Hashing.md5();
        if (mode == Algorithm.sha1) {
            hf = Hashing.sha1();
        } else if (mode == Algorithm.sha256) {
            hf = Hashing.sha256();
        } else if (mode == Algorithm.sha512) {
            hf = Hashing.sha512();
        }
        HashCode hc = hf.newHasher().putString(tokenid).hash();
        return toHex(hc.asBytes());

    } else {
        return tokenid;
    }
}

From source file:annis.libgui.AnnisBaseUI.java

/**
* Inject CSS into the UI./* w  w w.  jav a2s. c om*/
* This function will not add multiple style-elements if the
* exact CSS string was already added.
* @param cssContent
*/
public void injectUniqueCSS(String cssContent) {
    if (alreadyAddedCSS == null) {
        alreadyAddedCSS = new TreeSet<String>();
    }
    String hashForCssContent = Hashing.md5().hashString(cssContent).toString();
    if (!alreadyAddedCSS.contains(hashForCssContent)) {
        CSSInject cssInject = new CSSInject(UI.getCurrent());
        cssInject.setStyles(cssContent);
        alreadyAddedCSS.add(hashForCssContent);
    }
}

From source file:org.apache.twill.discovery.ZKDiscoveryService.java

/**
 * Generate unique node path for a given {@link Discoverable}.
 * @param discoverable An instance of {@link Discoverable}.
 * @return A node name based on the discoverable.
 *//*w  w w  . ja v a  2 s  .  c om*/
private String getNodePath(Discoverable discoverable) {
    InetSocketAddress socketAddress = discoverable.getSocketAddress();
    String node = Hashing.md5().newHasher().putBytes(socketAddress.getAddress().getAddress())
            .putInt(socketAddress.getPort()).hash().toString();

    return String.format("/%s/%s", discoverable.getName(), node);
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * Gets the md5 of the downloaded file/*from  w  w  w. ja  va2  s. c  o m*/
 * @param file - File to check
 * @return - string of file's md5
 * @throws IOException 
 */
public static String fileMD5(File file) throws IOException {
    if (file.exists()) {
        return Files.hash(file, Hashing.md5()).toString();
        //FileInputStream fis = new FileInputStream(file);
        //String result = DigestUtils.md5Hex(fis);
        //fis.close();
        //return result;
    } else
        return "";
}

From source file:com.google.devtools.build.lib.vfs.FileSystem.java

/**
 * Returns the MD5 digest of the file denoted by {@code path}. See
 * {@link Path#getMD5Digest} for specification.
 *//*  w ww .  ja v  a  2s  .co  m*/
protected byte[] getMD5Digest(final Path path) throws IOException {
    // Naive I/O implementation.  Subclasses may (and do) optimize.
    // This code is only used by the InMemory or Zip or other weird FSs.
    return new ByteSource() {
        @Override
        public InputStream openStream() throws IOException {
            return getInputStream(path);
        }
    }.hash(Hashing.md5()).asBytes();
}

From source file:org.sonatype.nexus.proxy.maven.maven2.M2Repository.java

@Override
protected StorageItem doRetrieveItem(ResourceStoreRequest request)
        throws IllegalOperationException, ItemNotFoundException, StorageException {
    // we do all this mockery (NEXUS-4218 and NEXUS-4243) ONLY when we are sure
    // that we deal with REMOTE REQUEST INITIATED BY OLD 2.x MAVEN and nothing else.
    // Before this fix, the code was executed whenever
    // "!ModelVersionUtility.LATEST_MODEL_VERSION.equals( userSupportedVersion ) )" was true
    // and it was true even for userSupportedVersion being null (ie. not user agent string supplied!)!!!
    final boolean remoteCall = request.getRequestContext().containsKey(AccessManager.REQUEST_REMOTE_ADDRESS);
    final String userAgent = (String) request.getRequestContext().get(AccessManager.REQUEST_AGENT);

    if (remoteCall && null != userAgent) {
        final Version userSupportedVersion = getClientSupportedVersion(userAgent);

        // we still can make up our mind here, we do this only if we know: this request is about metadata,
        // the client's metadata version is known and it is not the latest one
        if (M2ArtifactRecognizer.isMetadata(request.getRequestPath()) && userSupportedVersion != null
                && !ModelVersionUtility.LATEST_MODEL_VERSION.equals(userSupportedVersion)) {
            // metadata checksum files are calculated and cached as side-effect
            // of doRetrieveMetadata.
            final StorageFileItem mdItem;
            if (M2ArtifactRecognizer.isChecksum(request.getRequestPath())) {
                String path = request.getRequestPath();
                if (request.getRequestPath().endsWith(".md5")) {
                    path = path.substring(0, path.length() - 4);
                } else if (request.getRequestPath().endsWith(".sha1")) {
                    path = path.substring(0, path.length() - 5);
                }//from  w w  w .  ja v  a2 s  .c om
                // we have to keep original reqest's flags: localOnly and remoteOnly are strange ones, so
                // we do a hack here
                // second, since we initiate a request for different path within a context of this request,
                // we need to be careful about it
                ResourceStoreRequest mdRequest = new ResourceStoreRequest(path, request.isRequestLocalOnly(),
                        request.isRequestRemoteOnly());
                mdRequest.getRequestContext().setParentContext(request.getRequestContext());

                mdItem = (StorageFileItem) super.retrieveItem(false, mdRequest);
            } else {
                mdItem = (StorageFileItem) super.doRetrieveItem(request);
            }

            try {
                Metadata metadata;
                try (final InputStream inputStream = mdItem.getInputStream()) {
                    metadata = MetadataBuilder.read(inputStream);
                }

                Version requiredVersion = getClientSupportedVersion(userAgent);
                Version metadataVersion = ModelVersionUtility.getModelVersion(metadata);

                if (requiredVersion == null || requiredVersion.equals(metadataVersion)) {
                    return super.doRetrieveItem(request);
                }

                ModelVersionUtility.setModelVersion(metadata, requiredVersion);

                ByteArrayOutputStream mdOutput = new ByteArrayOutputStream();

                MetadataBuilder.write(metadata, mdOutput);

                final byte[] content;
                if (M2ArtifactRecognizer.isChecksum(request.getRequestPath())) {
                    String digest;
                    if (request.getRequestPath().endsWith(".md5")) {
                        digest = Hashing.md5().hashBytes(mdOutput.toByteArray()).toString();
                    } else {
                        digest = Hashing.sha1().hashBytes(mdOutput.toByteArray()).toString();
                    }
                    content = (digest + '\n').getBytes("UTF-8");
                } else {
                    content = mdOutput.toByteArray();
                }

                String mimeType = getMimeSupport().guessMimeTypeFromPath(getMimeRulesSource(),
                        request.getRequestPath());
                ContentLocator contentLocator = new ByteArrayContentLocator(content, mimeType);

                DefaultStorageFileItem result = new DefaultStorageFileItem(this, request, true, false,
                        contentLocator);
                result.setCreated(mdItem.getCreated());
                result.setModified(System.currentTimeMillis());
                return result;
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.error("Error parsing metadata, serving as retrieved", e);
                } else {
                    log.error("Error parsing metadata, serving as retrieved: " + e.getMessage());
                }

                return super.doRetrieveItem(request);
            }
        }
    }

    return super.doRetrieveItem(request);
}

From source file:com.marvinformatics.formatter.FormatterMojo.java

/**
 * @param str//from  w  w  w  .  ja v a  2  s .  c  o m
 * @return
 * @throws UnsupportedEncodingException
 */
private String md5hash(String str) throws UnsupportedEncodingException {
    return Hashing.md5().hashBytes(str.getBytes(encoding)).toString();
}

From source file:org.jclouds.kinetic.strategy.internal.KineticStorageStrategyImpl.java

private Blob createBlobFromByteSource(final String container, final String key, final ByteSource byteSource) {
    BlobBuilder builder = blobBuilders.get();
    builder.name(key);//from   ww  w  .j a  v a 2s.c om
    File file = getFileForBlobKey(container, key);
    try {
        String cacheControl = null;
        String contentDisposition = null;
        String contentEncoding = null;
        String contentLanguage = null;
        String contentType = null;
        HashCode hashCode = null;
        Date expires = null;
        ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder();

        UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(file.toPath());
        if (view != null) {
            Set<String> attributes = ImmutableSet.copyOf(view.list());

            cacheControl = readStringAttributeIfPresent(view, attributes, XATTR_CACHE_CONTROL);
            contentDisposition = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_DISPOSITION);
            contentEncoding = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_ENCODING);
            contentLanguage = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_LANGUAGE);
            contentType = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_TYPE);
            if (contentType == null && autoDetectContentType) {
                contentType = probeContentType(file.toPath());
            }
            if (attributes.contains(XATTR_CONTENT_MD5)) {
                ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_CONTENT_MD5));
                view.read(XATTR_CONTENT_MD5, buf);
                hashCode = HashCode.fromBytes(buf.array());
            }
            if (attributes.contains(XATTR_EXPIRES)) {
                ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_EXPIRES));
                view.read(XATTR_EXPIRES, buf);
                buf.flip();
                expires = new Date(buf.asLongBuffer().get());
            }
            for (String attribute : attributes) {
                if (!attribute.startsWith(XATTR_USER_METADATA_PREFIX)) {
                    continue;
                }
                String value = readStringAttributeIfPresent(view, attributes, attribute);
                userMetadata.put(attribute.substring(XATTR_USER_METADATA_PREFIX.length()), value);
            }

            builder.payload(byteSource).cacheControl(cacheControl).contentDisposition(contentDisposition)
                    .contentEncoding(contentEncoding).contentLanguage(contentLanguage)
                    .contentLength(byteSource.size()).contentMD5(hashCode).contentType(contentType)
                    .expires(expires).userMetadata(userMetadata.build());
        } else {
            builder.payload(byteSource).contentLength(byteSource.size())
                    .contentMD5(byteSource.hash(Hashing.md5()).asBytes());
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    Blob blob = builder.build();
    blob.getMetadata().setContainer(container);
    blob.getMetadata().setLastModified(new Date(file.lastModified()));
    blob.getMetadata().setSize(file.length());
    if (blob.getPayload().getContentMetadata().getContentMD5() != null)
        blob.getMetadata()
                .setETag(base16().lowerCase().encode(blob.getPayload().getContentMetadata().getContentMD5()));
    return blob;
}