Java 类org.springframework.util.DigestUtils 实例源码

项目:JavaQuarkBBS    文件:UserController.java   
@ApiOperation("登录接口")
@ApiImplicitParams({
        @ApiImplicitParam(name = "email", value = "用户邮箱",dataType = "String"),
        @ApiImplicitParam(name = "password", value = "用户密码",dataType = "String")
})
@PostMapping("/login")
public QuarkResult Login(String email,String password) {

    QuarkResult result = restProcessor(() -> {
        User loginUser = userService.findByEmail(email);
        if (loginUser == null)
            return QuarkResult.warn("用户邮箱不存在,请重新输入");
        if (!loginUser.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes())))
            return QuarkResult.warn("用户密码错误,请重新输入");
        String token = userService.LoginUser(loginUser);
        return QuarkResult.ok(token);
    });
    return result;
}
项目:camunda-migrator    文件:ZipResourceServiceHashTest.java   
@Test
public void shouldCreateHashForFile() {
  //given
  PowerMockito.mockStatic(IoUtil.class);
  PowerMockito.mockStatic(DigestUtils.class);
  byte[] bytes = new byte[]{1,2,3};
  final String fileEntry = "fileEntry";
  final ZipInputStream zipInputStream = mock(ZipInputStream.class);
  when(IoUtil.readInputStream(zipInputStream, fileEntry)).thenReturn(bytes);
  final String hash = "hash";
  when(DigestUtils.md5DigestAsHex(bytes)).thenReturn(hash);

  //when
  final String result = zipResourceService.createHashForFile(zipInputStream, fileEntry);

  //then
  assertThat(result, equalTo(hash));
}
项目:xmall    文件:RegisterServiceImpl.java   
@Override
public int register(String userName,String userPwd) {

    TbMember tbMember=new TbMember();
    tbMember.setUsername(userName);

    if(userName.isEmpty()||userPwd.isEmpty()){
        return -1; //用户名密码不能为空
    }
    boolean result = checkData(userName, 1);
    if (!result) {
        return 0; //该用户名已被注册
    }

    //MD5加密
    String md5Pass = DigestUtils.md5DigestAsHex(userPwd.getBytes());
    tbMember.setPassword(md5Pass);
    tbMember.setState(1);
    tbMember.setCreated(new Date());
    tbMember.setUpdated(new Date());

    if(tbMemberMapper.insert(tbMember)!=1){
        throw new XmallException("注册用户失败");
    }
    return 1;
}
项目:xmall    文件:MemberServiceImpl.java   
@Override
public TbMember addMember(MemberDto memberDto) {

    TbMember tbMember= DtoUtil.MemberDto2Member(memberDto);

    if(getMemberByUsername(tbMember.getUsername())!=null){
        throw new XmallException("用户名已被注册");
    }
    if(getMemberByPhone(tbMember.getPhone())!=null){
        throw new XmallException("手机号已被注册");
    }
    if(getMemberByEmail(tbMember.getEmail())!=null){
        throw new XmallException("邮箱已被注册");
    }

    tbMember.setState(1);
    tbMember.setCreated(new Date());
    tbMember.setUpdated(new Date());
    String md5Pass = DigestUtils.md5DigestAsHex(tbMember.getPassword().getBytes());
    tbMember.setPassword(md5Pass);

    if(tbMemberMapper.insert(tbMember)!=1){
        throw new XmallException("添加用户失败");
    }
    return getMemberByPhone(tbMember.getPhone());
}
项目:xmall    文件:MemberServiceImpl.java   
@Override
public TbMember updateMember(Long id,MemberDto memberDto) {

    TbMember tbMember = DtoUtil.MemberDto2Member(memberDto);
    tbMember.setId(id);
    tbMember.setUpdated(new Date());
    TbMember oldMember=getMemberById(id);
    tbMember.setState(oldMember.getState());
    tbMember.setCreated(oldMember.getCreated());
    if(tbMember.getPassword()==null||tbMember.getPassword()==""){
        tbMember.setPassword(oldMember.getPassword());
    }else{
        String md5Pass = DigestUtils.md5DigestAsHex(tbMember.getPassword().getBytes());
        tbMember.setPassword(md5Pass);
    }

    if (tbMemberMapper.updateByPrimaryKey(tbMember) != 1){
        throw new XmallException("更新会员信息失败");
    }
    return getMemberById(id);
}
项目:xmall    文件:MemberServiceImpl.java   
@Override
public TbMember changePassMember(Long id, MemberDto memberDto) {

    TbMember tbMember=getMemberById(id);
    if(tbMember.getPassword()==null||tbMember.getPassword()==""){
        tbMember.setPassword(tbMember.getPassword());
    }else{
        String md5Pass = DigestUtils.md5DigestAsHex(tbMember.getPassword().getBytes());
        tbMember.setPassword(md5Pass);
    }

    if (tbMemberMapper.updateByPrimaryKey(tbMember) != 1){
        throw new XmallException("修改会员密码失败");
    }
    return getMemberById(id);
}
项目:xmall    文件:UserServiceImpl.java   
@Override
public int addUser(TbUser user) {

    if(!getUserByName(user.getUsername())){
        throw new XmallException("用户名已存在");
    }
    if(!getUserByPhone(user.getPhone())){
        throw new XmallException("手机号已存在");
    }
    if(!getUserByEmail(user.getEmail())){
        throw new XmallException("邮箱已存在");
    }
    String md5Pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
    user.setPassword(md5Pass);
    user.setState(1);
    user.setCreated(new Date());
    user.setUpdated(new Date());
    if(tbUserMapper.insert(user)!=1){
        throw new XmallException("添加用户失败");
    }
    return 1;
}
项目:summer    文件:CacheAdvice.java   
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
    String etag = serverHttpRequest.getHeaders().getFirst(HttpHeaders.IF_NONE_MATCH);
    if (!((GET.equals(serverHttpRequest.getMethod().name())) || (HEAD.equals(serverHttpRequest.getMethod().name())))) {
        return o;
    }
    String md5;
    if (o instanceof ResponseEntity) {
        ResponseEntity response = (ResponseEntity) o;
        md5 = DigestUtils.md5DigestAsHex(JsonUtils.toJsonString(response.getBody()).getBytes());
    } else {
        md5 = DigestUtils.md5DigestAsHex(JsonUtils.toJsonString(o).getBytes());
    }
    serverHttpResponse.getHeaders().add("Etag", md5);
    if (md5.equalsIgnoreCase(etag)) {
        serverHttpResponse.setStatusCode(HttpStatus.NOT_MODIFIED);
        return null;
    } else {
        return o;
    }
}
项目:eHMP    文件:RpcUriUtils.java   
public static String sanitize(String uri, ConnectionSpec auth) {
    try {
        String sanitizedUserInfo = "";
        if ((auth != null) && (StringUtils.hasText(auth.toString()))) {
            if (auth instanceof AccessVerifyConnectionSpec) {
                String password = ((AccessVerifyConnectionSpec) auth).getCredentials();
                password = DigestUtils.md5DigestAsHex(password.getBytes("UTF-8"));
                String division = ((AccessVerifyConnectionSpec) auth).getDivision();
                if (StringUtils.hasText(division)) {
                    sanitizedUserInfo = division + DIVISION_CREDENTIALS_DELIMITER + password;
                } else {
                    sanitizedUserInfo = password;
                }
            }
        }
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(uri).userInfo(sanitizedUserInfo);
        return builder.build().toString();
    } catch (UnsupportedEncodingException e) {
        // NOOP: should never happen (UTF-8 built into JVM)
        return null;
    }
}
项目:extclassgenerator    文件:ModelGenerator.java   
public static void writeModel(HttpServletRequest request,
        HttpServletResponse response, ModelBean model, OutputConfig outputConfig)
        throws IOException {

    byte[] data = generateJavascript(model, outputConfig).getBytes(UTF8_CHARSET);
    String ifNoneMatch = request.getHeader("If-None-Match");
    String etag = "\"0" + DigestUtils.md5DigestAsHex(data) + "\"";

    response.setHeader("ETag", etag);

    if (etag.equals(ifNoneMatch)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    response.setContentType("application/javascript");
    response.setCharacterEncoding(UTF8_CHARSET.name());
    response.setContentLength(data.length);

    @SuppressWarnings("resource")
    ServletOutputStream out = response.getOutputStream();
    out.write(data);
    out.flush();
}
项目:xbin-store    文件:UserServiceImpl.java   
/**
 * 请求格式 POST
 * 用户注册
 *
 * @param user Tbuser POJO Json
 * @return {
 *          status: 200 //200 成功 400 数据错误 500 系统异常
 *          msg: "OK" //错误 注册失败. 请校验数据后请再提交数据.
 *          data: null
 *         }
 */
@Override
public XbinResult register(TbUser user) {

    if (user == null) {
        return XbinResult.build(400, "error", "数据为空");
    }

    boolean usernameb = (boolean) checkUserDate(user.getUsername(), ERROR, null).getData();
    boolean phoneb = (boolean) checkUserDate(user.getPhone(), 2, null).getData();
    boolean emailb = (boolean) checkUserDate(user.getEmail(), 3, null).getData();

    if (usernameb & phoneb & emailb) {
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));

        user.setCreated(new Date());
        user.setUpdated(new Date());

        try {
            userMapper.insert(user);
        } catch (Exception e) {

            logger.error("保存数据库失败!注册失败", e);
            return XbinResult.build(500, "error", "系统异常. 请稍后重试");
        }
        return XbinResult.ok();
    }

    return XbinResult.build(400, "error", "注册失败. 请校验数据后请再提交数据");


}
项目:JavaQuarkBBS    文件:UserServiceImpl.java   
@Override
public void createUser(String email, String username, String password) {
    User user = new User();
    user.setEmail(email);
    user.setUsername(username);
    user.setInitTime(new Date());
    user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
    repository.save(user);
}
项目:JavaQuarkBBS    文件:UserServiceImpl.java   
@Override
public void updateUserPassword(String token, String oldpsd, String newpsd) {
    User cacheuser = redisService.getString(REDIS_USER_KEY + token);
    if (cacheuser == null)
        throw new ServiceProcessException("用户Session过期,请重新登录");
    User user = repository.findOne(cacheuser.getId());
    if(!user.getPassword().equals(DigestUtils.md5DigestAsHex(oldpsd.getBytes())))
        throw new ServiceProcessException("原始密码错误,请重新输入");
    user.setPassword(DigestUtils.md5DigestAsHex(newpsd.getBytes()));
    repository.save(user);
    redisService.deleteString(REDIS_USER_KEY+token);
}
项目:fish-admin    文件:StorageService.java   
/**
 * 如果图片的大小大于1M,那么进行等比压缩为1280x1280图片
 * @param file
 * @return
 * @throws Exception
 */
public Storage store(MultipartFile file) throws Exception {

    if (file.isEmpty()) {
        throw new Exception("Failed to store empty file " + file.getOriginalFilename());
    }

    String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
    byte[] bytes;
    // 如果原图片大于1M, 那么压缩图片
    if (file.getSize() > M) {
        bytes = ImageUtil.compress(file.getInputStream(), fileType, 1920, 1920);
    } else {
        bytes = file.getBytes();
    }

    String contentHash = DigestUtils.md5DigestAsHex(bytes);
    Storage oldStorage = storageRepository.findByFileHash(contentHash);
    if (oldStorage != null) return oldStorage;

    try {
        Path destDir = Paths.get(storageDirectory, contentHash.substring(0, 2));
        if (!Files.exists(destDir)) Files.createDirectory(destDir);

        // String filePath = contentHash.substring(0, 2) + "/" + contentHash.substring(2) + "." + fileType;
        Storage storage = new Storage();
        storage.setFileHash(contentHash);
        storage.setFileName(file.getName());
        storage.setFileType(file.getContentType());
        storage.setFileSize(file.getSize());
        storage.setOriginalFileName(file.getOriginalFilename());

        return storageRepository.save(storage);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

}
项目:xmall    文件:UserServiceImpl.java   
@Override
public int changePassword(TbUser tbUser) {

    TbUser old=tbUserMapper.selectByPrimaryKey(tbUser.getId());
    old.setUpdated(new Date());
    String md5Pass = DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes());
    old.setPassword(md5Pass);
    if(tbUserMapper.updateByPrimaryKey(old)!=1){
        throw new XmallException("修改用户密码失败");
    }
    return 1;
}
项目:xq_seckill_microservice    文件:SpecialServiceImpl.java   
private String getMd5Url(Long id) throws UnsupportedEncodingException {
    String cacheKey = CacheKeyGenerator.generate(String.class, "getMd5Url", id);
    // 先从缓存中取
    String md5Url = byteRedisClient.getByteObj(cacheKey, String.class);
    if (StringUtils.isBlank(md5Url)) {
        String saltUrl = id + "/" + Instant.now().toEpochMilli() + "/" + appProperties.getPrivateSalt();
        md5Url = DigestUtils.md5DigestAsHex(saltUrl.getBytes(AppConstants.CHARSET_UTF8));
        byteRedisClient.setByteObj(cacheKey, md5Url, 3600);
    }
    return md5Url;
}
项目:tinker-manager    文件:PatchService.java   
public PatchInfo savePatch(AppInfo appInfo, VersionInfo versionInfo, String description, MultipartFile multipartFile) {
    List<PatchInfo> patchInfoList = patchInfoMapper.findByUidAndVersionName(appInfo.getUid(),versionInfo.getVersionName());
    int maxPatchVersion = getMaxPatchVersion(patchInfoList) + 1;
    String childPath = appInfo.getUid() + "/" + versionInfo.getVersionName() + "/" + maxPatchVersion + "/";
    PatchInfo patchInfo = new PatchInfo();
    try {
        String fileHash = DigestUtils.md5DigestAsHex(multipartFile.getBytes());
        File path = new File(new File(fileStoragePath), childPath);
        File patchFile = new File(path,fileHash + "_patch.zip");

        if (!path.exists() && !path.mkdirs()) {
            throw new BizException("文件目录创建失败");
        }
        multipartFile.transferTo(patchFile);

        patchInfo.setUserId(appInfo.getUserId());
        patchInfo.setAppUid(appInfo.getUid());
        patchInfo.setUid(UUID.randomUUID().toString().replaceAll("-", ""));
        patchInfo.setVersionName(versionInfo.getVersionName());
        patchInfo.setPatchVersion(maxPatchVersion);
        patchInfo.setPatchSize(patchFile.length());
        patchInfo.setFileHash(fileHash);
        patchInfo.setDescription(description);
        patchInfo.setStoragePath(patchFile.getAbsolutePath());
        patchInfo.setDownloadUrl(getDownloadUrl(patchStaticUrl,childPath + patchFile.getName()));
        patchInfo.setCreatedAt(new Date());
        patchInfo.setUpdatedAt(new Date());

        Integer id = patchInfoMapper.insert(patchInfo);
        patchInfo.setId(id);
    } catch (IOException e) {
        e.printStackTrace();
        throw new BizException("文件保存失败");
    }

    facadeService.clearCache();
    return patchInfo;
}
项目:tinker-manager    文件:AccountService.java   
public boolean authenticate(String username,String password) {
    BasicUser basicUser = findByUsername(username);
    if (basicUser == null) {
        return false;
    }
    String correctPassword = DigestUtils.md5DigestAsHex((globalSecretKey + "_" + password).getBytes());
    return basicUser.getPassword().equals(correctPassword);
}
项目:tinker-manager    文件:AccountService.java   
public void save(BasicUser basicUser) {
    basicUser.setPassword(DigestUtils.md5DigestAsHex((globalSecretKey + "_" + basicUser.getPassword()).getBytes()));
    basicUser.setCreatedAt(new Date());
    basicUser.setUpdatedAt(new Date());
    Integer id = userMapper.insert(basicUser);
    basicUser.setId(id);
}
项目:message-gateway    文件:SecurityService.java   
public String generateApiKey(final SMSBridge smsBridge) {
    try {
        final String source = smsBridge.generateApiKey() ;
        return DigestUtils.md5DigestAsHex(source.getBytes("UTF-8"));
    } catch (Exception ex) {
        logger.error("Could not create API key, reason,", ex);
        throw new IllegalArgumentException(ex);
    }
}
项目:cutdb    文件:UserServiceImpl.java   
@Override
public User register(String name, String password, Boolean sex, Org org) {
    User user = new User();
    user.setName(name);
    user.setCreateDate(new Date());
    user.setSex(sex);
    user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
    user.setOrg(org);
    userDao.insert(user);
    return user;
}
项目:hsweb-framework    文件:MethodInterceptorHolder.java   
public static MethodInterceptorHolder create(MethodInvocation invocation) {
    String id = DigestUtils.md5DigestAsHex(String.valueOf(invocation.getMethod().hashCode()).getBytes());
    String[] argNames = nameDiscoverer.getParameterNames(invocation.getMethod());
    Object[] args = invocation.getArguments();
    Map<String, Object> argMap = new LinkedHashMap<>();
    for (int i = 0, len = args.length; i < len; i++) {
        argMap.put(argNames[i] == null ? "arg" + i : argNames[i], args[i]);
    }
    return new MethodInterceptorHolder(id,
            invocation.getMethod(),
            invocation.getThis(), argMap);
}
项目:oma-riista-web    文件:FrontendController.java   
@Override
public String load(final String path) throws Exception {
    final org.springframework.core.io.Resource resource = new ServletContextResource(servletContext, path);
    try {
        byte[] content = FileCopyUtils.copyToByteArray(resource.getInputStream());
        return DigestUtils.md5DigestAsHex(content);
    } catch (IOException ex) {
        LOG.error("Could not calculate MD5 for resource: {}", path);
        return runtimeEnvironmentUtil.getRevision();
    }
}
项目:spring4-understanding    文件:ContentVersionStrategy.java   
@Override
public String getResourceVersion(Resource resource) {
    try {
        byte[] content = FileCopyUtils.copyToByteArray(resource.getInputStream());
        return DigestUtils.md5DigestAsHex(content);
    }
    catch (IOException ex) {
        throw new IllegalStateException("Failed to calculate hash for " + resource, ex);
    }
}
项目:spring4-understanding    文件:AbstractSockJsService.java   
@Override
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
    if (!HttpMethod.GET.equals(request.getMethod())) {
        sendMethodNotAllowed(response, HttpMethod.GET);
        return;
    }

    String content = String.format(IFRAME_CONTENT, getSockJsClientLibraryUrl());
    byte[] contentBytes = content.getBytes(UTF8_CHARSET);
    StringBuilder builder = new StringBuilder("\"0");
    DigestUtils.appendMd5DigestAsHex(contentBytes, builder);
    builder.append('"');
    String etagValue = builder.toString();

    List<String> ifNoneMatch = request.getHeaders().getIfNoneMatch();
    if (!CollectionUtils.isEmpty(ifNoneMatch) && ifNoneMatch.get(0).equals(etagValue)) {
        response.setStatusCode(HttpStatus.NOT_MODIFIED);
        return;
    }

    response.getHeaders().setContentType(new MediaType("text", "html", UTF8_CHARSET));
    response.getHeaders().setContentLength(contentBytes.length);

    // No cache in order to check every time if IFrame are authorized
    addNoCacheHeaders(response);
    response.getHeaders().setETag(etagValue);
    response.getBody().write(contentBytes);
}
项目:mongodb-aggregate-query-support    文件:BinaryDataTest.java   
@Test
public void mustReturnBinaryBeanQueriedWithMd5Hash() {
  TestBinaryBean binaryBean = new TestBinaryBean();
  byte[] md5Hash = DigestUtils.md5Digest(String.valueOf(System.nanoTime()).getBytes());
  binaryBean.setMd5Hash(md5Hash);
  testBinaryRepository.save(binaryBean);
  TestBinaryBean actualBean = testBinaryRepository.getByMd5Hash(md5Hash);
  Assert.assertNotNull(actualBean);
  Assert.assertEquals(actualBean.getMd5Hash(), binaryBean.getMd5Hash());
}
项目:java-platform    文件:Cart.java   
/**
 * 获取令牌
 * 
 * @return 令牌
 */
@Transient
public String getToken() {
    HashCodeBuilder hashCodeBuilder = new HashCodeBuilder(17, 37).append(getKey());
    if (getCartItems() != null) {
        for (CartItem cartItem : getCartItems()) {
            hashCodeBuilder.append(cartItem.getProduct()).append(cartItem.getQuantity())
                    .append(cartItem.getPrice());
        }
    }
    return DigestUtils.md5DigestAsHex(hashCodeBuilder.toString().getBytes());
}
项目:powop    文件:CDNImageHelper.java   
public String getCDNUrl(Image img, int size) {
    int id = Integer.parseInt(img.getIdentifier().substring(
            img.getIdentifier().lastIndexOf(':') + 1,
            img.getIdentifier().length()));

    return String.format("%s/%s.jpg",
            CDNPrefix,
            DigestUtils.md5DigestAsHex((id + "-" + size + "-" + CDNKey).getBytes()));
}
项目:spring-security-digest    文件:RestDigestAuthenticationEntryPoint.java   
public void commence(HttpServletRequest request,
        HttpServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    // compute a nonce (do not use remote IP address due to proxy farms)
    // format of nonce is:
    // base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key))
    long expiryTime = System.currentTimeMillis()
            + (super.getNonceValiditySeconds() * 1000);
    String signatureValue = DigestUtils.md5DigestAsHex(new String(
            expiryTime + ":" + super.getKey()).getBytes());
    String nonceValue = expiryTime + ":" + signatureValue;
    String nonceValueBase64 = new String(Base64.encode(nonceValue
            .getBytes()));

    // qop is quality of protection, as defined by RFC 2617.
    // we do not use opaque due to IE violation of RFC 2617 in not
    // representing opaque on subsequent requests in same session.
    String authenticateHeader = "DigestCustom realm=\"" + super.getRealmName()
            + "\", " + "qop=\"auth\", nonce=\"" + nonceValueBase64 + "\"";

    if (authException instanceof NonceExpiredException) {
        authenticateHeader = authenticateHeader + ", stale=\"true\"";
    }

    if (logger.isDebugEnabled()) {
        logger.debug("WWW-Authenticate header sent to user agent: "
                + authenticateHeader);
    }

    httpResponse.addHeader("WWW-Authenticate", authenticateHeader);
    httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,
            authException.getMessage());
}
项目:AgileAlligators    文件:FacilityController.java   
private String generateETagHeaderValue( byte[] bytes )
{
    StringBuilder builder = new StringBuilder( "\"0" );
    DigestUtils.appendMd5DigestAsHex( bytes, builder );
    builder.append( '"' );
    return builder.toString();
}
项目:eHMP    文件:SanitizeCredentialsSerializer.java   
@Override
public void serialize(String value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {
    ConnectionSpec auth = ConnectionSpecFactory.create(value);
    if (auth instanceof AccessVerifyConnectionSpec) {
        jgen.writeString(DigestUtils.md5DigestAsHex(((AccessVerifyConnectionSpec) auth).getCredentials().getBytes("UTF-8")));
    } else {
        jgen.writeString(auth.toString());
    }
}
项目:ABRAID-MP    文件:GitSourceCodeManager.java   
/**
 * Creates a unique, valid, folder name from the repository url, which will be used to store the cloned repository.
 * @return The folder path.
 */
private Path getRepositoryDirectory() {
    String repositoryUrl = configurationService.getModelRepositoryUrl();

    String hash = DigestUtils.md5DigestAsHex(repositoryUrl.getBytes(Charsets.US_ASCII));

    if (repositoryUrl.length() > FILE_NAME_MAX_URL_LENGTH) {
        repositoryUrl = repositoryUrl.substring(0, FILE_NAME_MAX_URL_LENGTH);
    }

    String folderName = String.format("%s - %s", repositoryUrl, hash).replaceAll(FILE_NAME_INVALID_CHARS, "_");
    return Paths.get(baseRepositoryCachePath, folderName);
}
项目:adjule    文件:JooqUsersDao.java   
private void getUserInfo(final UserDetailView userDetailView, final String login) {
    final ProfileView profileView =
            jooq.select()
                .from(PROFILES)
                .join(USERS).using(USERS.USER_ID)
                .where(USERS.LOGIN.eq(login))
                .fetchOne(mapper -> {
                    final ProfileView view = new ProfileView();
                    view.setFirstname(mapper.getValue(PROFILES.FIRST_NAME));
                    view.setLastname(mapper.getValue(PROFILES.LAST_NAME));
                    view.setNickname(mapper.getValue(PROFILES.NICKNAME));
                    view.setLogin(mapper.getValue(USERS.LOGIN));
                    view.setEmail(mapper.getValue(USERS.EMAIL));
                    Optional.ofNullable(mapper.getValue(PROFILES.SEX))
                            .ifPresent(sex -> view.setSex(sex.getLiteral()));
                    view.setStudentNumber(mapper.getValue(
                            PROFILES.STUDENT_NUMBER));
                    if (view.getEmail() != null) {
                        view.setAvatarUrl(GRAVATAR_SERVICE_URL + DigestUtils
                                .md5DigestAsHex(
                                        view.getEmail()
                                                   .getBytes()));
                    }
                    view.setAbout(mapper.getValue(PROFILES.ABOUT));
                    return view;
                });
    userDetailView.setProfile(profileView);
}
项目:arcus-spring    文件:ArcusCache.java   
/**
 * serviceId, prefix, name 값을 사용하여 아커스 키를 생성합니다. serviceId는 필수값이며, prefix 또는
 * name 둘 중에 하나가 반드시 있어야 합니다. name과 prefix값이 모두 있다면 prefix 값을 사용합니다.
 * <p>
 * 키 생성 로직은 다음과 같습니다.
 * <p>
 * serviceId + (prefix | name) + ":" + key.toString();
 * <p>
 * 만약 전체 키의 길이가 250자를 넘을 경우에는 key.toString() 대신 그 값을 MD5로 압축한 값을 사용합니다.
 *
 * @param key
 * @return
 */
public String createArcusKey(final Object key) {
  Assert.notNull(key);
  String keyString, arcusKey;

  if (key instanceof ArcusStringKey) {
    keyString = ((ArcusStringKey) key).getStringKey().replace(' ', '_') +
            String.valueOf(((ArcusStringKey) key).getHash());
  } else if (key instanceof Integer) {
    keyString = key.toString();
  } else {
    keyString = key.toString();
    int hash = ArcusStringKey.light_hash(keyString);
    keyString = keyString.replace(' ', '_') + String.valueOf(hash);
  }

  arcusKey = serviceId + name + ":" + keyString;
  if (this.prefix != null) {
    arcusKey = serviceId + prefix + ":" + keyString;
  }
  if (arcusKey.length() > 250) {
    String digestedString = DigestUtils.md5DigestAsHex(keyString
            .getBytes());
    arcusKey = serviceId + name + ":" + digestedString;
    if (this.prefix != null) {
      arcusKey = serviceId + prefix + ":" + digestedString;
    }
  }
  return arcusKey;
}
项目:further-open-core    文件:BaseXServerBean.java   
/**
 * Set the default admin/admin password to a random 130 bit String
 * 
 * @return
 */
private String changeAdminPassword()
{
    final StringBuilder sb = new StringBuilder();
    // Set the admin password to a random 130 bit String
    sb.append("ALTER USER admin "
            + DigestUtils.md5DigestAsHex((new BigInteger(130, new SecureRandom())
                    .toString(32)).getBytes()));
    return sb.toString();
}
项目:further-open-core    文件:BaseXServerBean.java   
/**
 * Create a new user to login with based off of {@link #defaultUsername} and
 * {@link #defaultPassword}
 * 
 * @return
 */
private String createUser()
{
    final StringBuilder sb = new StringBuilder();
    sb.append("CREATE USER ");
    sb.append(defaultUsername);
    sb.append(" ");
    sb.append(DigestUtils.md5DigestAsHex(defaultPassword.getBytes()));
    sb.append(";");
    final String output = sb.toString();
    return output;
}
项目:whois    文件:DatabaseHelper.java   
public static synchronized void setupDatabase() {
    if (dbBaseName != null) {
        return;
    }

    final JdbcTemplate jdbcTemplate = createDefaultTemplate();
    ensureLocalhost(jdbcTemplate);
    cleanupOldTables(jdbcTemplate);

    final String uniqueForkId = DigestUtils.md5DigestAsHex(UUID.randomUUID().toString().getBytes());

    dbBaseName = "test_" + System.currentTimeMillis() + "_" + uniqueForkId;

    setupDatabase(jdbcTemplate, "acl.database", "ACL", "acl_schema.sql");
    setupDatabase(jdbcTemplate, "mailupdates.database", "MAILUPDATES", "mailupdates_schema.sql");
    setupDatabase(jdbcTemplate, "whois.db", "WHOIS", "whois_schema.sql", "whois_data.sql");
    setupDatabase(jdbcTemplate, "internals.database", "INTERNALS", "internals_schema.sql", "internals_data.sql");

    final String masterUrl = String.format("jdbc:log:mariadb://localhost/%s_WHOIS;driver=%s", dbBaseName, JDBC_DRIVER);
    System.setProperty("whois.db.master.url", masterUrl);
    System.setProperty("whois.db.master.driver", LoggingDriver.class.getName());

    final String slaveUrl = String.format("jdbc:mariadb://localhost/%s_WHOIS", dbBaseName);
    System.setProperty("whois.db.slave.url", slaveUrl);
    System.setProperty("whois.db.driver", JDBC_DRIVER);

    final String grsSlaveUrl = String.format("jdbc:mariadb://localhost/%s", dbBaseName);
    System.setProperty("whois.db.grs.slave.baseurl", grsSlaveUrl);
    System.setProperty("whois.db.grs.master.baseurl", grsSlaveUrl);
}
项目:edoras-one-initializr    文件:MainController.java   
private String createUniqueId(String content) {
    StringBuilder builder = new StringBuilder();
    DigestUtils.appendMd5DigestAsHex(content.getBytes(StandardCharsets.UTF_8),
            builder);
    return builder.toString();
}
项目:edoras-one-initializr    文件:UiController.java   
private String createUniqueId(String content) {
    StringBuilder builder = new StringBuilder();
    DigestUtils.appendMd5DigestAsHex(content.getBytes(StandardCharsets.UTF_8), builder);
    return builder.toString();
}
项目:sucok-framework    文件:Utils.java   
public static String shortUUID() {
    return DigestUtils.md5DigestAsHex(UUID.randomUUID().toString().getBytes()).substring(8, 23);
}