cn.hutool.core.util.ArrayUtil Java Examples

The following examples show how to use cn.hutool.core.util.ArrayUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 7 votes vote down vote up
/**
 * 发送正文中有静态资源的邮件
 *
 * @param to      收件人地址
 * @param subject 邮件主题
 * @param content 邮件内容
 * @param rscPath 静态资源地址
 * @param rscId   静态资源id
 * @param cc      抄送地址
 * @throws MessagingException 邮件发送异常
 */
@Override
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    if (ArrayUtil.isNotEmpty(cc)) {
        helper.setCc(cc);
    }
    FileSystemResource res = new FileSystemResource(new File(rscPath));
    helper.addInline(rscId, res);

    mailSender.send(message);
}
 
Example #2
Source File: MaxSubArray.java    From algorithm-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public static int maxSubArray(int[] nums) {
    int[] result = new int[nums.length];
    result[0] = nums[0];
    int max = nums[0];
    for (int i = 1; i < nums.length; i++) {
        result[i] = Math.max(result[i - 1] + nums[i], nums[i]);
        if (max < result[i]) {
            max = result[i];
        }

        if (log.isDebugEnabled()) {
            log.debug(ArrayUtil.toString(result));
        }
    }
    return max;
}
 
Example #3
Source File: EmailMessageSender.java    From magic-starter with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 处理简单邮件类型
 *
 * @param message 邮件内容
 * @return boolean
 */
private boolean processSimpleEmail(EmailMessage message) {
	// 注意邮件发送可能出现异常,注意catch
	try {
		SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
		simpleMailMessage.setFrom("\"" + message.getFrom() + "\" <" + username + ">");
		simpleMailMessage.setTo(ArrayUtil.toArray(message.getTos(), String.class));
		simpleMailMessage.setSubject(message.getSubject());
		simpleMailMessage.setText(message.getContent());

		// 设置抄送人列表
		if (CollUtil.isEmpty(message.getCcs())) {
			simpleMailMessage.setCc(ArrayUtil.toArray(message.getCcs(), String.class));
		}
		mailSender.send(simpleMailMessage);
		return true;
	} catch (Exception e) {
		log.error("简单邮件发送异常!", e);
		return false;
	}
}
 
Example #4
Source File: LoginProcessSetTenantFilter.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    try {
        DefaultSavedRequest savedRequest = (DefaultSavedRequest)request.getSession().getAttribute(SAVED_REQUEST);
        if (savedRequest != null) {
            String[] clientIds = savedRequest.getParameterValues("client_id");
            if (ArrayUtil.isNotEmpty(clientIds)) {
                //保存租户id
                TenantContextHolder.setTenant(clientIds[0]);
            }
        }
        chain.doFilter(request, response);
    } finally {
        TenantContextHolder.clear();
    }
}
 
Example #5
Source File: CloudUserDetailsServiceImpl.java    From smaker with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 构建userdetails
 *
 * @param result 用户信息
 * @return
 */
private UserDetails getUserDetails(SmakerResult<UserInfo> result) {
	if (result == null || result.getData() == null) {
		throw new UsernameNotFoundException("用户不存在");
	}

	UserInfo info = result.getData();
	Set<String> dbAuthsSet = new HashSet<>();
	if (ArrayUtil.isNotEmpty(info.getRoles())) {
		// 获取角色
		Arrays.stream(info.getRoles()).forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE + role));
		// 获取资源
		dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));

	}
	Collection<? extends GrantedAuthority> authorities
		= AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
	SysUser user = info.getSysUser();

	// 构造security用户
	return new CloudUser(user.getUserId(), user.getDeptId(), user.getUsername(), SecurityConstants.BCRYPT + user.getPassword(),
		StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL), true, true, true, authorities);
}
 
Example #6
Source File: SysUserController.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 删除用户
 */
@SysLog("删除用户")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('sys:user:delete')")
public ResponseEntity<String> delete(@RequestBody Long[] userIds){
	if (userIds.length == 0) {
		return ResponseEntity.badRequest().body("请选择需要删除的用户");
	}
	if(ArrayUtil.contains(userIds, Constant.SUPER_ADMIN_ID)){
		return ResponseEntity.badRequest().body("系统管理员不能删除");
	}
	if(ArrayUtil.contains(userIds, SecurityUtils.getSysUser().getUserId())){
		return ResponseEntity.badRequest().body("当前用户不能删除");
	}
	sysUserService.deleteBatch(userIds,SecurityUtils.getSysUser().getShopId());
	return ResponseEntity.ok().build();
}
 
Example #7
Source File: SpelUtil.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 支持 #p0 参数索引的表达式解析
 * @param rootObject 根对象,method 所在的对象
 * @param spel 表达式
 * @param method ,目标方法
 * @param args 方法入参
 * @return 解析后的字符串
 */
public static String parse(Object rootObject,String spel, Method method, Object[] args) {
    if (StrUtil.isBlank(spel)) {
        return StrUtil.EMPTY;
    }
    //获取被拦截方法参数名列表(使用Spring支持类库)
    LocalVariableTableParameterNameDiscoverer u =
            new LocalVariableTableParameterNameDiscoverer();
    String[] paraNameArr = u.getParameterNames(method);
    if (ArrayUtil.isEmpty(paraNameArr)) {
        return spel;
    }
    //使用SPEL进行key的解析
    ExpressionParser parser = new SpelExpressionParser();
    //SPEL上下文
    StandardEvaluationContext context = new MethodBasedEvaluationContext(rootObject,method,args,u);
    //把方法参数放入SPEL上下文中
    for (int i = 0; i < paraNameArr.length; i++) {
        context.setVariable(paraNameArr[i], args[i]);
    }
    return parser.parseExpression(spel).getValue(context, String.class);
}
 
Example #8
Source File: DataMigrationUtils.java    From v-mock with MIT License 6 votes vote down vote up
/**
 * 获取所有历史DB文件集合
 *
 * @return List<File>集合
 */
private static List<File> getHistoryDataFileList() {
    // 历史数据库文件都是存在临时目录下
    String tempFilePath = System.getProperty("java.io.tmpdir");
    File[] tempFileArr = FileUtil.ls(tempFilePath);
    // 临时目录没文件,返回 null
    if (ArrayUtil.isEmpty(tempFileArr)) {
        return null;
    }
    // 过滤掉非db文件
    Stream<File> filesStream = Arrays.stream(tempFileArr)
            .filter(file -> file.isFile() && file.getName().matches("sqlite-jdbc-tmp-.*\\.db"));
    // 转为List返回
    List<File> fileList = filesStream.collect(Collectors.toList());
    return fileList;
}
 
Example #9
Source File: AuthorizationServerConfiguration.java    From fw-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 配置客户端一些信息
 *
 * @param clients
 * @throws Exception
 */
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    InMemoryClientDetailsServiceBuilder build = clients.inMemory();
    if (ArrayUtil.isNotEmpty(securityProperties.getOauth().getClients())) {
        for (OAuth2ClientProperties config : securityProperties.getOauth().getClients()) {
            build.withClient(config.getClientId())
                    .secret(passwordEncoder.encode(config.getClientSecret()))
                    .accessTokenValiditySeconds(config.getAccessTokenValiditySeconds())
                    .refreshTokenValiditySeconds(60 * 60 * 24 * 15)
                    .authorizedGrantTypes("refresh_token", "password", "authorization_code")//OAuth2支持的验证模式
                    .redirectUris("http://www.baidu.com")
                    .scopes("all");
        }
    }
}
 
Example #10
Source File: AuthorizationServerConfiguration.java    From fw-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 配置客户端一些信息
 *
 * @param clients
 * @throws Exception
 */
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    InMemoryClientDetailsServiceBuilder build = clients.inMemory();
    if (ArrayUtil.isNotEmpty(securityProperties.getOauth().getClients())) {
        for (OAuth2ClientProperties config : securityProperties.getOauth().getClients()) {
            build.withClient(config.getClientId())
                    .secret(passwordEncoder.encode(config.getClientSecret()))
                    .accessTokenValiditySeconds(config.getAccessTokenValiditySeconds())
                    .refreshTokenValiditySeconds(config.getRefreshTokenValiditySecond())
                    .authorizedGrantTypes("refresh_token", "password", "authorization_code")//OAuth2支持的验证模式
                    .redirectUris(config.getRedirectUri())
                    .autoApprove(config.getAutoApprove())//设置自动认证
                    .scopes(config.getScope());
        }
    }
}
 
Example #11
Source File: DictionaryItemServiceImpl.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Map<String, String>> map(String[] types) {
    if (ArrayUtil.isEmpty(types)) {
        return Collections.emptyMap();
    }
    LbqWrapper<DictionaryItem> query = Wraps.<DictionaryItem>lbQ()
            .in(DictionaryItem::getDictionaryType, types)
            .eq(DictionaryItem::getStatus, true)
            .orderByAsc(DictionaryItem::getSortValue);
    List<DictionaryItem> list = super.list(query);

    //key 是类型
    Map<String, List<DictionaryItem>> typeMap = list.stream().collect(groupingBy(DictionaryItem::getDictionaryType, LinkedHashMap::new, toList()));

    //需要返回的map
    Map<String, Map<String, String>> typeCodeNameMap = new LinkedHashMap<>(typeMap.size());

    typeMap.forEach((key, items) -> {
        ImmutableMap<String, String> itemCodeMap = MapHelper.uniqueIndex(items, DictionaryItem::getCode, DictionaryItem::getName);
        typeCodeNameMap.put(key, itemCodeMap);
    });
    return typeCodeNameMap;
}
 
Example #12
Source File: AuthorityGeneralController.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "获取当前系统指定枚举", notes = "获取当前系统指定枚举")
@GetMapping("/enums")
public R<Map<String, Map<String, String>>> enums(@RequestParam(value = "codes[]", required = false) String[] codes) {
    if (ArrayUtil.isEmpty(codes)) {
        return R.success(ENUM_MAP);
    }

    Map<String, Map<String, String>> map = new HashMap<>(codes.length);

    for (String code : codes) {
        if (ENUM_MAP.containsKey(code)) {
            map.put(code, ENUM_MAP.get(code));
        }
    }
    return R.success(map);
}
 
Example #13
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用根据主键更新,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param pk         主键
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer updateById(T t, P pk, Boolean ignoreNull) {
	String tableName = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> StrUtil.appendIfMissing(s, " = ?")).collect(Collectors.toList());
	String params = StrUtil.join(Const.SEPARATOR_COMMA, columns);

	// 构造值
	List<Object> valueList = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).collect(Collectors.toList());
	valueList.add(pk);

	Object[] values = ArrayUtil.toArray(valueList, Object.class);

	String sql = StrUtil.format("UPDATE {table} SET {params} where id = ?", Dict.create().set("table", tableName).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #14
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 发送带附件的邮件
 *
 * @param to       收件人地址
 * @param subject  邮件主题
 * @param content  邮件内容
 * @param filePath 附件地址
 * @param cc       抄送地址
 * @throws MessagingException 邮件发送异常
 */
@Override
public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    if (ArrayUtil.isNotEmpty(cc)) {
        helper.setCc(cc);
    }
    FileSystemResource file = new FileSystemResource(new File(filePath));
    String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
    helper.addAttachment(fileName, file);

    mailSender.send(message);
}
 
Example #15
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 发送正文中有静态资源的邮件
 *
 * @param to      收件人地址
 * @param subject 邮件主题
 * @param content 邮件内容
 * @param rscPath 静态资源地址
 * @param rscId   静态资源id
 * @param cc      抄送地址
 * @throws MessagingException 邮件发送异常
 */
@Override
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    if (ArrayUtil.isNotEmpty(cc)) {
        helper.setCc(cc);
    }
    FileSystemResource res = new FileSystemResource(new File(rscPath));
    helper.addInline(rscId, res);

    mailSender.send(message);
}
 
Example #16
Source File: BlackUserDetailsServiceImpl.java    From black-shop with Apache License 2.0 6 votes vote down vote up
/**
 * buildUserDails 构建用户详情
 * @param result
 * @return
 */
private UserDetails buildUserDails(ResponseResult<UserInfoDTO> result) {
	if (result == null || !result.hasBody()) {
		log.error("用户信息错误或不存在!!!");
		throw new UsernameNotFoundException("用户信息不存在");
	}
	UserInfoDTO userinfo = result.getResult();
	Set<String> dbAuthsSet = new HashSet<>();

	if(ArrayUtil.isNotEmpty(userinfo.getPermissions())){
		// 获取角色
		Arrays.stream(userinfo.getRoles()).forEach(roleId -> dbAuthsSet.add("ROLE_" + roleId));
		// 获取资源
		dbAuthsSet.addAll(Arrays.asList(userinfo.getPermissions()));
	}
	Collection<? extends GrantedAuthority> authorities
			= AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
	SysUserDTO sysUserDTO = userinfo.getSysUser();
	return new SecurityUserDetail(sysUserDTO.getUserId(), sysUserDTO.getUsername(), "{bcrypt}" + sysUserDTO.getPassword(),
			true, true, true, true, authorities);
}
 
Example #17
Source File: SysUserServiceImpl.java    From black-shop with Apache License 2.0 6 votes vote down vote up
@Override
public UserInfoDTO getUserInfo(SysUser sysUser) {
	UserInfoDTO userInfo = new UserInfoDTO();
	//设置用户对象实体
	userInfo.setSysUser(BeanUtils.transfrom(SysUserDTO.class,sysUser));
	//设置角色id列表
	List<Integer> roleIds = sysRoleService.findRolesByUserId(sysUser.getUserId())
			.stream()
			.map(SysRole::getRoleId)
			.collect(Collectors.toList());
	userInfo.setRoles(ArrayUtil.toArray(roleIds, Integer.class));
	//设置权限列表
	Set<String> permissions = new HashSet<>();

	roleIds.forEach(roleId->{
		List<String> permissionList = sysMenuService.findMenuByRoleId(roleId)
				.stream()
				.filter(menuDto -> StringUtils.isNotEmpty(menuDto.getPermission()))
				.map(MenuDTO::getPermission)
				.collect(Collectors.toList());
		permissions.addAll(permissionList);
	});
	userInfo.setPermissions(ArrayUtil.toArray(permissions, String.class));
	return userInfo;
}
 
Example #18
Source File: OauthGeneralController.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "获取当前系统指定枚举", notes = "获取当前系统指定枚举")
@GetMapping("/enums")
public R<Map<String, Map<String, String>>> enums(@RequestParam(value = "codes[]", required = false) String[] codes) {
    if (ArrayUtil.isEmpty(codes)) {
        return R.success(ENUM_MAP);
    }

    Map<String, Map<String, String>> map = new HashMap<>(codes.length);

    for (String code : codes) {
        if (ENUM_MAP.containsKey(code)) {
            map.put(code, ENUM_MAP.get(code));
        }
    }
    return R.success(map);
}
 
Example #19
Source File: DictionaryItemServiceImpl.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Map<String, String>> map(String[] types) {
    if (ArrayUtil.isEmpty(types)) {
        return Collections.emptyMap();
    }
    LbqWrapper<DictionaryItem> query = Wraps.<DictionaryItem>lbQ()
            .in(DictionaryItem::getDictionaryType, types)
            .eq(DictionaryItem::getStatus, true)
            .orderByAsc(DictionaryItem::getSortValue);
    List<DictionaryItem> list = super.list(query);

    //key 是类型
    Map<String, List<DictionaryItem>> typeMap = list.stream().collect(groupingBy(DictionaryItem::getDictionaryType, LinkedHashMap::new, toList()));

    //需要返回的map
    Map<String, Map<String, String>> typeCodeNameMap = new LinkedHashMap<>(typeMap.size());

    typeMap.forEach((key, items) -> {
        ImmutableMap<String, String> itemCodeMap = MapHelper.uniqueIndex(items, DictionaryItem::getCode, DictionaryItem::getName);
        typeCodeNameMap.put(key, itemCodeMap);
    });
    return typeCodeNameMap;
}
 
Example #20
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用根据主键更新,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param pk         主键
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer updateById(T t, P pk, Boolean ignoreNull) {
	String tableName = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> StrUtil.appendIfMissing(s, " = ?")).collect(Collectors.toList());
	String params = StrUtil.join(Const.SEPARATOR_COMMA, columns);

	// 构造值
	List<Object> valueList = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).collect(Collectors.toList());
	valueList.add(pk);

	Object[] values = ArrayUtil.toArray(valueList, Object.class);

	String sql = StrUtil.format("UPDATE {table} SET {params} where id = ?", Dict.create().set("table", tableName).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #21
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 发送带附件的邮件
 *
 * @param to       收件人地址
 * @param subject  邮件主题
 * @param content  邮件内容
 * @param filePath 附件地址
 * @param cc       抄送地址
 * @throws MessagingException 邮件发送异常
 */
@Override
public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    if (ArrayUtil.isNotEmpty(cc)) {
        helper.setCc(cc);
    }
    FileSystemResource file = new FileSystemResource(new File(filePath));
    String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
    helper.addAttachment(fileName, file);

    mailSender.send(message);
}
 
Example #22
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 发送正文中有静态资源的邮件
 *
 * @param to      收件人地址
 * @param subject 邮件主题
 * @param content 邮件内容
 * @param rscPath 静态资源地址
 * @param rscId   静态资源id
 * @param cc      抄送地址
 * @throws MessagingException 邮件发送异常
 */
@Override
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    if (ArrayUtil.isNotEmpty(cc)) {
        helper.setCc(cc);
    }
    FileSystemResource res = new FileSystemResource(new File(rscPath));
    helper.addInline(rscId, res);

    mailSender.send(message);
}
 
Example #23
Source File: UserServiceImpl.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 通过查用户的全部信息
 *
 * @param userVo 用户
 * @return
 */
@Override
@Transactional(readOnly = true, rollbackFor = Exception.class)
public UserInfo getInfo(UserVo userVo) {
	UserInfo userInfo = new UserInfo();
	userInfo.setUser(userVo);
	List<Role> roles = roleService.findListByUserId(userVo.getId());
	//设置角色列表  (ID)
	List<String> roleIds = roles.stream()
		.map(Role::getId)
		.collect(Collectors.toList());
	userInfo.setRoles(ArrayUtil.toArray(roleIds, String.class));
	//设置权限列表(menu.permission)
	Set<String> permissions = new HashSet<>();
	roleIds.forEach(roleId -> {
		List<String> permissionList = menuService.findListByRoleId(roleId)
			.stream()
			.filter(menuVo -> StringUtil.isNotEmpty(menuVo.getPermission()))
			.map(MenuVo::getPermission)
			.collect(Collectors.toList());
		permissions.addAll(permissionList);
	});
	userInfo.setPermissions(ArrayUtil.toArray(permissions, String.class));
	return userInfo;
}
 
Example #24
Source File: WebConfigurer.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
	public void onStartup(ServletContext servletContext) {
		if (env.getActiveProfiles().length != 0) {
			log.info("Web application configuration, using profiles: {}", Arrays.toString(env.getActiveProfiles()));
		}
		EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
			DispatcherType.ASYNC);
//        initPageInitParamFilter(servletContext, disps);
//        initMetrics(servletContext, disps);
		if (ArrayUtil.contains(env.getActiveProfiles(), CommonConstants.SPRING_PROFILE_PRODUCTION)) {
			initCachingHttpHeadersFilter(servletContext, disps);
		}
//		log.debug("Registering bodyFilter");
//		FilterRegistration.Dynamic bodyFilter = servletContext.addFilter(
//			"bodyFilter",
//			new BodyFilter(applicationProperties));
//		bodyFilter.addMappingForUrlPatterns(disps, true,
//			applicationProperties.getAdminPath("/*"));
//		bodyFilter.setAsyncSupported(true);

		log.info("Web application fully configured");
	}
 
Example #25
Source File: BaseDao.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 通用根据主键更新,自增列需要添加 {@link Pk} 注解
 *
 * @param t          对象
 * @param pk         主键
 * @param ignoreNull 是否忽略 null 值
 * @return 操作的行数
 */
protected Integer updateById(T t, P pk, Boolean ignoreNull) {
	String tableName = getTableName(t);

	List<Field> filterField = getField(t, ignoreNull);

	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> StrUtil.appendIfMissing(s, " = ?")).collect(Collectors.toList());
	String params = StrUtil.join(Const.SEPARATOR_COMMA, columns);

	// 构造值
	List<Object> valueList = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).collect(Collectors.toList());
	valueList.add(pk);

	Object[] values = ArrayUtil.toArray(valueList, Object.class);

	String sql = StrUtil.format("UPDATE {table} SET {params} where id = ?", Dict.create().set("table", tableName).set("params", params));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	return jdbcTemplate.update(sql, values);
}
 
Example #26
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 发送带附件的邮件
 *
 * @param to       收件人地址
 * @param subject  邮件主题
 * @param content  邮件内容
 * @param filePath 附件地址
 * @param cc       抄送地址
 * @throws MessagingException 邮件发送异常
 */
@Override
public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    if (ArrayUtil.isNotEmpty(cc)) {
        helper.setCc(cc);
    }
    FileSystemResource file = new FileSystemResource(new File(filePath));
    String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
    helper.addAttachment(fileName, file);

    mailSender.send(message);
}
 
Example #27
Source File: SysUserServiceImpl.java    From smaker with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 通过查用户的全部信息
 *
 * @param sysUser 用户
 * @return
 */
@Override
public UserInfo findUserInfo(SysUser sysUser) {
	UserInfo userInfo = new UserInfo();
	userInfo.setSysUser(sysUser);
	//设置角色列表  (ID)
	List<Integer> roleIds = sysRoleService.findRolesByUserId(sysUser.getUserId())
		.stream()
		.map(SysRole::getRoleId)
		.collect(Collectors.toList());
	userInfo.setRoles(ArrayUtil.toArray(roleIds, Integer.class));

	//设置权限列表(menu.permission)
	Set<String> permissions = new HashSet<>();
	roleIds.forEach(roleId -> {
		List<String> permissionList = sysMenuService.findMenuByRoleId(roleId)
			.stream()
			.filter(menuVo -> StringUtils.isNotEmpty(menuVo.getPermission()))
			.map(MenuVO::getPermission)
			.collect(Collectors.toList());
		permissions.addAll(permissionList);
	});
	userInfo.setPermissions(ArrayUtil.toArray(permissions, String.class));
	return userInfo;
}
 
Example #28
Source File: SearchBuilder.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
/**
 * 设置索引名
 * @param indices 索引名数组
 */
public SearchBuilder setIndices(String... indices) {
    if (ArrayUtil.isNotEmpty(indices)) {
        searchRequest.indices(indices);
    }
    return this;
}
 
Example #29
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 发送HTML邮件
 *
 * @param to      收件人地址
 * @param subject 邮件主题
 * @param content 邮件内容
 * @param cc      抄送地址
 * @throws MessagingException 邮件发送异常
 */
@Override
public void sendHtmlMail(String to, String subject, String content, String... cc) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    if (ArrayUtil.isNotEmpty(cc)) {
        helper.setCc(cc);
    }
    mailSender.send(message);
}
 
Example #30
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 发送文本邮件
 *
 * @param to      收件人地址
 * @param subject 邮件主题
 * @param content 邮件内容
 * @param cc      抄送地址
 */
@Override
public void sendSimpleMail(String to, String subject, String content, String... cc) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    if (ArrayUtil.isNotEmpty(cc)) {
        message.setCc(cc);
    }
    mailSender.send(message);
}