private String getMd5(URL pluginURL) throws IOException { return MessageDigestGenerator.getDigestString(pluginURL); }
public String calcDigestString(InputStream is) throws IOException { add(is); return getDigestString(); }
/** * Copies the input stream data to the output stream and returns the * copied data's digest string. * * Note: the streams are never closed - the caller is responsible for that. * * @param in input content * @param out where to write the input content * @return the copied content's digest string (aka hashcode) */ public String copyAndCalculateHashcode(InputStream in, OutputStream out) { try { byte[] buffer = new byte[32768]; BufferedInputStream bufferedStream = new BufferedInputStream(in, buffer.length); for (int bytesRead = bufferedStream.read(buffer); bytesRead != -1; bytesRead = bufferedStream.read(buffer)) { out.write(buffer, 0, bytesRead); this.generator.add(buffer, 0, bytesRead); } out.flush(); } catch (IOException ioe) { throw new RuntimeException("Stream data cannot be copied", ioe); } return this.generator.getDigestString(); } }
/** * 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; }
private boolean isNewOrUpdated(String pluginName) { DeploymentInfo deploymentInfo = this.deploymentInfos.get(pluginName); if (deploymentInfo == null) { throw new IllegalStateException("DeploymentInfo was not found for plugin [" + pluginName + " ] - it should have been initialized by preprocessPlugin()."); } PluginManagerLocal pluginMgr = LookupUtil.getPluginManager(); Plugin plugin = pluginMgr.getPlugin(pluginName); if (null == plugin) { log.debug("New plugin [" + pluginName + "] detected."); return true; } String md5 = null; try { md5 = MessageDigestGenerator.getDigestString(new File(deploymentInfo.url.toURI())); } catch (Exception e) { log.error("Error generating MD5 for plugin [" + pluginName + "]. Cause: " + e); } if (!plugin.getMd5().equals(md5)) { log.debug("Updated plugin [" + pluginName + "] detected."); return true; } return false; }
/** * If the caller provided a default value, it is used. If the default * value is <code>null</code>, this will generate a version string * equal to the file's MD5 hashcode. If this fails to calculate the * MD5, a runtime exception is thrown. * * @param defaultValue the string to return, unless this is <code>null</code> * @return the default value if not <code>null</code>, otherwise, the MD5 of the file */ public String getVersion(String defaultValue) { if (defaultValue != null) { return defaultValue; } try { return MessageDigestGenerator.getDigestString(getContentFile()); } catch (IOException e) { throw new RuntimeException("Cannot generate version for file [" + getContentFile() + "]", e); } }
return messageDigest.getDigestString();
contentDetails.put(UPLOAD_SHA256, digestGenerator.getDigestString());
sha = messageDigest.getDigestString(); writeSHAToManifest(deploymentDirectory, sha);
private void restoreExternalBackupFilesRecursive(String rootDir, File backupDir, String base, FileHashcodeMap map, DeployDifferences diff, boolean dryRun) throws Exception { File[] children = backupDir.listFiles(); if (children != null) { for (File child : children) { if (child.isDirectory()) { restoreExternalBackupFilesRecursive(rootDir, child, base, map, diff, dryRun); } else { String childRelativePath = child.getAbsolutePath().substring(base.length()); File restoredFile = new File(rootDir, childRelativePath); debug("Restoring backup file [", child, "] to external location [", restoredFile, "]. dryRun=" + dryRun); if (!dryRun) { restoredFile.getParentFile().mkdirs(); String hashcode = copyFileAndCalcHashcode(child, restoredFile); map.put(restoredFile.getAbsolutePath(), hashcode); } else { map.put(restoredFile.getAbsolutePath(), MessageDigestGenerator.getDigestString(child)); } diff.addRestoredFile(restoredFile.getAbsolutePath(), child.getAbsolutePath()); } } } return; }
@ExcludeDefaultInterceptors @Override public File getRemoteClientVersionFile() throws Exception { File versionFile = new File(getDataDownloadDir(), "rhq-client-version.properties"); File zip = getRemoteClientBinaryFile(); Boolean needVersionFile = FileUtil.isNewer(zip, versionFile); if (needVersionFile == null || needVersionFile.booleanValue()) { // we do not have the version properties file yet or it must be regenerated, let's extract some info and create one StringBuilder serverVersionInfo = new StringBuilder(); CoreServerMBean coreServer = LookupUtil.getCoreServer(); serverVersionInfo.append(RHQ_SERVER_VERSION + '=').append(coreServer.getVersion()).append('\n'); serverVersionInfo.append(RHQ_SERVER_BUILD_NUMBER + '=').append(coreServer.getBuildNumber()).append('\n'); // calculate the MD5 of the client zip log.info("Remote Client Binary File: " + zip.getAbsolutePath()); String md5Property = RHQ_CLIENT_MD5 + '=' + MessageDigestGenerator.getDigestString(zip) + '\n'; // now write the server version info in our internal version file our servlet will use FileOutputStream versionFileOutputStream = new FileOutputStream(versionFile); try { versionFileOutputStream.write(serverVersionInfo.toString().getBytes()); versionFileOutputStream.write(md5Property.getBytes()); } finally { try { versionFileOutputStream.close(); } catch (Exception ignore) { } } log.info("Remote Client Version File: " + versionFile); } return versionFile; }
hashcode = hashcodeGenerator.getDigestString(); } else { if (!dryRun) { hashcode = MessageDigestGenerator.getDigestString(stream);
private void restoreBackupFilesRecursive(File file, String base, File destDir, FileHashcodeMap map, DeployDifferences diff, boolean dryRun) throws Exception { File[] children = file.listFiles(); if (children != null) { for (File child : children) { if (child.isDirectory()) { restoreBackupFilesRecursive(child, base, destDir, map, diff, dryRun); } else { String childRelativePath = child.getAbsolutePath().substring(base.length()); //if (this.deploymentData.isManageRootDir() || new File(childRelativePath).getParent() != null) { File restoredFile = new File(destDir, childRelativePath); debug("Restoring backup file [", child, "] to [", restoredFile, "]. dryRun=", dryRun); if (!dryRun) { restoredFile.getParentFile().mkdirs(); String hashcode = copyFileAndCalcHashcode(child, restoredFile); map.put(childRelativePath, hashcode); } else { map.put(childRelativePath, MessageDigestGenerator.getDigestString(child)); } diff.addRestoredFile(childRelativePath, child.getAbsolutePath()); //} else { // debug("Skipping the restoration of the backed up file [", childRelativePath, // "] since this deployment was told to not manage the root directory"); //} } } } return; }
String md5Property = RHQ_AGENT_LATEST_MD5 + '=' + MessageDigestGenerator.getDigestString(binaryFile) + '\n';
/** * Creates a {@link Plugin} object for the given plugin jar and caches it. * @param pluginJar information about this plugin jar will be cached * @param md5 if known, this is the plugin jar's MD5, <code>null</code> if not known * @return the plugin jar files's information that has been cached * @throws Exception if failed to get information about the plugin */ private Plugin cacheFilesystemAgentPluginJar(File pluginJar, String md5) throws Exception { if (md5 == null) { // don't calculate the MD5 is we've already done it before md5 = MessageDigestGenerator.getDigestString(pluginJar); } URL pluginUrl = pluginJar.toURI().toURL(); PluginDescriptor descriptor = AgentPluginDescriptorUtil.loadPluginDescriptorFromUrl(pluginUrl); String version = AgentPluginDescriptorUtil.getPluginVersion(pluginJar, descriptor).toString(); String name = descriptor.getName(); Plugin plugin = new Plugin(name, pluginJar.getName()); plugin.setMd5(md5); plugin.setVersion(version); plugin.setMtime(pluginJar.lastModified()); this.agentPluginsOnFilesystem.put(pluginJar, plugin); return plugin; }
/** * 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(); }
/** * Creates a {@link ServerPlugin} object for the given plugin jar and caches it. * @param pluginJar information about this plugin jar will be cached * @param md5 if known, this is the plugin jar's MD5, <code>null</code> if not known * @return the plugin jar file's information that has been cached * @throws Exception if failed to get information about the plugin */ private ServerPlugin cacheFilesystemServerPluginJar(File pluginJar, @Nullable String md5) throws Exception { if (md5 == null) { // don't calculate the MD5 is we've already done it before md5 = MessageDigestGenerator.getDigestString(pluginJar); } URL pluginUrl = pluginJar.toURI().toURL(); ServerPluginDescriptorType descriptor = ServerPluginDescriptorUtil.loadPluginDescriptorFromUrl(pluginUrl); String version = ServerPluginDescriptorUtil.getPluginVersion(pluginJar, descriptor).toString(); String name = descriptor.getName(); ServerPlugin plugin = new ServerPlugin(name, pluginJar.getName()); plugin.setType(new ServerPluginType(descriptor).stringify()); plugin.setMd5(md5); plugin.setVersion(version); plugin.setMtime(pluginJar.lastModified()); this.serverPluginsOnFilesystem.put(pluginJar, new PluginWithDescriptor(plugin, descriptor)); return plugin; }
plugin.setMD5(MessageDigestGenerator.getDigestString(localPluginFile));
/** * 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; }