public StreamCopyDigest() { this.generator = new MessageDigestGenerator(); }
/** * Creates the visitor. When the visitor hits a zip entry whose name matches * filesToRealizeRegex, that zip entry will be realized via the template engine prior * to its hashcode being computed. In other words the file's hashcode will be computed * on the content after its replacement variables have been replaced. * If you just want this visitor to walk a zip file without realizing any files, pass in * a null pattern or pass in a null template engine. This will, in effect, * have this visitor collect all zip file entry names and calculate their hashcodes based on * all content within the zip file. * * @param filesToRealizeRegex pattern of files that are to be realized prior to hashcodes being computed * @param templateEngine the template engine that replaces replacement variables in files to be realized */ public InMemoryZipFileVisitor(Pattern filesToRealizeRegex, TemplateEngine templateEngine) { if (filesToRealizeRegex == null || templateEngine == null) { filesToRealizeRegex = null; templateEngine = null; } this.filesToRealizeRegex = filesToRealizeRegex; this.templateEngine = templateEngine; this.hashcodeGenerator = new MessageDigestGenerator(); }
/** * Similar to {@link #getDigest(InputStream)}, only this returns the digest as a String. * * @param is the stream whose data is to be used to calculate the digest * * @return the stream data's digest as a String * * @throws IOException if failed to read the stream for some reason */ public static String getDigestString(InputStream is) throws IOException { MessageDigestGenerator md5 = new MessageDigestGenerator(MD5); return md5.calcDigestString(is); }
/** * Calculates a digest for a given string and returns the digest's String representation. * * @param source_str the string whose contents will be used as the data to calculate the digest * * @return the string's digest or hash as a String */ public static String getDigestString(String source_str) { MessageDigestGenerator md5 = new MessageDigestGenerator(MD5); return md5.calcDigestString(source_str); }
/** * Calculates the digest for a given file. The file's contents will be used as the source data for the digest calculation. * * @param file the file whose contents are to be used to calculate the digest. * * @return the file content's digest as a String * * @throws IOException if the file could not be read or accessed */ public static String getDigestString(File file) throws IOException { MessageDigestGenerator md5 = new MessageDigestGenerator(MD5); return md5.calcDigestString(file); }
/** * Calculates the digest for a given file. The file's contents will be used as the source data for the digest calculation. * * @param file the file whose contents are to be used to calculate the digest. * * @return the file content's digest * * @throws IOException if the file could not be read or accessed */ public static byte[] getDigest(File file) throws IOException { MessageDigestGenerator md5 = new MessageDigestGenerator(MD5); return md5.calcDigest(file); }
/** * Calculates the digest for a given file. The file's contents will be used as the source data for the digest calculation. * * @param url the URL whose contents are to be used to calculate the digest. * * @return the URL content's digest as a String * * @throws IOException if the URL could not be read or accessed */ public static String getDigestString(URL url) throws IOException { MessageDigestGenerator md5 = new MessageDigestGenerator(MD5); return md5.calcDigestString(url); }
/** * Returns the digest for the data found in the given stream. The digest is returned as a byte array; if you want * the digest as a String, call getDigestString methods instead. * * @param is the stream whose data is to be used to calculate the digest * * @return the stream data's hash * * @throws IOException if failed to read the stream for some reason */ public static byte[] getDigest(InputStream is) throws IOException { MessageDigestGenerator md5 = new MessageDigestGenerator(MD5); return md5.calcDigest(is); }
/** * Calculates a digest for a given string. * * @param source_str the string whose contents will be used as the data to calculate the digest * * @return the string's digest * * @throws RuntimeException if a system error occurred - should never really happen */ public static byte[] getDigest(String source_str) { MessageDigestGenerator md5 = new MessageDigestGenerator(MD5); return md5.calcDigest(source_str); }
/** * Computes SHA256 for an archived content. * * @param contentFile content archive * @return SHA256 of the archive */ private String computeSHAForArchivedContent(File contentFile) { if (!contentFile.isDirectory()) { try { MessageDigestGenerator messageDigest = new MessageDigestGenerator(MessageDigestGenerator.SHA_256); return messageDigest.calcDigestString(contentFile); } catch (Exception ex) { log.error("Not able to compute SHA256 for " + contentFile.getPath() + " ."); } } return null; }
/** * This can be used to generate the digest hash from the command line. * * @param args one and only one filename - may or may not be a .jar file. * * @throws Exception if failed to compute the digest for some reason */ public static void main(String[] args) throws Exception { String file = args[0]; String digest = MessageDigestGenerator.getDigestString(new File(file)); System.out.println("MD5=" + digest); digest = new MessageDigestGenerator(SHA_256).calcDigestString(new File(file)); System.out.println("SHA-256=" + digest); } }
@SuppressWarnings("unchecked") public String getResourceSubscriptionMD5(int resourceId) { MessageDigestGenerator md5Generator = new MessageDigestGenerator(); Query q = entityManager.createNamedQuery(Repo.QUERY_FIND_REPOS_BY_RESOURCE_ID); q.setParameter("resourceId", resourceId); List<Repo> repos = q.getResultList(); for (Repo repo : repos) { long modifiedTimestamp = repo.getLastModifiedDate(); Date modifiedDate = new Date(modifiedTimestamp); md5Generator.add(Integer.toString(modifiedDate.hashCode()).getBytes()); } String digestString = md5Generator.getDigestString(); return digestString; }
/** * Creates a new package described by the specified details. The destination of the content in the provided input * stream will be determined by the package name. * * @param contentFile the file to write the content to * @param content content to be written for the package. NOTE this Stream will be closed by this method. * @param unzip if <code>true</code>, the content stream will be treated like a ZIP file and be unzipped as * it is written, using the package name as the base directory; if <code>false</code> the * content will be written to directly to a file using the package name as the file name */ public void createContent(File destination, File content, boolean unzip) { try { if (unzip) { ZipUtil.unzipFile(content, destination); String sha = new MessageDigestGenerator(MessageDigestGenerator.SHA_256).calcDigestString(content); writeSHAToManifest(destination, sha); } else { InputStream contentStream = new BufferedInputStream(new FileInputStream(content)); FileUtil.writeFile(contentStream, destination); } } catch (IOException e) { throw new RuntimeException("Error creating artifact for contentFile: " + destination, e); } }
private static String computeDigest(ResourceType rt, Collection<MeasurementDefinition> measurements, Collection<OperationDefinition> operations, Collection<PackageType> packageTypes, ConfigurationDefinition pluginConfigurationDefinition, ConfigurationDefinition resourceConfigurationDefinition) { StringBuilder representation = new StringBuilder(); addResourceTypeRepresentation(rt, representation); addMeasurementDefinitionsRepresentations(measurements, representation); addOperationDefinitionsRepresentations(operations, representation); addPackageTypesRepresentations(packageTypes, representation); addRepresentation(pluginConfigurationDefinition, representation); addRepresentation(resourceConfigurationDefinition, representation); return new MessageDigestGenerator(MessageDigestGenerator.SHA_256).calcDigestString(representation.toString()); }
/** * Calculates a unique key based on parents' resource keys. * * @param prefixKey extra key to be appended at the beginning of the digest process * @return key */ private String getAncestryBasedResourceKey(String prefixKey) { MessageDigestGenerator messageDigest = new MessageDigestGenerator(MessageDigestGenerator.SHA_256); if (prefixKey != null) { messageDigest.add(prefixKey.getBytes()); } messageDigest.add(this.resource.getResourceKey().getBytes()); ResourceContext<?> ancestor = this.parentResourceContext; while (ancestor != null) { messageDigest.add(ancestor.getResourceKey().getBytes()); ancestor = ancestor.getParentResourceContext(); } return messageDigest.getDigestString(); }
private void mergedStructuredIntoRaws(Configuration configuration, ResourceConfigurationFacet facet) { Set<RawConfiguration> rawConfigs = facet.loadRawConfigurations(); if (rawConfigs == null) { return; } prepareConfigForMergeIntoRaws(configuration, rawConfigs); Queue<RawConfiguration> queue = new LinkedList<RawConfiguration>(rawConfigs); while (!queue.isEmpty()) { RawConfiguration originalRaw = queue.poll(); RawConfiguration mergedRaw = facet.mergeRawConfiguration(configuration, originalRaw); if (mergedRaw != null) { //TODO bypass validation of structured config for template values String contents = mergedRaw.getContents(); String sha256 = new MessageDigestGenerator(MessageDigestGenerator.SHA_256).calcDigestString(contents); mergedRaw.setContents(contents, sha256); updateRawConfig(configuration, originalRaw, mergedRaw); } } }
public void mergeRawConfig(Configuration from, RawConfiguration existingConfig, RawConfiguration toUpdate) throws Exception { Augeas aug = null; try { String lens = configMap.get(existingConfig.getPath()); aug = createAugeas(lens, existingConfig.getContents()); String file = getFile(aug); for (String pathSuffix : nodePaths.get(existingConfig.getPath())) { String propName = ("/files" + existingConfig.getPath() + "/" + pathSuffix).substring(rootNodePath .length()); String propValue = translator.getPropertyValue(propName, from); aug.set("/files" + file + "/" + pathSuffix, propValue); } aug.save(); toUpdate.setPath(existingConfig.getPath()); String contents = FileUtils.readFileToString(new File(file)); String sha256 = new MessageDigestGenerator(MessageDigestGenerator.SHA_256).calcDigestString(contents); toUpdate.setContents(contents, sha256); } finally { if (aug != null) { aug.close(); } } }
public void updateBackingContent(String filename, String displayVersion) { File file = new File(filename); if (!file.exists()) { throw new IllegalArgumentException("File not found: " + file.getAbsolutePath()); } if (file.isDirectory()) { throw new IllegalArgumentException("File expected, found directory: " + file.getAbsolutePath()); } String sha = null; try { sha = new MessageDigestGenerator(MessageDigestGenerator.SHA_256).calcDigestString(file); } catch (Exception e) { //do nothing because the sha will remain null. LOG.error("Message digest for the package bits failed.", e); } String packageVersion = "[sha256=" + sha + "]"; InstalledPackage oldPackage = getBackingContent(); ContentManagerRemote contentManager = remoteClient.getProxy(ContentManagerRemote.class); ContentUploader contentUploader = new ContentUploader(contentManager); String temporaryContentHandle = contentUploader.upload(file); PackageVersion pv = contentManager.createPackageVersionWithDisplayVersion(remoteClient.getSubject(), oldPackage.getPackageVersion().getGeneralPackage().getName(), oldPackage.getPackageVersion() .getGeneralPackage().getPackageType().getId(), packageVersion, displayVersion, oldPackage .getPackageVersion().getArchitecture().getId(), temporaryContentHandle); contentManager.deployPackagesWithNote(remoteClient.getSubject(), new int[] { resourceClientProxy.getId() }, new int[] { pv.getId() }, "CLI deployment request"); }
private void mergeRawsIntoStructured(Configuration configuration, ResourceConfigurationFacet facet) { Configuration structuredConfig = facet.loadStructuredConfiguration(); if (structuredConfig != null) { prepareConfigForMergeIntoStructured(configuration, structuredConfig); for (RawConfiguration rawConfig : configuration.getRawConfigurations()) { String contents = rawConfig.getContents(); String sha256 = new MessageDigestGenerator(MessageDigestGenerator.SHA_256).calcDigestString(contents); rawConfig.setContents(contents, sha256); structuredConfig.addRawConfiguration(rawConfig); facet.mergeStructuredConfiguration(rawConfig, configuration); } } }
/** * Will return the persisted Resource Configuration update, or null if the specified Configuration * is identical to the currently persisted Configuration. */ private ResourceConfigurationUpdate persistNewAgentReportedResourceConfiguration(Resource resource, Configuration liveConfig) throws ConfigurationUpdateStillInProgressException { if (liveConfig.getRawConfigurations() != null) { for (RawConfiguration raw : liveConfig.getRawConfigurations()) { MessageDigestGenerator sha256Generator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256); sha256Generator.add(raw.getContents().getBytes()); raw.setSha256(sha256Generator.getDigestString()); } } /* * NOTE: We pass the overlord, since this is a system side-effect. here, the system * and *not* the user, is choosing to persist the most recent configuration because it was different * from the last known value. again, the user isn't attempting to change the value; instead, *JON* * is triggering save based on the semantics that we want to provide for configuration updates. * For the same reason, we pass null as the subject. */ ResourceConfigurationUpdate update = this.configurationManager .persistResourceConfigurationUpdateInNewTransaction(this.subjectManager.getOverlord(), resource.getId(), liveConfig, ConfigurationUpdateStatus.SUCCESS, null, false); // resource.setResourceConfiguration(liveConfig.deepCopy(false)); resource.setResourceConfiguration(liveConfig.deepCopyWithoutProxies()); return update; }