Java常用代码

来自ling
跳转至: 导航搜索

@Async

表达式

 List<String> deptIdList = dataScopeService.getAllChildIds(user.getDeptId()).getData().stream().map(SysDeptVO::getId).collect(Collectors.toList());
list.stream().collect(Collectors.groupingBy(IitDeductionPersonalInfo::getBasePersonalInfoUuid))
map.forEach((k, v) -> {System.out.println("key:value = " + k + ":" + v);});

Ognl Reflect

public boolean isUnique(final Object entity, final String[] propertyNames) {
       AssertHelper.allHasText(propertyNames);
       Assert.notNull(entity);
       Session session = getSession();
       Criteria criteria = session.createCriteria(entity.getClass()).setProjection(Projections.rowCount());
       try {
           for (int i = 0; i < propertyNames.length; i++) {
               Object parse = Ognl.parseExpression(propertyNames[i]);
               Object queryObject = Ognl.getValue(parse, entity);
               criteria.add(Restrictions.eq(propertyNames[i], queryObject));
           }
           ClassMetadata classMetadata = getClassMetadata(entity.getClass());
           if (classMetadata != null) {
               String identiferPropertyName = classMetadata.getIdentifierPropertyName();
               Object identiferValue = ReflectUtils.getFieldContent(entity, identiferPropertyName);
               if (identiferValue != null) {
                   criteria.add(Restrictions.not(Restrictions.eq(identiferPropertyName, identiferValue)));
               }
           }
       } catch (Exception e) {
           throw new RuntimeException("唯一性校验反射异常");
       }
       Object result = criteria.uniqueResult();
       if (result != null) {
           return Boolean.valueOf(Integer.valueOf(result.toString()) < 1);
       }
       return true;
   }

list.stream().collect(Collectors.groupingBy(IitDeductionPersonalInfo::getBasePersonalInfoUuid))

public List<IitDeductionClaimHCompareVo> iitDeductionClaimHCompare(Date start, Date end) {
		if (start == null) {
			start = DateUtil.addMonth(end, -1);
		}
		int startYear = DateUtil.getYear(start);
		int startMonth = DateUtil.getMonth(start);
		int endYear = DateUtil.getYear(end);
		int endMonth = DateUtil.getMonth(end);
		Criteria criteria = Criteria.where("orgId").is(this.getOrgId())
				.and("tenantId").is(this.getTenantId())
				.and("year").in(Arrays.asList(endYear, startYear))
				.and("month").in(Arrays.asList(endMonth, startMonth));
		List<IitDeductionPersonalInfo> list = this.mongoDao.query(IitDeductionPersonalInfo.class, criteria);
		Map<String, List<IitDeductionPersonalInfo>> groupMap = list.stream().collect(Collectors.groupingBy(IitDeductionPersonalInfo::getBasePersonalInfoUuid));
		List<IitDeductionClaimHCompareVo> result = new ArrayList<>(list.size());
		groupMap.forEach((k,v) -> {
			if(v.size() > 1) {
				v.sort((t1,t2) -> {
					int a = t1.getYear() * 12 + t1.getMonth();
					int b = t2.getYear() * 12 + t2.getMonth();
					return a == b ? 0 : a > b ? 1 : -1;
				});
				IitDeductionClaimHCompareVo startVo = JsonUtil.json2bean(v.get(0).getInfoJson(), IitDeductionClaimHCompareVo.class);
				IitDeductionClaimHCompareVo endVo =  JsonUtil.json2bean(v.get(1).getInfoJson(), IitDeductionClaimHCompareVo.class);
				if (endVo.compare(startVo)) {
					result.add(endVo);
				}
			}else {
				IitDeductionPersonalInfo startRpt = v.get(0);
				if(startRpt.getYear() == endYear && startRpt.getMonth() == endMonth){
					IitDeductionClaimHCompareVo startVo = JsonUtil.json2bean(startRpt.getInfoJson(), IitDeductionClaimHCompareVo.class);
					result.add(startVo);
				}
			}
		});
		return result;
	}

	private ServiceResponse<String> exportDeductiontExcel2(DeductionexportForm form,
			IitDeductionPersonalReportType type) {
		int year = DateUtil.getYear(form.getPeriod());
		int month = DateUtil.getMonth(form.getPeriod());
		Criteria criteria = Criteria.where("year").is(year).and("month").is(month).and("orgId").is(this.getOrgId())
				.and("tenantId").is(this.getTenantId());
		if (StringUtils.isNotBlank(form.getUserInfo())) {
			criteria.orOperator(Criteria.where("fullFillingMap.baseInfo_taxPayerName").is(form.getUserInfo()),
					Criteria.where("fullFillingMap.baseInfo_email").is(form.getUserInfo()),
					Criteria.where("fullFillingMap.baseInfo_phoneNumer").is(form.getUserInfo()));
		}
		Query query = new Query().addCriteria(criteria);
		List<IitDeductionPersonalReport> list = this.mongoDao.query(IitDeductionPersonalReport.class, query);
		List<IitDeductionPersonalReport> newList = this.initDate(form, list);
		if (CollectionUtils.isNotEmpty(newList)) {
			Map<String, Map<String, Object>> annoMap = new HashMap<>();
			Arrays.stream(IitDeductionPersonalReportVo.class.getDeclaredFields()).forEach(s -> {
				ExportExcel anno = s.getAnnotation(ExportExcel.class);
				if (anno != null) {
					Map<String, Object> m = new HashMap<>(3);
					m.put("sheet", anno.sheet());
					m.put("row", anno.row());
					m.put("cell", anno.cell());
					annoMap.put(s.getName(), m);
				}
			});
			Map<String, String> enumMessage = getEnumMessage();
			List<Map<String, Object>> content = new ArrayList<>();
			if (type == IitDeductionPersonalReportType.update) {
				IitReportDto rd = new IitReportDto();
				rd.setChangeMap(Collections.EMPTY_MAP);
				Map<String, BaseCityVo> cityMap = this.getAllCity();
				rd.setCityMap(cityMap);
				Map<String, BaseCountryVo> countryMap = this.getAllCountry();
				rd.setCountryMap(countryMap);
				rd.setEnumMessage(enumMessage);
				Map<String, BaseNationalityVo> nationalityMap = this.getAllNationality();
				rd.setNationalityMap(nationalityMap);
				rd.setType(IitDeductionPersonalReportType.full);

				newList.forEach(s -> {
					/*
					 * ExtendDetachedCriteria cer =
					 * ExtendDetachedCriteria.forClass(IitDeductionClaimH.class);
					 * cer.add(Restrictions.or( Restrictions.and(Restrictions.eq("periodYear",
					 * year),Restrictions.lt("periodMonth", month)), Restrictions.lt("periodYear",
					 * year) )) .addOrder(Order.desc("periodYear"))
					 * .addOrder(Order.desc("periodMonth")); IitDeductionClaimH endH =
					 * (IitDeductionClaimH)findOneByCriteria(cer);
					 */

					Criteria cer = Criteria.where("basePersonalInfoUuid").is(s.getBasePersonalInfoUuid());
					cer.orOperator(Criteria.where("year").is(year).and("month").lt(month),
							Criteria.where("year").lt(year));
					Query que = new Query(criteria);
					que.with(Sort.by(Direction.ASC, "year", "month"));
					IitDeductionPersonalReport endReport = mongoDao.findOne(IitDeductionPersonalReport.class, que);
					if (endReport != null) {
						IitDeductionClaimH startH = convertToIitDeductionClaimH(s.getFullFillingMap(), enumMessage,
								nationalityMap, countryMap, cityMap);
						IitDeductionClaimH endH = convertToIitDeductionClaimH(endReport.getFullFillingMap(),
								enumMessage, nationalityMap, countryMap, cityMap);
						Map<String, Boolean> changeMap = diff(endH, startH, false);
						if (!changeMap.isEmpty()) {
							// Map<String,Object> map =
							// getFullFillingMapByCliamH(s,enumMessage,Collections.EMPTY_MAP,IitDeductionPersonalReportType.full);
							Map<String, Object> map = getFullFillingMapByCliamH(rd);
							content.add(map);
						}
					}
				});
			} else {
				newList.forEach(s -> {
					/*
					 * Map<String,Object> map =
					 * getFullFillingMapByCliamH(s,enumMessage,Collections.EMPTY_MAP,
					 * IitDeductionPersonalReportType.full); content.add(map);
					 */
					content.add(s.getFullFillingMap());
				});
			}

			if (!content.isEmpty()) {
				ServiceFile templateFile = new ServiceFile(REPORT_EXCEL_FILE);
				String rquestUuid = this.getService(IExcelTaxDeductionReportService.class)
						.submitReportRequestList(templateFile, content, annoMap);
				return ServiceResponse.success(rquestUuid, null);
			}
		}
		return ServiceResponse.error("没有可导出数据");
	}

map循环

    /**
     * 遍历Map第五种
     * 通过k,v遍历,Java8独有的
     */
    @Test
    public void testFive() {
        System.out.println("---------------------Only JAVA8 ------------------------------");
        long time = System.currentTimeMillis();
        System.out.println(time);
        map.forEach((k, v) -> {System.out.println("key:value = " + k + ":" + v);});
        System.out.println("遍历完花费总时间为:"+(System.currentTimeMillis()-time));
    }

list循环

items.forEach(item->System.out.println(item));
//输出 : C
items.forEach(item->{
    if("C".equals(item)){
        System.out.println(item);
    }
});

hibernate

EntityManagerFactory factory = JpaUtil.getEntityManager().getEntityManagerFactory();
		Metamodel metamodel = factory.getMetamodel();
		metamodel.getEntities().forEach(entityType -> {
			System.out.println(entityType.getName());
			entityType.getAttributes().forEach(attribute -> {
				log.info(attribute.getName());
			});
		});

StopWatch

    public void processPPTX(PPTXContext params) throws IOException {
        StopWatch stopWatch = new StopWatch("生成PPT整个PPT时间");
        stopWatch.start("<<<<load template>>>>");
        InputStream in = PPTXUtils.class.getResourceAsStream(params.getTemplatePath());
        XMLSlideShow ppt = new XMLSlideShow(in);
        stopWatch.stop();

//        XSLFSlide slide6 = ppt.getSlides().get(5);
//        for (XSLFShape shape : slide6.getShapes()) {
//            if (shape instanceof XSLFTable) {
//                XSLFTable xslfTable = (XSLFTable) shape;
//                for (XSLFTableRow row : xslfTable.getRows()) {
//                    log.info(row.getHeight() + "");
//                }
//            }
//        }

        stopWatch.start("<<<<process slide>>>>");
//        for (int i = 0; i < ppt.getSlides().size(); i++) {
//            XSLFSlide slide = ppt.getSlides().get(i);
        XSLFSlide slide = ppt.getSlides().get(0);
        PPTXUtils.replaceRegValue(slide, params);
//        }
        XSLFSlide slide5 = ppt.getSlides().get(5);
        PPTXUtils.processTable(ppt, slide5, params, 5);
        stopWatch.stop();

        stopWatch.start("<<<<保存到磁盘>>>>");
        ppt.write(new FileOutputStream(params.getOutputPath()));
        stopWatch.stop();

        log.info("PPT 时间 ={}", stopWatch.prettyPrint());
    }

@Async

@Async