常用Util

常用Util

压缩zip

public class ZipUtil{
    public static void zip(String target,String source) throws Exception{
        try(ZipOutputStream out=new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target)))){
            File source = new File(source);
            // Todo
            Compress(out,source,source.getName());
        }
    }
    public static void Compress(ZipOutputStream zipOut,File sourceFile,String baseName) throws Exception{
        if(sourceFile.isDirectory){
            File[] fileList = sourceFile.listFiles();
            if(fileList == null || fileList.length==0){
                zipOut.putNextEntry(new ZipEntry(baseName+"/"));
            }else{
                fileList.foreach((file)->Compress(zipOut,file,baseName+"/"+file.getName()));
            }
        }else{
            zipOut.putNextEntry(new ZipEntry(baseName));
            try(BufferedInputStream bis=new BufferedInputStream(new FileInputStream(sourceFile))){
                int tag;
                while((tag=bis.read()!=-1)){
                    zipOut.write(tag);
                }
            }
        }
    }
}

获取系统类型

public class CommonUtil{
    public static boolean isLinuxOs(){
        String SysType = System.getProperty("os.name");
        Pattern.matches("Linux.*", SysType) ? return true : return false;
    }
}

自定义注解

使用过程

1、定义一个interface,命名为BaseCheck,BaseCheck里面有一个抽象的check方法,check方法返回值是boolean。
2、定义校验的注解,比如:@NotNull、@Length。
3、根据上面的注解,分别定义对应的校验类,比如:NotNullCheck、LengthCheck。
4、NotNullCheck、LengthCheck都需要实现BaseCheck的check方法,你要在check方法里面写校验流程。
5、定义一个容器,在工程启动的时候,把NotNullCheck和LengthCheck的对象塞到里面,
如果你使用spring,直接在NotNullCheck和LengthCheck上面加个注解@Component,也能达到同样的效果。
6、定义一个拦截器或者切面。
7、在这个拦截器或者切面里,拿到请求的参数,也就是那个user对象。
8、通过反射,获取到这个user对象所对应的类,类的名字肯定就是User了。
9、遍历User里面的所有Field,检查每一个Field是否含有注解。
10、遍历Field上的所有注解。
11、假设找到一个注解@NotNull,就去找一下对应的校验类,
BaseCheck baseCheck = 容器.get("NotNullCheck")
或者BaseCheck baseCheck = (BaseCheck) SpringUtl.getBean("NotNullCheck")
12、如果找到,也就是baseCheck不为空,则通过反射获取这个Field的实际值,将这个值作为参数,调用baseCheck.check方法
13、baseCheck.check如果返回false则报错,如果返回true则继续,直到遍历完所有Field、所有注解

两个示例

示例一:切面获取注解,并进行自定义处理

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
    /** 模块 */
    String title() default "";
    /** 功能 */
    String action() default "";
}

@Aspect
@Component("logAspect")
@EnableAspectJAutoProxy // <aop:aspectj-autoproxy/>
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
    // 配置织入点
    @Pointcut("@annotation(com.test.aspact.Log)")
    public void logPointCut() {
    }
    /**
     * 前置通知 用于拦截操作,在方法返回后执行
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
	handleLog(joinPoint, null);
    }
    /**
     * 拦截异常操作,有异常时执行
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfter(JoinPoint joinPoint, Exception e) {
	handleLog(joinPoint, e);
    }
      /**
     * 是否存在注解,如果存在就获取->这里只获取切入点的注解
     */
    private static Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
	Signature signature = joinPoint.getSignature();
	MethodSignature methodSignature = (MethodSignature) signature;
	Method method = methodSignature.getMethod();
	if (method != null) {
	    return method.getAnnotation(Log.class);
		}
		return null;
    }
    // 定义注解处理方法,被通知调用(传入异常)
    private void handleLog(JoinPoint joinPoint, Exception e) {
	try {
	    // 获得注解
	    Log controllerLog = getAnnotationLog(joinPoint);
	    if (controllerLog == null) {
		return;
	    }
	    // 获得方法名称
	    String className = joinPoint.getTarget().getClass().getName();
	    String methodName = joinPoint.getSignature().getName();
	    String action = controllerLog.action();
	    String title = controllerLog.title();
	    //打印日志,如有需要还可以存入数据库
	    log.info(">>>>>>>>>>>>>模块名称:{}",title);
	    log.info(">>>>>>>>>>>>>操作名称:{}",action);
	    log.info(">>>>>>>>>>>>>类名:{}",className);
	    log.info(">>>>>>>>>>>>>方法名:{}",methodName);
	} catch (Exception exp) {
	    // 记录本地异常日志
	    log.error("==前置通知异常==");
	    log.error("异常信息:{}", exp.getMessage());
	    exp.printStackTrace();
	}
    }
}

@Controller
public class HelloController {
    private static final Logger log = LoggerFactory.getLogger(HelloController.class); 
    @RequestMapping("/hello")
    //对应的自定义注解,当方法上写这个注解时,就会进入切面类中
    @Log(title="哈喽模块",action="say哈喽")
    public String sayHello() {
	log.info("HelloController sayHello:{}","hello world!");
	return "hello";
    }
}

jackson常用Util

publci class JsonUtils {
    private static final Logger log = LoggerFactory.getLogger(JsonUtils.class);
    private static final ObjectMapper objectMapper = null;
    public JsonUtils(){}
    private static ObjectMapper initObjectMapper() {
        ObjectMapper newObjectMapper = new ObjectMapper();
        // unknow properties -> throws exception
        newObjectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        // unknow beans -> empty(null) object
        newObjectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // serialization include null
        newObjectMapper.setSerializationInclusion(Include.NON_NULL);
        newObjectMapper.disable(new MapperFeature[]{MapperFeature.USE_GETTERS_AS_SETTERS});
        return newObjectMapper;
    }

    public static String toJsonStr(Object value) {
        try {
            return objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException var2) {
            log.error("Json转换失败", var2);
            throw new RuntimeException(var2);
        }
    }

    public static byte[] toJsonBytes(Object value) {
        try {
            return objectMapper.writeValueAsBytes(value);
        } catch (JsonProcessingException var2) {
            log.error("Json转换失败", var2);
            throw new RuntimeException(var2);
        }
    }

    public static String toJsonStr(Object value, String[] properties) {
        try {
            // filter properties
            SimpleBeanPropertyFilter sbp = SimpleBeanPropertyFilter.filterOutAllExcept(properties);
            FilterProvider filterProvider = (new SimpleFilterProvider()).addFilter("propertyFilterMixIn", sbp);
            return objectMapper.writer(filterProvider).writeValueAsString(value);
        } catch (Exception var4) {
            log.error("Json转换失败", var4);
            throw new RuntimeException(var4);
        }
    }

    public static String toJsonStrWithExcludeProperties(Object value, String[] properties2Exclude) {
        try {
            SimpleBeanPropertyFilter sbp = SimpleBeanPropertyFilter.serializeAllExcept(properties2Exclude);
            FilterProvider filterProvider = (new SimpleFilterProvider()).addFilter("propertyFilterMixIn", sbp);
            return objectMapper.writer(filterProvider).writeValueAsString(value);
        } catch (Exception var4) {
            log.error("Json转换失败", var4);
            throw new RuntimeException(var4);
        }
    }

    public static void writeJsonStr(OutputStream out, Object value) {
        try {
            objectMapper.writeValue(out, value);
        } catch (Exception var3) {
            log.error("Json转换失败", var3);
            throw new RuntimeException(var3);
        }
    }

    public static <T> T fromJson(String jsonString, Class<T> clazz) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        } else {
            try {
                return objectMapper.readValue(jsonString, clazz);
            } catch (IOException var3) {
                log.warn("parse json string error:" + jsonString, var3);
                return null;
            }
        }
    }

    public static <T> T fromJson(String jsonString, Class<T> clazz, Class<?>... elementClasses) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        } else {
            try {
                return elementClasses.length == 0 ? objectMapper.readValue(jsonString, clazz) : objectMapper.readValue(jsonString, getGenericsType(clazz, elementClasses));
            } catch (IOException var4) {
                log.warn("parse json string error:" + jsonString, var4);
                return null;
            }
        }
    }

    public static JavaType getGenericsType(Class<?> collectionClass, Class<?>... elementClasses) {
        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    static {
        objectMapper = initObjectMapper();
    }
}

级联递归

VUE

<script>
    methods:{
        query(e){
            if(this.loading&&(!e&&e!==0))return
            if(e) this.valueId=e
            this.loading=true
            getItems({
                appId: this.valueId,name:"",page:1,size:10000
            }).then(r=>{
                this.loading=false
                if(r.code===0&&r.items){
                    const getPageAll = list =>{
                        const getAll = arr =>{
                            const pages = []
                            arr.forEach(item=>{
                                item.show = true
                                if(item.typeName==='页面'){
                                    if(item.children && item.children.length){
                                        pages.push({
                                            label: item.name,
                                            value: item.id,
                                            children: getAll(item.children)
                                        })
                                    }else{
                                        pages.push({
                                            label: item.name,
                                            value: item.id
                                        })
                                    }
                                }
                            })
                            return pages
                        }
                        return getAll(list)
                    }
                    const pages = getPageAll(this.resourceData)
                    const pageOptions = pages
                    this.pageOptions = pageOptions
                }
            })
        }
    }
        
</script>

java

public Page<PageResourceVo> findByPage(int page,int size, String name,String appId){
    Pageable pageable = PageRequest.of(page-1,size);
    Page<PageResource> pageResources;
     if (Objects.nonNull(appId)){
            pageResources = pageResourceRepository.findByNameLikeAndAppIdAndParentId(queryName, appId, null, pageable);
        }else {
            pageResources = pageResourceRepository.findByNameLikeAndParentId(queryName, null, pageable);
        }
        List<PageResourceVo> pageResourceVos = pageResources.getContent()
                .stream()
                .map(this::convertToVo).collect(Collectors.toList());//这里convertToVo可以加入权限过滤
        // 查询子类型
        getAllChildren(pageResourceVos);
        return new PageImpl<>(pageResourceVos, pageable, pageResources.getTotalElements());
}
private void getAllChildren(List<PageResourceVo> pageResourceVos){
    List<PageResource> childs = pageResourceRepository.findByParentId(o.getId());
    if (Objects.nonNull(childs) && !childs.isEmpty()){
        List<PageResourceVo> children = childs.stream().map(this::convertToVo).collect(Collectors.toList());
        o.setChildren(children);
        getAllChildren(children);
    }
}
posted @ 2020-12-04 11:38  WheelCode  阅读(142)  评论(0)    收藏  举报