public String regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1.获取参数,设置给user对象 */ String loginname = request.getParameter("loginname"); String loginpass = request.getParameter("loginpass"); String reloginpass = request.getParameter("reloginpass"); String email = request.getParameter("email"); Users formUser = new Users(); formUser.setUName(loginname); String md5Digest = DigestUtils.md5Hex(loginpass); formUser.setUPassword(md5Digest); // formUser.setUPassword(loginpass); String md5DigestRepass = DigestUtils.md5Hex(reloginpass); formUser.setReloginpass(md5DigestRepass); formUser.setUEmail(email); /* * 2.校验参数 */ Map<String, String> errors = validateRegist(formUser); if (errors.size() > 0) { request.setAttribute("errors", errors); // 显示错误信息 request.setAttribute("formUser", formUser); // 回显表单信息 return "f:/regist.jsp"; } /* * 3.调用service层方法 */ userService.regist(formUser); return "f:/login.jsp"; // 转发到登录页面 }
public String getSecretToken(String nonce) throws OpenRDFException, IOException { if (nonce == null || nonce.length() == 0) throw new BadRequest("Missing nonce"); String uri = this.getResource().stringValue(); String hash = DigestUtils.md5Hex(uri); String secret = this.getRealm().getOriginSecret(); return DigestUtils.md5Hex(hash + ":" + nonce + ":" + secret); }
public void testReadChunkedData() throws MongoException, IOException { byte[] data1 = "first chunk".getBytes(); byte[] sha1 = DigestUtils.sha(data1); byte[] data2 = " second chunk".getBytes(); byte[] sha2 = DigestUtils.sha(data2); byte[] data = "first chunk second chunk".getBytes(); byte[] sha = DigestUtils.sha(data); prepareMockData("test.v7files.content", new BasicBSONObject("_id", sha1).append("in", data1)); prepareMockData("test.v7files.content", new BasicBSONObject("_id", sha2).append("in", data2)); prepareMockData( "test.v7files.content", new BasicBSONObject("_id", sha) .append("store", "cat") .append( "base", Arrays.asList( new BasicBSONObject("sha", sha1).append("length", data1.length), new BasicBSONObject("sha", sha2).append("length", data2.length)))); Mongo mongo = getMongo(); ContentStorage storage = new MongoContentStorage(mongo.getDB("test").getCollection("v7files.content")); Content check = storage.getContent(sha); assertEquals(new String(data), IOUtils.toString(check.getInputStream())); assertEquals(data.length, check.getLength()); mongo.close(); }
private static String computeKeyHash(String memcachedPrefix, NamedKey key) { // hash keys to keep things under 250 characters for memcached return memcachedPrefix + ":" + DigestUtils.sha1Hex(key.namespace) + ":" + DigestUtils.sha1Hex(key.key); }
public SystemUser update( SystemUserVO systemUserVO, String oldPassword, String[] roleNames, String[] groupNames, Database db) throws ConstraintException, SystemException, Exception { logger.info("systemUserVO:" + systemUserVO.getUserName()); logger.info("oldPassword:"******"newPassword:"******"roleNames:" + roleNames); logger.info("groupNames:" + groupNames); if (CmsPropertyHandler.getUsePasswordEncryption()) { String password = systemUserVO.getPassword(); try { byte[] encryptedPassRaw = DigestUtils.sha(password); String encryptedPass = new String(new Base64().encode(encryptedPassRaw), "ASCII"); password = encryptedPass; systemUserVO.setPassword(password); byte[] encryptedOldPasswordRaw = DigestUtils.sha(oldPassword); String encryptedOldPassword = new String(new Base64().encode(encryptedOldPasswordRaw), "ASCII"); oldPassword = encryptedOldPassword; } catch (Exception e) { logger.error("Error generating password:"******"Wrong user or password."); systemUserVO.setUserName(systemUser.getUserName()); if (roleNames != null) { systemUser.getRoles().clear(); for (int i = 0; i < roleNames.length; i++) { Role role = RoleController.getController().getRoleWithName(roleNames[i], db); systemUser.getRoles().add(role); role.getSystemUsers().add(systemUser); } } if (groupNames != null) { systemUser.getGroups().clear(); for (int i = 0; i < groupNames.length; i++) { Group group = GroupController.getController().getGroupWithName(groupNames[i], db); systemUser.getGroups().add(group); group.getSystemUsers().add(systemUser); } } // systemUserVO.setPassword(systemUser.getPassword()); systemUser.setValueObject(systemUserVO); return systemUser; }
/** * Response is calculated using H1 = md5("username:realm:password") H2 = md5("httpmethod:uri") * response = md5("H1:nonce:nc:cnonce:qop:H2") */ private String calculateResponse() throws UnsupportedEncodingException, NoSuchAlgorithmException { String hash_1 = DigestUtils.md5Hex((username + ":" + realm + ":" + password)); String hash_2 = DigestUtils.md5Hex((httpMethod + ":" + uri)); String hash_3_string = hash_1 + ":" + nonce + ":" + nounceCount + ":" + clientNonce + ":" + qop + ":" + hash_2; return DigestUtils.md5Hex(hash_3_string); }
/** * 生成文件摘要 * * @param strFilePath 文件路径 * @param file_digest_type 摘要算法 * @return 文件摘要结果 */ public static String getAbstract(String strFilePath, String file_digest_type) throws IOException { PartSource file = new FilePartSource(new File(strFilePath)); if (file_digest_type.equals("MD5")) { return DigestUtils.md5Hex(file.createInputStream()); } else if (file_digest_type.equals("SHA")) { return DigestUtils.sha256Hex(file.createInputStream()); } else { return ""; } }
/** * 生成文件摘要 * * @param strFilePath 文件路径 * @param file_digest_type 摘要算法 * @return 文件摘要结果 */ public static String getAbstract(String strFilePath, String file_digest_type) throws IOException { PartSource file = new FilePartSource(new File(strFilePath)); switch (file_digest_type) { case "MD5": return DigestUtils.md5Hex(file.createInputStream()); case "SHA": return DigestUtils.sha256Hex(file.createInputStream()); default: return ""; } }
/* * 测试generateSessionId */ @Test public void testGenerateSessionId() throws Exception { String tipSecret = "taobao1234"; dsg.setTipSecret(tipSecret); Class clazz = dsg.getClass(); Method method = clazz.getDeclaredMethod( "generateSessionId", char.class, String.class, String.class, String[].class); method.setAccessible(true); // userId的长度大于等于4位 { String userId = "214637"; String appSecret = "taobao123"; String appkey = "zhenzi"; String[] appkeys = new String[] {appkey}; StringBuilder md5 = new StringBuilder() .append(appSecret) .append(System.currentTimeMillis() / (24 * 60 * 60 * 1000)) .append(appkey) .append(userId) .append(tipSecret); StringBuilder sessionKey = new StringBuilder("2"); sessionKey.append("4637"); sessionKey.append(DigestUtils.md5Hex(md5.toString().getBytes("utf-8"))); String result = (String) method.invoke(dsg, '2', userId, appSecret, appkeys); assertEquals(sessionKey.toString(), result); } // userId的长度小于4位 { String userId = "37"; String appSecret = "taobao123"; String appkey = "zhenzi"; String[] appkeys = new String[] {appkey}; StringBuilder md5 = new StringBuilder() .append(appSecret) .append(System.currentTimeMillis() / (24 * 60 * 60 * 1000)) .append(appkey) .append(userId) .append(tipSecret); StringBuilder sessionKey = new StringBuilder("2"); sessionKey.append("0037"); sessionKey.append(DigestUtils.md5Hex(md5.toString().getBytes("utf-8"))); String result = (String) method.invoke(dsg, '2', userId, appSecret, appkeys); assertEquals(sessionKey.toString(), result); } }
/** * 生成签名 * * @param parameterMap 参数 * @return 签名 */ private String generateSign(Map<String, ?> parameterMap) { PluginConfig pluginConfig = getPluginConfig(); return DigestUtils.md5Hex( joinKeyValue( new TreeMap<String, Object>(parameterMap), null, "&key=" + DigestUtils.md5Hex(pluginConfig.getAttribute("key")), "&", true, "signMethod", "signature")); }
public String doIclubLogin() { LOGGER.info("Class :: " + this.getClass() + " :: Method :: doIclubLogin"); if (!validateLogin()) { try { WebClient client = IclubWebHelper.createCustomClient( BASE_URL + "person/login/" + bean.getLName() + "/" + Base64.encodeBase64URLSafeString(DigestUtils.md5(bean.getLPasswd()))); ResponseModel response = client.accept(MediaType.APPLICATION_JSON).get(ResponseModel.class); client.close(); if (response.getStatusCode() == 0) { setTheme(); IclubWebHelper.addMessage("Person Logged-In successfully", FacesMessage.SEVERITY_INFO); WebClient loginClient = IclubWebHelper.createCustomClient(BASE_URL + "person/" + bean.getLName()); IclubLoginModel model = loginClient.accept(MediaType.APPLICATION_JSON).get(IclubLoginModel.class); loginClient.close(); if (model != null && model.getLId() != null) { IclubWebHelper.addObjectIntoSession( BUNDLE.getString("logged.in.user.id"), model.getIclubPersonBByLPersonId()); IclubWebHelper.addObjectIntoSession( BUNDLE.getString("logged.in.user.scname"), bean.getLName()); WebClient personClient = IclubWebHelper.createCustomClient( U_BASE_URL + "get/" + model.getIclubPersonBByLPersonId()); IclubPersonModel personModel = personClient.accept(MediaType.APPLICATION_JSON).get(IclubPersonModel.class); personClient.close(); IclubWebHelper.addObjectIntoSession( BUNDLE.getString("logged.in.user.name"), personModel.getPFName() + (personModel.getPLName() == null ? "" : personModel.getPLName() + " ")); IclubWebHelper.addObjectIntoSession( BUNDLE.getString("logged.in.role.id"), model.getIclubRoleType()); return "/pages/dashboard/user/main.xhtml?faces-redirect=true"; } else { IclubWebHelper.addMessage( "Person Profile Fetch Error - Contact Admin", FacesMessage.SEVERITY_ERROR); return ""; } } else { IclubWebHelper.addMessage( "Login error :: " + response.getStatusDesc(), FacesMessage.SEVERITY_ERROR); return ""; } } catch (Exception e) { LOGGER.error(e, e); IclubWebHelper.addMessage("Login error :: " + e.getMessage(), FacesMessage.SEVERITY_ERROR); return ""; } } else { return ""; } }
/** * 删除节点。 @Title: removeCacheNode * * @author: zzh * @date: 2016年12月4日 下午8:34:15 * @version: v1.0.0 */ private static void removeCacheNode(String nodeIp) { // 删除当前IP的虚拟节点信息 CacheNode cacheNode = new CacheNode(nodeIp); // 获取当前节点的虚拟节点信息 List<VisualCacheNode> vNodesList = genVisualCacheNode(cacheNode); // 从hash环中删除虚拟节点信息 for (VisualCacheNode c : vNodesList) { String vNodeName = c.getNodeName(); String md5VisualNodeKey = DigestUtils.md5Hex(vNodeName); // 使用common-codec工具包 int hashNodeName = DJBHash(md5VisualNodeKey); visualNodeMap.remove(hashNodeName); System.out.println("删除虚拟节点,虚拟节点名称:" + vNodeName + ",真实节点:" + c.getRealCacheNode()); // 删除后,受到影响的节点:即数据和流量需要迁移到的节点信息 SortedMap<Integer, VisualCacheNode> vs = visualNodeMap.tailMap(hashNodeName); VisualCacheNode nodeInfo = null; if (vs != null && vs.size() > 0) { int affectVnshash = vs.firstKey(); nodeInfo = visualNodeMap.get(affectVnshash); } else { nodeInfo = visualNodeMap.get(visualNodeMap.firstKey()); } System.out.println("删除当前虚拟节点" + vNodeName + " , 受到影响的虚拟节点(原本虚拟节点的数据和流量将迁移到此节点):" + nodeInfo); } // 踢出真实节点 removeRealCache(nodeIp); }
/** * 增加一个新节点 @Title: addCacheNode * * @author: zzh * @date: 2016年12月2日 下午8:56:38 * @version: v1.0.0 */ private static void addCacheNode() { // 添加到真实Node列表 CacheNode newNode = new CacheNode("10.9.1.100"); realNodeList.add(newNode); // 生成虚拟节点 List<VisualCacheNode> addVisualNodeList = genVisualCacheNode(newNode); // 查询哪些节点受到影响,即数据需要分散 for (VisualCacheNode vnode : addVisualNodeList) { String nodeName = vnode.getNodeName(); String md5VisualNodeKey = DigestUtils.md5Hex(nodeName); // 使用common-codec工具包 int hashNodeName = DJBHash(md5VisualNodeKey); SortedMap<Integer, VisualCacheNode> vs = visualNodeMap.tailMap(hashNodeName + 1); // 排除掉自己。 VisualCacheNode nodeInfo = null; if (vs != null && vs.size() > 0) { int affectVnshash = vs.firstKey(); nodeInfo = visualNodeMap.get(affectVnshash); } else { nodeInfo = visualNodeMap.get(visualNodeMap.firstKey()); } System.out.println("新添节点,受到影响的虚拟节点:" + nodeInfo); } // 将虚拟节点加入到hash环中 addVisualCacheNodeIntoCircle(addVisualNodeList); }
public RemotePlugin setFile(File f) { try (FileInputStream fis = new FileInputStream(f)) { return this.setFile(f.getName(), DigestUtils.md5Hex(fis)); } catch (IOException e) { throw new IllegalStateException("Fail to compute hash", e); } }
@Test public void testMD5() { String str = "app_id=1814810&buy_amount=10&cp_order_id=mt_meizu_7337605_1398766447_1&create_time=1398766520051¬ify_id=1398766589010¬ify_time=2014-04-29 18:16:29&order_id=14042900000000044&partner_id=0&pay_time=1398766589036&product_id=pid_meizu_7337605_1398766447_1&product_per_price=0.1&product_unit=gold&total_price=1.0&trade_status=3"; str += (":" + "eSikRwObIpkg9Bmt3ty1R8CJf4nlE5bL"); System.out.println(DigestUtils.md5Hex(str)); }
private void validateMessage(OAuthAccessor accessor, MessageInfo info, boolean tokenEndpoint) throws OAuthException, IOException, URISyntaxException { info.message.validateMessage(accessor, new FakeTimeOAuthValidator()); String bodyHash = info.message.getParameter("oauth_body_hash"); if (tokenEndpoint && bodyHash != null) { throw new RuntimeException("Can't have body hash on token endpoints"); } SignatureType sigType = OAuthUtil.getSignatureType(tokenEndpoint, info.request.getHeader("Content-Type")); switch (sigType) { case URL_ONLY: break; case URL_AND_FORM_PARAMS: if (bodyHash != null) { throw new RuntimeException("Can't have body hash in form-encoded request"); } break; case URL_AND_BODY_HASH: if (bodyHash == null) { throw new RuntimeException("Requiring oauth_body_hash parameter"); } byte[] received = Base64.decodeBase64(CharsetUtil.getUtf8Bytes(bodyHash)); byte[] expected = DigestUtils.sha(info.rawBody); if (!Arrays.equals(received, expected)) { throw new RuntimeException("oauth_body_hash mismatch"); } } }
/** * @param username ... * @param pw ... * @return ... */ public boolean authenticate(String username, String pw) { if (this.file.exists() && (this.file.lastModified() > this.lastRead)) { readFile(); } else if (!this.file.exists() && (this.users.size() > 0)) { this.users.clear(); } String realpw = this.users.getProperty(username); if (realpw != null) { try { // check if password matches // first we try with unix crypt algorithm String cryptpw = Crypt.crypt(realpw, pw); if (realpw.equals(cryptpw)) { return true; } // then try MD5 if (realpw.equals(DigestUtils.md5(pw))) { return true; } } catch (Exception x) { return false; } } else { if (this.parentFile != null) { return this.parentFile.authenticate(username, pw); } } return false; }
private String getEmailValidationKey(AppUser user) { String randomString = RandomStringUtils.randomAlphanumeric(EMAIL_VALIDATION_KEY_LENGTH); String hashedUsername = DigestUtils.md2Hex(user.getEmailAddress()); return randomString + hashedUsername; }
@Override public void save(EditableModel obj) throws DaoException { ExternalApp externalApp = (ExternalApp) obj; externalApp.setAppId(createAppId()); externalApp.setThreeDesKey(getUUID()); externalApp.setCreateTime(new Date()); externalApp.setUpdateTime(externalApp.getCreateTime()); User user = new User(); user.setUserName(externalApp.getAppName()); user.setPassword(DigestUtils.md5Hex(SystemConfig.getString("system.user.default-password"))); user.setCreateTime(new Date()); user.setUpdateTime(user.getCreateTime()); user.setState(Constants.FLAG_USER_STATE_USING.value()); user.setType(Constants.FLAG_USER_TYPE_APPUSER.value()); try { userDao.save(user); User newUser = userDao.queryByUserName(user.getUserName()); externalApp.setUser(newUser); externalAppDao.save(externalApp); } catch (Exception e) { LogUtil.error(this, "ExternalAppServiceImpl.save error", e); throw new DaoException(e); } }
@Override public long login( HttpServletRequest request, HttpServletResponse response, String loginName, String pwd, boolean persistent) throws PassportAccountException { loginName = StringUtils.trim(loginName); pwd = StringUtils.trim(pwd); if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(pwd)) { throw new PassportAccountException(PassportAccountException.ACCOUNT_OR_PWD_ERROR); } Passport passport = passportService.getPassportByLoginName(loginName); if (null == passport || !StringUtils.equals(passport.getPassword(), DigestUtils.md5Hex(pwd))) { throw new PassportAccountException(PassportAccountException.ACCOUNT_OR_PWD_ERROR); } Thirdparty tp = null; TpUser tpUser = tpUserService.getTpUserByUid(passport.getId()); if (null != tpUser) { tp = InitData.getTpByTpNameAndJoinType(tpUser.getTpName(), JoinTypeEnum.CONNECT); } doLogin( request, response, passport.getId(), tp != null ? tp.getId() : 0L, RunType.WEB, persistent); nativeLoginCounter.incr(null, 1); return passport.getId(); }
/** 功能:修改图片 */ @ResponseBody @RequestMapping(value = "/upLoadImages", method = RequestMethod.POST) public ResultMsg upLoadImages(String id2, @RequestParam MultipartFile[] images2, String gid) throws Exception { ResultMsg result = new ResultMsg(); result.setResultMessage("errors"); MusicBg music = new MusicBg(); if (images2 != null && images2.length > 0) { for (MultipartFile $file : images2) { if (!$file.isEmpty()) { String name = $file.getOriginalFilename(); String ext = name.substring(name.lastIndexOf("."), name.length()); String sha1 = DigestUtils.shaHex($file.getInputStream()); String fileName = sha1 + ext; String path = Constants.DEFAULT_UPLOADIMAGEPATH + File.separator + Constants.sha1ToPath(sha1); Constants.mkdirs(path); FileUtils.copyInputStreamToFile($file.getInputStream(), new File(path, fileName)); music.setImageSha1(sha1); music.setImage(fileName); } } } music.setId(id2); if (this.musicBgService.addMusicBg(music, gid)) { result.setResultMessage("success"); } return result; }
public static String makeFinalParamStringWithSign( String apiId, String messageId, String timestamp, Map<String, Object> params, String secret, String contentKey) { String result = null; if (StringUtils.isNotBlank(apiId) && StringUtils.isNotBlank(messageId) && StringUtils.isNotBlank(timestamp) && StringUtils.isNotBlank(secret)) { Map<String, Object> finalMap = new HashMap<String, Object>(); finalMap.put("ApiId", apiId); finalMap.put("MessageID", messageId); finalMap.put("TimeStamp", timestamp); finalMap.put("Validate", DigestUtils.md5Hex(apiId + secret + timestamp).toUpperCase()); finalMap.putAll(params); ObjectMapper mapper = new ObjectMapper(); try { result = "_data=" + YjBase64Util.encode(mapper.writeValueAsString(finalMap), contentKey); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; }
private File getCachedImage(File file, int size) throws IOException { String md5 = DigestUtils.md5Hex(file.getPath()); File cachedImage = new File(getImageCacheDirectory(size), md5 + ".jpeg"); // Is cache missing or obsolete? if (!cachedImage.exists() || FileUtil.lastModified(file) > cachedImage.lastModified()) { InputStream in = null; OutputStream out = null; try { in = getImageInputStream(file); out = new FileOutputStream(cachedImage); BufferedImage image = ImageIO.read(in); if (image == null) { throw new Exception("Unable to decode image."); } image = scale(image, size, size); ImageIO.write(image, "jpeg", out); } catch (Throwable x) { // Delete corrupt (probably empty) thumbnail cache. LOG.warn("Failed to create thumbnail for " + file, x); IOUtils.closeQuietly(out); cachedImage.delete(); throw new IOException("Failed to create thumbnail for " + file + ". " + x.getMessage()); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } return cachedImage; }
public void save(Connection connection, String serviceKey, File file) { String sql = " insert into " + BlobItemDomainFactory.TABLENAME + " (ID_, BUSINESSKEY_, FILEID_, SERVICEKEY_, NAME_, TYPE_, FILENAME_, PATH_, LASTMODIFIED_, LOCKED_, STATUS_, DATA_, CREATEBY_, CREATEDATE_)" + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "; PreparedStatement psmt = null; try { psmt = connection.prepareStatement(sql); psmt.setString(1, UUID32.getUUID()); psmt.setString(2, serviceKey); psmt.setString(3, DigestUtils.md5Hex(file.getAbsolutePath())); psmt.setString(4, serviceKey); psmt.setString(5, file.getName()); psmt.setString(6, "Execution"); psmt.setString(7, file.getAbsolutePath()); psmt.setString(8, file.getAbsolutePath()); psmt.setLong(9, file.lastModified()); psmt.setInt(10, 0); psmt.setInt(11, 1); psmt.setBytes(12, FileUtils.getBytes(file)); psmt.setString(13, "system"); psmt.setTimestamp(14, DateUtils.toTimestamp(new java.util.Date())); psmt.executeUpdate(); } catch (Exception ex) { logger.error(ex); ex.printStackTrace(); throw new RuntimeException(ex); } finally { JdbcUtils.close(psmt); } }
/** * MD5加密 * * @param str * @return */ public static String MD5(String str) { if (str != null) { return DigestUtils.md5Hex(str); } else { return null; } }
protected String calculateUaAuthHeader(HttpRequestBase method, Map<String, String> cookies) { final String userAgent = this.getHeaderValue(method, USER_AGENT); final String requestId = this.getHeaderValue(method, RETS_REQUEST_ID); final String sessionId = cookies.get(RETS_SESSION_ID); final String retsVersion = this.getHeaderValue(method, RETS_VERSION); String secretHash = DigestUtils.md5Hex(String.format("%s:%s", userAgent, this.userAgentPassword)); String pieces = String.format( "%s:%s:%s:%s", secretHash, StringUtils.trimToEmpty(requestId), StringUtils.trimToEmpty(sessionId), retsVersion); return String.format("Digest %s", DigestUtils.md5Hex(pieces)); }
/** 功能:添加修改 */ @RequestMapping(value = "/save", method = RequestMethod.POST) public ModelAndView save(@RequestParam MultipartFile[] images, String gid) throws Exception { ModelAndView mav = new ModelAndView(com.baofeng.utils.Constants.COREWEB_BUILDITEMS + "/musicbg"); MusicBg music = new MusicBg(); if (images != null && images.length > 0) { for (MultipartFile $file : images) { if (!$file.isEmpty()) { String name = $file.getOriginalFilename(); String ext = name.substring(name.lastIndexOf("."), name.length()); String sha1 = DigestUtils.shaHex($file.getInputStream()); String fileName = sha1 + ext; String path = Constants.DEFAULT_UPLOADIMAGEPATH + File.separator + Constants.sha1ToPath(sha1); Constants.mkdirs(path); FileUtils.copyInputStreamToFile($file.getInputStream(), new File(path, fileName)); music.setImageSha1(sha1); music.setImage(fileName); } } } this.musicBgService.addMusicBg(music, gid); WeekService week = this.weekServiceService.readWeekService(gid); if (week != null) { mav.addObject("week", week); } return mav; }
/** * 随机初始化一部分数据分散到虚拟节点上 @Title: initRadomData2VisualNode * * @author: zzh * @date: 2016年12月1日 下午7:59:23 * @version: v1.0.0 */ private static void initRadomData2VisualNode() { for (int i = 0; i < 100; i++) { String dataKey = DigestUtils.md5Hex(new Random(System.nanoTime()).nextInt() + ""); VisualCacheNode nearestCacheNode = getVisualCacheNode(dataKey); // 将key值和真实缓存节点的关联关系存储起来 dataCache.put(dataKey, nearestCacheNode.getRealCacheNode()); // 补充当前节点上存储的key值信息 List<String> keyList = vNodeCacheDataMap.get(nearestCacheNode.getNodeName()); if (keyList == null) { keyList = new ArrayList<String>(); } keyList.add(dataKey); vNodeCacheDataMap.put(nearestCacheNode.getNodeName(), keyList); System.out.println( "当前测试数据key=" + dataKey + ",使用虚拟节点:" + nearestCacheNode.getNodeName() + ",真实Cache节点:" + nearestCacheNode.getRealCacheNode().getNodeName()); } }
public static String md5Checksum(File file) { try { return DigestUtils.md5Hex(new FileInputStream(file)); } catch (IOException ioe) { throw new CLIException(REASON_IO_ERROR, ioe); } }
public String shorten(String longUrl, int urlLength) { if (urlLength < 0 || urlLength > 6) { throw new IllegalArgumentException("the length of url must be between 0 and 6"); } String md5Hex = DigestUtils.md5Hex(longUrl); // 6 digit binary can indicate 62 letter & number from 0-9a-zA-Z int binaryLength = urlLength * 6; long binaryLengthFixer = Long.valueOf(StringUtils.repeat("1", binaryLength), BINARY); for (int i = 0; i < 4; i++) { String subString = StringUtils.substring(md5Hex, i * 8, (i + 1) * 8); subString = Long.toBinaryString(Long.valueOf(subString, 16) & binaryLengthFixer); subString = StringUtils.leftPad(subString, binaryLength, "0"); StringBuilder sbBuilder = new StringBuilder(); for (int j = 0; j < urlLength; j++) { String subString2 = StringUtils.substring(subString, j * 6, (j + 1) * 6); int charIndex = Integer.valueOf(subString2, BINARY) & NUMBER_61; sbBuilder.append(DIGITS[charIndex]); } String shortUrl = sbBuilder.toString(); if (lookupLong(shortUrl) != null) { continue; } else { return shortUrl; } } // if all 4 possibilities are already exists return null; }