proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/store/serviceimpl/StoreAddressServiceImpl.java
StoreAddressServiceImpl
getStoreAddress
class StoreAddressServiceImpl extends ServiceImpl<StoreAddressMapper, StoreAddress> implements StoreAddressService { @Override public IPage<StoreAddress> getStoreAddress(String storeId, PageVO pageVo) {<FILL_FUNCTION_BODY>} @Override public StoreAddress addStoreAddress(String storeId, StoreAddress storeAddress) { //获取当前登录商家账号 storeAddress.setStoreId(storeId); //添加自提点 this.save(storeAddress); return storeAddress; } @Override public StoreAddress editStoreAddress(String storeId, StoreAddress storeAddress) { //获取当前登录商家账号 storeAddress.setStoreId(storeId); //添加自提点 this.updateById(storeAddress); return storeAddress; } @Override public Boolean removeStoreAddress(String id) { return this.removeById(id); } }
//获取当前登录商家账号 LambdaQueryWrapper<StoreAddress> lambdaQueryWrapper = Wrappers.lambdaQuery(); lambdaQueryWrapper.eq(StoreAddress::getStoreId, storeId); return this.page(PageUtil.initPage(pageVo), lambdaQueryWrapper);
240
77
317
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/system/aspect/interceptor/SystemLogAspect.java
SaveSystemLogThread
run
class SaveSystemLogThread implements Runnable { @Autowired private SystemLogVO systemLogVO; @Autowired private SystemLogService systemLogService; public SaveSystemLogThread(SystemLogVO systemLogVO, SystemLogService systemLogService) { this.systemLogVO = systemLogVO; this.systemLogService = systemLogService; } @Override public void run() {<FILL_FUNCTION_BODY>} }
try { systemLogService.saveLog(systemLogVO); } catch (Exception e) { log.error("系统日志保存异常,内容{}:", systemLogVO, e); }
121
56
177
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/system/entity/dto/HotWordsSettingItem.java
HotWordsSettingItem
getScore
class HotWordsSettingItem implements Comparable<HotWordsSettingItem>, Serializable { @ApiModelProperty(value = "热词") private String keywords; @ApiModelProperty(value = "默认分数") private Integer score; public Integer getScore() {<FILL_FUNCTION_BODY>} public void setScore(Integer score) { this.score = score; } @Override public int compareTo(HotWordsSettingItem pointSettingItem) { return pointSettingItem.getScore(); } }
if (score == null || score < 0) { return 0; } return score;
148
30
178
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/system/entity/dto/OssSetting.java
OssSetting
getType
class OssSetting implements Serializable { private static final long serialVersionUID = 2975271656230801861L; /** * oss类型 */ private String type; /** * 阿里云-域名 */ private String aliyunOSSEndPoint = ""; /** * 阿里云-储存空间 */ private String aliyunOSSBucketName = ""; // /** // * 阿里云-存放路径路径 // */ // private String aliyunOSSPicLocation = ""; /** * 阿里云-密钥id */ private String aliyunOSSAccessKeyId = ""; /** * 阿里云-密钥 */ private String aliyunOSSAccessKeySecret = ""; /** * minio服务地址 */ private String m_endpoint; /** * minio 前端请求地址 */ private String m_frontUrl; /** * minio用户名 */ private String m_accessKey; /** * minio密码 */ private String m_secretKey; /** * minio bucket名称 */ private String m_bucketName; /** * 华为云-发起者的Access Key * * @return */ String huaweicloudOBSAccessKey; /** * 华为云-密钥 */ String huaweicloudOBSSecretKey; /** * 华为云OBS-节点 */ String huaweicloudOBSEndPoint; /** * 华为云OBS-桶 */ private String huaweicloudOBSBucketName = ""; /** * 腾讯云 用户的 SecretId */ String tencentCOSSecretId; /** * 腾讯云 用户的 SecretKey */ String tencentCOSSecretKey; /** * 腾讯云 bucket 的地域 */ String tencentCOSRegion; /** * 腾讯云 bucket */ String tencentCOSBucket; /** * 腾讯云-域名 */ private String tencentCOSEndPoint = ""; public String getType() {<FILL_FUNCTION_BODY>} }
//默认给阿里云oss存储类型 if (StringUtils.isEmpty(type)) { return OssEnum.ALI_OSS.name(); } return type;
634
50
684
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/system/entity/dto/PointSetting.java
PointSetting
getConsumer
class PointSetting implements Serializable { private static final long serialVersionUID = -4261856614779031745L; @ApiModelProperty(value = "注册") private Integer register; @ApiModelProperty(value = "消费1元赠送多少积分") private Integer consumer; @ApiModelProperty(value = "积分付款X积分=1元") private Integer money; @ApiModelProperty(value = "每日签到积分") private Integer signIn; @ApiModelProperty(value = "订单评价赠送积分") private Integer comment; @ApiModelProperty(value = "积分具体设置") private List<PointSettingItem> pointSettingItems = new ArrayList<>(); public Integer getRegister() { if (register == null || register < 0) { return 0; } return register; } public Integer getMoney() { if (money == null || money < 0) { return 0; } return money; } public Integer getConsumer() {<FILL_FUNCTION_BODY>} public Integer getSignIn() { if (signIn == null || signIn < 0) { return 0; } return signIn; } public Integer getComment() { if (comment == null || comment < 0) { return 0; } return comment; } }
if (consumer == null || consumer < 0) { return 0; } return consumer;
379
31
410
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/system/entity/dto/PointSettingItem.java
PointSettingItem
getPoint
class PointSettingItem implements Comparable<PointSettingItem>, Serializable { @ApiModelProperty(value = "签到天数") private Integer day; @ApiModelProperty(value = "赠送积分") private Integer point; public Integer getPoint() {<FILL_FUNCTION_BODY>} public void setPoint(Integer point) { this.point = point; } @Override public int compareTo(PointSettingItem pointSettingItem) { return this.day - pointSettingItem.getDay(); } }
if (point == null || point < 0) { return 0; } return point;
147
30
177
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/system/entity/dto/payment/dto/PaymentSupportForm.java
PaymentSupportForm
getClients
class PaymentSupportForm { /** * 客户端类型列表 * * @return 客户端类型 */ public List<ClientTypeEnum> getClients() {<FILL_FUNCTION_BODY>} /** * 支付方式列表 * * @return 即支持的支付方式集合 */ public List<PaymentMethodEnum> getPayments() { List<PaymentMethodEnum> keys = new ArrayList<>(); for (PaymentMethodEnum paymentMethodEnum : PaymentMethodEnum.values()) { if (paymentMethodEnum.equals(PaymentMethodEnum.BANK_TRANSFER)){ continue; } keys.add(paymentMethodEnum); } return keys; } }
List<ClientTypeEnum> keys = new ArrayList<>(); for (ClientTypeEnum clientTypeEnum : ClientTypeEnum.values()) { if (clientTypeEnum.equals(ClientTypeEnum.UNKNOWN)){ continue; } keys.add(clientTypeEnum); } return keys;
199
79
278
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/system/serviceimpl/AppVersionServiceImpl.java
AppVersionServiceImpl
checkAppVersion
class AppVersionServiceImpl extends ServiceImpl<AppVersionMapper, AppVersion> implements AppVersionService { @Override public AppVersion getAppVersion(String appType) { return this.baseMapper.getLatestVersion(appType); } @Override public boolean checkAppVersion(AppVersion appVersion) {<FILL_FUNCTION_BODY>} }
if (null == appVersion) { throw new ServiceException(ResultCode.APP_VERSION_PARAM_ERROR); } if (StringUtils.isBlank(appVersion.getType())) { throw new ServiceException(ResultCode.APP_VERSION_TYPE_ERROR); } //检测版本是否存在(同类型APP下版本不允许重复) if (null != this.getOne(new LambdaQueryWrapper<AppVersion>() .eq(AppVersion::getVersion, appVersion.getVersion()) .eq(AppVersion::getType, appVersion.getType()) .ne(appVersion.getId() != null, AppVersion::getId, appVersion.getId()))) { throw new ServiceException(ResultCode.APP_VERSION_EXIST); } return true;
93
200
293
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/system/serviceimpl/LogisticsServiceImpl.java
LogisticsServiceImpl
labelOrder
class LogisticsServiceImpl extends ServiceImpl<LogisticsMapper, Logistics> implements LogisticsService { @Autowired private LogisticsPluginFactory logisticsPluginFactory; @Autowired private OrderService orderService; @Autowired private OrderItemService orderItemService; @Autowired private StoreLogisticsService storeLogisticsService; @Autowired private StoreDetailService storeDetailService; @Autowired private SettingService settingService; @Override public Traces getLogisticTrack(String logisticsId, String logisticsNo, String phone) { try { return logisticsPluginFactory.filePlugin().pollQuery(this.getById(logisticsId), logisticsNo, phone); } catch (Exception e) { log.error("获取物流公司错误", e); } return null; } @Override public Traces getLogisticMapTrack(String logisticsId, String logisticsNo, String phone, String from, String to) { try { return logisticsPluginFactory.filePlugin().pollMapTrack(this.getById(logisticsId), logisticsNo, phone, from, to); } catch (Exception e) { log.error("获取物流公司错误", e); } return null; } @Override public Map labelOrder(String orderSn, String logisticsId) {<FILL_FUNCTION_BODY>} @Override public String sfCreateOrder(OrderDetailVO orderDetailVO) { return logisticsPluginFactory.filePlugin().createOrder(orderDetailVO); } @Override public List<Logistics> getOpenLogistics() { LambdaQueryWrapper<Logistics> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(Logistics::getDisabled, SwitchEnum.OPEN.name()); return this.list(queryWrapper); } @Override public LogisticsSetting getLogisticsSetting() { Setting setting = settingService.get(SettingEnum.LOGISTICS_SETTING.name()); return JSONUtil.toBean(setting.getSettingValue(), LogisticsSetting.class); } }
//获取设置 LogisticsSetting logisticsSetting = this.getLogisticsSetting(); //获取订单及子订单 Order order = OperationalJudgment.judgment(orderService.getBySn(orderSn)); if ((LogisticsEnum.SHUNFENG.name().equals(logisticsSetting.getType()) && order.getDeliverStatus().equals(DeliverStatusEnum.DELIVERED.name()) && order.getOrderStatus().equals(OrderStatusEnum.DELIVERED.name())) || (order.getDeliverStatus().equals(DeliverStatusEnum.UNDELIVERED.name()) && order.getOrderStatus().equals(OrderStatusEnum.UNDELIVERED.name()))) { //订单货物 List<OrderItem> orderItems = orderItemService.getByOrderSn(orderSn); //获取对应物流 Logistics logistics; if(LogisticsEnum.SHUNFENG.name().equals(logisticsSetting.getType())){ logistics = this.getOne(new LambdaQueryWrapper<Logistics>().eq(Logistics::getCode,"SF")); }else{ logistics = this.getById(logisticsId); } // 店铺-物流公司设置 LambdaQueryWrapper<StoreLogistics> lambdaQueryWrapper = Wrappers.lambdaQuery(); lambdaQueryWrapper.eq(StoreLogistics::getLogisticsId, logistics.getId()); lambdaQueryWrapper.eq(StoreLogistics::getStoreId, order.getStoreId()); StoreLogistics storeLogistics = storeLogisticsService.getOne(lambdaQueryWrapper); //获取店家信息 StoreDeliverGoodsAddressDTO storeDeliverGoodsAddressDTO = storeDetailService.getStoreDeliverGoodsAddressDto(order.getStoreId()); LabelOrderDTO labelOrderDTO = new LabelOrderDTO(); labelOrderDTO.setOrder(order); labelOrderDTO.setOrderItems(orderItems); labelOrderDTO.setLogistics(logistics); labelOrderDTO.setStoreLogistics(storeLogistics); labelOrderDTO.setStoreDeliverGoodsAddressDTO(storeDeliverGoodsAddressDTO); //触发电子面单 return logisticsPluginFactory.filePlugin().labelOrder(labelOrderDTO); } else { throw new ServiceException(ResultCode.ORDER_LABEL_ORDER_ERROR); }
544
604
1,148
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/system/serviceimpl/SensitiveWordsServiceImpl.java
SensitiveWordsServiceImpl
resetCache
class SensitiveWordsServiceImpl extends ServiceImpl<SensitiveWordsMapper, SensitiveWords> implements SensitiveWordsService { @Autowired private Cache<List<String>> cache; @Override public void resetCache() {<FILL_FUNCTION_BODY>} }
List<SensitiveWords> sensitiveWordsList = this.list(); if (sensitiveWordsList == null || sensitiveWordsList.isEmpty()) { return; } List<String> sensitiveWords = sensitiveWordsList.stream().map(SensitiveWords::getSensitiveWord).collect(Collectors.toList()); cache.put(CachePrefix.SENSITIVE.getPrefix(), sensitiveWords);
74
107
181
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/verification/ImageUtil.java
ImageUtil
readPixel
class ImageUtil { /** * 添加水印 * * @param oriImage 原图 * @param text 文字 * @throws IOException 流操作异常 */ public static void addWatermark(BufferedImage oriImage, String text) { Graphics2D graphics2D = oriImage.createGraphics(); //设置水印文字颜色 graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); //设置水印文字Font graphics2D.setColor(Color.black); //设置水印文字透明度 graphics2D.setFont(new Font("宋体", Font.BOLD, 30)); //第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y) graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.4f)); graphics2D.drawString(text, 10, 40); graphics2D.dispose(); } /** * 干扰图 * * @param oriImage 原图 * @param templateImage 模板图 * @param x 随机扣取坐标X * @param y 随机扣取坐标y */ public static void interfereTemplate(BufferedImage oriImage, BufferedImage templateImage, int x, int y) { //临时数组遍历用于高斯模糊存周边像素值 int[][] matrix = new int[3][3]; int[] values = new int[9]; int xLength = templateImage.getWidth(); int yLength = templateImage.getHeight(); //模板图像宽度 for (int i = 0; i < xLength; i++) { //模板图片高度 for (int j = 0; j < yLength; j++) { //如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中 int rgb = templateImage.getRGB(i, j); if (rgb < 0) { //抠图区域高斯模糊 readPixel(oriImage, x + i, y + j, values); fillMatrix(matrix, values); oriImage.setRGB(x + i, y + j, avgMatrix(matrix)); } //防止数组越界判断 if (i == (xLength - 1) || j == (yLength - 1)) { continue; } int rightRgb = templateImage.getRGB(i + 1, j); int downRgb = templateImage.getRGB(i, j + 1); //描边处理,,取带像素和无像素的界点,判断该点是不是临界轮廓点,如果是设置该坐标像素是白色 boolean rgbImage = ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0) || (rgb < 0 && downRgb >= 0)); } } } /** * @param oriImage 原图 * @param templateImage 模板图 * @param newImage 新抠出的小图 * @param x 随机扣取坐标X * @param y 随机扣取坐标y */ public static void cutByTemplate(BufferedImage oriImage, BufferedImage templateImage, BufferedImage newImage, int x, int y) { //临时数组遍历用于高斯模糊存周边像素值 int[][] matrix = new int[3][3]; int[] values = new int[9]; int xLength = templateImage.getWidth(); int yLength = templateImage.getHeight(); //模板图像宽度 for (int i = 0; i < xLength; i++) { //模板图片高度 for (int j = 0; j < yLength; j++) { //如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中 int rgb = templateImage.getRGB(i, j); if (rgb < 0) { newImage.setRGB(i, j, oriImage.getRGB(x + i, y + j)); //抠图区域高斯模糊 readPixel(oriImage, x + i, y + j, values); fillMatrix(matrix, values); oriImage.setRGB(x + i, y + j, avgMatrix(matrix)); } //防止数组越界判断 if (i == (xLength - 1) || j == (yLength - 1)) { continue; } int rightRgb = templateImage.getRGB(i + 1, j); int downRgb = templateImage.getRGB(i, j + 1); //描边处理,,取带像素和无像素的界点,判断该点是不是临界轮廓点,如果是设置该坐标像素是白色 boolean rgbImage = ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0) || (rgb < 0 && downRgb >= 0)); if (rgbImage) { newImage.setRGB(i, j, Color.GRAY.getRGB()); } } } } public static void readPixel(BufferedImage img, int x, int y, int[] pixels) {<FILL_FUNCTION_BODY>} public static void fillMatrix(int[][] matrix, int[] values) { int filled = 0; for (int[] x : matrix) { for (int j = 0; j < x.length; j++) { x[j] = values[filled++]; } } } public static int avgMatrix(int[][] matrix) { int r = 0; int g = 0; int b = 0; for (int[] x : matrix) { for (int j = 0; j < x.length; j++) { if (j == 1) { continue; } Color c = new Color(x[j]); r += c.getRed(); g += c.getGreen(); b += c.getBlue(); } } return new Color(r / 8, g / 8, b / 8).getRGB(); } }
int xStart = x - 1; int yStart = y - 1; int current = 0; for (int i = xStart; i < 3 + xStart; i++) { for (int j = yStart; j < 3 + yStart; j++) { int tx = i; if (tx < 0) { tx = -tx; } else if (tx >= img.getWidth()) { tx = x; } int ty = j; if (ty < 0) { ty = -ty; } else if (ty >= img.getHeight()) { ty = y; } pixels[current++] = img.getRGB(tx, ty); } }
1,699
192
1,891
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/verification/SliderImageUtil.java
SliderImageUtil
pictureTemplatesCut
class SliderImageUtil { private static final int BOLD = 5; private static final String IMG_FILE_TYPE = "jpg"; private static final String TEMP_IMG_FILE_TYPE = "png"; /** * 根据模板切图 * * @param sliderFile 滑块 * @param originalFile 原图 * @param watermark 水印 * @param interfereNum 干扰选项 * @return 滑块参数 * @throws Exception sliderFile, originalFile */ public static Map<String, Object> pictureTemplatesCut( SerializableStream sliderFile, SerializableStream interfereSliderFile, SerializableStream originalFile, String watermark, Integer interfereNum) throws Exception {<FILL_FUNCTION_BODY>} }
Random random = new Random(); Map<String, Object> pictureMap = new HashMap<>(16); //拼图 BufferedImage sliderImage = ImageIO.read(Base64DecodeMultipartFile.base64ToInputStream(sliderFile.getBase64())); int sliderWidth = sliderImage.getWidth(); int sliderHeight = sliderImage.getHeight(); //原图 BufferedImage originalImage = ImageIO.read(Base64DecodeMultipartFile.base64ToInputStream(originalFile.getBase64())); int originalWidth = originalImage.getWidth(); int originalHeight = originalImage.getHeight(); //随机生成抠图坐标X,Y //X轴距离右端targetWidth Y轴距离底部targetHeight以上 int randomX = random.nextInt(originalWidth - 3 * sliderWidth) + 2 * sliderWidth; int randomY = random.nextInt(originalHeight - sliderHeight); log.info("原图大小{} x {},随机生成的坐标 X,Y 为({},{})", originalWidth, originalHeight, randomX, randomY); //新建一个和模板一样大小的图像,TYPE_4BYTE_ABGR表示具有8位RGBA颜色分量的图像,正常取imageTemplate.getType() BufferedImage newImage = new BufferedImage(sliderWidth, sliderHeight, sliderImage.getType()); //得到画笔对象 Graphics2D graphics = newImage.createGraphics(); //如果需要生成RGB格式,需要做如下配置,Transparency 设置透明 newImage = graphics.getDeviceConfiguration().createCompatibleImage(sliderWidth, sliderHeight, Transparency.TRANSLUCENT); //新建的图像根据模板颜色赋值,源图生成遮罩 ImageUtil.cutByTemplate(originalImage, sliderImage, newImage, randomX, randomY); //干扰项 if (interfereNum > 0) { BufferedImage interfereSliderImage = ImageIO.read(Base64DecodeMultipartFile.base64ToInputStream(interfereSliderFile.getBase64())); for (int i = 0; i < interfereNum; i++) { int interfereX = random.nextInt(originalWidth - 3 * sliderWidth) + 2 * sliderWidth; int interfereY = random.nextInt(originalHeight - sliderHeight); ImageUtil.interfereTemplate(originalImage, interfereSliderImage, interfereX, interfereY); } } //设置“抗锯齿”的属性 graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setStroke(new BasicStroke(BOLD, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); graphics.drawImage(newImage, 0, 0, null); graphics.dispose(); //添加水印 // ImageUtil.addWatermark(originalImage, watermark); //新建流 ByteArrayOutputStream newImageOs = new ByteArrayOutputStream(); //利用ImageIO类提供的write方法,将bi以png图片的数据模式写入流。 ImageIO.write(newImage, TEMP_IMG_FILE_TYPE, newImageOs); byte[] newImagery = newImageOs.toByteArray(); //新建流 ByteArrayOutputStream oriImagesOs = new ByteArrayOutputStream(); //利用ImageIO类提供的write方法,将bi以jpg图片的数据模式写入流 ImageIO.write(originalImage, IMG_FILE_TYPE, oriImagesOs); byte[] oriImageByte = oriImagesOs.toByteArray(); pictureMap.put("slidingImage", "data:image/png;base64," + Base64Utils.encodeToString(newImagery)); pictureMap.put("backImage", "data:image/png;base64," + Base64Utils.encodeToString(oriImageByte)); // x轴 pictureMap.put("randomX", randomX); // y轴 pictureMap.put("randomY", randomY); pictureMap.put("originalHeight", originalHeight); pictureMap.put("originalWidth", originalWidth); pictureMap.put("sliderHeight", sliderHeight); pictureMap.put("sliderWidth", sliderWidth); return pictureMap;
213
1,122
1,335
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/verification/VerificationSDK.java
VerificationSDK
checked
class VerificationSDK { @Autowired private Cache cache; /** * 生成一个token 用于获取校验中心的验证码逻辑 * * @return */ public boolean checked(String verificationKey, String uuid) {<FILL_FUNCTION_BODY>} }
//生成校验KEY,在验证码服务做记录 String key = CachePrefix.VERIFICATION_KEY.getPrefix() + verificationKey; cache.get(key); return true;
85
53
138
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/verification/aop/VerificationInterceptor.java
VerificationInterceptor
interceptor
class VerificationInterceptor { @Autowired private VerificationService verificationService; @Before("@annotation(cn.lili.modules.verification.aop.annotation.Verification)") public void interceptor(JoinPoint pjp) {<FILL_FUNCTION_BODY>} }
MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); Verification verificationAnnotation = method.getAnnotation(Verification.class); VerificationEnums verificationEnums = verificationAnnotation.type(); String uuid = verificationAnnotation.uuid(); boolean result = verificationService.check(uuid, verificationEnums); if (result) { return; } throw new ServiceException(ResultCode.VERIFICATION_ERROR);
81
119
200
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/verification/service/impl/VerificationSourceServiceImpl.java
VerificationSourceServiceImpl
initCache
class VerificationSourceServiceImpl extends ServiceImpl<VerificationSourceMapper, VerificationSource> implements VerificationSourceService { @Autowired private Cache<VerificationDTO> cache; @Override public VerificationDTO initCache() {<FILL_FUNCTION_BODY>} @Override public VerificationDTO getVerificationCache() { VerificationDTO verificationDTO; try { verificationDTO = cache.get(VERIFICATION_CACHE); } catch (ClassCastException cce) { verificationDTO = null; } if (verificationDTO == null || verificationDTO.getVerificationResources().size() <= 0 || verificationDTO.getVerificationSlider().size() <= 0) { return initCache(); } return verificationDTO; } }
List<VerificationSource> dbList = this.list(); List<VerificationSource> resourceList = new ArrayList<>(); List<VerificationSource> sliderList = new ArrayList<>(); for (VerificationSource item : dbList) { if (item.getType().equals(VerificationSourceEnum.RESOURCE.name())) { resourceList.add(item); } else if (item.getType().equals(VerificationSourceEnum.SLIDER.name())) { sliderList.add(item); } } VerificationDTO verificationDTO = new VerificationDTO(); verificationDTO.setVerificationResources(resourceList); verificationDTO.setVerificationSlider(sliderList); cache.put(VERIFICATION_CACHE, verificationDTO); return verificationDTO;
208
206
414
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/wallet/serviceimpl/MemberWithdrawApplyServiceImpl.java
MemberWithdrawApplyServiceImpl
getMemberWithdrawPage
class MemberWithdrawApplyServiceImpl extends ServiceImpl<MemberWithdrawApplyMapper, MemberWithdrawApply> implements MemberWithdrawApplyService { @Autowired private RocketMQTemplate rocketMQTemplate; @Autowired private RocketmqCustomProperties rocketmqCustomProperties; /** * 会员余额 */ @Autowired private MemberWalletService memberWalletService; @Override @Transactional(rollbackFor = Exception.class) public Boolean audit(String applyId, Boolean result, String remark) { MemberWithdrawalMessage memberWithdrawalMessage = new MemberWithdrawalMessage(); //查询申请记录 MemberWithdrawApply memberWithdrawApply = this.getById(applyId); memberWithdrawApply.setInspectRemark(remark); memberWithdrawApply.setInspectTime(new Date()); if (memberWithdrawApply != null) { //获取账户余额 MemberWalletVO memberWalletVO = memberWalletService.getMemberWallet(memberWithdrawApply.getMemberId()); //校验金额是否满足提现,因为是从冻结金额扣减,所以校验的是冻结金额 if (memberWalletVO.getMemberFrozenWallet() < memberWithdrawApply.getApplyMoney()) { throw new ServiceException(ResultCode.WALLET_WITHDRAWAL_FROZEN_AMOUNT_INSUFFICIENT); } //如果审核通过 则微信直接提现,反之则记录审核状态 if (Boolean.TRUE.equals(result)) { memberWithdrawApply.setApplyStatus(WithdrawStatusEnum.VIA_AUDITING.name()); } else { memberWithdrawApply.setApplyStatus(WithdrawStatusEnum.FAIL_AUDITING.name()); //保存修改审核记录 this.updateById(memberWithdrawApply); } //发送审核消息 memberWithdrawalMessage.setStatus(memberWithdrawApply.getApplyStatus()); memberWithdrawalMessage.setMemberWithdrawApplyId(memberWithdrawApply.getId()); memberWithdrawalMessage.setMemberId(memberWithdrawApply.getMemberId()); memberWithdrawalMessage.setPrice(memberWithdrawApply.getApplyMoney()); String destination = rocketmqCustomProperties.getMemberTopic() + ":" + MemberTagsEnum.MEMBER_WITHDRAWAL.name(); rocketMQTemplate.asyncSend(destination, memberWithdrawalMessage, RocketmqSendCallbackBuilder.commonCallback()); return true; } throw new ServiceException(ResultCode.WALLET_APPLY_ERROR); } @Override public IPage<MemberWithdrawApply> getMemberWithdrawPage(PageVO pageVO, MemberWithdrawApplyQueryVO memberWithdrawApplyQueryVO) {<FILL_FUNCTION_BODY>} }
//构建查询条件 QueryWrapper<MemberWithdrawApply> queryWrapper = new QueryWrapper<>(); //会员名称 queryWrapper.like(!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getMemberName()), "member_name", memberWithdrawApplyQueryVO.getMemberName()); //充值订单号 queryWrapper.eq(!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getSn()), "sn", memberWithdrawApplyQueryVO.getSn()); //会员id queryWrapper.eq(!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getMemberId()), "member_id", memberWithdrawApplyQueryVO.getMemberId()); //已付款的充值订单 queryWrapper.eq(!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getApplyStatus()), "apply_status", memberWithdrawApplyQueryVO.getApplyStatus()); //开始时间和结束时间 if (!StringUtils.isEmpty(memberWithdrawApplyQueryVO.getStartDate()) && !StringUtils.isEmpty(memberWithdrawApplyQueryVO.getEndDate())) { Date start = cn.hutool.core.date.DateUtil.parse(memberWithdrawApplyQueryVO.getStartDate()); Date end = cn.hutool.core.date.DateUtil.parse(memberWithdrawApplyQueryVO.getEndDate()); queryWrapper.between("create_time", start, end); } queryWrapper.orderByDesc("create_time"); //查询返回数据 return this.baseMapper.selectPage(PageUtil.initPage(pageVO), queryWrapper);
718
383
1,101
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/wallet/serviceimpl/RechargeServiceImpl.java
RechargeServiceImpl
paySuccess
class RechargeServiceImpl extends ServiceImpl<RechargeMapper, Recharge> implements RechargeService { /** * 会员预存款 */ @Autowired private MemberWalletService memberWalletService; @Override public Recharge recharge(Double price) { if (price == null || price <= 0 || price > 1000000) { throw new ServiceException(ResultCode.RECHARGE_PRICE_ERROR); } //获取当前登录的会员 AuthUser authUser = UserContext.getCurrentUser(); //构建sn String sn = "Y" + SnowFlake.getId(); //整合充值订单数据 Recharge recharge = new Recharge(sn, authUser.getId(), authUser.getUsername(), price); //添加预存款充值账单 this.save(recharge); //返回预存款 return recharge; } @Override public IPage<Recharge> rechargePage(PageVO page, RechargeQueryVO rechargeQueryVO) { //构建查询条件 QueryWrapper<Recharge> queryWrapper = new QueryWrapper<>(); //会员名称 queryWrapper.like(!CharSequenceUtil.isEmpty(rechargeQueryVO.getMemberName()), "member_name", rechargeQueryVO.getMemberName()); //充值订单号 queryWrapper.eq(!CharSequenceUtil.isEmpty(rechargeQueryVO.getRechargeSn()), "recharge_sn", rechargeQueryVO.getRechargeSn()); //会员id queryWrapper.eq(!CharSequenceUtil.isEmpty(rechargeQueryVO.getMemberId()), "member_id", rechargeQueryVO.getMemberId()); //支付时间 开始时间和结束时间 if (!CharSequenceUtil.isEmpty(rechargeQueryVO.getStartDate()) && !CharSequenceUtil.isEmpty(rechargeQueryVO.getEndDate())) { Date start = cn.hutool.core.date.DateUtil.parse(rechargeQueryVO.getStartDate()); Date end = cn.hutool.core.date.DateUtil.parse(rechargeQueryVO.getEndDate()); queryWrapper.between("pay_time", start, end); } queryWrapper.orderByDesc("create_time"); //查询返回数据 return this.page(PageUtil.initPage(page), queryWrapper); } @Override public void paySuccess(String sn, String receivableNo, String paymentMethod) {<FILL_FUNCTION_BODY>} @Override public Recharge getRecharge(String sn) { Recharge recharge = this.getOne(new QueryWrapper<Recharge>().eq("recharge_sn", sn)); if (recharge != null) { return recharge; } throw new ServiceException(ResultCode.ORDER_NOT_EXIST); } @Override public void rechargeOrderCancel(String sn) { Recharge recharge = this.getOne(new QueryWrapper<Recharge>().eq("recharge_sn", sn)); if (recharge != null) { recharge.setPayStatus(PayStatusEnum.CANCEL.name()); this.updateById(recharge); } } }
//根据sn获取支付账单 Recharge recharge = this.getOne(new QueryWrapper<Recharge>().eq("recharge_sn", sn)); //如果支付账单不为空则进行一下逻辑 if (recharge != null && !recharge.getPayStatus().equals(PayStatusEnum.PAID.name())) { //将此账单支付状态更改为已支付 recharge.setPayStatus(PayStatusEnum.PAID.name()); recharge.setReceivableNo(receivableNo); recharge.setPayTime(new DateTime()); recharge.setRechargeWay(paymentMethod); //执行保存操作 this.updateById(recharge); //增加预存款余额 memberWalletService.increase(new MemberWalletUpdateDTO(recharge.getRechargeMoney(), recharge.getMemberId(), "会员余额充值,充值单号为:" + recharge.getRechargeSn(), DepositServiceTypeEnum.WALLET_RECHARGE.name())); }
807
264
1,071
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/wallet/serviceimpl/WalletLogServiceImpl.java
WalletLogServiceImpl
depositLogPage
class WalletLogServiceImpl extends ServiceImpl<WalletLogMapper, WalletLog> implements WalletLogService { @Override public IPage<WalletLog> depositLogPage(PageVO page, DepositQueryVO depositQueryVO) {<FILL_FUNCTION_BODY>} }
//构建查询条件 QueryWrapper<WalletLog> depositLogQueryWrapper = new QueryWrapper<>(); //会员名称 depositLogQueryWrapper.like(!CharSequenceUtil.isEmpty(depositQueryVO.getMemberName()), "member_name", depositQueryVO.getMemberName()); //会员id depositLogQueryWrapper.eq(!CharSequenceUtil.isEmpty(depositQueryVO.getMemberId()), "member_id", depositQueryVO.getMemberId()); //开始时间和技术时间 if (!CharSequenceUtil.isEmpty(depositQueryVO.getStartDate()) && !CharSequenceUtil.isEmpty(depositQueryVO.getEndDate())) { Date start = cn.hutool.core.date.DateUtil.parse(depositQueryVO.getStartDate()); Date end = cn.hutool.core.date.DateUtil.parse(depositQueryVO.getEndDate()); depositLogQueryWrapper.between("create_time", start, end); } //查询返回数据 return this.page(PageUtil.initPage(page), depositLogQueryWrapper);
71
272
343
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/wechat/serviceimpl/WechatMPMessageServiceImpl.java
WechatMPMessageServiceImpl
init
class WechatMPMessageServiceImpl extends ServiceImpl<WechatMPMessageMapper, WechatMPMessage> implements WechatMPMessageService { @Autowired private WechatAccessTokenUtil wechatAccessTokenUtil; /** * get 获取所有的模版 */ private final String allMsgTpl = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token="; /** * 获取keyid */ private final String keywords = "https://api.weixin.qq.com/wxaapi/newtmpl/getpubtemplatekeywords?access_token="; /** * post 删除模版 添加模版 获取模版id */ private final String delMsgTpl = "https://api.weixin.qq.com/wxaapi/newtmpl/deltemplate?access_token="; /** * post 添加模版 */ private final String addTpl = "https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token="; @Override public void init() {<FILL_FUNCTION_BODY>} public List<WechatMPMessageData> initData() { List<WechatMPMessageData> msg = new ArrayList<>(); //支付提醒 List<WechatMessageItemEnums> PAIDkeyWord = new ArrayList<>(); PAIDkeyWord.add(WechatMessageItemEnums.ORDER_SN); PAIDkeyWord.add(WechatMessageItemEnums.MEMBER_NAME); PAIDkeyWord.add(WechatMessageItemEnums.PRICE); PAIDkeyWord.add(WechatMessageItemEnums.GOODS_INFO); msg.add(new WechatMPMessageData( "订单支付成功,准备发货", "487", PAIDkeyWord, OrderStatusEnum.UNDELIVERED)); //发货提醒 List<WechatMessageItemEnums> deliverdKeyWord = new ArrayList<>(); deliverdKeyWord.add(WechatMessageItemEnums.ORDER_SN); deliverdKeyWord.add(WechatMessageItemEnums.GOODS_INFO); deliverdKeyWord.add(WechatMessageItemEnums.LOGISTICS_NAME); deliverdKeyWord.add(WechatMessageItemEnums.LOGISTICS_NO); msg.add(new WechatMPMessageData( "订单发货成功", "374", deliverdKeyWord, OrderStatusEnum.DELIVERED)); //已完成 List<WechatMessageItemEnums> completeKeyWord = new ArrayList<>(); completeKeyWord.add(WechatMessageItemEnums.SHOP_NAME); completeKeyWord.add(WechatMessageItemEnums.GOODS_INFO); msg.add(new WechatMPMessageData( "订单完成", "3606", completeKeyWord, OrderStatusEnum.COMPLETED)); return msg; } }
this.baseMapper.deleteAll(); try { String accessToken = wechatAccessTokenUtil.cgiAccessToken(ClientTypeEnum.WECHAT_MP); //获取已有模版,删除 String context = HttpUtil.get(allMsgTpl + accessToken); log.info("获取全部模版:{}", context); JSONObject jsonObject = new JSONObject(context); WechatMessageUtil.wechatHandler(jsonObject); List<String> oldList = new ArrayList<>(); if (jsonObject.containsKey("data")) { jsonObject.getJSONArray("data").forEach(item -> { oldList.add(JSONUtil.parseObj(item).getStr("priTmplId")); }); } if (oldList.size() != 0) { oldList.forEach(templateId -> { Map<String, Object> params = new HashMap<>(1); params.put("priTmplId", templateId); String message = WechatMessageUtil.wechatHandler(HttpUtil.post(delMsgTpl + accessToken, params)); log.info("删除模版请求:{},删除模版响应:{}", params, message); }); } //加入数据 List<WechatMPMessageData> tmpList = initData(); tmpList.forEach(tplData -> { WechatMPMessage wechatMPMessage = new WechatMPMessage(); Map params = new HashMap<>(16); params.put("tid", tplData.getTid()); //获取微信消息订阅keys String keywordsItems = WechatMessageUtil.wechatHandler(HttpUtil.get(keywords + accessToken, params)); JSONArray jsonArray = new JSONObject(keywordsItems).getJSONArray("data"); List<WechatMessageKeyword> keywordArray = jsonArray.toList(WechatMessageKeyword.class); log.info("keywords:" + keywordArray); //存放约定好的kids List<String> kids = new ArrayList<>(tplData.keyWord.size()); List<String> kidTexts = new ArrayList<>(tplData.keyWord.size()); keywordArray: for (WechatMessageItemEnums enums : tplData.getKeyWord()) { for (String tplKey : enums.getText()) { for (WechatMessageKeyword wechatMessageKeyword : keywordArray) { if (wechatMessageKeyword.getName().equals(tplKey)) { kids.add(wechatMessageKeyword.getKid()); kidTexts.add(wechatMessageKeyword.getRule() + wechatMessageKeyword.getKid()); continue keywordArray; } } } } params = new HashMap<>(4); params.put("tid", tplData.getTid()); params.put("kidList", kids); params.put("sceneDesc", tplData.getSceneDesc()); String content = HttpUtils.doPostWithJson(addTpl + accessToken, params); log.info("添加模版参数:{},添加模版响应:{}", params, content); JSONObject tplContent = new JSONObject(content); WechatMessageUtil.wechatHandler(tplContent); //如果包含模版id则进行操作,否则抛出异常 if (tplContent.containsKey("priTmplId")) { wechatMPMessage.setCode(tplContent.getStr("priTmplId")); } else { throw new ServiceException(ResultCode.WECHAT_MP_MESSAGE_TMPL_ERROR); } wechatMPMessage.setName(tplData.getSceneDesc()); wechatMPMessage.setTemplateId(tplData.getTid()); wechatMPMessage.setKeywords(JSONUtil.toJsonStr(tplData.getKeyWord())); wechatMPMessage.setKeywordsText(JSONUtil.toJsonStr(kidTexts)); wechatMPMessage.setEnable(true); wechatMPMessage.setOrderStatus(tplData.getOrderStatus().name()); this.save(wechatMPMessage); }); } catch (Exception e) { log.error("初始化微信消息异常", e); }
770
1,076
1,846
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/wechat/serviceimpl/WechatMessageServiceImpl.java
WechatMessageServiceImpl
init
class WechatMessageServiceImpl extends ServiceImpl<WechatMessageMapper, WechatMessage> implements WechatMessageService { @Autowired private WechatAccessTokenUtil wechatAccessTokenUtil; /** * 设置行业 */ private final String setIndustry = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token="; /** * get 获取所有的模版 */ private final String allMsgTpl = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token="; /** * post 删除模版 添加模版 获取模版id */ private final String delMsgTpl = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token="; /** * post 添加模版 */ private final String addTpl = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token="; @Override public void init() {<FILL_FUNCTION_BODY>} /** * 初始化数据 * * @return */ private List<WechatMessageData> initData() { List<WechatMessageData> msg = new ArrayList<>(); //新订单消息提示 msg.add(new WechatMessageData( "订单支付成功通知", "订单支付成功通知", "如有问题,请联系在线客服", "OPENTM207498902", WechatMessageItemEnums.MEMBER_NAME.name() + "," + WechatMessageItemEnums.ORDER_SN.name() + "," + WechatMessageItemEnums.PRICE.name() + "," + WechatMessageItemEnums.GOODS_INFO.name(), OrderStatusEnum.UNDELIVERED)); //已发货 msg.add(new WechatMessageData( "订单发货", "您的订单已发货", "如有问题,请联系在线客服", "OPENTM200565259", WechatMessageItemEnums.ORDER_SN.name() + "," + WechatMessageItemEnums.LOGISTICS_NAME.name() + "," + WechatMessageItemEnums.LOGISTICS_NO.name(), OrderStatusEnum.DELIVERED)); //已完成 msg.add(new WechatMessageData( "订单完成", "您的订单已完成,是否有什么想对掌柜说的话呢", "诚邀您来评价,评价还赠送积分哦", "OPENTM416131050", WechatMessageItemEnums.MEMBER_NAME.name() + "," + WechatMessageItemEnums.ORDER_SN.name() + "," + WechatMessageItemEnums.PRICE.name() + "," + WechatMessageItemEnums.GOODS_INFO.name(), OrderStatusEnum.COMPLETED)); return msg; } }
try { this.baseMapper.deleteAll(); //获取token String accessToken = wechatAccessTokenUtil.cgiAccessToken(ClientTypeEnum.H5); //设置行业 Map<String, Object> setIndustryParams = new HashMap<>(16); //互联网/电子商务 setIndustryParams.put("industry_id1", 1); //通信与运营商 setIndustryParams.put("industry_id2", 5); String context = HttpUtils.doPostWithJson(setIndustry + accessToken, setIndustryParams); log.info("设置模版请求{},设置行业响应:{}", setIndustryParams, context); //获取已有模版,删除 context = HttpUtil.get(allMsgTpl + accessToken); JSONObject jsonObject = new JSONObject(context); log.info("获取全部模版:{}", context); WechatMessageUtil.wechatHandler(jsonObject); List<String> oldList = new ArrayList<>(); if (jsonObject.containsKey("template_list")) { jsonObject.getJSONArray("template_list").forEach(item -> { oldList.add(JSONUtil.parseObj(item).getStr("template_id")); }); } /* if (oldList.size() != 0) { oldList.forEach(templateId -> { Map<String, Object> params = new HashMap<>(1); params.put("template_id", templateId); String message = WechatMessageUtil.wechatHandler(HttpUtils.doPostWithJson(delMsgTpl + accessToken, params)); log.info("删除模版请求:{},删除模版响应:{}", params, message); }); }*/ //加入数据 List<WechatMessageData> tmpList = initData(); tmpList.forEach(tplData -> { WechatMessage wechatMessage = new WechatMessage(); Map<String, Object> params = new HashMap<>(1); params.put("template_id_short", tplData.getMsgId()); String message = HttpUtils.doPostWithJson(addTpl + accessToken, params); log.info("添加模版请求:{},添加模版响应:{}", params, message); JSONObject tplContent = new JSONObject(message); WechatMessageUtil.wechatHandler(tplContent); //如果包含模版id则进行操作,否则抛出异常 if (tplContent.containsKey("template_id")) { wechatMessage.setCode(tplContent.getStr("template_id")); } else { throw new ServiceException(ResultCode.WECHAT_MP_MESSAGE_TMPL_ERROR); } wechatMessage.setName(tplData.getName()); wechatMessage.setFirst(tplData.getFirst()); wechatMessage.setRemark(tplData.getRemark()); wechatMessage.setKeywords(tplData.getKeyWord()); wechatMessage.setEnable(true); wechatMessage.setOrderStatus(tplData.getOrderStatus().name()); this.save(wechatMessage); }); } catch (Exception e) { log.error("初始化微信消息异常", e); }
806
848
1,654
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/wechat/util/WechatAccessTokenUtil.java
WechatAccessTokenUtil
cgiAccessToken
class WechatAccessTokenUtil { @Autowired private Cache cache; @Autowired private SettingService settingService; /** * 获取某一平台等cgi token 用于业务调用,例如发送公众号消息 * * @param clientTypeEnum h5 公众号 / wechatMP 微信小程序 * @return */ public String cgiAccessToken(ClientTypeEnum clientTypeEnum) {<FILL_FUNCTION_BODY>} /** * 获取某一平台等cgi token 用于业务调用,例如发送公众号消息 * * @param clientTypeEnum * @return */ public String cgiJsApiTicket(ClientTypeEnum clientTypeEnum) { //缓存一下token String token = cache.getString(CachePrefix.WECHAT_JS_API_TOKEN.getPrefix() + clientTypeEnum.name()); if (token != null) { return token; } String accessToken = this.cgiAccessToken(clientTypeEnum); try { String content = new HttpUtils().get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi"); JSONObject object = new JSONObject(content); String ticket = object.getStr("ticket"); Long expires = object.getLong("expires_in"); cache.put(CachePrefix.WECHAT_JS_API_TOKEN.getPrefix() + clientTypeEnum.name(), ticket, expires); return ticket; } catch (Exception e) { log.error("微信JsApi签名异常", e); throw new ServiceException(ResultCode.WECHAT_JSAPI_SIGN_ERROR); } } /** * 清除 token * @param clientTypeEnum */ public void removeAccessToken(ClientTypeEnum clientTypeEnum) { cache.remove(CachePrefix.WECHAT_CGI_ACCESS_TOKEN.getPrefix() + clientTypeEnum.name()); } }
//h5 和MP 才有获取token的能力 if (clientTypeEnum.equals(ClientTypeEnum.H5) || clientTypeEnum.equals(ClientTypeEnum.WECHAT_MP)) { //缓存一下token String token = cache.getString(CachePrefix.WECHAT_CGI_ACCESS_TOKEN.getPrefix() + clientTypeEnum.name()); if (token != null) { return token; } //获取微信配置 Setting setting = settingService.get(SettingEnum.WECHAT_CONNECT.name()); if (setting == null) { log.error("获取token客户端异常" + clientTypeEnum.name() + ",客户端未配置微信参数,请前往后台=》联合登陆,进行对应微信配置"); return null; } //获取配置,获取对应的配置 WechatConnectSetting wechatConnectSetting = new Gson().fromJson(setting.getSettingValue(), WechatConnectSetting.class); WechatConnectSettingItem item = null; for (WechatConnectSettingItem wechatConnectSettingItem : wechatConnectSetting.getWechatConnectSettingItems()) { if (wechatConnectSettingItem.getClientType().equals(clientTypeEnum.name())) { item = wechatConnectSettingItem; } } //微信h5配置与否 if (item == null) { return null; } //获取token String content = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + item.getAppId() + "&secret=" + item.getAppSecret()); JSONObject object = new JSONObject(content); log.info("token获取【" + clientTypeEnum.name() + "】返回" + object.toString()); String accessToken = object.get("access_token").toString(); cache.put(CachePrefix.WECHAT_CGI_ACCESS_TOKEN.getPrefix() + clientTypeEnum.name(), object.getStr("access_token"), object.getLong("expires_in")); return accessToken; } else { log.error("获取token客户端异常" + clientTypeEnum.name()); return null; }
535
572
1,107
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/wechat/util/WechatMessageData.java
WechatMessageData
createData
class WechatMessageData { /** * 抬头文字 */ private String first; /** * 备注文字 */ private String remark; /** * 消息内容 */ private List<String> messageData; /** * 小程序消息内容 */ private Map<String, String> mpMessageData; /** * kids */ private List<String> kids; /** * 创建data数据 * * @return */ public Map<String, Map<String, String>> createData() {<FILL_FUNCTION_BODY>} /** * 创建data数据 * * @return */ public Map<String, Map<String, String>> createMPData() { LinkedHashMap<String, Map<String, String>> dataMap = new LinkedHashMap<>(); for (String key : mpMessageData.keySet()) { dataMap.put(key, createValue(mpMessageData.get(key))); } return dataMap; } /** * 创建统一格式的map * * @param msg * @return */ private Map<String, String> createValue(String msg) { Map<String, String> map = new HashMap<>(2); map.put("value", msg); return map; } }
Map<String, Map<String, String>> dataMap = new LinkedHashMap<>(); //拼接开头 dataMap.put("first", this.createValue(first)); //拼接关键字 for (int i = 0; i < messageData.size(); i++) { dataMap.put("keyword" + (i + 1), createValue(this.messageData.get(i))); } //拼接备注 dataMap.put("remark", createValue(this.remark)); return dataMap;
367
137
504
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/modules/wechat/util/WechatMpCodeUtil.java
WechatMpCodeUtil
createQrCode
class WechatMpCodeUtil { private static String UN_LIMIT_API = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="; private static String CREATE_QR_CODE = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="; @Autowired private WechatAccessTokenUtil wechatAccessTokenUtil; @Autowired private ShortLinkService shortLinkService; /** * 生成分享二维码 * * @param path 路径 * @return */ public String createQrCode(String path) {<FILL_FUNCTION_BODY>} /** * 生成分享二维码 * * @param page * @param scene * @return */ public String createCode(String page, String scene) { try { //短链接存储 ShortLink shortLink = new ShortLink(); shortLink.setOriginalParams(scene); List<ShortLink> shortLinks = shortLinkService.queryShortLinks(shortLink); if (shortLinks.size() > 0) { shortLink = shortLinks.get(0); } else { shortLink.setOriginalParams(scene); shortLinkService.save(shortLink); shortLink = shortLinkService.queryShortLinks(shortLink).get(0); } String accessToken = wechatAccessTokenUtil.cgiAccessToken(ClientTypeEnum.WECHAT_MP); Map<String, Object> params = new HashMap<>(4); params.put("page", page); params.put("scene", shortLink.getId()); params.put("width", "280"); //======================================================================// //执行URL Post调用 //======================================================================// CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(UN_LIMIT_API + accessToken); httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json"); //必须是json模式的 post String body = JSON.toJSONString(params); StringEntity entity = new StringEntity(body); entity.setContentType("image/png"); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); //======================================================================// //处理HTTP返回结果 //======================================================================// InputStream contentStream = httpEntity.getContent(); byte[] bytes = toByteArray(contentStream); contentStream.read(bytes); //返回内容 return Base64.getEncoder().encodeToString(bytes); } catch (Exception e) { log.error("生成二维码错误:", e); throw new ServiceException(ResultCode.WECHAT_QRCODE_ERROR); } } /** * @param input * @return * @throws IOException */ @SneakyThrows public static byte[] toByteArray(InputStream input) { ByteArrayOutputStream output = new ByteArrayOutputStream(); copy(input, output); return output.toByteArray(); } /** * @param input * @param output * @return * @throws IOException */ public static int copy(InputStream input, OutputStream output) throws IOException { long count = copyLarge(input, output); if (count > 2147483647L) { return -1; } return (int) count; } /** * @param input * @param output * @return * @throws IOException */ public static long copyLarge(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[4096]; long count = 0L; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } }
try { String accessToken = wechatAccessTokenUtil.cgiAccessToken(ClientTypeEnum.WECHAT_MP); Map<String, String> params = new HashMap<>(2); params.put("path", path); params.put("width", "280"); //======================================================================// //执行URL Post调用 //======================================================================// CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(CREATE_QR_CODE + accessToken); httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json"); //必须是json模式的 post String body = JSON.toJSONString(params); StringEntity entity = new StringEntity(body); entity.setContentType("image/png"); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); //======================================================================// //处理HTTP返回结果 //======================================================================// InputStream contentStream = httpEntity.getContent(); byte[] bytes = toByteArray(contentStream); contentStream.read(bytes); //返回内容 return Base64.getEncoder().encodeToString(bytes); } catch (Exception e) { log.error("生成二维码错误:", e); throw new ServiceException(ResultCode.WECHAT_QRCODE_ERROR); }
1,060
364
1,424
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/mybatis/heath/DataSourceHealthConfig.java
DataSourceHealthConfig
createIndicator
class DataSourceHealthConfig extends DataSourceHealthContributorAutoConfiguration { @Value("${spring.datasource.dbcp2.validation-query:select 1}") private String defaultQuery; public DataSourceHealthConfig(Map<String, DataSource> dataSources, ObjectProvider<DataSourcePoolMetadataProvider> metadataProviders) { super(dataSources, metadataProviders); } @Override protected AbstractHealthIndicator createIndicator(DataSource source) {<FILL_FUNCTION_BODY>} }
DataSourceHealthIndicator indicator = (DataSourceHealthIndicator) super.createIndicator(source); if (!StringUtils.hasText(indicator.getQuery())) { indicator.setQuery(defaultQuery); } return indicator;
137
65
202
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/mybatis/mybatisplus/MyMetaObjectHandler.java
MyMetaObjectHandler
insertFill
class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) {<FILL_FUNCTION_BODY>} @Override public void updateFill(MetaObject metaObject) { AuthUser authUser = UserContext.getCurrentUser(); if (authUser != null) { this.setFieldValByName("updateBy", authUser.getUsername(), metaObject); } this.setFieldValByName("updateTime", new Date(), metaObject); } }
AuthUser authUser = UserContext.getCurrentUser(); if (authUser != null) { this.setFieldValByName("createBy", authUser.getUsername(), metaObject); } else { this.setFieldValByName("createBy", "SYSTEM", metaObject); } //有创建时间字段,切字段值为空 if (metaObject.hasGetter("createTime")) { this.setFieldValByName("createTime", new Date(), metaObject); } //有值,则写入 if (metaObject.hasGetter("deleteFlag")) { this.setFieldValByName("deleteFlag", false, metaObject); } if (metaObject.hasGetter("id")) { //如果已经配置id,则不再写入 if (metaObject.getValue("id") == null) { this.setFieldValByName("id", String.valueOf(SnowFlake.getId()), metaObject); } }
136
251
387
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/mybatis/mybatisplus/MybatisPlusConfig.java
MybatisPlusConfig
mybatisPlusInterceptor
class MybatisPlusConfig { /** * 分页插件,自动识别数据库类型 */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>} }
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; //阻断解析器,测试环境使用 // PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); // // List<ISqlParser> sqlParserList = new ArrayList<>(); // //攻击 SQL 阻断解析器、加入解析链 // sqlParserList.add(new BlockAttackSqlParser()); // paginationInterceptor.setSqlParserList(sqlParserList); // return paginationInterceptor;
65
175
240
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/mybatis/mybatisplus/external/SpiceSqlInjector.java
SpiceSqlInjector
getMethodList
class SpiceSqlInjector extends DefaultSqlInjector { /** * 如果只需增加方法,保留mybatis plus自带方法, * 可以先获取super.getMethodList(),再添加add */ @Override public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {<FILL_FUNCTION_BODY>} }
// 注意:此SQL注入器继承了DefaultSqlInjector(默认注入器),调用了DefaultSqlInjector的getMethodList方法,保留了mybatis-plus的自带方法 List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo); // 注入InsertBatchSomeColumn // 在!t.isLogicDelete()表示不要逻辑删除字段,!"update_time".equals(t.getColumn())表示不要字段名为 update_time 的字段,不对进行操作 // methodList.add(new InsertBatchSomeColumn(t -> !t.isLogicDelete() && !"update_time".equals(t.getColumn()))); // 要逻辑删除 t.isLogicDelete() 默认不要 methodList.add(new InsertBatchSomeColumn(t -> !t.isLogicDelete())); methodList.add(new InsertIgnoreBatchAllColumn("insertIgnoreBatchAllColumn")); return methodList;
102
251
353
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/mybatis/sharding/CreateTimeShardingDatabaseAlgorithm.java
CreateTimeShardingDatabaseAlgorithm
doSharding
class CreateTimeShardingDatabaseAlgorithm implements PreciseShardingAlgorithm<Long>, RangeShardingAlgorithm { @Override public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {<FILL_FUNCTION_BODY>} @Override public Collection<String> doSharding(Collection collection, RangeShardingValue rangeShardingValue) { Collection<String> collect = new ArrayList<>(); Range<Integer> valueRange = rangeShardingValue.getValueRange(); //开始年份结束年份 String start = DateUtil.toString(valueRange.lowerEndpoint().longValue(), "yyyy"); String end = DateUtil.toString(valueRange.upperEndpoint().longValue(), "yyyy"); //循环增加区间的查询条件 for (Integer i = Integer.valueOf(start); i <= Integer.valueOf(end); i++) { collect.add("data" + i); } return collect; } }
Long createTime = preciseShardingValue.getValue(); String value = DateUtil.toString(createTime, "yyyy"); //data2019,data2020 return "data" + value;
247
56
303
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/mybatis/sharding/CreateTimeShardingTableAlgorithm.java
CreateTimeShardingTableAlgorithm
doSharding
class CreateTimeShardingTableAlgorithm implements PreciseShardingAlgorithm<Long>, RangeShardingAlgorithm { @Override public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {<FILL_FUNCTION_BODY>} @Override public Collection<String> doSharding(Collection collection, RangeShardingValue rangeShardingValue) { Collection<String> collect = new ArrayList<>(); Range<Integer> valueRange = rangeShardingValue.getValueRange(); Integer startMonth = Convert.toInt(DateUtil.toString(valueRange.lowerEndpoint().longValue(), "MM")); Integer endMonth = Convert.toInt(DateUtil.toString(valueRange.upperEndpoint().longValue(), "MM")); Integer startYear = Convert.toInt(DateUtil.toString(valueRange.lowerEndpoint().longValue(), "yyyy")); Integer endYear = Convert.toInt(DateUtil.toString(valueRange.upperEndpoint().longValue(), "yyyy")); //如果是同一年查询 //2020-1~2020-2 if (startYear.equals(endYear)) { for (Integer i = startYear; i <= endYear; i++) { for (Integer j = startMonth; j <= endMonth; j++) { collect.add("li_order_" + i + "_" + j); } } } //2020-1~2021-2 else { for (Integer i = startYear; i <= endYear; i++) { //如果是第一年 if (i.equals(startYear)) { //计算从 开始月份 到 今年到12月 for (Integer j = startMonth; j <= 12; j++) { collect.add("li_order_" + i + "_" + j); } } //如果是最后一年 else if (i.equals(endYear)) { //计算从 1月 到 最后一年结束月份 for (Integer j = 1; j <= endMonth; j++) { collect.add("li_order_" + i + "_" + j); } } //中间年份处理 else { //中间年份,每个月都要进行查询处理 for (Integer j = 1; j <= 12; j++) { collect.add("li_order_" + i + "_" + j); } } } } return collect; } }
Long createTime = preciseShardingValue.getValue(); String monthValue = DateUtil.toString(createTime, "MM"); String yearValue = DateUtil.toString(createTime, "yyyy"); Integer month = Integer.valueOf(monthValue); Integer year = Integer.valueOf(yearValue); //li_order_1,li_order_2~ return "li_order_" + year + "_" + month;
624
108
732
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/mybatis/sharding/CreateTimeShardingTableAlgorithmBak.java
CreateTimeShardingTableAlgorithmBak
doSharding
class CreateTimeShardingTableAlgorithmBak implements PreciseShardingAlgorithm<Long>, RangeShardingAlgorithm { @Override public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {<FILL_FUNCTION_BODY>} @Override public Collection<String> doSharding(Collection collection, RangeShardingValue rangeShardingValue) { Collection<String> collect = new ArrayList<>(); //因为考虑到 假设2019-05~2020-05 //这快是没办法处理的,因为分库分表之后,每个库都要进行查询,如果操作为,1-4月,那么2020年数据查询正确了,可是2019年到5-12月数据就查询不到了 //这里需要做一些性能的浪费,现在看来是没办法处理到 for (Integer i = 1; i <= 12; i++) { collect.add("li_order_" + i); } return collect; } }
Long createTime = preciseShardingValue.getValue(); String value = DateUtil.toString(createTime, "MM"); Integer month = Integer.valueOf(value); //li_order_1,li_order_2~ return "li_order_" + month;
268
71
339
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/mybatis/util/PageUtil.java
PageUtil
listToPage
class PageUtil { //有order by 注入风险,限制长度 static final Integer orderByLengthLimit = 20; /** * Mybatis-Plus分页封装 * * @param page 分页VO * @param <T> 范型 * @return 分页响应 */ public static <T> Page<T> initPage(PageVO page) { int pageNumber = page.getPageNumber(); int pageSize = page.getPageSize(); String sort = page.getSort(); String order = page.getOrder(); if (pageNumber < 1) { pageNumber = 1; } if (pageSize < 1) { pageSize = 10; } if (pageSize > 100) { pageSize = 100; } Page<T> p = new Page<>(pageNumber, pageSize); if (CharSequenceUtil.isNotBlank(sort)) { if (sort.length() > orderByLengthLimit || SqlFilter.hit(sort)) { log.error("排序字段长度超过限制或包含sql关键字,请关注:{}", sort); return p; } boolean isAsc = false; if (!CharSequenceUtil.isBlank(order)) { if ("desc".equals(order.toLowerCase())) { isAsc = false; } else if ("asc".equals(order.toLowerCase())) { isAsc = true; } } if (isAsc) { p.addOrder(OrderItem.asc(sort)); } else { p.addOrder(OrderItem.desc(sort)); } } return p; } private void orderByHandler() { } /** * 生成条件搜索 全对象对比 equals * 如果需要like 需要另行处理 * * @param object 对象(根据对象构建查询条件) * @return 查询wrapper */ public static <T> QueryWrapper<T> initWrapper(Object object) { return initWrapper(object, null); } /** * 生成条件搜索 全对象对比 * * @param object 对象 * @param searchVo 查询条件 * @return 查询wrapper */ public static <T> QueryWrapper<T> initWrapper(Object object, SearchVO searchVo) { QueryWrapper<T> queryWrapper = new QueryWrapper<>(); //创建时间区间判定 if (searchVo != null && CharSequenceUtil.isNotBlank(searchVo.getStartDate()) && CharSequenceUtil.isNotBlank(searchVo.getEndDate())) { Date start = DateUtil.parse(searchVo.getStartDate()); Date end = DateUtil.parse(searchVo.getEndDate()); queryWrapper.between("create_time", start, DateUtil.endOfDay(end)); } if (object != null) { String[] fieldNames = BeanUtil.getFiledName(object); //遍历所有属性 for (int j = 0; j < fieldNames.length; j++) { //获取属性的名字 String key = fieldNames[j]; //获取值 Object value = BeanUtil.getFieldValueByName(key, object); //如果值不为空才做查询处理 if (value != null && !"".equals(value)) { //字段数据库中,驼峰转下划线 queryWrapper.eq(StringUtils.camel2Underline(key), value); } } } return queryWrapper; } /** * List 手动分页 * * @param page 分页对象 * @param list 分页集合 * @return 范型结果 */ public static <T> List<T> listToPage(PageVO page, List<T> list) {<FILL_FUNCTION_BODY>} /** * 转换分页类型 * * @param originPage 原分页 * @param records 新分页数据 * @param <T> 新类型 * @return 新类型分页 */ public static <T> IPage<T> convertPage(IPage originPage, List<T> records) { IPage<T> resultPage = new Page<>(); if (originPage != null) { resultPage.setCurrent(originPage.getCurrent()); resultPage.setPages(originPage.getPages()); resultPage.setTotal(originPage.getTotal()); resultPage.setSize(originPage.getSize()); resultPage.setRecords(records); } return resultPage; } }
int pageNumber = page.getPageNumber() - 1; int pageSize = page.getPageSize(); if (pageNumber < 0) { pageNumber = 0; } if (pageSize < 1) { pageSize = 10; } if (pageSize > 100) { pageSize = 100; } int fromIndex = pageNumber * pageSize; int toIndex = pageNumber * pageSize + pageSize; if (fromIndex > list.size()) { return new ArrayList<>(); } else if (toIndex >= list.size()) { return list.subList(fromIndex, list.size()); } else { return list.subList(fromIndex, toIndex); }
1,234
197
1,431
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/trigger/delay/AbstractDelayQueueMachineFactory.java
AbstractDelayQueueMachineFactory
addJob
class AbstractDelayQueueMachineFactory { @Autowired private Cache cache; /** * 插入任务id * * @param jobId 任务id(队列内唯一) * @param triggerTime 执行时间 时间戳(毫秒) * @return 是否插入成功 */ public boolean addJob(String jobId, Long triggerTime) {<FILL_FUNCTION_BODY>} /** * 要实现延时队列的名字 * @return 延时队列的名字 */ public abstract String setDelayQueueName(); }
//redis 中排序时间 long delaySeconds = triggerTime / 1000; //增加延时任务 参数依次为:队列名称、执行时间、任务id boolean result = cache.zAdd(setDelayQueueName(), delaySeconds, jobId); log.info("增加延时任务, 缓存key {}, 执行时间 {},任务id {}", setDelayQueueName(), DateUtil.toString(triggerTime), jobId); return result;
159
122
281
<no_super_class>
lilishop_lilishop
lilishop/framework/src/main/java/cn/lili/trigger/interfaces/impl/RocketmqTimerTrigger.java
RocketmqTimerTrigger
addDelay
class RocketmqTimerTrigger implements TimeTrigger { @Autowired private RocketMQTemplate rocketMQTemplate; @Autowired private Cache<Integer> cache; @Autowired private PromotionDelayQueue promotionDelayQueue; @Override public void addDelay(TimeTriggerMsg timeTriggerMsg) {<FILL_FUNCTION_BODY>} @Override public void execute(TimeTriggerMsg timeTriggerMsg) { this.addExecute(timeTriggerMsg.getTriggerExecutor(), timeTriggerMsg.getParam(), timeTriggerMsg.getTriggerTime(), timeTriggerMsg.getUniqueKey(), timeTriggerMsg.getTopic() ); } /** * 将任务添加到mq,mq异步队列执行。 * <p> * 本系统中redis相当于延时任务吊起机制,而mq才是实际的业务消费,执行任务的存在 * * @param executorName 执行器beanId * @param param 执行参数 * @param triggerTime 执行时间 时间戳 秒为单位 * @param uniqueKey 如果是一个 需要有 修改/取消 延时任务功能的延时任务,<br/> * 请填写此参数,作为后续删除,修改做为唯一凭证 <br/> * 建议参数为:COUPON_{ACTIVITY_ID} 例如 coupon_123<br/> * 业务内全局唯一 * @param topic rocketmq topic */ private void addExecute(String executorName, Object param, Long triggerTime, String uniqueKey, String topic) { TimeTriggerMsg timeTriggerMsg = new TimeTriggerMsg(executorName, triggerTime, param, uniqueKey, topic); Message<TimeTriggerMsg> message = MessageBuilder.withPayload(timeTriggerMsg).build(); log.info("延时任务发送信息:{}", message); this.rocketMQTemplate.asyncSend(topic, message, RocketmqSendCallbackBuilder.commonCallback()); } @Override public void edit(String executorName, Object param, Long oldTriggerTime, Long triggerTime, String uniqueKey, int delayTime, String topic) { this.delete(executorName, oldTriggerTime, uniqueKey, topic); this.addDelay(new TimeTriggerMsg(executorName, triggerTime, param, uniqueKey, topic)); } @Override public void delete(String executorName, Long triggerTime, String uniqueKey, String topic) { String generateKey = DelayQueueTools.generateKey(executorName, triggerTime, uniqueKey); log.info("删除延时任务{}", generateKey); this.cache.remove(generateKey); } }
//执行器唯一key String uniqueKey = timeTriggerMsg.getUniqueKey(); if (StringUtils.isEmpty(uniqueKey)) { uniqueKey = StringUtils.getRandStr(10); } //执行任务key String generateKey = DelayQueueTools.generateKey(timeTriggerMsg.getTriggerExecutor(), timeTriggerMsg.getTriggerTime(), uniqueKey); this.cache.put(generateKey, 1); //设置延时任务 if (Boolean.TRUE.equals(promotionDelayQueue.addJob(JSONUtil.toJsonStr(timeTriggerMsg), timeTriggerMsg.getTriggerTime()))) { log.info("延时任务标识: {}", generateKey); log.info("定时执行在【" + DateUtil.toString(timeTriggerMsg.getTriggerTime(), "yyyy-MM-dd HH:mm:ss") + "】,消费【" + timeTriggerMsg.getParam().toString() + "】"); } else { log.error("延时任务添加失败:{}", timeTriggerMsg); }
720
273
993
<no_super_class>
lilishop_lilishop
lilishop/im-api/src/main/java/cn/lili/controller/im/ImMessageController.java
ImMessageController
save
class ImMessageController { private final ImMessageService imMessageService; @GetMapping(value = "/{id}") @ApiOperation(value = "查看Im消息详情") public ResultMessage<ImMessage> get(@PathVariable String id) { ImMessage imMessage = imMessageService.getById(id); return ResultUtil.data(imMessage); } @GetMapping @ApiOperation(value = "分页获取Im消息") public ResultMessage<List<ImMessage>> historyMessage(MessageQueryParams messageQueryParams) { List<ImMessage> data = imMessageService.getList(messageQueryParams); return ResultUtil.data(data); } @PostMapping @ApiOperation(value = "新增Im消息") public ResultMessage<ImMessage> save(ImMessage imMessage) {<FILL_FUNCTION_BODY>} @PutMapping("/{id}") @ApiOperation(value = "更新Im消息") public ResultMessage<ImMessage> update(@PathVariable String id, ImMessage imMessage) { if (imMessageService.updateById(imMessage)) { return ResultUtil.data(imMessage); } throw new ServiceException(ResultCode.IM_MESSAGE_EDIT_ERROR); } @DeleteMapping(value = "/{ids}") @ApiOperation(value = "删除Im消息") public ResultMessage<Object> delAllByIds(@PathVariable List ids) { imMessageService.removeByIds(ids); return ResultUtil.success(); } @GetMapping(value = "/newMessage") @ApiOperation(value = "查看是否有新消息") public ResultMessage<Boolean> hasNewMessage(String accessToken) { return ResultUtil.data(imMessageService.hasNewMessage(accessToken)); } @GetMapping(value = "/unreadMessage") @ApiOperation(value = "获取所有未读消息") public ResultMessage<Long> getUnreadMessageCount() { return ResultUtil.data(imMessageService.unreadMessageCount()); } @PutMapping(value = "/clean/unred") @ApiOperation(value = "清除所有未读消息") public ResultMessage<Object> cleanUnreadMessage() { imMessageService.cleanUnreadMessage(); return ResultUtil.success(); } }
if (imMessageService.save(imMessage)) { return ResultUtil.data(imMessage); } throw new ServiceException(ResultCode.IM_MESSAGE_ADD_ERROR);
588
51
639
<no_super_class>
lilishop_lilishop
lilishop/im-api/src/main/java/cn/lili/controller/im/WebSocketServer.java
WebSocketServer
operation
class WebSocketServer { /** * 消息服务 */ private final ImMessageService imMessageService; private final ImTalkService imTalkService; /** * 在线人数 * PS 注意,只能单节点,如果多节点部署需要自行寻找方案 */ private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>(); /** * 建立连接 * * @param session */ @OnOpen public void onOpen(@PathParam("accessToken") String accessToken, Session session) { AuthUser authUser = UserContext.getAuthUser(accessToken); String sessionId = UserEnums.STORE.equals(authUser.getRole()) ? authUser.getStoreId() : authUser.getId(); //如果已有会话,则进行下线提醒。 if (sessionPools.containsKey(sessionId)) { log.info("用户重复登陆,旧用户下线"); Session oldSession = sessionPools.get(sessionId); sendMessage(oldSession, MessageVO.builder().messageResultType(MessageResultType.OFFLINE).result("用户异地登陆").build()); try { oldSession.close(); } catch (Exception e) { e.printStackTrace(); } } sessionPools.put(sessionId, session); } /** * 关闭连接 */ @OnClose public void onClose(@PathParam("accessToken") String accessToken) { AuthUser authUser = UserContext.getAuthUser(accessToken); log.info("用户断开断开连接:{}", JSONUtil.toJsonStr(authUser)); sessionPools.remove(authUser); } /** * 发送消息 * * @param msg * @throws IOException */ @OnMessage public void onMessage(@PathParam("accessToken") String accessToken, String msg) { log.info("发送消息:{}", msg); MessageOperation messageOperation = JSON.parseObject(msg, MessageOperation.class); operation(accessToken, messageOperation); } /** * IM操作 * * @param accessToken * @param messageOperation */ private void operation(String accessToken, MessageOperation messageOperation) {<FILL_FUNCTION_BODY>} /** * 发送消息 * * @param sessionId sessionId * @param message 消息对象 */ private void sendMessage(String sessionId, MessageVO message) { Session session = sessionPools.get(sessionId); sendMessage(session, message); } /** * 发送消息 * * @param session 会话 * @param message 消息对象 */ private void sendMessage(Session session, MessageVO message) { if (session != null) { try { session.getBasicRemote().sendText(JSON.toJSONString(message, true)); } catch (Exception e) { e.printStackTrace(); } } } /** * socket exception * * @param session * @param throwable */ @OnError public void onError(Session session, Throwable throwable) { log.error("socket异常: {}", session.getId(), throwable); } }
AuthUser authUser = UserContext.getAuthUser(accessToken); switch (messageOperation.getOperationType()) { case PING: break; case MESSAGE: //保存消息 ImMessage imMessage = new ImMessage(messageOperation); imMessageService.save(imMessage); //修改最后消息信息 imTalkService.update(new LambdaUpdateWrapper<ImTalk>().eq(ImTalk::getId, messageOperation.getTalkId()).set(ImTalk::getLastTalkMessage, messageOperation.getContext()) .set(ImTalk::getLastTalkTime, imMessage.getCreateTime()) .set(ImTalk::getLastMessageType, imMessage.getMessageType())); //发送消息 sendMessage(messageOperation.getTo(), new MessageVO(MessageResultType.MESSAGE, imMessage)); break; case READ: if (!StringUtils.isEmpty(messageOperation.getContext())) { imMessageService.read(messageOperation.getTalkId(), accessToken); } break; case UNREAD: sendMessage(authUser.getId(), new MessageVO(MessageResultType.UN_READ, imMessageService.unReadMessages(accessToken))); break; case HISTORY: sendMessage(authUser.getId(), new MessageVO(MessageResultType.HISTORY, imMessageService.historyMessage(accessToken, messageOperation.getTo()))); break; default: break; }
868
372
1,240
<no_super_class>
lilishop_lilishop
lilishop/im-api/src/main/java/cn/lili/controller/security/ImSecurityConfig.java
ImSecurityConfig
configure
class ImSecurityConfig extends WebSecurityConfigurerAdapter { /** * spring security -》 权限不足处理 */ @Autowired private CorsConfigurationSource corsConfigurationSource; @Override protected void configure(HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>} }
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http .authorizeRequests(); registry .and() //禁止网页iframe .headers().frameOptions().disable() .and() .authorizeRequests() //任何请求 .anyRequest() //需要身份认证 .permitAll() .and() //允许跨域 .cors().configurationSource(corsConfigurationSource).and() //关闭跨站请求防护 .csrf().disable();
84
143
227
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/distribution/DistributionManagerController.java
DistributionManagerController
retreat
class DistributionManagerController { @Autowired private DistributionService distributionService; @ApiOperation(value = "分页获取") @GetMapping(value = "/getByPage") public ResultMessage<IPage<Distribution>> getByPage(DistributionSearchParams distributionSearchParams, PageVO page) { return ResultUtil.data(distributionService.distributionPage(distributionSearchParams, page)); } @PreventDuplicateSubmissions @ApiOperation(value = "清退分销商") @PutMapping(value = "/retreat/{id}") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "分销商id", required = true, paramType = "path", dataType = "String") }) public ResultMessage<Object> retreat(@PathVariable String id) {<FILL_FUNCTION_BODY>} @PreventDuplicateSubmissions @ApiOperation(value = "恢复分销商") @PutMapping(value = "/resume/{id}") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "分销商id", required = true, paramType = "path", dataType = "String") }) public ResultMessage<Object> resume(@PathVariable String id) { if (distributionService.resume(id)) { return ResultUtil.success(); } else { throw new ServiceException(ResultCode.DISTRIBUTION_RETREAT_ERROR); } } @PreventDuplicateSubmissions @ApiOperation(value = "审核分销商") @PutMapping(value = "/audit/{id}") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "分销商id", required = true, paramType = "path", dataType = "String"), @ApiImplicitParam(name = "status", value = "审核结果,PASS 通过 REFUSE 拒绝", required = true, paramType = "query", dataType = "String") }) public ResultMessage<Object> audit(@NotNull @PathVariable String id, @NotNull String status) { if (distributionService.audit(id, status)) { return ResultUtil.success(); } else { throw new ServiceException(ResultCode.DISTRIBUTION_AUDIT_ERROR); } } }
if (distributionService.retreat(id)) { return ResultUtil.success(); } else { throw new ServiceException(ResultCode.DISTRIBUTION_RETREAT_ERROR); }
595
56
651
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/goods/CategoryManagerController.java
CategoryManagerController
disable
class CategoryManagerController { /** * 分类 */ @Autowired private CategoryService categoryService; /** * 商品 */ @Autowired private GoodsService goodsService; @ApiOperation(value = "查询某分类下的全部子分类列表") @ApiImplicitParam(name = "parentId", value = "父id,顶级为0", required = true, dataType = "String", paramType = "path") @GetMapping(value = "/{parentId}/all-children") public ResultMessage<List<Category>> list(@PathVariable String parentId) { return ResultUtil.data(this.categoryService.dbList(parentId)); } @ApiOperation(value = "查询全部分类列表") @GetMapping(value = "/allChildren") public ResultMessage<List<CategoryVO>> list(CategorySearchParams categorySearchParams) { return ResultUtil.data(this.categoryService.listAllChildren(categorySearchParams)); } @PostMapping @DemoSite @ApiOperation(value = "添加商品分类") public ResultMessage<Category> saveCategory(@Valid Category category) { //非顶级分类 if (category.getParentId() != null && !"0".equals(category.getParentId())) { Category parent = categoryService.getById(category.getParentId()); if (parent == null) { throw new ServiceException(ResultCode.CATEGORY_PARENT_NOT_EXIST); } if (category.getLevel() >= 4) { throw new ServiceException(ResultCode.CATEGORY_BEYOND_THREE); } } if (categoryService.saveCategory(category)) { return ResultUtil.data(category); } throw new ServiceException(ResultCode.CATEGORY_SAVE_ERROR); } @PutMapping @DemoSite @ApiOperation(value = "修改商品分类") public ResultMessage<Category> updateCategory(@Valid CategoryVO category) { Category catTemp = categoryService.getById(category.getId()); if (catTemp == null) { throw new ServiceException(ResultCode.CATEGORY_NOT_EXIST); } categoryService.updateCategory(category); return ResultUtil.data(category); } @DeleteMapping(value = "/{id}") @DemoSite @ApiImplicitParam(name = "id", value = "分类ID", required = true, paramType = "path", dataType = "String") @ApiOperation(value = "通过id删除分类") public ResultMessage<Category> delAllByIds(@NotNull @PathVariable String id) { Category category = new Category(); category.setParentId(id); List<Category> list = categoryService.findByAllBySortOrder(category); if (list != null && !list.isEmpty()) { throw new ServiceException(ResultCode.CATEGORY_HAS_CHILDREN); } //查询某商品分类的商品数量 long count = goodsService.getGoodsCountByCategory(id); if (count > 0) { throw new ServiceException(ResultCode.CATEGORY_HAS_GOODS); } categoryService.delete(id); return ResultUtil.success(); } @PutMapping(value = "/disable/{id}") @ApiImplicitParams({ @ApiImplicitParam(name = "goodsId", value = "分类ID", required = true, paramType = "path", dataType = "String") }) @DemoSite @ApiOperation(value = "后台 禁用/启用 分类") public ResultMessage<Object> disable(@PathVariable String id, @RequestParam Boolean enableOperations) {<FILL_FUNCTION_BODY>} }
Category category = categoryService.getById(id); if (category == null) { throw new ServiceException(ResultCode.CATEGORY_NOT_EXIST); } categoryService.updateCategoryStatus(id, enableOperations); return ResultUtil.success();
969
72
1,041
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/goods/CategoryParameterGroupManagerController.java
CategoryParameterGroupManagerController
saveOrUpdate
class CategoryParameterGroupManagerController { /** * 参数组 */ @Autowired private ParametersService parametersService; /** * 分类参数 */ @Autowired private CategoryParameterGroupService categoryParameterGroupService; @ApiOperation(value = "查询某分类下绑定的参数信息") @GetMapping(value = "/{categoryId}") @ApiImplicitParam(value = "分类id", required = true, dataType = "String", paramType = "path") public ResultMessage<List<ParameterGroupVO>> getCategoryParam(@PathVariable String categoryId) { return ResultUtil.data(categoryParameterGroupService.getCategoryParams(categoryId)); } @ApiOperation(value = "保存数据") @PostMapping public ResultMessage<CategoryParameterGroup> saveOrUpdate(@Validated CategoryParameterGroup categoryParameterGroup) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "更新数据") @PutMapping public ResultMessage<CategoryParameterGroup> update(@Validated CategoryParameterGroup categoryParameterGroup) { if (categoryParameterGroupService.updateById(categoryParameterGroup)) { return ResultUtil.data(categoryParameterGroup); } throw new ServiceException(ResultCode.CATEGORY_PARAMETER_UPDATE_ERROR); } @ApiOperation(value = "通过id删除参数组") @ApiImplicitParam(name = "id", value = "参数组ID", required = true, dataType = "String", paramType = "path") @DeleteMapping(value = "/{id}") public ResultMessage<Object> delAllByIds(@PathVariable String id) { //删除参数 parametersService.remove(new QueryWrapper<Parameters>().eq("group_id", id)); //删除参数组 categoryParameterGroupService.removeById(id); return ResultUtil.success(); } }
if (categoryParameterGroupService.save(categoryParameterGroup)) { return ResultUtil.data(categoryParameterGroup); } throw new ServiceException(ResultCode.CATEGORY_PARAMETER_SAVE_ERROR);
478
59
537
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/goods/CategorySpecificationManagerController.java
CategorySpecificationManagerController
saveCategoryBrand
class CategorySpecificationManagerController { /** * 分类规格 */ @Autowired private CategorySpecificationService categorySpecificationService; /** * 规格 */ @Autowired private SpecificationService specificationService; @ApiOperation(value = "查询某分类下绑定的规格信息") @GetMapping(value = "/{categoryId}") @ApiImplicitParam(name = "categoryId", value = "分类id", required = true, dataType = "String", paramType = "path") public List<Specification> getCategorySpec(@PathVariable String categoryId) { return categorySpecificationService.getCategorySpecList(categoryId); } @ApiOperation(value = "查询某分类下绑定的规格信息,商品操作使用") @GetMapping(value = "/goods/{categoryId}") @ApiImplicitParam(name = "categoryId", value = "分类id", required = true, dataType = "String", paramType = "path") public List<Specification> getSpec(@PathVariable String categoryId) { return specificationService.list(); } @ApiOperation(value = "保存某分类下绑定的规格信息") @PostMapping(value = "/{categoryId}") @ApiImplicitParams({ @ApiImplicitParam(name = "categoryId", value = "分类id", required = true, paramType = "path", dataType = "String"), @ApiImplicitParam(name = "categorySpecs", value = "规格id数组", required = true, paramType = "query", dataType = "String[]") }) public ResultMessage<String> saveCategoryBrand(@PathVariable String categoryId, @RequestParam String[] categorySpecs) {<FILL_FUNCTION_BODY>} }
//删除分类规格绑定信息 this.categorySpecificationService.remove(new QueryWrapper<CategorySpecification>().eq("category_id", categoryId)); //绑定规格信息 if (categorySpecs != null && categorySpecs.length > 0) { List<CategorySpecification> categorySpecifications = new ArrayList<>(); for (String categorySpec : categorySpecs) { categorySpecifications.add(new CategorySpecification(categoryId, categorySpec)); } categorySpecificationService.saveBatch(categorySpecifications); } return ResultUtil.success();
458
149
607
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/goods/GoodsManagerController.java
GoodsManagerController
auth
class GoodsManagerController { /** * 商品 */ @Autowired private GoodsService goodsService; /** * 规格商品 */ @Autowired private GoodsSkuService goodsSkuService; @ApiOperation(value = "分页获取") @GetMapping(value = "/list") public ResultMessage<IPage<Goods>> getByPage(GoodsSearchParams goodsSearchParams) { return ResultUtil.data(goodsService.queryByParams(goodsSearchParams)); } @ApiOperation(value = "分页获取商品列表") @GetMapping(value = "/sku/list") public ResultMessage<IPage<GoodsSku>> getSkuByPage(GoodsSearchParams goodsSearchParams) { return ResultUtil.data(goodsSkuService.getGoodsSkuByPage(goodsSearchParams)); } @ApiOperation(value = "分页获取待审核商品") @GetMapping(value = "/auth/list") public ResultMessage<IPage<Goods>> getAuthPage(GoodsSearchParams goodsSearchParams) { goodsSearchParams.setAuthFlag(GoodsAuthEnum.TOBEAUDITED.name()); return ResultUtil.data(goodsService.queryByParams(goodsSearchParams)); } @PreventDuplicateSubmissions @ApiOperation(value = "管理员下架商品", notes = "管理员下架商品时使用") @ApiImplicitParams({ @ApiImplicitParam(name = "goodsId", value = "商品ID", required = true, paramType = "query", allowMultiple = true), @ApiImplicitParam(name = "reason", value = "下架理由", required = true, paramType = "query") }) @DemoSite @PutMapping(value = "/{goodsId}/under") public ResultMessage<Object> underGoods(@PathVariable String goodsId, @NotEmpty(message = "下架原因不能为空") @RequestParam String reason) { List<String> goodsIds = Arrays.asList(goodsId.split(",")); if (Boolean.TRUE.equals(goodsService.managerUpdateGoodsMarketAble(goodsIds, GoodsStatusEnum.DOWN, reason))) { return ResultUtil.success(); } throw new ServiceException(ResultCode.GOODS_UNDER_ERROR); } @PreventDuplicateSubmissions @ApiOperation(value = "管理员审核商品", notes = "管理员审核商品") @ApiImplicitParams({ @ApiImplicitParam(name = "goodsIds", value = "商品ID", required = true, paramType = "path", allowMultiple = true, dataType = "int"), @ApiImplicitParam(name = "authFlag", value = "审核结果", required = true, paramType = "query", dataType = "string") }) @PutMapping(value = "{goodsIds}/auth") public ResultMessage<Object> auth(@PathVariable List<String> goodsIds, @RequestParam String authFlag) {<FILL_FUNCTION_BODY>} @PreventDuplicateSubmissions @ApiOperation(value = "管理员上架商品", notes = "管理员上架商品时使用") @PutMapping(value = "/{goodsId}/up") @ApiImplicitParams({ @ApiImplicitParam(name = "goodsId", value = "商品ID", required = true, allowMultiple = true) }) public ResultMessage<Object> unpGoods(@PathVariable List<String> goodsId) { if (Boolean.TRUE.equals(goodsService.updateGoodsMarketAble(goodsId, GoodsStatusEnum.UPPER, ""))) { return ResultUtil.success(); } throw new ServiceException(ResultCode.GOODS_UPPER_ERROR); } @ApiOperation(value = "通过id获取商品详情") @GetMapping(value = "/get/{id}") public ResultMessage<GoodsVO> get(@PathVariable String id) { GoodsVO goods = goodsService.getGoodsVO(id); return ResultUtil.data(goods); } }
//校验商品是否存在 if (goodsService.auditGoods(goodsIds, GoodsAuthEnum.valueOf(authFlag))) { return ResultUtil.success(); } throw new ServiceException(ResultCode.GOODS_AUTH_ERROR);
1,055
70
1,125
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/goods/ParameterManagerController.java
ParameterManagerController
save
class ParameterManagerController { @Autowired private ParametersService parametersService; @ApiOperation(value = "添加参数") @PostMapping public ResultMessage<Parameters> save(@Valid Parameters parameters) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "编辑参数") @PutMapping public ResultMessage<Parameters> update(@Valid Parameters parameters) { if (parametersService.updateParameter(parameters)) { return ResultUtil.data(parameters); } throw new ServiceException(ResultCode.PARAMETER_UPDATE_ERROR); } @ApiOperation(value = "通过id删除参数") @ApiImplicitParam(name = "id", value = "参数ID", required = true, paramType = "path") @DeleteMapping(value = "/{id}") public ResultMessage<Object> delById(@PathVariable String id) { parametersService.removeById(id); return ResultUtil.success(); } }
if (parametersService.save(parameters)) { return ResultUtil.data(parameters); } throw new ServiceException(ResultCode.PARAMETER_SAVE_ERROR);
252
49
301
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/goods/SpecificationManagerController.java
SpecificationManagerController
page
class SpecificationManagerController { @Autowired private SpecificationService specificationService; @GetMapping("/all") @ApiOperation(value = "获取所有可用规格") public ResultMessage<List<Specification>> getAll() { return ResultUtil.data(specificationService.list()); } @GetMapping @ApiOperation(value = "搜索规格") public ResultMessage<Page<Specification>> page(String specName, PageVO page) {<FILL_FUNCTION_BODY>} @PostMapping @ApiOperation(value = "保存规格") public ResultMessage<Object> save(@Valid Specification specification) { specificationService.save(specification); return ResultUtil.success(); } @PutMapping("/{id}") @ApiOperation(value = "更改规格") public ResultMessage<Object> update(@Valid Specification specification, @PathVariable String id) { specification.setId(id); return ResultUtil.data(specificationService.saveOrUpdate(specification)); } @DeleteMapping("/{ids}") @ApiImplicitParam(name = "ids", value = "规格ID", required = true, dataType = "String", allowMultiple = true, paramType = "path") @ApiOperation(value = "批量删除") public ResultMessage<Object> delAllByIds(@PathVariable List<String> ids) { return ResultUtil.data(specificationService.deleteSpecification(ids)); } }
LambdaQueryWrapper<Specification> lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.like(CharSequenceUtil.isNotEmpty(specName), Specification::getSpecName, specName); return ResultUtil.data(specificationService.page(PageUtil.initPage(page), lambdaQueryWrapper));
382
82
464
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/member/MemberGradeManagerController.java
MemberGradeManagerController
daa
class MemberGradeManagerController { @Autowired private MemberGradeService memberGradeService; @ApiOperation(value = "通过id获取会员等级") @ApiImplicitParam(name = "id", value = "会员等级ID", required = true, dataType = "String", paramType = "path") @GetMapping(value = "/get/{id}") public ResultMessage<MemberGrade> get(@PathVariable String id) { return ResultUtil.data(memberGradeService.getById(id)); } @ApiOperation(value = "获取会员等级分页") @GetMapping(value = "/getByPage") public ResultMessage<IPage<MemberGrade>> getByPage(PageVO page) { return ResultUtil.data(memberGradeService.page(PageUtil.initPage(page))); } @ApiOperation(value = "添加会员等级") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "会员等级ID", required = true, paramType = "path") }) @PostMapping(value = "/add") public ResultMessage<Object> daa(@Validated MemberGrade memberGrade) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "修改会员等级") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "会员等级ID", required = true, paramType = "path") }) @PutMapping(value = "/update/{id}") public ResultMessage<Object> update(@PathVariable String id,MemberGrade memberGrade) { if (memberGradeService.updateById(memberGrade)) { return ResultUtil.success(ResultCode.SUCCESS); } throw new ServiceException(ResultCode.ERROR); } @ApiOperation(value = "删除会员等级") @ApiImplicitParam(name = "id", value = "会员等级ID", required = true, dataType = "String", paramType = "path") @DeleteMapping(value = "/delete/{id}") public ResultMessage<IPage<Object>> delete(@PathVariable String id) { if(memberGradeService.getById(id).getIsDefault()){ throw new ServiceException(ResultCode.USER_GRADE_IS_DEFAULT); }else if(memberGradeService.removeById(id)){ return ResultUtil.success(ResultCode.SUCCESS); } throw new ServiceException(ResultCode.ERROR); } }
if (memberGradeService.save(memberGrade)) { return ResultUtil.success(ResultCode.SUCCESS); } throw new ServiceException(ResultCode.ERROR);
639
49
688
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/message/MemberNoticeManagerController.java
MemberNoticeManagerController
readAll
class MemberNoticeManagerController { @Autowired private MemberNoticeService memberNoticeService; @ApiOperation(value = "获取详情") @GetMapping(value = "/{id}") public ResultMessage<MemberNotice> get(@PathVariable String id) { MemberNotice memberNotice = memberNoticeService.getById(id); return ResultUtil.data(memberNotice); } @ApiOperation(value = "分页获取站内信") @GetMapping(value = "/page") public ResultMessage<IPage<MemberNotice>> getByPage( PageVO page) { IPage<MemberNotice> data = memberNoticeService.page(PageUtil.initPage(page)); return ResultUtil.data(data); } @ApiOperation(value = "阅读消息") @PostMapping("/read/{ids}") public ResultMessage<Object> read(@PathVariable List ids) { UpdateWrapper updateWrapper = new UpdateWrapper(); updateWrapper.in("id", ids); updateWrapper.set("is_read", true); memberNoticeService.update(updateWrapper); return ResultUtil.success(); } @ApiOperation(value = "阅读全部") @PostMapping("/read/all") public ResultMessage<Object> readAll() {<FILL_FUNCTION_BODY>} @ApiOperation(value = "批量删除") @DeleteMapping(value = "/{ids}") public ResultMessage<Object> delAllByIds(@PathVariable List ids) { memberNoticeService.removeByIds(ids); return ResultUtil.success(); } @ApiOperation(value = "删除所有") @DeleteMapping public ResultMessage<Object> deleteAll() { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("member_id", UserContext.getCurrentUser().getId()); memberNoticeService.remove(queryWrapper); return ResultUtil.success(); } }
UpdateWrapper updateWrapper = new UpdateWrapper(); updateWrapper.in("member_id", UserContext.getCurrentUser().getId()); updateWrapper.set("is_read", true); memberNoticeService.update(updateWrapper); return ResultUtil.success();
490
66
556
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/order/OrderComplaintManagerController.java
OrderComplaintManagerController
addCommunication
class OrderComplaintManagerController { /** * 交易投诉 */ @Autowired private OrderComplaintService orderComplaintService; /** * 交易投诉沟通 */ @Autowired private OrderComplaintCommunicationService orderComplaintCommunicationService; @ApiOperation(value = "通过id获取") @ApiImplicitParam(name = "id", value = "投诉单ID", required = true, paramType = "path") @GetMapping(value = "/{id}") public ResultMessage<OrderComplaintVO> get(@PathVariable String id) { return ResultUtil.data(orderComplaintService.getOrderComplainById(id)); } @ApiOperation(value = "分页获取") @GetMapping public ResultMessage<IPage<OrderComplaint>> get(OrderComplaintSearchParams searchParams, PageVO pageVO) { return ResultUtil.data(orderComplaintService.getOrderComplainByPage(searchParams, pageVO)); } @ApiOperation(value = "更新数据") @PutMapping public ResultMessage<OrderComplaintVO> update(OrderComplaintVO orderComplainVO) { orderComplaintService.updateOrderComplain(orderComplainVO); return ResultUtil.data(orderComplainVO); } @ApiOperation(value = "添加交易投诉对话") @ApiImplicitParams({ @ApiImplicitParam(name = "complainId", value = "投诉单ID", required = true, paramType = "query"), @ApiImplicitParam(name = "content", value = "内容", required = true, paramType = "query") }) @PostMapping("/communication") public ResultMessage<OrderComplaintCommunicationVO> addCommunication(@RequestParam String complainId, @RequestParam String content) {<FILL_FUNCTION_BODY>} @PreventDuplicateSubmissions @ApiOperation(value = "修改状态") @PutMapping(value = "/status") public ResultMessage<Object> updateStatus(OrderComplaintOperationParams orderComplainVO) { orderComplaintService.updateOrderComplainByStatus(orderComplainVO); return ResultUtil.success(); } @PreventDuplicateSubmissions @ApiOperation(value = "仲裁") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "投诉单ID", required = true, paramType = "path"), @ApiImplicitParam(name = "arbitrationResult", value = "仲裁结果", required = true, paramType = "query") }) @PutMapping(value = "/complete/{id}") public ResultMessage<Object> complete(@PathVariable String id, String arbitrationResult) { //新建对象 OrderComplaintOperationParams orderComplaintOperationParams = new OrderComplaintOperationParams(); orderComplaintOperationParams.setComplainId(id); orderComplaintOperationParams.setArbitrationResult(arbitrationResult); orderComplaintOperationParams.setComplainStatus(OrderComplaintStatusEnum.COMPLETE.name()); //修改状态 orderComplaintService.updateOrderComplainByStatus(orderComplaintOperationParams); return ResultUtil.success(); } }
AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser()); OrderComplaintCommunicationVO communicationVO = new OrderComplaintCommunicationVO(complainId, content, CommunicationOwnerEnum.PLATFORM.name(), currentUser.getUsername(), currentUser.getId()); orderComplaintCommunicationService.addCommunication(communicationVO); return ResultUtil.data(communicationVO);
842
108
950
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/order/OrderManagerController.java
OrderManagerController
updateOrderPrice
class OrderManagerController { /** * 订单 */ @Autowired private OrderService orderService; /** * 订单价格 */ @Autowired private OrderPriceService orderPriceService; @ApiOperation(value = "查询订单列表分页") @GetMapping public ResultMessage<IPage<OrderSimpleVO>> queryMineOrder(OrderSearchParams orderSearchParams) { return ResultUtil.data(orderService.queryByParams(orderSearchParams)); } @ApiOperation(value = "查询订单导出列表") @GetMapping("/queryExportOrder") public ResultMessage<List<OrderExportDTO>> queryExportOrder(OrderSearchParams orderSearchParams) { return ResultUtil.data(orderService.queryExportOrder(orderSearchParams)); } @ApiOperation(value = "订单明细") @ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, dataType = "String", paramType = "path") @GetMapping(value = "/{orderSn}") public ResultMessage<OrderDetailVO> detail(@PathVariable String orderSn) { return ResultUtil.data(orderService.queryDetail(orderSn)); } @PreventDuplicateSubmissions @ApiOperation(value = "确认收款") @ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, dataType = "String", paramType = "path") @PostMapping(value = "/{orderSn}/pay") public ResultMessage<Object> payOrder(@PathVariable String orderSn) { orderPriceService.adminPayOrder(orderSn); return ResultUtil.success(); } @PreventDuplicateSubmissions @ApiOperation(value = "修改收货人信息") @ApiImplicitParam(name = "orderSn", value = "订单sn", required = true, dataType = "String", paramType = "path") @PostMapping(value = "/update/{orderSn}/consignee") public ResultMessage<Order> consignee(@NotNull(message = "参数非法") @PathVariable String orderSn, @Valid MemberAddressDTO memberAddressDTO) { return ResultUtil.data(orderService.updateConsignee(orderSn, memberAddressDTO)); } @PreventDuplicateSubmissions @ApiOperation(value = "修改订单价格") @ApiImplicitParams({ @ApiImplicitParam(name = "orderSn", value = "订单sn", required = true, dataType = "String", paramType = "path"), @ApiImplicitParam(name = "price", value = "订单价格", required = true, dataType = "Double", paramType = "query"), }) @PutMapping(value = "/update/{orderSn}/price") public ResultMessage<Order> updateOrderPrice(@PathVariable String orderSn, @NotNull(message = "订单价格不能为空") @RequestParam Double price) {<FILL_FUNCTION_BODY>} @PreventDuplicateSubmissions @ApiOperation(value = "取消订单") @ApiImplicitParams({ @ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, dataType = "String", paramType = "path"), @ApiImplicitParam(name = "reason", value = "取消原因", required = true, dataType = "String", paramType = "query") }) @PostMapping(value = "/{orderSn}/cancel") public ResultMessage<Order> cancel(@ApiIgnore @PathVariable String orderSn, @RequestParam String reason) { return ResultUtil.data(orderService.cancel(orderSn, reason)); } @ApiOperation(value = "查询物流踪迹") @ApiImplicitParams({ @ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, dataType = "String", paramType = "path") }) @PostMapping(value = "/getTraces/{orderSn}") public ResultMessage<Object> getTraces(@NotBlank(message = "订单编号不能为空") @PathVariable String orderSn) { return ResultUtil.data(orderService.getTraces(orderSn)); } }
if (NumberUtil.isGreater(Convert.toBigDecimal(price), Convert.toBigDecimal(0))) { return ResultUtil.data(orderPriceService.updatePrice(orderSn, price)); } else { return ResultUtil.error(ResultCode.ORDER_PRICE_ERROR); }
1,075
79
1,154
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/other/AppVersionManagerController.java
AppVersionManagerController
add
class AppVersionManagerController { @Autowired private AppVersionService appVersionService; @ApiOperation(value = "查询app升级消息", response = AppVersion.class) @GetMapping @ApiImplicitParams({ @ApiImplicitParam(name = "type", value = "APP类型", required = true, dataType = "type", paramType = "query") }) public ResultMessage<IPage<AppVersion>> getByPage(PageVO page, String type) { return ResultUtil.data(this.appVersionService.page(PageUtil.initPage(page), new QueryWrapper<AppVersion>().eq(StringUtils.isNotEmpty(type), "type", type).orderByDesc("create_time"))); } @ApiOperation(value = "添加app版本信息", response = AppVersion.class) @PostMapping public ResultMessage<Object> add(@Valid AppVersion appVersion) {<FILL_FUNCTION_BODY>} @PutMapping(value = "/{id}") @ApiOperation(value = "修改app版本信息", response = AppVersion.class) @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "主键", required = true, dataType = "String", paramType = "path") }) public ResultMessage<Object> edit(@Valid AppVersion appVersion, @PathVariable String id) { if(this.appVersionService.checkAppVersion(appVersion)){ if(this.appVersionService.updateById(appVersion)){ return ResultUtil.success(); } } throw new ServiceException(ResultCode.ERROR); } @DeleteMapping(value = "/{id}") @ApiOperation(value = "删除app版本") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "要删除的app版本主键", required = true, dataType = "String", paramType = "path") }) public ResultMessage<Boolean> delete(@PathVariable String id) { if(this.appVersionService.removeById(id)){ return ResultUtil.success(); } throw new ServiceException(ResultCode.ERROR); } }
if(this.appVersionService.checkAppVersion(appVersion)){ if(this.appVersionService.save(appVersion)){ return ResultUtil.success(); } } throw new ServiceException(ResultCode.ERROR);
548
62
610
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/other/ArticleCategoryManagerController.java
ArticleCategoryManagerController
update
class ArticleCategoryManagerController { /** * 文章分类 */ @Autowired private ArticleCategoryService articleCategoryService; @ApiOperation(value = "查询分类列表") @GetMapping(value = "/all-children") public ResultMessage<List<ArticleCategoryVO>> allChildren() { try { return ResultUtil.data(this.articleCategoryService.allChildren()); } catch (Exception e) { log.error("查询分类列表错误", e); } return null; } @ApiOperation(value = "查看文章分类") @ApiImplicitParam(name = "id", value = "文章分类ID", required = true, dataType = "String", paramType = "path") @GetMapping(value = "/{id}") public ResultMessage<ArticleCategory> getArticleCategory(@PathVariable String id) { return ResultUtil.data(this.articleCategoryService.getById(id)); } @ApiOperation(value = "保存文章分类") @PostMapping public ResultMessage<ArticleCategory> save(@Valid ArticleCategory articleCategory) { if (articleCategory.getLevel() == null) { articleCategory.setLevel(0); } if (articleCategory.getSort() == null) { articleCategory.setSort(0); } return ResultUtil.data(articleCategoryService.saveArticleCategory(articleCategory)); } @ApiOperation(value = "修改文章分类") @ApiImplicitParam(name = "id", value = "文章分类ID", required = true, dataType = "String", paramType = "path") @PutMapping("/update/{id}") public ResultMessage<ArticleCategory> update(@Valid ArticleCategory articleCategory, @PathVariable("id") String id) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "删除文章分类") @ApiImplicitParam(name = "id", value = "文章分类ID", required = true, dataType = "String", paramType = "path") @DeleteMapping("/{id}") public ResultMessage<ArticleCategory> deleteById(@PathVariable String id) { articleCategoryService.deleteById(id); return ResultUtil.success(); } }
if (articleCategory.getLevel() == null) { articleCategory.setLevel(0); } if (articleCategory.getSort() == null) { articleCategory.setSort(0); } articleCategory.setId(id); return ResultUtil.data(articleCategoryService.updateArticleCategory(articleCategory));
567
89
656
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/other/CustomWordsController.java
CustomWordsController
getCustomWords
class CustomWordsController { /** * 分词 */ @Autowired private CustomWordsService customWordsService; /** * 设置 */ @Autowired private SettingService settingService; @GetMapping public String getCustomWords(String secretKey) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "添加自定义分词") @PostMapping public ResultMessage<CustomWordsVO> addCustomWords(@Valid CustomWordsVO customWords) { customWordsService.addCustomWords(customWords); return ResultUtil.data(customWords); } @ApiOperation(value = "修改自定义分词") @PutMapping public ResultMessage<CustomWordsVO> updateCustomWords(@Valid CustomWordsVO customWords) { customWordsService.updateCustomWords(customWords); return ResultUtil.data(customWords); } @ApiOperation(value = "删除自定义分词") @ApiImplicitParam(name = "id", value = "文章ID", required = true, dataType = "String", paramType = "path") @DeleteMapping("/{id}") public ResultMessage<String> deleteCustomWords(@NotNull @PathVariable String id) { customWordsService.deleteCustomWords(id); return ResultUtil.success(); } @ApiOperation(value = "分页获取自定义分词") @ApiImplicitParam(name = "words", value = "分词", required = true, dataType = "String", paramType = "query") @GetMapping("/page") public ResultMessage<IPage<CustomWords>> getCustomWords(@RequestParam String words, PageVO pageVo) { return ResultUtil.data(customWordsService.getCustomWordsByPage(words, pageVo)); } }
if (CharSequenceUtil.isEmpty(secretKey)) { return ""; } Setting setting = settingService.get(SettingKeys.ES_SIGN.name()); if (setting == null || CharSequenceUtil.isEmpty(setting.getSettingValue())) { return ""; } JSONObject jsonObject = JSONUtil.parseObj(setting.getSettingValue()); //如果密钥不正确,返回空 if (!secretKey.equals(jsonObject.get("secretKey"))) { return ""; } String res = customWordsService.deploy(); try { return new String(res.getBytes(), StandardCharsets.UTF_8); } catch (Exception e) { log.error("获取分词错误", e); } return "";
487
197
684
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/other/broadcast/StudioManagerController.java
StudioManagerController
recommend
class StudioManagerController { @Autowired private StudioService studioService; @ApiOperation(value = "获取店铺直播间列表") @ApiImplicitParam(name = "status", value = "直播间状态", paramType = "query") @GetMapping public ResultMessage<IPage<StudioVO>> page(PageVO pageVO, String status) { return ResultUtil.data(studioService.studioList(pageVO, null, status)); } @ApiOperation(value = "获取店铺直播间详情") @ApiImplicitParam(name = "studioId", value = "直播间ID", required = true, paramType = "path") @GetMapping("/{studioId}") public ResultMessage<StudioVO> studioInfo(@PathVariable String studioId) { return ResultUtil.data(studioService.getStudioVO(studioId)); } @ApiOperation(value = "是否推荐直播间") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "Id", required = true, paramType = "path"), @ApiImplicitParam(name = "recommend", value = "是否推荐", required = true, paramType = "query") }) @PutMapping("/recommend/{id}") public ResultMessage<Object> recommend(@PathVariable String id, @NotNull boolean recommend) {<FILL_FUNCTION_BODY>} }
if (studioService.update(new UpdateWrapper<Studio>() .eq("id", id) .set("recommend", recommend))) { return ResultUtil.success(); } throw new ServiceException(ResultCode.ERROR);
359
65
424
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/passport/AdminUserManagerController.java
AdminUserManagerController
login
class AdminUserManagerController { @Autowired private AdminUserService adminUserService; /** * 会员 */ @Autowired private MemberService memberService; @Autowired private VerificationService verificationService; @PostMapping(value = "/login") @ApiOperation(value = "登录管理员") public ResultMessage<Token> login(@NotNull(message = "用户名不能为空") @RequestParam String username, @NotNull(message = "密码不能为空") @RequestParam String password, @RequestHeader String uuid) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "注销接口") @PostMapping("/logout") public ResultMessage<Object> logout() { this.memberService.logout(UserEnums.MANAGER); return ResultUtil.success(); } @ApiOperation(value = "刷新token") @GetMapping("/refresh/{refreshToken}") public ResultMessage<Object> refreshToken(@NotNull(message = "刷新token不能为空") @PathVariable String refreshToken) { return ResultUtil.data(this.adminUserService.refreshToken(refreshToken)); } @GetMapping(value = "/info") @ApiOperation(value = "获取当前登录用户接口") public ResultMessage<AdminUser> getUserInfo() { AuthUser tokenUser = UserContext.getCurrentUser(); if (tokenUser != null) { AdminUser adminUser = adminUserService.findByUsername(tokenUser.getUsername()); adminUser.setPassword(null); return ResultUtil.data(adminUser); } throw new ServiceException(ResultCode.USER_NOT_LOGIN); } @PutMapping(value = "/edit") @ApiOperation(value = "修改用户自己资料", notes = "用户名密码不会修改") public ResultMessage<Object> editOwner(AdminUser adminUser) { AuthUser tokenUser = UserContext.getCurrentUser(); if (tokenUser != null) { //查询当前管理员 AdminUser oldAdminUser = adminUserService.findByUsername(tokenUser.getUsername()); oldAdminUser.setAvatar(adminUser.getAvatar()); oldAdminUser.setNickName(adminUser.getNickName()); if (!adminUserService.updateById(oldAdminUser)) { throw new ServiceException(ResultCode.USER_EDIT_ERROR); } return ResultUtil.success(ResultCode.USER_EDIT_SUCCESS); } throw new ServiceException(ResultCode.USER_NOT_LOGIN); } @PutMapping(value = "/admin/edit") @ApiOperation(value = "超级管理员修改其他管理员资料") @DemoSite public ResultMessage<Object> edit(@Valid AdminUser adminUser, @RequestParam(required = false) List<String> roles) { if (!adminUserService.updateAdminUser(adminUser, roles)) { throw new ServiceException(ResultCode.USER_EDIT_ERROR); } return ResultUtil.success(ResultCode.USER_EDIT_SUCCESS); } /** * 修改密码 * * @param password * @param newPassword * @return */ @PutMapping(value = "/editPassword") @ApiOperation(value = "修改密码") @DemoSite public ResultMessage<Object> editPassword(String password, String newPassword) { adminUserService.editPassword(password, newPassword); return ResultUtil.success(ResultCode.USER_EDIT_SUCCESS); } @PostMapping(value = "/resetPassword/{ids}") @ApiOperation(value = "重置密码") @DemoSite public ResultMessage<Object> resetPassword(@PathVariable List ids) { adminUserService.resetPassword(ids); return ResultUtil.success(ResultCode.USER_EDIT_SUCCESS); } @GetMapping @ApiOperation(value = "多条件分页获取用户列表") public ResultMessage<IPage<AdminUserVO>> getByCondition(AdminUserDTO user, SearchVO searchVo, PageVO pageVo) { IPage<AdminUserVO> page = adminUserService.adminUserPage(PageUtil.initPage(pageVo), PageUtil.initWrapper(user, searchVo)); return ResultUtil.data(page); } @PostMapping @ApiOperation(value = "添加用户") public ResultMessage<Object> register(@Valid AdminUserDTO adminUser, @RequestParam(required = false) List<String> roles) { int rolesMaxSize = 10; try { if (roles != null && roles.size() >= rolesMaxSize) { throw new ServiceException(ResultCode.PERMISSION_BEYOND_TEN); } adminUserService.saveAdminUser(adminUser, roles); return ResultUtil.success(); } catch (Exception e) { log.error("添加用户错误", e); return ResultUtil.error(ResultCode.USER_ADD_ERROR); } } @PutMapping(value = "/enable/{userId}") @ApiOperation(value = "禁/启 用 用户") @DemoSite public ResultMessage<Object> disable(@ApiParam("用户唯一id标识") @PathVariable String userId, Boolean status) { AdminUser user = adminUserService.getById(userId); if (user == null) { throw new ServiceException(ResultCode.USER_NOT_EXIST); } user.setStatus(status); adminUserService.updateById(user); //登出用户 if (Boolean.FALSE.equals(status)) { List<String> userIds = new ArrayList<>(); userIds.add(userId); adminUserService.logout(userIds); } return ResultUtil.success(); } @DeleteMapping(value = "/{ids}") @ApiOperation(value = "批量通过ids删除") @DemoSite public ResultMessage<Object> delAllByIds(@PathVariable List<String> ids) { adminUserService.deleteCompletely(ids); return ResultUtil.success(); } }
if (verificationService.check(uuid, VerificationEnums.LOGIN)) { return ResultUtil.data(adminUserService.login(username, password)); } else { throw new ServiceException(ResultCode.VERIFICATION_ERROR); }
1,609
66
1,675
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/permission/MenuManagerController.java
MenuManagerController
add
class MenuManagerController { @Autowired private MenuService menuService; @ApiOperation(value = "搜索菜单") @GetMapping public ResultMessage<List<Menu>> searchPermissionList(MenuSearchParams searchParams) { return ResultUtil.data(menuService.searchList(searchParams)); } @ApiOperation(value = "添加") @PostMapping @DemoSite public ResultMessage<Menu> add(Menu menu) {<FILL_FUNCTION_BODY>} @ApiImplicitParam(name = "id", value = "菜单ID", required = true, paramType = "path", dataType = "String") @ApiOperation(value = "编辑") @PutMapping(value = "/{id}") @DemoSite public ResultMessage<Menu> edit(@PathVariable String id, Menu menu) { menu.setId(id); menuService.saveOrUpdateMenu(menu); return ResultUtil.data(menu); } @ApiOperation(value = "批量删除") @DeleteMapping(value = "/{ids}") @DemoSite public ResultMessage<Menu> delByIds(@PathVariable List<String> ids) { menuService.deleteIds(ids); return ResultUtil.success(); } @ApiOperation(value = "获取所有菜单") @GetMapping("/tree") public ResultMessage<List<MenuVO>> getAllMenuList() { return ResultUtil.data(menuService.tree()); } @ApiOperation(value = "获取所有菜单--根据当前用户角色") @GetMapping("/memberMenu") public ResultMessage<List<MenuVO>> memberMenu() { return ResultUtil.data(menuService.findUserTree()); } }
try { menuService.saveOrUpdateMenu(menu); } catch (Exception e) { log.error("添加菜单错误", e); } return ResultUtil.data(menu);
447
54
501
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/permission/StoreMenuManagerController.java
StoreMenuManagerController
add
class StoreMenuManagerController { @Autowired private StoreMenuService storeMenuService; @ApiOperation(value = "搜索菜单") @GetMapping public ResultMessage<List<StoreMenu>> searchPermissionList(MenuSearchParams searchParams) { return ResultUtil.data(storeMenuService.searchList(searchParams)); } @ApiOperation(value = "添加") @PostMapping @DemoSite public ResultMessage<StoreMenu> add(StoreMenu menu) {<FILL_FUNCTION_BODY>} @ApiImplicitParam(name = "id", value = "菜单ID", required = true, paramType = "path", dataType = "String") @ApiOperation(value = "编辑") @PutMapping(value = "/{id}") @DemoSite public ResultMessage<StoreMenu> edit(@PathVariable String id, StoreMenu menu) { menu.setId(id); storeMenuService.saveOrUpdateMenu(menu); return ResultUtil.data(menu); } @ApiOperation(value = "批量删除") @DeleteMapping(value = "/{ids}") @DemoSite public ResultMessage<Menu> delByIds(@PathVariable List<String> ids) { storeMenuService.deleteIds(ids); return ResultUtil.success(); } @ApiOperation(value = "获取所有菜单") @GetMapping("/tree") public ResultMessage<List<StoreMenuVO>> getAllMenuList() { return ResultUtil.data(storeMenuService.tree()); } }
try { storeMenuService.saveOrUpdateMenu(menu); } catch (Exception e) { log.error("添加菜单错误", e); } return ResultUtil.data(menu);
399
55
454
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/promotion/CouponActivityManagerController.java
CouponActivityManagerController
addCouponActivity
class CouponActivityManagerController { @Autowired private CouponActivityService couponActivityService; @ApiOperation(value = "获取优惠券活动分页") @GetMapping public ResultMessage<IPage<CouponActivity>> getCouponActivityPage(PageVO page, CouponActivity couponActivity) { return ResultUtil.data(couponActivityService.page(PageUtil.initPage(page), PageUtil.initWrapper(couponActivity))); } @ApiOperation(value = "获取优惠券活动") @ApiImplicitParam(name = "couponActivityId", value = "优惠券活动ID", required = true, paramType = "path") @GetMapping("/{couponActivityId}") public ResultMessage<CouponActivityVO> getCouponActivity(@PathVariable String couponActivityId) { return ResultUtil.data(couponActivityService.getCouponActivityVO(couponActivityId)); } @ApiOperation(value = "添加优惠券活动") @PostMapping public ResultMessage<CouponActivity> addCouponActivity(@RequestBody(required = false) CouponActivityDTO couponActivityDTO) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "关闭优惠券活动") @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "优惠券活动ID", required = true, dataType = "String", paramType = "path")}) @DeleteMapping("/{id}") public ResultMessage<CouponActivity> updateStatus(@PathVariable String id) { if (couponActivityService.updateStatus(Collections.singletonList(id), null, null)) { return ResultUtil.success(ResultCode.SUCCESS); } throw new ServiceException(ResultCode.ERROR); } }
for (CouponActivityItem couponActivityItem : couponActivityDTO.getCouponActivityItems()) { if (couponActivityItem.getNum() > 5) { throw new ServiceException(ResultCode.COUPON_ACTIVITY_MAX_NUM); } } if (couponActivityService.savePromotions(couponActivityDTO)) { return ResultUtil.data(couponActivityDTO); } return ResultUtil.error(ResultCode.COUPON_ACTIVITY_SAVE_ERROR);
451
135
586
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/promotion/CouponManagerController.java
CouponManagerController
getByPage
class CouponManagerController { @Autowired private CouponService couponService; @Autowired private MemberCouponService memberCouponService; @ApiOperation(value = "获取优惠券列表") @GetMapping public ResultMessage<IPage<CouponVO>> getCouponList(CouponSearchParams queryParam, PageVO page) { if (queryParam.getStoreId() == null) { queryParam.setStoreId(PromotionTools.PLATFORM_ID); } return ResultUtil.data(couponService.pageVOFindAll(queryParam, page)); } @ApiOperation(value = "获取优惠券详情") @GetMapping("/{couponId}") public ResultMessage<CouponVO> getCoupon(@PathVariable String couponId) { CouponVO coupon = couponService.getDetail(couponId); return ResultUtil.data(coupon); } @ApiOperation(value = "添加优惠券") @PostMapping(consumes = "application/json", produces = "application/json") public ResultMessage<CouponVO> addCoupon(@RequestBody CouponVO couponVO) { this.setStoreInfo(couponVO); couponService.savePromotions(couponVO); return ResultUtil.data(couponVO); } @ApiOperation(value = "修改优惠券") @PutMapping(consumes = "application/json", produces = "application/json") public ResultMessage<Coupon> updateCoupon(@RequestBody CouponVO couponVO) { this.setStoreInfo(couponVO); Coupon coupon = couponService.getById(couponVO.getId()); couponService.updatePromotions(couponVO); return ResultUtil.data(coupon); } @ApiOperation(value = "修改优惠券状态") @PutMapping("/status") public ResultMessage<Object> updateCouponStatus(String couponIds, Long startTime, Long endTime) { String[] split = couponIds.split(","); if (couponService.updateStatus(Arrays.asList(split), startTime, endTime)) { return ResultUtil.success(ResultCode.COUPON_EDIT_STATUS_SUCCESS); } throw new ServiceException(ResultCode.COUPON_EDIT_STATUS_ERROR); } @ApiOperation(value = "批量删除") @DeleteMapping(value = "/{ids}") public ResultMessage<Object> delAllByIds(@PathVariable List<String> ids) { couponService.removePromotions(ids); return ResultUtil.success(); } @ApiOperation(value = "会员优惠券作废") @PutMapping(value = "/member/cancellation/{id}") public ResultMessage<Object> cancellation(@PathVariable String id) { AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser()); memberCouponService.cancellation(currentUser.getId(), id); return ResultUtil.success(ResultCode.COUPON_CANCELLATION_SUCCESS); } @ApiOperation(value = "根据优惠券id券分页获取会员领详情") @GetMapping(value = "/member/{id}") public ResultMessage<IPage<MemberCoupon>> getByPage(@PathVariable String id, PageVO page) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "获取优惠券领取详情") @GetMapping(value = "/received") public ResultMessage<IPage<MemberCouponVO>> getReceiveByPage(MemberCouponSearchParams searchParams, PageVO page) { IPage<MemberCouponVO> result = memberCouponService.getMemberCouponsPage(PageUtil.initPage(page), searchParams); return ResultUtil.data(result); } private void setStoreInfo(CouponVO couponVO) { AuthUser currentUser = UserContext.getCurrentUser(); if (currentUser == null) { throw new ServiceException(ResultCode.USER_NOT_EXIST); } couponVO.setStoreId(PromotionTools.PLATFORM_ID); couponVO.setStoreName(PromotionTools.PLATFORM_NAME); } }
QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>(); IPage<MemberCoupon> data = memberCouponService.page(PageUtil.initPage(page), queryWrapper.eq("coupon_id", id) ); return ResultUtil.data(data);
1,090
77
1,167
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/promotion/FullDiscountManagerController.java
FullDiscountManagerController
updateCouponStatus
class FullDiscountManagerController { @Autowired private FullDiscountService fullDiscountService; @ApiOperation(value = "获取满优惠列表") @GetMapping public ResultMessage<IPage<FullDiscount>> getCouponList(FullDiscountSearchParams searchParams, PageVO page) { return ResultUtil.data(fullDiscountService.pageFindAll(searchParams, page)); } @ApiOperation(value = "获取满优惠详情") @GetMapping("/{id}") public ResultMessage<FullDiscountVO> getCouponDetail(@PathVariable String id) { return ResultUtil.data(fullDiscountService.getFullDiscount(id)); } @ApiOperation(value = "修改满额活动状态") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "满额活动ID", required = true, paramType = "path"), @ApiImplicitParam(name = "promotionStatus", value = "满额活动状态", required = true, paramType = "path") }) @PutMapping("/status/{id}") public ResultMessage<Object> updateCouponStatus(@PathVariable String id, Long startTime, Long endTime) {<FILL_FUNCTION_BODY>} }
if (fullDiscountService.updateStatus(Collections.singletonList(id), startTime, endTime)) { return ResultUtil.success(ResultCode.SUCCESS); } return ResultUtil.error(ResultCode.ERROR);
322
61
383
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/promotion/KanJiaActivityGoodsManagerController.java
KanJiaActivityGoodsManagerController
delete
class KanJiaActivityGoodsManagerController { @Autowired private KanjiaActivityGoodsService kanJiaActivityGoodsService; @PostMapping @ApiOperation(value = "添加砍价活动") public ResultMessage<Object> add(@RequestBody KanjiaActivityGoodsOperationDTO kanJiaActivityGoodsOperationDTO) { kanJiaActivityGoodsService.add(kanJiaActivityGoodsOperationDTO); return ResultUtil.success(); } @ApiOperation(value = "获取砍价活动分页") @GetMapping public ResultMessage<IPage<KanjiaActivityGoods>> getKanJiaActivityPage(KanjiaActivityGoodsParams kanJiaParams, PageVO page) { return ResultUtil.data(kanJiaActivityGoodsService.pageFindAll(kanJiaParams, page)); } @GetMapping("/{id}") @ApiOperation(value = "获取积分商品详情") public ResultMessage<Object> getPointsGoodsDetail(@PathVariable("id") String goodsId) { KanjiaActivityGoodsDTO kanJiaActivityGoodsDTO = kanJiaActivityGoodsService.getKanjiaGoodsDetail(goodsId); return ResultUtil.data(kanJiaActivityGoodsDTO); } @PutMapping @ApiOperation(value = "修改砍价商品") public ResultMessage<Object> updatePointsGoods(@RequestBody KanjiaActivityGoodsDTO kanJiaActivityGoodsDTO) { if (!kanJiaActivityGoodsService.updateKanjiaActivityGoods(kanJiaActivityGoodsDTO)) { return ResultUtil.error(ResultCode.KANJIA_GOODS_UPDATE_ERROR); } return ResultUtil.success(); } @DeleteMapping("/{ids}") @ApiOperation(value = "删除砍价商品") public ResultMessage<Object> delete(@PathVariable String ids) {<FILL_FUNCTION_BODY>} }
if (kanJiaActivityGoodsService.removePromotions(Arrays.asList(ids.split(",")))) { return ResultUtil.success(); } throw new ServiceException(ResultCode.KANJIA_GOODS_DELETE_ERROR);
529
69
598
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/promotion/PintuanManagerController.java
PintuanManagerController
openPintuan
class PintuanManagerController { @Autowired private PintuanService pintuanService; @Autowired private PromotionGoodsService promotionGoodsService; @GetMapping(value = "/{id}") @ApiOperation(value = "通过id获取") public ResultMessage<PintuanVO> get(@PathVariable String id) { PintuanVO pintuan = pintuanService.getPintuanVO(id); return ResultUtil.data(pintuan); } @GetMapping @ApiOperation(value = "根据条件分页查询拼团活动列表") public ResultMessage<IPage<Pintuan>> getPintuanByPage(PintuanSearchParams queryParam, PageVO pageVo) { IPage<Pintuan> pintuanIPage = pintuanService.pageFindAll(queryParam, pageVo); return ResultUtil.data(pintuanIPage); } @GetMapping("/goods/{pintuanId}") @ApiOperation(value = "根据条件分页查询拼团活动商品列表") public ResultMessage<IPage<PromotionGoods>> getPintuanGoodsByPage(@PathVariable String pintuanId, PageVO pageVo) { PromotionGoodsSearchParams searchParams = new PromotionGoodsSearchParams(); searchParams.setPromotionId(pintuanId); searchParams.setPromotionType(PromotionTypeEnum.PINTUAN.name()); return ResultUtil.data(promotionGoodsService.pageFindAll(searchParams, pageVo)); } @PutMapping("/status/{pintuanIds}") @ApiOperation(value = "操作拼团活动状态") public ResultMessage<String> openPintuan(@PathVariable String pintuanIds, Long startTime, Long endTime) {<FILL_FUNCTION_BODY>} }
if (pintuanService.updateStatus(Arrays.asList(pintuanIds.split(",")), startTime, endTime)) { return ResultUtil.success(ResultCode.PINTUAN_MANUAL_OPEN_SUCCESS); } throw new ServiceException(ResultCode.PINTUAN_MANUAL_OPEN_ERROR);
467
93
560
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/promotion/PointsGoodsManagerController.java
PointsGoodsManagerController
delete
class PointsGoodsManagerController { @Autowired private PointsGoodsService pointsGoodsService; @PostMapping(consumes = "application/json", produces = "application/json") @ApiOperation(value = "添加积分商品") public ResultMessage<Object> addPointsGoods(@RequestBody List<PointsGoods> pointsGoodsList) { if (pointsGoodsService.savePointsGoodsBatch(pointsGoodsList)) { return ResultUtil.success(); } return ResultUtil.error(ResultCode.POINT_GOODS_ERROR); } @PutMapping(consumes = "application/json", produces = "application/json") @ApiOperation(value = "修改积分商品") public ResultMessage<Object> updatePointsGoods(@RequestBody PointsGoodsVO pointsGoods) { Objects.requireNonNull(UserContext.getCurrentUser()); pointsGoodsService.updatePromotions(pointsGoods); return ResultUtil.success(); } @PutMapping("/status/{ids}") @ApiOperation(value = "修改积分商品状态") public ResultMessage<Object> updatePointsGoodsStatus(@PathVariable String ids, Long startTime, Long endTime) { if (pointsGoodsService.updateStatus(Arrays.asList(ids.split(",")), startTime, endTime)) { return ResultUtil.success(); } return ResultUtil.error(ResultCode.POINT_GOODS_ERROR); } @DeleteMapping("/{ids}") @ApiOperation(value = "删除积分商品") public ResultMessage<Object> delete(@PathVariable String ids) {<FILL_FUNCTION_BODY>} @GetMapping @ApiOperation(value = "分页获取积分商品") public ResultMessage<IPage<PointsGoods>> getPointsGoodsPage(PointsGoodsSearchParams searchParams, PageVO page) { IPage<PointsGoods> pointsGoodsByPage = pointsGoodsService.pageFindAll(searchParams, page); return ResultUtil.data(pointsGoodsByPage); } @GetMapping("/{id}") @ApiOperation(value = "获取积分商品详情") public ResultMessage<Object> getPointsGoodsDetail(@PathVariable String id) { PointsGoodsVO pointsGoodsDetail = pointsGoodsService.getPointsGoodsDetail(id); return ResultUtil.data(pointsGoodsDetail); } }
if (pointsGoodsService.removePromotions(Arrays.asList(ids.split(",")))) { return ResultUtil.success(); } throw new ServiceException(ResultCode.POINT_GOODS_ERROR);
620
61
681
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/promotion/PromotionManagerController.java
PromotionManagerController
getPromotionGoods
class PromotionManagerController { @Autowired private PromotionService promotionService; @Autowired private PromotionGoodsService promotionGoodsService; @GetMapping("/current") @ApiOperation(value = "获取当前进行中的促销活动") public ResultMessage<Map<String, List<PromotionGoods>>> getCurrentPromotion() { Map<String, List<PromotionGoods>> currentPromotion = promotionService.getCurrentPromotion(); return ResultUtil.data(currentPromotion); } @GetMapping("/{promotionId}/goods") @ApiOperation(value = "获取当前进行中的促销活动商品") public ResultMessage<IPage<PromotionGoods>> getPromotionGoods(@PathVariable String promotionId, String promotionType, PageVO pageVO) {<FILL_FUNCTION_BODY>} }
PromotionGoodsSearchParams searchParams = new PromotionGoodsSearchParams(); searchParams.setPromotionId(promotionId); searchParams.setPromotionType(promotionType); searchParams.setPromotionStatus(PromotionsStatusEnum.START.name()); IPage<PromotionGoods> promotionGoods = promotionGoodsService.pageFindAll(searchParams, pageVO); return ResultUtil.data(promotionGoods);
216
112
328
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/setting/LogManagerController.java
LogManagerController
getAllByPage
class LogManagerController { @Autowired private SystemLogService systemLogService; @GetMapping(value = "/getAllByPage") @ApiOperation(value = "分页获取全部") public ResultMessage<Object> getAllByPage(@RequestParam(required = false) Integer type, @RequestParam String searchKey, String operatorName, SearchVO searchVo, PageVO pageVo) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "批量删除") @DeleteMapping(value = "/{ids}") public ResultMessage<Object> delByIds(@PathVariable List<String> ids) { systemLogService.deleteLog(ids); return ResultUtil.success(); } @DeleteMapping @ApiOperation(value = "全部删除") public ResultMessage<Object> delAll() { systemLogService.flushAll(); return ResultUtil.success(); } }
try { return ResultUtil.data(systemLogService.queryLog(null, operatorName, searchKey, searchVo, pageVo)); } catch (Exception e) { log.error("日志获取错误",e); } return null;
248
68
316
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/setting/NoticeMessageManagerController.java
NoticeMessageManagerController
get
class NoticeMessageManagerController { @Autowired private NoticeMessageService noticeMessageService; @ApiOperation(value = "消息模板分页") @GetMapping @ApiImplicitParams({ @ApiImplicitParam(name = "type", value = "消息类型", dataType = "String", paramType = "query", allowableValues = "MEMBER,OTHER,STORE,WECHAT", allowMultiple = true) }) public ResultMessage<IPage<NoticeMessage>> getPage(PageVO pageVO, String type) { return ResultUtil.data(noticeMessageService.getMessageTemplate(pageVO, type)); } @ApiOperation(value = "根据id获取通知详情") @ApiImplicitParam(name = "id", value = "模板id", dataType = "String", paramType = "path") @GetMapping("/{id}") public ResultMessage<NoticeMessageDetailDTO> get(@PathVariable String id) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "修改站内信模板") @ApiImplicitParams({ @ApiImplicitParam(name = "noticeContent", value = "站内信内容", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "noticeTitle", value = "站内信模板标题", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "id", value = "模板id", dataType = "String", paramType = "path") }) @PutMapping("/{id}") public ResultMessage<NoticeMessage> updateNoticeTemplate(@RequestParam String noticeContent, @RequestParam String noticeTitle, @PathVariable String id) { //根据id获取当前消息模板 NoticeMessage noticeMessage = noticeMessageService.getById(id); if (noticeMessage != null) { noticeMessage.setNoticeContent(noticeContent); noticeMessage.setNoticeTitle(noticeTitle); noticeMessageService.updateById(noticeMessage); return ResultUtil.data(noticeMessage); } throw new ResourceNotFoundException(ResultCode.NOTICE_NOT_EXIST.message()); } @ApiOperation(value = "修改站内信状态") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "站内信状态", dataType = "String", paramType = "path"), @ApiImplicitParam(name = "status", value = "站内信状态", dataType = "String", paramType = "path") }) @PutMapping("/{id}/{status}") public ResultMessage<NoticeMessage> status(@PathVariable String id, @PathVariable String status) { //根据id获取当前消息模板 NoticeMessage messageTemplate = noticeMessageService.getById(id); if (messageTemplate != null) { //校验传递站内信是否符合规范 Boolean b = EnumUtils.isValidEnum(SwitchEnum.class, status); if (b) { //赋值执行修改操作 messageTemplate.setNoticeStatus(status); noticeMessageService.updateById(messageTemplate); return ResultUtil.data(messageTemplate); } throw new ServiceException(ResultCode.NOTICE_ERROR); } throw new ResourceNotFoundException(ResultCode.NOTICE_NOT_EXIST.message()); } }
//根据id获取当前消息模板 NoticeMessage noticeMessage = noticeMessageService.getById(id); if (noticeMessage != null) { NoticeMessageDetailDTO noticeMessageDetailDTO = new NoticeMessageDetailDTO(); BeanUtil.copyProperties(noticeMessage, noticeMessageDetailDTO); //组织消息变量 String[] variableNames = noticeMessage.getVariable().split(","); //定义返回参数中变量列表 List<String> variableValues = new ArrayList<>(); //循环消息变量赋值 if (variableNames.length > 0) { for (String variableName : variableNames) { if (NoticeMessageParameterEnum.getValueByType(variableName) != null) { variableValues.add(NoticeMessageParameterEnum.getValueByType(variableName)); } } noticeMessageDetailDTO.setVariables(variableValues); } return ResultUtil.data(noticeMessageDetailDTO); } throw new ResourceNotFoundException(ResultCode.NOTICE_NOT_EXIST.message());
852
267
1,119
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/statistics/IndexStatisticsManagerController.java
IndexStatisticsManagerController
index
class IndexStatisticsManagerController { /** * 首页统计 */ @Autowired private IndexStatisticsService indexStatisticsService; @ApiOperation(value = "获取首页查询数据") @GetMapping @PreventDuplicateSubmissions public ResultMessage<IndexStatisticsVO> index() {<FILL_FUNCTION_BODY>} @ApiOperation(value = "获取首页查询热卖商品TOP10") @GetMapping("/goodsStatistics") public ResultMessage<List<GoodsStatisticsDataVO>> goodsStatistics(GoodsStatisticsQueryParam goodsStatisticsQueryParam) { //按照金额查询 goodsStatisticsQueryParam.setType(StatisticsQuery.PRICE.name()); return ResultUtil.data(indexStatisticsService.goodsStatistics(goodsStatisticsQueryParam)); } @ApiOperation(value = "获取首页查询热卖店铺TOP10") @GetMapping("/storeStatistics") public ResultMessage<List<StoreStatisticsDataVO>> storeStatistics(StatisticsQueryParam statisticsQueryParam) { return ResultUtil.data(indexStatisticsService.storeStatistics(statisticsQueryParam)); } @ApiOperation(value = "通知提示信息") @GetMapping("/notice") public ResultMessage<IndexNoticeVO> notice() { return ResultUtil.data(indexStatisticsService.indexNotice()); } }
try { return ResultUtil.data(indexStatisticsService.indexStatistics()); } catch (Exception e) { log.error("获取首页查询数据错误",e); } return null;
362
57
419
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/statistics/OrderStatisticsManagerController.java
OrderStatisticsManagerController
order
class OrderStatisticsManagerController { @Autowired private OrderStatisticsService orderStatisticsService; @Autowired private AfterSaleStatisticsService afterSaleStatisticsService; @ApiOperation(value = "订单概览统计") @GetMapping("/overview") public ResultMessage<OrderOverviewVO> overview(StatisticsQueryParam statisticsQueryParam) { try { return ResultUtil.data(orderStatisticsService.overview(statisticsQueryParam)); } catch (Exception e) { log.error("订单概览统计错误",e); } return null; } @ApiOperation(value = "订单图表统计") @GetMapping public ResultMessage<List<OrderStatisticsDataVO>> statisticsChart(StatisticsQueryParam statisticsQueryParam) { try { return ResultUtil.data(orderStatisticsService.statisticsChart(statisticsQueryParam)); } catch (Exception e) { log.error("订单图表统计",e); } return null; } @ApiOperation(value = "订单统计") @GetMapping("/order") public ResultMessage<IPage<OrderSimpleVO>> order(StatisticsQueryParam statisticsQueryParam, PageVO pageVO) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "退单统计") @GetMapping("/refund") public ResultMessage<IPage<AfterSale>> refund(StatisticsQueryParam statisticsQueryParam, PageVO pageVO) { return ResultUtil.data(afterSaleStatisticsService.getStatistics(statisticsQueryParam, pageVO)); } }
try { return ResultUtil.data(orderStatisticsService.getStatistics(statisticsQueryParam, pageVO)); } catch (Exception e) { log.error("订单统计",e); } return null;
408
61
469
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/store/StoreManagerController.java
StoreManagerController
getByMemberId
class StoreManagerController { /** * 店铺 */ @Autowired private StoreService storeService; /** * 店铺详情 */ @Autowired private StoreDetailService storeDetailService; @ApiOperation(value = "获取店铺分页列表") @GetMapping("/all") public ResultMessage<List<Store>> getAll() { return ResultUtil.data(storeService.list(new QueryWrapper<Store>().eq("store_disable", "OPEN"))); } @ApiOperation(value = "获取店铺分页列表") @GetMapping public ResultMessage<IPage<StoreVO>> getByPage(StoreSearchParams entity, PageVO page) { return ResultUtil.data(storeService.findByConditionPage(entity, page)); } @ApiOperation(value = "获取店铺详情") @ApiImplicitParam(name = "storeId", value = "店铺ID", required = true, paramType = "path", dataType = "String") @GetMapping(value = "/get/detail/{storeId}") public ResultMessage<StoreDetailVO> detail(@PathVariable String storeId) { // todo 对于刚提交审核的信息需要等待缓存失效后才能操作,否则缓存信息还在 return ResultUtil.data(storeDetailService.getStoreDetailVO(storeId)); } @ApiOperation(value = "添加店铺") @PostMapping(value = "/add") public ResultMessage<Store> add(@Valid AdminStoreApplyDTO adminStoreApplyDTO) { return ResultUtil.data(storeService.add(adminStoreApplyDTO)); } @ApiOperation(value = "编辑店铺") @ApiImplicitParam(name = "storeId", value = "店铺ID", required = true, paramType = "path", dataType = "String") @PutMapping(value = "/edit/{id}") public ResultMessage<Store> edit(@PathVariable String id, @Valid StoreEditDTO storeEditDTO) { storeEditDTO.setStoreId(id); return ResultUtil.data(storeService.edit(storeEditDTO)); } @ApiOperation(value = "审核店铺申请") @ApiImplicitParams({ @ApiImplicitParam(name = "passed", value = "是否通过审核 0 通过 1 拒绝 编辑操作则不需传递", paramType = "query", dataType = "int"), @ApiImplicitParam(name = "id", value = "店铺id", required = true, paramType = "path", dataType = "String") }) @PutMapping(value = "/audit/{id}/{passed}") public ResultMessage<Object> audit(@PathVariable String id, @PathVariable Integer passed) { storeService.audit(id, passed); return ResultUtil.success(); } @DemoSite @ApiOperation(value = "关闭店铺") @ApiImplicitParam(name = "id", value = "店铺id", required = true, dataType = "String", paramType = "path") @PutMapping(value = "/disable/{id}") public ResultMessage<Store> disable(@PathVariable String id) { storeService.disable(id); return ResultUtil.success(); } @ApiOperation(value = "开启店铺") @ApiImplicitParam(name = "id", value = "店铺id", required = true, dataType = "String", paramType = "path") @PutMapping(value = "/enable/{id}") public ResultMessage<Store> enable(@PathVariable String id) { storeService.enable(id); return ResultUtil.success(); } @ApiOperation(value = "查询一级分类列表") @ApiImplicitParam(name = "storeId", value = "店铺id", required = true, dataType = "String", paramType = "path") @GetMapping(value = "/managementCategory/{storeId}") public ResultMessage<List<StoreManagementCategoryVO>> firstCategory(@PathVariable String storeId) { return ResultUtil.data(this.storeDetailService.goodsManagementCategory(storeId)); } @ApiOperation(value = "根据会员id查询店铺信息") @GetMapping("/{memberId}/member") public ResultMessage<Store> getByMemberId(@Valid @PathVariable String memberId) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "将所有店铺导入店员表") @PostMapping("store/to/clerk") public ResultMessage<Object> storeToClerk(){ this.storeService.storeToClerk(); return ResultUtil.success(); } }
List<Store> list = storeService.list(new QueryWrapper<Store>().eq("member_id", memberId)); if (list.size() > 0) { return ResultUtil.data(list.get(0)); } return ResultUtil.data(null);
1,185
71
1,256
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/wallet/MemberWithdrawApplyManagerController.java
MemberWithdrawApplyManagerController
getByPage
class MemberWithdrawApplyManagerController { @Autowired private MemberWithdrawApplyService memberWithdrawApplyService; @ApiOperation(value = "分页获取提现记录") @GetMapping public ResultMessage<IPage<MemberWithdrawApply>> getByPage(PageVO page, MemberWithdrawApplyQueryVO memberWithdrawApplyQueryVO) {<FILL_FUNCTION_BODY>} @PreventDuplicateSubmissions @ApiOperation(value = "提现申请审核") @PostMapping @ApiImplicitParams({ @ApiImplicitParam(name = "applyId", value = "审核记录id", required = true, paramType = "query"), @ApiImplicitParam(name = "result", value = "审核结果", required = true, paramType = "query", dataType = "boolean"), @ApiImplicitParam(name = "remark", value = "审核备注", paramType = "query") }) public Boolean audit(String applyId, Boolean result, String remark) { return memberWithdrawApplyService.audit(applyId, result, remark); } }
//构建查询 返回数据 IPage<MemberWithdrawApply> memberWithdrawApplyPage = memberWithdrawApplyService.getMemberWithdrawPage(page, memberWithdrawApplyQueryVO); return ResultUtil.data(memberWithdrawApplyPage);
279
64
343
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/wallet/RechargeManagerController.java
RechargeManagerController
getByPage
class RechargeManagerController { @Autowired private RechargeService rechargeService; @ApiOperation(value = "分页获取预存款充值记录") @GetMapping public ResultMessage<IPage<Recharge>> getByPage(PageVO page, RechargeQueryVO rechargeQueryVO) {<FILL_FUNCTION_BODY>} }
//构建查询 返回数据 IPage<Recharge> rechargePage = rechargeService.rechargePage(page, rechargeQueryVO); return ResultUtil.data(rechargePage);
93
52
145
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/controller/wallet/WalletLogManagerController.java
WalletLogManagerController
getByPage
class WalletLogManagerController { @Autowired private WalletLogService walletLogService; @ApiOperation(value = "分页获取预存款充值记录") @GetMapping public ResultMessage<IPage<WalletLog>> getByPage(PageVO page, DepositQueryVO depositQueryVO) {<FILL_FUNCTION_BODY>} }
//构建查询 返回数据 IPage<WalletLog> depositLogPage = walletLogService.depositLogPage(page, depositQueryVO); return ResultUtil.data(depositLogPage);
94
55
149
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/security/ManagerAuthenticationFilter.java
ManagerAuthenticationFilter
doFilterInternal
class ManagerAuthenticationFilter extends BasicAuthenticationFilter { private final Cache cache; public final MenuService menuService; private final ManagerTokenGenerate managerTokenGenerate; public ManagerAuthenticationFilter(AuthenticationManager authenticationManager, MenuService menuService, ManagerTokenGenerate managerTokenGenerate, Cache cache) { super(authenticationManager); this.cache = cache; this.menuService = menuService; this.managerTokenGenerate = managerTokenGenerate; } @SneakyThrows @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {<FILL_FUNCTION_BODY>} /** * 自定义权限过滤 * * @param request 请求 * @param response 响应 * @param authentication 用户信息 */ private void customAuthentication(HttpServletRequest request, HttpServletResponse response, UsernamePasswordAuthenticationToken authentication) throws NoPermissionException { AuthUser authUser = (AuthUser) authentication.getDetails(); String requestUrl = request.getRequestURI(); //如果不是超级管理员, 则鉴权 if (Boolean.FALSE.equals(authUser.getIsSuper())) { String permissionCacheKey = CachePrefix.PERMISSION_LIST.getPrefix(UserEnums.MANAGER) + authUser.getId(); //获取缓存中的权限 Map<String, List<String>> permission = (Map<String, List<String>>) cache.get(permissionCacheKey); if (permission == null || permission.isEmpty()) { permission = managerTokenGenerate.permissionList(this.menuService.findAllMenu(authUser.getId())); cache.put(permissionCacheKey, permission); } //获取数据(GET 请求)权限 if (request.getMethod().equals(RequestMethod.GET.name())) { //如果用户的超级权限和查阅权限都不包含当前请求的api if (match(permission.get(PermissionEnum.SUPER.name()), requestUrl) || match(permission.get(PermissionEnum.QUERY.name()), requestUrl)) { } else { ResponseUtil.output(response, ResponseUtil.resultMap(false, 400, "权限不足")); log.error("当前请求路径:{},所拥有权限:{}", requestUrl, JSONUtil.toJsonStr(permission)); throw new NoPermissionException("权限不足"); } } //非get请求(数据操作) 判定鉴权 else { if (!match(permission.get(PermissionEnum.SUPER.name()), requestUrl)) { ResponseUtil.output(response, ResponseUtil.resultMap(false, 400, "权限不足")); log.error("当前请求路径:{},所拥有权限:{}", requestUrl, JSONUtil.toJsonStr(permission)); throw new NoPermissionException("权限不足"); } } } } /** * 校验权限 * * @param permissions 权限集合 * @param url 请求地址 * @return 是否拥有权限 */ boolean match(List<String> permissions, String url) { if (permissions == null || permissions.isEmpty()) { return false; } return PatternMatchUtils.simpleMatch(permissions.toArray(new String[0]), url); } /** * 获取token信息 * * @param jwt token信息 * @param response 响应 * @return 获取鉴权对象 */ private UsernamePasswordAuthenticationToken getAuthentication(String jwt, HttpServletResponse response) { try { Claims claims = Jwts.parser() .setSigningKey(SecretKeyUtil.generalKeyByDecoders()) .parseClaimsJws(jwt).getBody(); //获取存储在claims中的用户信息 String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString(); AuthUser authUser = new Gson().fromJson(json, AuthUser.class); //校验redis中是否有权限 if (cache.hasKey(CachePrefix.ACCESS_TOKEN.getPrefix(UserEnums.MANAGER, authUser.getId()) + jwt)) { //用户角色 List<GrantedAuthority> auths = new ArrayList<>(); auths.add(new SimpleGrantedAuthority("ROLE_" + authUser.getRole().name())); //构造返回信息 UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(authUser.getUsername(), null, auths); authentication.setDetails(authUser); return authentication; } ResponseUtil.output(response, 403, ResponseUtil.resultMap(false, 403, "登录已失效,请重新登录")); return null; } catch (ExpiredJwtException e) { log.debug("user analysis exception:", e); } catch (Exception e) { log.error("other exception:", e); } return null; } }
//从header中获取jwt String jwt = request.getHeader(SecurityEnum.HEADER_TOKEN.getValue()); //如果没有token 则return if (StrUtil.isBlank(jwt)) { chain.doFilter(request, response); return; } //获取用户信息,存入context UsernamePasswordAuthenticationToken authentication = getAuthentication(jwt, response); //自定义权限过滤 if (authentication != null) { customAuthentication(request, response, authentication); SecurityContextHolder.getContext().setAuthentication(authentication); } chain.doFilter(request, response);
1,290
167
1,457
<no_super_class>
lilishop_lilishop
lilishop/manager-api/src/main/java/cn/lili/security/ManagerSecurityConfig.java
ManagerSecurityConfig
configure
class ManagerSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public MenuService menuService; /** * 忽略验权配置 */ @Autowired private IgnoredUrlsProperties ignoredUrlsProperties; /** * spring security -》 权限不足处理 */ @Autowired private CustomAccessDeniedHandler accessDeniedHandler; @Autowired private Cache<String> cache; @Autowired private CorsConfigurationSource corsConfigurationSource; @Autowired private ManagerTokenGenerate managerTokenGenerate; @Override protected void configure(HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>} }
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http .authorizeRequests(); //配置的url 不需要授权 for (String url : ignoredUrlsProperties.getUrls()) { registry.antMatchers(url).permitAll(); } registry .and() //禁止网页iframe .headers().frameOptions().disable() .and() .authorizeRequests() //任何请求 .anyRequest() //需要身份认证 .authenticated() .and() //允许跨域 .cors().configurationSource(corsConfigurationSource).and() //关闭跨站请求防护 .csrf().disable() //前后端分离采用JWT 不需要session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() //自定义权限拒绝处理类 .exceptionHandling().accessDeniedHandler(accessDeniedHandler) .and() //添加JWT认证过滤器 .addFilter(new ManagerAuthenticationFilter(authenticationManager(), menuService, managerTokenGenerate, cache));
184
296
480
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/distribution/DistributionGoodsStoreController.java
DistributionGoodsStoreController
cancel
class DistributionGoodsStoreController { /** * 分销商品 */ @Autowired private DistributionGoodsService distributionGoodsService; /** * 已选择分销商品 */ @Autowired private DistributionSelectedGoodsService distributionSelectedGoodsService; @ApiOperation(value = "获取分销商商品列表") @GetMapping public ResultMessage<IPage<DistributionGoodsVO>> distributionGoods(DistributionGoodsSearchParams distributionGoodsSearchParams) { return ResultUtil.data(distributionGoodsService.goodsPage(distributionGoodsSearchParams)); } @ApiOperation(value = "选择商品参与分销") @ApiImplicitParam(name = "skuId", value = "规格ID", required = true, dataType = "String", paramType = "path") @PutMapping(value = "/checked/{skuId}") public ResultMessage<DistributionGoods> distributionCheckGoods(@NotNull(message = "规格ID不能为空") @PathVariable String skuId, @NotNull(message = "佣金金额不能为空") @RequestParam Double commission) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); return ResultUtil.data(distributionGoodsService.checked(skuId, commission, storeId)); } @ApiOperation(value = "取消分销商品") @ApiImplicitParam(name = "id", value = "分销商商品ID", required = true, paramType = "path") @DeleteMapping(value = "/cancel/{id}") public ResultMessage<Object> cancel(@NotNull @PathVariable String id) {<FILL_FUNCTION_BODY>} }
OperationalJudgment.judgment(distributionGoodsService.getById(id)); //清除分销商已选择分销商品 distributionSelectedGoodsService.remove(new QueryWrapper<DistributionSelectedGoods>().eq("distribution_goods_id", id)); //清除分销商品 distributionGoodsService.removeById(id); return ResultUtil.success();
437
99
536
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/distribution/DistributionOrderStoreController.java
DistributionOrderStoreController
distributionOrder
class DistributionOrderStoreController { /** * 分销订单 */ @Autowired private DistributionOrderService distributionOrderService; @ApiOperation(value = "获取分销订单列表") @GetMapping public ResultMessage<IPage<DistributionOrder>> distributionOrder(DistributionOrderSearchParams distributionOrderSearchParams) {<FILL_FUNCTION_BODY>} }
String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); //获取当前登录商家账号-查询当前店铺的分销订单 distributionOrderSearchParams.setStoreId(storeId); //查询分销订单列表 IPage<DistributionOrder> distributionOrderPage = distributionOrderService.getDistributionOrderPage(distributionOrderSearchParams); return ResultUtil.data(distributionOrderPage);
105
114
219
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/goods/CategoryStoreController.java
CategoryStoreController
getListAll
class CategoryStoreController { /** * 分类 */ @Autowired private CategoryService categoryService; /** * 分类品牌 */ @Autowired private CategoryBrandService categoryBrandService; /** * 店铺详情 */ @Autowired private StoreDetailService storeDetailService; @ApiOperation(value = "获取店铺经营的分类") @GetMapping(value = "/all") public ResultMessage<List<CategoryVO>> getListAll() {<FILL_FUNCTION_BODY>} @ApiOperation(value = "获取所选分类关联的品牌信息") @GetMapping(value = "/{categoryId}/brands") @ApiImplicitParams({ @ApiImplicitParam(name = "categoryId", value = "分类id", required = true, paramType = "path"), }) public List<CategoryBrandVO> queryBrands(@PathVariable String categoryId) { return this.categoryBrandService.getCategoryBrandList(categoryId); } }
String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); //获取店铺经营范围 String goodsManagementCategory = storeDetailService.getStoreDetail(storeId).getGoodsManagementCategory(); return ResultUtil.data(this.categoryService.getStoreCategory(goodsManagementCategory.split(",")));
271
85
356
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/member/StoreUserController.java
StoreUserController
getStoreInfo
class StoreUserController { @Autowired private MemberService memberService; @Autowired private StoreService storeService; @GetMapping(value = "/info") @ApiOperation(value = "获取当前登录用户接口") public ResultMessage<Member> getUserInfo() { AuthUser tokenUser = UserContext.getCurrentUser(); if (tokenUser != null) { Member member = memberService.findByUsername(tokenUser.getUsername()); member.setPassword(null); return ResultUtil.data(member); } throw new ServiceException(ResultCode.USER_NOT_LOGIN); } @GetMapping(value = "") @ApiOperation(value = "获取当前登录店铺接口") public ResultMessage<Store> getStoreInfo() {<FILL_FUNCTION_BODY>} }
AuthUser tokenUser = UserContext.getCurrentUser(); if (tokenUser != null) { Store store = storeService.getById(tokenUser.getStoreId()); return ResultUtil.data(store); } throw new ServiceException(ResultCode.USER_NOT_LOGIN);
223
76
299
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/message/StoreMessageController.java
StoreMessageController
getPage
class StoreMessageController { /** * 商家消息 */ @Autowired private StoreMessageService storeMessageService; @ApiOperation(value = "获取商家消息") @ApiImplicitParam(name = "status", value = "状态", required = true, paramType = "query") @GetMapping public ResultMessage<IPage<StoreMessage>> getPage(String status, PageVO pageVo) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); StoreMessageQueryVO storeMessageQueryVO = new StoreMessageQueryVO(); storeMessageQueryVO.setStatus(status); storeMessageQueryVO.setStoreId(storeId); IPage<StoreMessage> page = storeMessageService.getPage(storeMessageQueryVO, pageVo); return ResultUtil.data(page); } @ApiOperation(value = "获取商家消息总汇") @GetMapping("/all") public ResultMessage<Map<String, Object>> getPage(PageVO pageVo) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "已读操作") @ApiImplicitParam(name = "id", value = "店铺消息id", required = true, paramType = "path") @PutMapping("/{id}/read") public ResultMessage<Boolean> readMessage(@PathVariable String id) { OperationalJudgment.judgment(storeMessageService.getById(id)); Boolean result = storeMessageService.editStatus(MessageStatusEnum.ALREADY_READY.name(), id); return ResultUtil.data(result); } @ApiOperation(value = "回收站还原消息") @ApiImplicitParam(name = "id", value = "店铺消息id", required = true, paramType = "path") @PutMapping("/{id}/reduction") public ResultMessage<Boolean> reductionMessage(@PathVariable String id) { OperationalJudgment.judgment(storeMessageService.getById(id)); Boolean result = storeMessageService.editStatus(MessageStatusEnum.ALREADY_READY.name(), id); return ResultUtil.data(result); } @ApiOperation(value = "删除操作") @ApiImplicitParam(name = "id", value = "店铺消息id", required = true, paramType = "path") @DeleteMapping("/{id}/delete") public ResultMessage<Boolean> deleteMessage(@PathVariable String id) { OperationalJudgment.judgment(storeMessageService.getById(id)); Boolean result = storeMessageService.editStatus(MessageStatusEnum.ALREADY_REMOVE.name(), id); return ResultUtil.data(result); } @ApiOperation(value = "彻底删除操作") @ApiImplicitParam(name = "id", value = "店铺消息id", required = true, paramType = "path") @DeleteMapping("/{id}") public ResultMessage<Boolean> disabled(@PathVariable String id) { OperationalJudgment.judgment(storeMessageService.getById(id)); Boolean result = storeMessageService.deleteByMessageId(id); return ResultUtil.data(result); } }
String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); //返回值定义 Map<String, Object> map = new HashMap<>(4); StoreMessageQueryVO storeMessageQueryVO = new StoreMessageQueryVO(); storeMessageQueryVO.setStoreId(storeId); //未读消息 storeMessageQueryVO.setStatus(MessageStatusEnum.UN_READY.name()); IPage<StoreMessage> page = storeMessageService.getPage(storeMessageQueryVO, pageVo); map.put("UN_READY", page); //已读消息 storeMessageQueryVO.setStatus(MessageStatusEnum.ALREADY_READY.name()); page = storeMessageService.getPage(storeMessageQueryVO, pageVo); map.put("ALREADY_READY", page); //回收站 storeMessageQueryVO.setStatus(MessageStatusEnum.ALREADY_REMOVE.name()); page = storeMessageService.getPage(storeMessageQueryVO, pageVo); map.put("ALREADY_REMOVE", page); return ResultUtil.data(map);
815
289
1,104
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/order/OrderComplaintStoreController.java
OrderComplaintStoreController
addCommunication
class OrderComplaintStoreController { /** * 交易投诉 */ @Autowired private OrderComplaintService orderComplaintService; /** * 投诉沟通 */ @Autowired private OrderComplaintCommunicationService orderComplaintCommunicationService; @ApiOperation(value = "通过id获取") @ApiImplicitParam(name = "id", value = "投诉单ID", required = true, paramType = "path") @GetMapping(value = "/{id}") public ResultMessage<OrderComplaintVO> get(@PathVariable String id) { return ResultUtil.data(OperationalJudgment.judgment(orderComplaintService.getOrderComplainById(id))); } @ApiOperation(value = "分页获取") @GetMapping public ResultMessage<IPage<OrderComplaint>> get(OrderComplaintSearchParams searchParams, PageVO pageVO) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); searchParams.setStoreId(storeId); return ResultUtil.data(orderComplaintService.getOrderComplainByPage(searchParams, pageVO)); } @ApiOperation(value = "添加交易投诉对话") @ApiImplicitParams({ @ApiImplicitParam(name = "complainId", value = "投诉单ID", required = true, paramType = "query"), @ApiImplicitParam(name = "content", value = "内容", required = true, paramType = "query") }) @PostMapping("/communication") public ResultMessage<OrderComplaintCommunicationVO> addCommunication(@RequestParam String complainId, @RequestParam String content) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "修改申诉信息") @PutMapping public ResultMessage<OrderComplaintVO> update(OrderComplaintVO orderComplainVO) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); orderComplainVO.setStoreId(storeId); orderComplaintService.updateOrderComplain(orderComplainVO); return ResultUtil.data(orderComplainVO); } @PreventDuplicateSubmissions @ApiOperation(value = "申诉") @PutMapping("/appeal") public ResultMessage<OrderComplaintVO> appeal(StoreAppealVO storeAppealVO) { orderComplaintService.appeal(storeAppealVO); return ResultUtil.data(orderComplaintService.getOrderComplainById(storeAppealVO.getOrderComplaintId())); } @PreventDuplicateSubmissions @ApiOperation(value = "修改状态") @PutMapping(value = "/status") public ResultMessage<Object> updateStatus(OrderComplaintOperationParams orderComplainVO) { orderComplaintService.updateOrderComplainByStatus(orderComplainVO); return ResultUtil.success(); } }
AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser()); OrderComplaintCommunicationVO communicationVO = new OrderComplaintCommunicationVO(complainId, content, CommunicationOwnerEnum.STORE.name(), currentUser.getUsername(), currentUser.getStoreId()); orderComplaintCommunicationService.addCommunication(communicationVO); return ResultUtil.success();
775
106
881
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/other/broadcast/CommodityStoreController.java
CommodityStoreController
delete
class CommodityStoreController { @Autowired private CommodityService commodityService; @ApiOperation(value = "获取店铺直播商品列表") @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "商品名称", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "auditStatus", value = "直播商品状态", dataType = "String", paramType = "query") }) @GetMapping public ResultMessage<IPage<CommodityVO>> page(String auditStatus, String name, PageVO pageVO) { return ResultUtil.data(commodityService.commodityList(pageVO, name, auditStatus)); } @ApiOperation(value = "添加店铺直播商品") @ApiImplicitParam(name = "commodityList", value = "直播商品列表", paramType = "body", allowMultiple = true, dataType = "Commodity") @PostMapping public ResultMessage<Object> addCommodity(@RequestBody List<Commodity> commodityList) { if (commodityService.addCommodity(commodityList)) { return ResultUtil.success(ResultCode.SUCCESS); } throw new ServiceException(ResultCode.ERROR); } @ApiOperation(value = "删除店铺直播商品") @ApiImplicitParam(name = "goodsId", value = "直播商品ID", dataType = "String", paramType = "path") @DeleteMapping("/{goodsId}") public ResultMessage<Object> delete(@PathVariable String goodsId) {<FILL_FUNCTION_BODY>} }
if (commodityService.deleteCommodity(goodsId)) { return ResultUtil.success(ResultCode.SUCCESS); } throw new ServiceException(ResultCode.ERROR);
422
52
474
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/other/broadcast/StudioStoreController.java
StudioStoreController
edit
class StudioStoreController { @Autowired private StudioService studioService; @ApiOperation(value = "获取店铺直播间列表") @ApiImplicitParam(name = "status", value = "直播间状态", paramType = "query", dataType = "String") @GetMapping public ResultMessage<IPage<StudioVO>> page(PageVO pageVO, String status) { return ResultUtil.data(studioService.studioList(pageVO, null, status)); } @ApiOperation(value = "获取店铺直播间详情") @ApiImplicitParam(name = "studioId", value = "直播间ID", required = true, dataType = "String", paramType = "path") @GetMapping("/studioInfo/{studioId}") public ResultMessage<StudioVO> studioInfo(@PathVariable String studioId) { return ResultUtil.data(OperationalJudgment.judgment(studioService.getStudioVO(studioId))); } @ApiOperation(value = "添加直播间") @PostMapping public ResultMessage<Object> add(@Validated Studio studio) { if (Boolean.TRUE.equals(studioService.create(studio))) { return ResultUtil.success(ResultCode.SUCCESS); } throw new ServiceException(ResultCode.ERROR); } @ApiOperation(value = "修改直播间") @PutMapping("/edit") public ResultMessage<Object> edit(Studio studio) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "店铺直播间添加商品") @ApiImplicitParams({ @ApiImplicitParam(name = "roomId", value = "房间ID", required = true, dataType = "Integer", paramType = "path"), @ApiImplicitParam(name = "liveGoodsId", value = "直播商品ID", required = true, dataType = "Integer", paramType = "path") }) @PutMapping(value = "/push/{roomId}/{liveGoodsId}") public ResultMessage<Studio> push(@PathVariable Integer roomId, @PathVariable Integer liveGoodsId, @RequestParam String goodsId) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); if (Boolean.TRUE.equals(studioService.push(roomId, liveGoodsId, storeId, goodsId))) { return ResultUtil.success(ResultCode.SUCCESS); } throw new ServiceException(ResultCode.ERROR); } @ApiOperation(value = "店铺直播间删除商品") @ApiImplicitParams({ @ApiImplicitParam(name = "roomId", value = "房间ID", required = true, dataType = "Integer", paramType = "path"), @ApiImplicitParam(name = "liveGoodsId", value = "直播商品ID", required = true, dataType = "Integer", paramType = "path") }) @DeleteMapping(value = "/deleteInRoom/{roomId}/{liveGoodsId}") public ResultMessage<Studio> deleteInRoom(@PathVariable Integer roomId, @PathVariable Integer liveGoodsId) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); if (Boolean.TRUE.equals(studioService.goodsDeleteInRoom(roomId, liveGoodsId, storeId))) { return ResultUtil.success(ResultCode.SUCCESS); } throw new ServiceException(ResultCode.ERROR); } }
OperationalJudgment.judgment(studioService.getById(studio.getId())); if (Boolean.TRUE.equals(studioService.edit(studio))) { return ResultUtil.success(ResultCode.SUCCESS); } throw new ServiceException(ResultCode.ERROR);
886
78
964
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/permission/ClerkStoreController.java
ClerkStoreController
add
class ClerkStoreController { @Autowired private ClerkService clerkService; @Autowired private MemberService memberService; @GetMapping @ApiOperation(value = "分页获取店员列表") public ResultMessage<IPage<ClerkVO>> page(ClerkQueryDTO clerkQueryDTO, PageVO pageVo) { IPage<ClerkVO> page = clerkService.clerkForPage(pageVo, clerkQueryDTO); return ResultUtil.data(page); } @GetMapping("/{id}") @ApiOperation(value = "获取店员详细") public ResultMessage<ClerkVO> get(@PathVariable String id) { return ResultUtil.data(clerkService.get(id)); } @PostMapping("/{mobile}/check") @ApiOperation(value = "检测手机号码有效性") public ResultMessage<Object> check(@PathVariable @Phone(message = "手机号码格式不正确") String mobile) { return ResultUtil.data(clerkService.checkClerk(mobile)); } @PostMapping @ApiOperation(value = "添加店员") public ResultMessage<Object> add(@Valid ClerkAddDTO clerkAddDTO) {<FILL_FUNCTION_BODY>} @PutMapping("/{id}") @ApiImplicitParam(name = "id", value = "店员id", required = true, paramType = "path") @ApiOperation(value = "修改店员") public ResultMessage<Clerk> edit(@PathVariable String id, @Valid ClerkEditDTO clerkEditDTO) { clerkEditDTO.setId(id); return ResultUtil.data(clerkService.updateClerk(clerkEditDTO)); } @PutMapping(value = "/enable/{clerkId}") @ApiOperation(value = "禁/启 用 店员") @DemoSite public ResultMessage<Object> disable(@ApiParam("用户唯一id标识") @PathVariable String clerkId, Boolean status) { clerkService.disable(clerkId, status); return ResultUtil.success(); } @DeleteMapping(value = "/delByIds/{ids}") @ApiOperation(value = "删除店员") public ResultMessage<Object> deleteClerk(@PathVariable List<String> ids) { clerkService.deleteClerk(ids); return ResultUtil.success(); } @PostMapping(value = "/resetPassword/{ids}") @ApiOperation(value = "重置密码") @DemoSite public ResultMessage<Object> resetPassword(@PathVariable List ids) { clerkService.resetPassword(ids); return ResultUtil.success(ResultCode.USER_EDIT_SUCCESS); } }
int rolesMaxSize = 10; try { if (clerkAddDTO.getRoles() != null && clerkAddDTO.getRoles().size() >= rolesMaxSize) { throw new ServiceException(ResultCode.PERMISSION_BEYOND_TEN); } //校验是否已经是会员 Member member = memberService.findByMobile(clerkAddDTO.getMobile()); if (member == null) { //添加会员 MemberAddDTO memberAddDTO = new MemberAddDTO(); memberAddDTO.setMobile(clerkAddDTO.getMobile()); memberAddDTO.setPassword(clerkAddDTO.getPassword()); memberAddDTO.setUsername(clerkAddDTO.getUsername()); member = memberService.addMember(memberAddDTO); } else { //校验要添加的会员是否已经是店主 if (Boolean.TRUE.equals(member.getHaveStore())) { throw new ServiceException(ResultCode.STORE_APPLY_DOUBLE_ERROR); } //校验会员的有效性 if (Boolean.FALSE.equals(member.getDisabled())) { throw new ServiceException(ResultCode.USER_STATUS_ERROR); } } //添加店员 clerkAddDTO.setMemberId(member.getId()); clerkAddDTO.setShopkeeper(false); clerkAddDTO.setStoreId(UserContext.getCurrentUser().getStoreId()); clerkService.saveClerk(clerkAddDTO); //修改此会员拥有店铺 List<String> ids = new ArrayList<>(); ids.add(member.getId()); memberService.updateHaveShop(true, UserContext.getCurrentUser().getStoreId(), ids); } catch (ServiceException se) { log.info(se.getMsg(), se); throw se; } catch (Exception e) { log.error("添加店员出错", e); } return ResultUtil.success();
719
515
1,234
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/promotion/CouponStoreController.java
CouponStoreController
updateCouponStatus
class CouponStoreController { @Autowired private CouponService couponService; @Autowired private MemberCouponService memberCouponService; @GetMapping @ApiOperation(value = "获取优惠券列表") public ResultMessage<IPage<CouponVO>> getCouponList(CouponSearchParams queryParam, PageVO page) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); queryParam.setStoreId(storeId); IPage<CouponVO> coupons = couponService.pageVOFindAll(queryParam, page); return ResultUtil.data(coupons); } @ApiOperation(value = "获取优惠券详情") @GetMapping("/{couponId}") public ResultMessage<Coupon> getCouponList(@PathVariable String couponId) { CouponVO coupon = OperationalJudgment.judgment(couponService.getDetail(couponId)); return ResultUtil.data(coupon); } @ApiOperation(value = "添加优惠券") @PostMapping(consumes = "application/json", produces = "application/json") public ResultMessage<CouponVO> addCoupon(@RequestBody CouponVO couponVO) { AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser()); couponVO.setStoreId(currentUser.getStoreId()); couponVO.setStoreName(currentUser.getStoreName()); if (couponService.savePromotions(couponVO)) { return ResultUtil.data(couponVO); } return ResultUtil.error(ResultCode.COUPON_SAVE_ERROR); } @PutMapping(consumes = "application/json", produces = "application/json") @ApiOperation(value = "修改优惠券") public ResultMessage<Coupon> updateCoupon(@RequestBody CouponVO couponVO) { OperationalJudgment.judgment(couponService.getById(couponVO.getId())); AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser()); couponVO.setStoreId(currentUser.getStoreId()); couponVO.setStoreName(currentUser.getStoreName()); if (couponService.updatePromotions(couponVO)) { return ResultUtil.data(couponVO); } return ResultUtil.error(ResultCode.COUPON_SAVE_ERROR); } @DeleteMapping(value = "/{ids}") @ApiOperation(value = "批量删除") public ResultMessage<Object> delAllByIds(@PathVariable List<String> ids) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); LambdaQueryWrapper<Coupon> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.in(Coupon::getId, ids); queryWrapper.eq(Coupon::getStoreId, storeId); List<Coupon> list = couponService.list(queryWrapper); List<String> filterIds = list.stream().map(Coupon::getId).collect(Collectors.toList()); return couponService.removePromotions(filterIds) ? ResultUtil.success() : ResultUtil.error(ResultCode.COUPON_DELETE_ERROR); } @ApiOperation(value = "获取优惠券领取详情") @GetMapping(value = "/received") public ResultMessage<IPage<MemberCouponVO>> getReceiveByPage(MemberCouponSearchParams searchParams, PageVO page) { searchParams.setStoreId(Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId()); IPage<MemberCouponVO> result = memberCouponService.getMemberCouponsPage(PageUtil.initPage(page), searchParams); return ResultUtil.data(result); } @ApiOperation(value = "修改优惠券状态") @PutMapping("/status") public ResultMessage<Object> updateCouponStatus(String couponIds, Long startTime, Long endTime) {<FILL_FUNCTION_BODY>} }
AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser()); String[] split = couponIds.split(","); List<String> couponIdList = couponService.list(new LambdaQueryWrapper<Coupon>().in(Coupon::getId, Arrays.asList(split)).eq(Coupon::getStoreId, currentUser.getStoreId())).stream().map(Coupon::getId).collect(Collectors.toList()); if (couponService.updateStatus(couponIdList, startTime, endTime)) { return ResultUtil.success(ResultCode.COUPON_EDIT_STATUS_SUCCESS); } throw new ServiceException(ResultCode.COUPON_EDIT_STATUS_ERROR);
1,058
184
1,242
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/promotion/PintuanStoreController.java
PintuanStoreController
addPintuan
class PintuanStoreController { @Autowired private PintuanService pintuanService; @Autowired private PromotionGoodsService promotionGoodsService; @GetMapping @ApiOperation(value = "根据条件分页查询拼团活动列表") public ResultMessage<IPage<Pintuan>> getPintuanByPage(PintuanSearchParams queryParam, PageVO pageVo) { AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser()); queryParam.setStoreId(currentUser.getStoreId()); return ResultUtil.data(pintuanService.pageFindAll(queryParam, pageVo)); } @GetMapping(value = "/{id}") @ApiOperation(value = "通过id获取") public ResultMessage<PintuanVO> get(@PathVariable String id) { PintuanVO pintuan = OperationalJudgment.judgment(pintuanService.getPintuanVO(id)); return ResultUtil.data(pintuan); } @GetMapping("/goods/{pintuanId}") @ApiOperation(value = "根据条件分页查询拼团活动商品列表") public ResultMessage<IPage<PromotionGoods>> getPintuanGoodsByPage(@PathVariable String pintuanId, PageVO pageVo) { AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser()); PromotionGoodsSearchParams searchParams = new PromotionGoodsSearchParams(); searchParams.setStoreId(currentUser.getStoreId()); searchParams.setPromotionId(pintuanId); searchParams.setPromotionType(PromotionTypeEnum.PINTUAN.name()); return ResultUtil.data(promotionGoodsService.pageFindAll(searchParams, pageVo)); } @PostMapping(consumes = "application/json", produces = "application/json") @ApiOperation(value = "添加拼团活动") public ResultMessage<String> addPintuan(@RequestBody @Validated PintuanVO pintuan) {<FILL_FUNCTION_BODY>} @PutMapping(consumes = "application/json", produces = "application/json") @ApiOperation(value = "修改拼团活动") public ResultMessage<String> editPintuan(@RequestBody @Validated PintuanVO pintuan) { OperationalJudgment.judgment(pintuanService.getById(pintuan.getId())); AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser()); pintuan.setStoreId(currentUser.getStoreId()); pintuan.setStoreName(currentUser.getStoreName()); if (pintuan.getPromotionGoodsList() != null && !pintuan.getPromotionGoodsList().isEmpty()) { List<String> skuIds = pintuan.getPromotionGoodsList().stream().map(PromotionGoods::getSkuId).collect(Collectors.toList()); pintuan.setScopeId(ArrayUtil.join(skuIds.toArray(), ",")); } else { pintuan.setScopeId(null); } if (pintuanService.updatePromotions(pintuan)) { return ResultUtil.success(ResultCode.PINTUAN_EDIT_SUCCESS); } throw new ServiceException(ResultCode.PINTUAN_EDIT_ERROR); } @PutMapping("/status/{pintuanId}") @ApiOperation(value = "操作拼团活动状态") public ResultMessage<String> openPintuan(@PathVariable String pintuanId, Long startTime, Long endTime) { OperationalJudgment.judgment(pintuanService.getById(pintuanId)); if (pintuanService.updateStatus(Collections.singletonList(pintuanId), startTime, endTime)) { return ResultUtil.success(ResultCode.PINTUAN_MANUAL_OPEN_SUCCESS); } throw new ServiceException(ResultCode.PINTUAN_MANUAL_OPEN_ERROR); } @DeleteMapping("/{pintuanId}") @ApiOperation(value = "手动删除拼团活动") public ResultMessage<String> deletePintuan(@PathVariable String pintuanId) { OperationalJudgment.judgment(pintuanService.getById(pintuanId)); if (pintuanService.removePromotions(Collections.singletonList(pintuanId))) { return ResultUtil.success(ResultCode.PINTUAN_DELETE_SUCCESS); } throw new ServiceException(ResultCode.PINTUAN_DELETE_ERROR); } }
AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser()); pintuan.setStoreId(currentUser.getStoreId()); pintuan.setStoreName(currentUser.getStoreName()); if (pintuanService.savePromotions(pintuan)) { return ResultUtil.success(ResultCode.PINTUAN_ADD_SUCCESS); } throw new ServiceException(ResultCode.PINTUAN_ADD_ERROR);
1,193
119
1,312
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/promotion/SeckillStoreController.java
SeckillStoreController
addSeckillApply
class SeckillStoreController { @Autowired private SeckillService seckillService; @Autowired private SeckillApplyService seckillApplyService; @GetMapping @ApiOperation(value = "获取秒杀活动列表") public ResultMessage<IPage<Seckill>> getSeckillPage(SeckillSearchParams queryParam, PageVO pageVo) { IPage<Seckill> seckillPage = seckillService.pageFindAll(queryParam, pageVo); return ResultUtil.data(seckillPage); } @GetMapping("/apply") @ApiOperation(value = "获取秒杀活动申请列表") public ResultMessage<IPage<SeckillApply>> getSeckillApplyPage(SeckillSearchParams queryParam, PageVO pageVo) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); queryParam.setStoreId(storeId); IPage<SeckillApply> seckillPage = seckillApplyService.getSeckillApplyPage(queryParam, pageVo); return ResultUtil.data(seckillPage); } @GetMapping("/{seckillId}") @ApiOperation(value = "获取秒杀活动信息") public ResultMessage<Seckill> getSeckill(@PathVariable String seckillId) { return ResultUtil.data(seckillService.getById(seckillId)); } @GetMapping("/apply/{seckillApplyId}") @ApiOperation(value = "获取秒杀活动申请") public ResultMessage<SeckillApply> getSeckillApply(@PathVariable String seckillApplyId) { SeckillApply seckillApply = OperationalJudgment.judgment(seckillApplyService.getById(seckillApplyId)); return ResultUtil.data(seckillApply); } @PostMapping(path = "/apply/{seckillId}", consumes = "application/json", produces = "application/json") @ApiOperation(value = "添加秒杀活动申请") public ResultMessage<String> addSeckillApply(@PathVariable String seckillId, @RequestBody List<SeckillApplyVO> applyVos) {<FILL_FUNCTION_BODY>} @DeleteMapping("/apply/{seckillId}/{id}") @ApiOperation(value = "删除秒杀活动商品") public ResultMessage<String> deleteSeckillApply(@PathVariable String seckillId, @PathVariable String id) { OperationalJudgment.judgment(seckillApplyService.getById(id)); seckillApplyService.removeSeckillApply(seckillId, id); return ResultUtil.success(); } }
String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); seckillApplyService.addSeckillApply(seckillId, storeId, applyVos); return ResultUtil.success();
706
61
767
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/settings/PageDataStoreController.java
PageDataStoreController
getPageData
class PageDataStoreController { @Autowired private PageDataService pageDataService; @ApiOperation(value = "页面列表") @ApiImplicitParam(name = "pageClientType", value = "客户端类型", required = true, dataType = "String", paramType = "path") @GetMapping("/{pageClientType}/pageDataList") public ResultMessage<IPage<PageDataListVO>> pageDataList(@PathVariable String pageClientType, PageVO pageVO) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); PageDataDTO pageDataDTO = new PageDataDTO(); pageDataDTO.setPageType(PageEnum.STORE.name()); pageDataDTO.setPageClientType(pageClientType); pageDataDTO.setNum(storeId); return ResultUtil.data(pageDataService.getPageDataList(pageVO, pageDataDTO)); } @ApiOperation(value = "获取页面信息") @ApiImplicitParam(name = "id", value = "页面ID", required = true, dataType = "String", paramType = "path") @GetMapping(value = "/{id}") public ResultMessage<PageData> getPageData(@PathVariable String id) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "添加页面") @PostMapping("/save") public ResultMessage<PageData> addPageData(@Valid PageData pageData) { //添加店铺类型,填写店铺ID pageData.setPageType(PageEnum.STORE.name()); pageData.setNum(UserContext.getCurrentUser().getStoreId()); return ResultUtil.data(pageDataService.addPageData(pageData)); } @ApiOperation(value = "修改页面") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "页面ID", required = true, dataType = "String", paramType = "path") }) @PutMapping("/update/{id}") public ResultMessage<PageData> updatePageData(@Valid PageData pageData, @NotNull @PathVariable String id) { this.checkAuthority(id); pageData.setId(id); //添加店铺类型,填写店铺ID pageData.setPageType(PageEnum.STORE.name()); pageData.setNum(UserContext.getCurrentUser().getStoreId()); return ResultUtil.data(pageDataService.updatePageData(pageData)); } @ApiOperation(value = "发布页面") @ApiImplicitParam(name = "id", value = "页面ID", required = true, dataType = "String", paramType = "path") @PutMapping("/release/{id}") public ResultMessage<PageData> release(@PathVariable String id) { this.checkAuthority(id); return ResultUtil.data(pageDataService.releasePageData(id)); } @ApiOperation(value = "删除页面") @ApiImplicitParam(name = "id", value = "页面ID", required = true, dataType = "String", paramType = "path") @DeleteMapping("/removePageData/{id}") public ResultMessage<Object> remove(@PathVariable String id) { this.checkAuthority(id); return ResultUtil.data(pageDataService.removePageData(id)); } /** * 店铺权限判定 * * @param id */ private void checkAuthority(String id) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); LambdaQueryWrapper<PageData> queryWrapper = new LambdaQueryWrapper<PageData>().eq(PageData::getId, id).eq(PageData::getPageType, PageEnum.STORE.name()).eq(PageData::getNum, storeId); PageData data = pageDataService.getOne(queryWrapper); if (data == null) { throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR); } } }
//查询当前店铺下的页面数据 PageData pageData = pageDataService.getOne( new LambdaQueryWrapper<PageData>() .eq(PageData::getPageType, PageEnum.STORE.name()) .eq(PageData::getNum, UserContext.getCurrentUser().getStoreId()) .eq(PageData::getId, id)); return ResultUtil.data(pageData);
1,041
107
1,148
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/settings/StoreAddressController.java
StoreAddressController
edit
class StoreAddressController { /** * 店铺自提点 */ @Autowired private StoreAddressService storeAddressService; @ApiOperation(value = "获取商家自提点分页") @GetMapping public ResultMessage<IPage<StoreAddress>> get(PageVO pageVo) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); return ResultUtil.data(storeAddressService.getStoreAddress(storeId, pageVo)); } @ApiOperation(value = "获取商家自提点信息") @ApiImplicitParam(name = "id", value = "自提点ID", required = true, paramType = "path") @GetMapping("/{id}") public ResultMessage<StoreAddress> get(@PathVariable String id) { StoreAddress address = OperationalJudgment.judgment(storeAddressService.getById(id)); return ResultUtil.data(address); } @ApiOperation(value = "添加") @PostMapping public ResultMessage<StoreAddress> add(@Valid StoreAddress storeAddress) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); storeAddress.setStoreId(storeId); storeAddressService.save(storeAddress); return ResultUtil.data(storeAddress); } @ApiOperation(value = "编辑") @ApiImplicitParam(name = "id", value = "自提点ID", required = true, paramType = "path") @PutMapping("/{id}") public ResultMessage<StoreAddress> edit(@PathVariable String id, @Valid StoreAddress storeAddress) {<FILL_FUNCTION_BODY>} @ApiOperation(value = "删除") @ApiImplicitParam(name = "id", value = "自提点ID", required = true, paramType = "path") @DeleteMapping(value = "/{id}") public ResultMessage<Object> delByIds(@PathVariable String id) { OperationalJudgment.judgment(storeAddressService.getById(id)); storeAddressService.removeStoreAddress(id); return ResultUtil.success(); } }
OperationalJudgment.judgment(storeAddressService.getById(id)); String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); storeAddress.setId(id); storeAddress.setStoreId(storeId); storeAddressService.updateById(storeAddress); return ResultUtil.data(storeAddress);
556
94
650
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/controller/statistics/RefundOrderStatisticsStoreController.java
RefundOrderStatisticsStoreController
getPrice
class RefundOrderStatisticsStoreController { @Autowired private RefundOrderStatisticsService refundOrderStatisticsService; @ApiOperation(value = "获取退款统计列表") @GetMapping("/getByPage") public ResultMessage<IPage<RefundOrderStatisticsDataVO>> getByPage(PageVO pageVO, StatisticsQueryParam statisticsQueryParam) { String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); statisticsQueryParam.setStoreId(storeId); return ResultUtil.data(refundOrderStatisticsService.getRefundOrderStatisticsData(pageVO, statisticsQueryParam)); } @ApiOperation(value = "获取退款统计金额") @GetMapping("/getPrice") public ResultMessage<Object> getPrice(StatisticsQueryParam statisticsQueryParam) {<FILL_FUNCTION_BODY>} }
String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId(); statisticsQueryParam.setStoreId(storeId); Double price = refundOrderStatisticsService.getRefundOrderStatisticsPrice(statisticsQueryParam); return ResultUtil.data(price);
223
74
297
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/security/StoreAuthenticationFilter.java
StoreAuthenticationFilter
getAuthentication
class StoreAuthenticationFilter extends BasicAuthenticationFilter { private final Cache cache; private final StoreTokenGenerate storeTokenGenerate; private final StoreMenuRoleService storeMenuRoleService; private final ClerkService clerkService; public StoreAuthenticationFilter(AuthenticationManager authenticationManager, StoreTokenGenerate storeTokenGenerate, StoreMenuRoleService storeMenuRoleService, ClerkService clerkService, Cache cache) { super(authenticationManager); this.storeTokenGenerate = storeTokenGenerate; this.storeMenuRoleService = storeMenuRoleService; this.clerkService = clerkService; this.cache = cache; } @SneakyThrows @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { //从header中获取jwt String jwt = request.getHeader(SecurityEnum.HEADER_TOKEN.getValue()); //如果没有token 则return if (StrUtil.isBlank(jwt)) { chain.doFilter(request, response); return; } //获取用户信息,存入context UsernamePasswordAuthenticationToken authentication = getAuthentication(jwt, response); //自定义权限过滤 if (authentication != null) { customAuthentication(request, response, authentication); SecurityContextHolder.getContext().setAuthentication(authentication); } chain.doFilter(request, response); } /** * 获取token信息 * * @param jwt * @param response * @return */ private UsernamePasswordAuthenticationToken getAuthentication(String jwt, HttpServletResponse response) {<FILL_FUNCTION_BODY>} /** * 自定义权限过滤 * * @param request 请求 * @param response 响应 * @param authentication 用户信息 */ private void customAuthentication(HttpServletRequest request, HttpServletResponse response, UsernamePasswordAuthenticationToken authentication) throws NoPermissionException { AuthUser authUser = (AuthUser) authentication.getDetails(); String requestUrl = request.getRequestURI(); //如果不是超级管理员, 则鉴权 if (Boolean.FALSE.equals(authUser.getIsSuper())) { String permissionCacheKey = CachePrefix.PERMISSION_LIST.getPrefix(UserEnums.STORE) + authUser.getId(); //获取缓存中的权限 Map<String, List<String>> permission = (Map<String, List<String>>) cache.get(permissionCacheKey); if (permission == null || permission.isEmpty()) { //根据会员id查询店员信息 Clerk clerk = clerkService.getClerkByMemberId(authUser.getId()); if (clerk != null) { permission = storeTokenGenerate.permissionList(storeMenuRoleService.findAllMenu(clerk.getId(), authUser.getId())); cache.put(permissionCacheKey, permission); } } //获取数据(GET 请求)权限 if (request.getMethod().equals(RequestMethod.GET.name())) { //如果用户的超级权限和查阅权限都不包含当前请求的api if (match(permission.get(PermissionEnum.SUPER.name()), requestUrl) || match(permission.get(PermissionEnum.QUERY.name()), requestUrl)) { } else { ResponseUtil.output(response, ResponseUtil.resultMap(false, 400, "权限不足")); log.error("当前请求路径:{},所拥有权限:{}", requestUrl, JSONUtil.toJsonStr(permission)); throw new NoPermissionException("权限不足"); } } //非get请求(数据操作) 判定鉴权 else { if (!match(permission.get(PermissionEnum.SUPER.name()), requestUrl)) { ResponseUtil.output(response, ResponseUtil.resultMap(false, 400, "权限不足")); log.error("当前请求路径:{},所拥有权限:{}", requestUrl, JSONUtil.toJsonStr(permission)); throw new NoPermissionException("权限不足"); } } } } /** * 校验权限 * * @param permissions 权限集合 * @param url 请求地址 * @return 是否拥有权限 */ boolean match(List<String> permissions, String url) { if (permissions == null || permissions.isEmpty()) { return false; } return PatternMatchUtils.simpleMatch(permissions.toArray(new String[0]), url); } }
try { Claims claims = Jwts.parser() .setSigningKey(SecretKeyUtil.generalKeyByDecoders()) .parseClaimsJws(jwt).getBody(); //获取存储在claims中的用户信息 String json = claims.get(SecurityEnum.USER_CONTEXT.getValue()).toString(); AuthUser authUser = new Gson().fromJson(json, AuthUser.class); //校验redis中是否有权限 if (cache.hasKey(CachePrefix.ACCESS_TOKEN.getPrefix(UserEnums.STORE, authUser.getId()) + jwt)) { //用户角色 List<GrantedAuthority> auths = new ArrayList<>(); auths.add(new SimpleGrantedAuthority("ROLE_" + authUser.getRole().name())); //构造返回信息 UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(authUser.getUsername(), null, auths); authentication.setDetails(authUser); return authentication; } ResponseUtil.output(response, 403, ResponseUtil.resultMap(false, 403, "登录已失效,请重新登录")); return null; } catch (ExpiredJwtException e) { log.debug("user analysis exception:", e); } catch (Exception e) { log.error("user analysis exception:", e); } return null;
1,186
364
1,550
<no_super_class>
lilishop_lilishop
lilishop/seller-api/src/main/java/cn/lili/security/StoreSecurityConfig.java
StoreSecurityConfig
configure
class StoreSecurityConfig extends WebSecurityConfigurerAdapter { /** * 忽略验权配置 */ @Autowired private IgnoredUrlsProperties ignoredUrlsProperties; /** * spring security -》 权限不足处理 */ @Autowired private CustomAccessDeniedHandler accessDeniedHandler; @Autowired private Cache<String> cache; @Autowired private StoreTokenGenerate storeTokenGenerate; @Autowired private StoreMenuRoleService storeMenuRoleService; @Autowired private ClerkService clerkService; @Override protected void configure(HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>} }
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http .authorizeRequests(); //配置的url 不需要授权 for (String url : ignoredUrlsProperties.getUrls()) { registry.antMatchers(url).permitAll(); } registry.and() //禁止网页iframe .headers().frameOptions().disable() .and() .logout() .permitAll() .and() .authorizeRequests() //任何请求 .anyRequest() //需要身份认证 .authenticated() .and() //允许跨域 .cors().configurationSource((CorsConfigurationSource) SpringContextUtil.getBean("corsConfigurationSource")).and() //关闭跨站请求防护 .csrf().disable() //前后端分离采用JWT 不需要session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() //自定义权限拒绝处理类 .exceptionHandling().accessDeniedHandler(accessDeniedHandler) .and() //添加JWT认证过滤器 .addFilter(new StoreAuthenticationFilter(authenticationManager(), storeTokenGenerate, storeMenuRoleService, clerkService, cache));
190
330
520
<no_super_class>
liquibase_liquibase
liquibase/liquibase-cdi-jakarta/src/main/java/liquibase/integration/jakarta/cdi/CDIBootstrap.java
CDIBootstrap
afterBeanDiscovery
class CDIBootstrap implements Extension { private Bean<CDILiquibase> instance; void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager bm) {<FILL_FUNCTION_BODY>} void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager manager) { try { manager.getReference(instance, instance.getBeanClass(), manager.createCreationalContext(instance)).toString(); } catch (Exception ex) { event.addDeploymentProblem(ex); } } }
instance = new Bean<CDILiquibase>() { final AnnotatedType<CDILiquibase> at = bm.createAnnotatedType(CDILiquibase.class); final InjectionTarget<CDILiquibase> it = bm.getInjectionTargetFactory(at).createInjectionTarget(this); @Override public Set<Type> getTypes() { Set<Type> types = new HashSet<>(); types.add(CDILiquibase.class); types.add(Object.class); return types; } @Override public Set<Annotation> getQualifiers() { Set<Annotation> qualifiers = new HashSet<>(); qualifiers.add( new AnnotationLiteral<Default>() { private static final long serialVersionUID = 6919382612875193843L; } ); qualifiers.add( new AnnotationLiteral<Any>() { private static final long serialVersionUID = 972067042069411460L; } ); return qualifiers; } @Override public Class<? extends Annotation> getScope() { return ApplicationScoped.class; } @Override public String getName() { return "cdiLiquibase"; } @Override public Set<Class<? extends Annotation>> getStereotypes() { return Collections.emptySet(); } @Override public Class<?> getBeanClass() { return CDILiquibase.class; } @Override public boolean isAlternative() { return false; } @Override public Set<InjectionPoint> getInjectionPoints() { return it.getInjectionPoints(); } @Override public CDILiquibase create(CreationalContext<CDILiquibase> ctx) { CDILiquibase instance = it.produce(ctx); it.inject(instance, ctx); it.postConstruct(instance); return instance; } @Override public void destroy(CDILiquibase instance, CreationalContext<CDILiquibase> ctx) { it.preDestroy(instance); it.dispose(instance); ctx.release(); } }; abd.addBean(instance);
144
619
763
<no_super_class>
liquibase_liquibase
liquibase/liquibase-cdi-jakarta/src/main/java/liquibase/integration/jakarta/cdi/CDILiquibase.java
CDILiquibase
createLiquibase
class CDILiquibase implements Extension { @Inject @LiquibaseType ResourceAccessor resourceAccessor; @Inject @LiquibaseType protected CDILiquibaseConfig config; @Inject @LiquibaseType private DataSource dataSource; private boolean initialized; private boolean updateSuccessful; public boolean isInitialized() { return initialized; } public boolean isUpdateSuccessful() { return updateSuccessful; } @PostConstruct public void onStartup() { try { Logger log = Scope.getCurrentScope().getLog(getClass()); log.info("Booting Liquibase " + LiquibaseUtil.getBuildVersionInfo()); String hostName; try { hostName = NetUtil.getLocalHostName(); } catch (Exception e) { log.warning("Cannot find hostname: " + e.getMessage()); log.fine("", e); return; } if (!LiquibaseCommandLineConfiguration.SHOULD_RUN.getCurrentValue()) { log.info(String.format("Liquibase did not run on %s because %s was set to false.", hostName, LiquibaseCommandLineConfiguration.SHOULD_RUN.getKey() )); return; } if (!config.getShouldRun()) { log.info(String.format("Liquibase did not run on %s because CDILiquibaseConfig.shouldRun was set to false.", hostName)); return; } initialized = true; performUpdate(); } catch (Throwable e) { Scope.getCurrentScope().getLog(getClass()).severe(e.getMessage(), e); if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new UnexpectedLiquibaseException(e); } } protected void performUpdate() throws LiquibaseException { Connection c = null; Liquibase liquibase = null; try { c = dataSource.getConnection(); liquibase = createLiquibase(c); liquibase.update(new Contexts(config.getContexts()), new LabelExpression(config.getLabels())); updateSuccessful = true; } catch (SQLException e) { throw new DatabaseException(e); } catch (LiquibaseException ex) { updateSuccessful = false; throw ex; } finally { if ((liquibase != null) && (liquibase.getDatabase() != null)) { liquibase.getDatabase().close(); } else if (c != null) { try { c.rollback(); c.close(); } catch (SQLException e) { //nothing to do } } } } @SuppressWarnings("squid:S2095") protected Liquibase createLiquibase(Connection c) throws LiquibaseException {<FILL_FUNCTION_BODY>} /** * Subclasses may override this method add change some database settings such as * default schema before returning the database object. * * @param c * @return a Database implementation retrieved from the {@link liquibase.database.DatabaseFactory}. * @throws DatabaseException */ protected Database createDatabase(Connection c) throws DatabaseException { Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(c)); if (config.getDefaultSchema() != null) { database.setDefaultSchemaName(config.getDefaultSchema()); } return database; } }
Liquibase liquibase = new Liquibase(config.getChangeLog(), resourceAccessor, createDatabase(c)); if (config.getParameters() != null) { for (Map.Entry<String, String> entry : config.getParameters().entrySet()) { liquibase.setChangeLogParameter(entry.getKey(), entry.getValue()); } } if (config.isDropFirst()) { liquibase.dropAll(); } return liquibase;
950
129
1,079
<no_super_class>
liquibase_liquibase
liquibase/liquibase-cdi-jakarta/src/main/java/liquibase/integration/jakarta/cdi/SchemesTreeBuilder.java
SchemaNode
build
class SchemaNode { private final LiquibaseSchema item; private final Collection<SchemaNode> children = new ArrayList<>(); public SchemaNode(LiquibaseSchema item) { this.item = item; } public LiquibaseSchema getItem() { return item; } public Collection<SchemaNode> getChildren() { return Collections.unmodifiableCollection(children); } public void addChild(LiquibaseSchema child) { children.add(new SchemaNode(child)); } public SchemaNode find(String name) { SchemaNode result = null; if (this.item.name().equals(name)) { result = this; } else { for (SchemaNode child : children) { SchemaNode found = child.find(name); if ((result == null) && (found != null)) { result = child.find(name); } else if ((result != null) && (found != null)) { throw new IllegalStateException(String.format( "Duplicate schema names [%s] detected!", result.getItem().name())); } } } return result; } public List<LiquibaseSchema> toList() { List<LiquibaseSchema> list = new ArrayList<>(children.size() + 1); list.add(item); for (SchemaNode child : children) { list.addAll(child.toList()); } return list; } } /** * Builds a collection of schemes sorted according dependencies * * @param schemes All found Liquibase Schema annotations in 'war' or 'ear' type file. * @return sorted collection of schemes */ public List<LiquibaseSchema> build(final String id, Collection<LiquibaseSchema> schemes) {<FILL_FUNCTION_BODY>
log.fine(String.format("[id = %s] build(%s)", id, schemes)); log.info(String.format("[id = %s] Sorting schemes according dependencies...", id)); if (schemes.isEmpty()) { return Collections.emptyList(); } SchemaNode root = null; // first, copy schemes to no modify source collection schemes = new ArrayList<>(schemes); Collection<LiquibaseSchema> availableSchemes = new ArrayList<>(schemes); // then find not dependent schemes - this will the roots of hierarchy. List<LiquibaseSchema> notDependent = new ArrayList<>(); for (LiquibaseSchema liquibaseSchema : schemes) { String depends = liquibaseSchema.depends(); if (depends.trim().isEmpty()) { notDependent.add(liquibaseSchema); } } log.info(String.format("[id = %s] Found [%s] not dependent schemes.", id, notDependent.size())); if (notDependent.isEmpty()) { // if there is no not-dependent schema, then there is a cyclic dependency. throw new CyclicDependencyException(String.format("[id = %s] Not independent schemes, possible cyclic dependencies discovered.", id)); } else { // take first of not-dependent and use it as root of hierarchy. root = new SchemaNode(notDependent.get(0)); log.fine(String.format("[id = %s] Selected dependencies tree root [%s]", id, root.getItem())); availableSchemes.removeAll(notDependent); // we won't to check not-dependent schemes. notDependent.remove(root.getItem()); // remove root from not-dependent schemes schemes.retainAll(availableSchemes); // remove not-dependent from all schemes // now make all not-dependent schemes children to selected root. for (LiquibaseSchema liquibaseSchema : notDependent) { root.addChild(liquibaseSchema); } log.fine(String.format("[id = %s] Made other non-dependent schemes children of root. [%s] dependent schemes to resolve. Resolving...", id, availableSchemes.size() )); int cycles = 0; long start = System.currentTimeMillis(); // until we resolve all dependencies while (!availableSchemes.isEmpty()) { cycles++; log.fine(String.format("[id = %s] Resolution cycle [%s] started.", id, cycles)); int additions = 0; //we will count dependencies resolution for each resolution cycle. for (LiquibaseSchema liquibaseSchema : schemes) { log.fine(String.format( "[id = %s] LiquibaseSchema [name=%s] depends on liquibaseSchema [name=%s].", id, liquibaseSchema.name(), liquibaseSchema.depends() )); SchemaNode parent = root.find(liquibaseSchema.depends()); // we make the dependent liquibaseSchema as a child for it's dependency if found. If not, we just continue. if (parent == null) { log.fine(String.format( "[id = %s] Dependency not found in resolved dependencies tree, skipping liquibaseSchema [name=%s] for a while.", id, liquibaseSchema.name() )); boolean isDependencyMissed = true; for (LiquibaseSchema tmpLiquibaseSchema : availableSchemes) { if (tmpLiquibaseSchema.name().equalsIgnoreCase(liquibaseSchema.depends())) { isDependencyMissed = false; break; } } if (isDependencyMissed) { throw new DependencyNotFoundException(String.format( "[id = %s][name=%s] depends on [name=%s], but it is not found!", id, liquibaseSchema.name(), liquibaseSchema.depends() )); } } else { log.fine(String.format( "[id = %s] Dependency found for liquibaseSchema [name=%s], moving it to resolved dependencies tree.", id, liquibaseSchema.name() )); parent.addChild(liquibaseSchema); availableSchemes.remove(liquibaseSchema); additions++; } } log.fine(String.format("[id = %s] Resolution cycle [%s] completed", id, cycles)); //if not resolutions happened through resolution cycle, definitely there is a cyclic dependency. if (additions == 0) { throw new CyclicDependencyException(String.format("[id = %s] Cyclic dependencies discovered!", id)); } schemes.retainAll(availableSchemes); } log.info(String.format("[id = %s] Dependencies resolved in [cycles=%s, millis=%s]", id, cycles, System.currentTimeMillis() - start)); } return root.toList();
493
1,296
1,789
<no_super_class>
liquibase_liquibase
liquibase/liquibase-cdi/src/main/java/liquibase/integration/cdi/CDIBootstrap.java
CDIBootstrap
afterBeanDiscovery
class CDIBootstrap implements Extension { private Bean<CDILiquibase> instance; void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager bm) {<FILL_FUNCTION_BODY>} void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager manager) { try { manager.getReference(instance, instance.getBeanClass(), manager.createCreationalContext(instance)).toString(); } catch (Exception ex) { event.addDeploymentProblem(ex); } } }
AnnotatedType<CDILiquibase> at = bm.createAnnotatedType(CDILiquibase.class); final InjectionTarget<CDILiquibase> it = bm.createInjectionTarget(at); instance = new Bean<CDILiquibase>() { @Override public Set<Type> getTypes() { Set<Type> types = new HashSet<>(); types.add(CDILiquibase.class); types.add(Object.class); return types; } @Override public Set<Annotation> getQualifiers() { Set<Annotation> qualifiers = new HashSet<>(); qualifiers.add( new AnnotationLiteral<Default>() { private static final long serialVersionUID = 6919382612875193843L; } ); qualifiers.add( new AnnotationLiteral<Any>() { private static final long serialVersionUID = 972067042069411460L; } ); return qualifiers; } @Override public Class<? extends Annotation> getScope() { return ApplicationScoped.class; } @Override public String getName() { return "cdiLiquibase"; } @Override public Set<Class<? extends Annotation>> getStereotypes() { return Collections.emptySet(); } @Override public Class<?> getBeanClass() { return CDILiquibase.class; } @Override public boolean isAlternative() { return false; } @Override public boolean isNullable() { return false; } @Override public Set<InjectionPoint> getInjectionPoints() { return it.getInjectionPoints(); } @Override public CDILiquibase create(CreationalContext<CDILiquibase> ctx) { CDILiquibase localInstance = it.produce(ctx); it.inject(localInstance, ctx); it.postConstruct(localInstance); return localInstance; } @Override public void destroy(CDILiquibase instance, CreationalContext<CDILiquibase> ctx) { it.preDestroy(instance); it.dispose(instance); ctx.release(); } }; abd.addBean(instance);
145
628
773
<no_super_class>
liquibase_liquibase
liquibase/liquibase-cdi/src/main/java/liquibase/integration/cdi/CDILiquibase.java
CDILiquibase
performUpdate
class CDILiquibase implements Extension { @Inject @LiquibaseType ResourceAccessor resourceAccessor; @Inject @LiquibaseType protected CDILiquibaseConfig config; @Inject @LiquibaseType private DataSource dataSource; private boolean initialized; private boolean updateSuccessful; public boolean isInitialized() { return initialized; } public boolean isUpdateSuccessful() { return updateSuccessful; } @PostConstruct public void onStartup() { try { Logger log = Scope.getCurrentScope().getLog(getClass()); log.info("Booting Liquibase " + LiquibaseUtil.getBuildVersionInfo()); String hostName; try { hostName = NetUtil.getLocalHostName(); } catch (Exception e) { log.warning("Cannot find hostname: " + e.getMessage()); log.fine("", e); return; } if (!LiquibaseCommandLineConfiguration.SHOULD_RUN.getCurrentValue()) { log.info(String.format("Liquibase did not run on %s because %s was set to false.", hostName, LiquibaseCommandLineConfiguration.SHOULD_RUN.getKey() )); return; } if (!config.getShouldRun()) { log.info(String.format("Liquibase did not run on %s because CDILiquibaseConfig.shouldRun was set to false.", hostName)); return; } initialized = true; performUpdate(); } catch (Throwable e) { Scope.getCurrentScope().getLog(getClass()).severe(e.getMessage(), e); if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new UnexpectedLiquibaseException(e); } } protected void performUpdate() throws LiquibaseException {<FILL_FUNCTION_BODY>} @java.lang.SuppressWarnings("squid:S2095") protected Liquibase createLiquibase(Connection c) throws LiquibaseException { Liquibase liquibase = new Liquibase(config.getChangeLog(), resourceAccessor, createDatabase(c)); if (config.getParameters() != null) { for (Map.Entry<String, String> entry : config.getParameters().entrySet()) { liquibase.setChangeLogParameter(entry.getKey(), entry.getValue()); } } if (config.isDropFirst()) { liquibase.dropAll(); } return liquibase; } /** * Creates and returns a {@link Database} object retrieved from the {@link liquibase.database.DatabaseFactory}. * Subclasses may override this method to change some database settings, such as default schema, before returning * the database object. * * @param c the {@code JDBC} connection to use for creating the database * @return a {@link Database} implementation retrieved from the {@link liquibase.database.DatabaseFactory} * @throws DatabaseException if there is an error accessing the database */ protected Database createDatabase(Connection c) throws DatabaseException { Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(c)); if (config.getDefaultSchema() != null) { database.setDefaultSchemaName(config.getDefaultSchema()); } return database; } }
Connection c = null; Liquibase liquibase = null; try { c = dataSource.getConnection(); liquibase = createLiquibase(c); liquibase.update(new Contexts(config.getContexts()), new LabelExpression(config.getLabels())); updateSuccessful = true; } catch (SQLException e) { throw new DatabaseException(e); } catch (LiquibaseException ex) { updateSuccessful = false; throw ex; } finally { if ((liquibase != null) && (liquibase.getDatabase() != null)) { liquibase.getDatabase().close(); } else if (c != null) { try { c.rollback(); c.close(); } catch (SQLException e) { //nothing to do } } }
910
230
1,140
<no_super_class>
liquibase_liquibase
liquibase/liquibase-cdi/src/main/java/liquibase/integration/cdi/SchemesTreeBuilder.java
SchemaNode
find
class SchemaNode { private final LiquibaseSchema item; private final Collection<SchemaNode> children = new ArrayList<>(); public SchemaNode(LiquibaseSchema item) { this.item = item; } public LiquibaseSchema getItem() { return item; } public Collection<SchemaNode> getChildren() { return Collections.unmodifiableCollection(children); } public void addChild(LiquibaseSchema child) { children.add(new SchemaNode(child)); } public SchemaNode find(String name) {<FILL_FUNCTION_BODY>} public List<LiquibaseSchema> toList() { List<LiquibaseSchema> list = new ArrayList<>(children.size() + 1); list.add(item); for (SchemaNode child : children) { list.addAll(child.toList()); } return list; } }
SchemaNode result = null; if (this.item.name().equals(name)) { result = this; } else { for (SchemaNode child : children) { SchemaNode found = child.find(name); if ((result == null) && (found != null)) { result = child.find(name); } else if ((result != null) && (found != null)) { throw new IllegalStateException(String.format( "Duplicate schema names [%s] detected!", result.getItem().name())); } } } return result;
251
157
408
<no_super_class>
liquibase_liquibase
liquibase/liquibase-cli/src/main/java/liquibase/integration/commandline/CommandLineArgumentValueProvider.java
CommandLineArgumentValueProvider
keyMatches
class CommandLineArgumentValueProvider extends AbstractMapConfigurationValueProvider { private final SortedMap<String, Object> argumentValues = new TreeMap<>(); public CommandLineArgumentValueProvider(CommandLine.ParseResult parseResult) { while (parseResult != null) { for (CommandLine.Model.OptionSpec option : parseResult.matchedOptions()) { this.argumentValues.put(option.names()[0], option.getValue()); } parseResult = parseResult.subcommand(); } } @Override public int getPrecedence() { return 250; } @Override protected Map<?, ?> getMap() { return argumentValues; } @Override protected boolean keyMatches(String wantedKey, String storedKey) {<FILL_FUNCTION_BODY>} @Override protected String getSourceDescription() { return "Command argument"; } }
storedKey = String.valueOf(storedKey).replaceFirst("^--", ""); if (super.keyMatches(wantedKey, storedKey)) { return true; } if (wantedKey.startsWith("liquibase.command.")) { return super.keyMatches(wantedKey.replaceFirst("^liquibase\\.command\\.", ""), storedKey); } return super.keyMatches(wantedKey.replaceFirst("^liquibase\\.", ""), storedKey);
239
136
375
<methods>public non-sealed void <init>() ,public transient liquibase.configuration.ProvidedValue getProvidedValue(java.lang.String[]) <variables>private final Map<java.lang.String,liquibase.configuration.ProvidedValue> knownValues,private int knownValuesForHash,private final java.util.concurrent.locks.Lock knownValuesLock
liquibase_liquibase
liquibase/liquibase-cli/src/main/java/liquibase/integration/commandline/CommandRunner.java
CommandRunner
call
class CommandRunner implements Callable<CommandResults> { private CommandLine.Model.CommandSpec spec; @Override public CommandResults call() throws Exception {<FILL_FUNCTION_BODY>} public void setSpec(CommandLine.Model.CommandSpec spec) { this.spec = spec; } }
List<String> command = new ArrayList<>(); command.add(spec.commandLine().getCommandName()); CommandLine parentCommand = spec.commandLine().getParent(); while (!parentCommand.getCommandName().equals("liquibase")) { command.add(0, parentCommand.getCommandName()); parentCommand = parentCommand.getParent(); } final String[] commandName = LiquibaseCommandLine.getCommandNames(spec.commandLine()); for (int i=0; i<commandName.length; i++) { commandName[i] = StringUtil.toCamelCase(commandName[i]); } final CommandScope commandScope = new CommandScope(commandName); final String outputFile = LiquibaseCommandLineConfiguration.OUTPUT_FILE.getCurrentValue(); final OutputFileHandlerFactory outputFileHandlerFactory = Scope.getCurrentScope().getSingleton(OutputFileHandlerFactory.class); OutputFileHandler outputFileHandler = outputFileHandlerFactory.getOutputFileHandler(outputFile); try { if (outputFile != null) { outputFileHandler.create(outputFile, commandScope); } return commandScope.execute(); } catch (CommandValidationException cve) { Throwable cause = cve.getCause(); if (cause instanceof MissingRequiredArgumentException) { // This is a list of the arguments which the init project command supports. The thinking here is that if the user // forgets to supply one of these arguments, we're going to remind them about the init project command, which // can help them figure out what they should be providing here. final Set<String> initProjectArguments = Stream.of(CommonArgumentNames.CHANGELOG_FILE, CommonArgumentNames.URL, CommonArgumentNames.USERNAME, CommonArgumentNames.PASSWORD).map(CommonArgumentNames::getArgumentName).collect(Collectors.toSet()); throw new CommandValidationException(cve.getMessage() + (initProjectArguments.contains(((MissingRequiredArgumentException) cause).getArgumentName()) ? ". If you need to configure new liquibase project files and arguments, run the 'liquibase init project' command." : "")); } else { throw cve; } } finally { outputFileHandler.close(); }
83
557
640
<no_super_class>
liquibase_liquibase
liquibase/liquibase-cli/src/main/java/liquibase/integration/commandline/LiquibaseLauncherSettings.java
LiquibaseLauncherSettings
getSetting
class LiquibaseLauncherSettings { private static final String LIQUIBASE_HOME_JVM_PROPERTY_NAME = "liquibase.home"; private static final String LIQUIBASE_LAUNCHER_DEBUG_JVM_PROPERTY_NAME = "liquibase.launcher.debug"; private static final String LIQUIBASE_LAUNCHER_PARENT_CLASSLOADER_JVM_PROPERTY_NAME = "liquibase.launcher.parent_classloader"; /** * Agglutinates the different settings, i.e., environment variables or associated JVM system properties, that can be * used for customizing the behavior of the class. */ enum LiquibaseLauncherSetting { LIQUIBASE_HOME(LIQUIBASE_HOME_JVM_PROPERTY_NAME), LIQUIBASE_LAUNCHER_DEBUG(LIQUIBASE_LAUNCHER_DEBUG_JVM_PROPERTY_NAME), LIQUIBASE_LAUNCHER_PARENT_CLASSLOADER(LIQUIBASE_LAUNCHER_PARENT_CLASSLOADER_JVM_PROPERTY_NAME); private final String jvmPropertyName; LiquibaseLauncherSetting(String jvmPropertyName) { this.jvmPropertyName = jvmPropertyName; } String getJvmPropertyName() { return this.jvmPropertyName; } } static String getSetting(LiquibaseLauncherSetting setting) {<FILL_FUNCTION_BODY>} }
String value = System.getProperty(setting.getJvmPropertyName()); if (value != null) { return value; } return System.getenv(setting.name());
386
52
438
<no_super_class>
liquibase_liquibase
liquibase/liquibase-cli/src/main/java/liquibase/integration/commandline/VersionUtils.java
VersionUtils
listLibraries
class VersionUtils { public static Path getLiquibaseHomePath(Path workingDirectory) throws IOException { return new File(ObjectUtil.defaultIfNull(getSetting(LIQUIBASE_HOME), workingDirectory.toAbsolutePath().toString())).getAbsoluteFile().getCanonicalFile().toPath(); } public static List<String> listLibraries(Map<String, LibraryInfo> libraryInfo, Path liquibaseHomePath, Path workingDirectory, Version mdcVersion) throws IOException {<FILL_FUNCTION_BODY>} public static Map<String, LibraryInfo> getLibraryInfoMap() throws URISyntaxException, IOException { Map<String, LibraryInfo> libraryInfo = new HashMap<>(); final ClassLoader classLoader = VersionUtils.class.getClassLoader(); if (classLoader instanceof URLClassLoader) { for (URL url : ((URLClassLoader) classLoader).getURLs()) { if (!url.toExternalForm().startsWith("file:")) { continue; } final File file = new File(url.toURI()); if (file.getName().equals("liquibase-core.jar")) { continue; } if (file.exists() && file.getName().toLowerCase().endsWith(".jar")) { final LibraryInfo thisInfo = getLibraryInfo(file); libraryInfo.putIfAbsent(thisInfo.name, thisInfo); } } } return libraryInfo; } private static LibraryInfo getLibraryInfo(File pathEntryFile) throws IOException { try (final JarFile jarFile = new JarFile(pathEntryFile)) { final LibraryInfo libraryInfo = new LibraryInfo(); libraryInfo.file = pathEntryFile; final Manifest manifest = jarFile.getManifest(); if (manifest != null) { libraryInfo.name = getValue(manifest, "Bundle-Name", "Implementation-Title", "Specification-Title"); libraryInfo.version = getValue(manifest, "Bundle-Version", "Implementation-Version", "Specification-Version"); libraryInfo.vendor = getValue(manifest, "Bundle-Vendor", "Implementation-Vendor", "Specification-Vendor"); } handleCompilerJarEdgeCase(pathEntryFile, jarFile, libraryInfo); if (libraryInfo.name == null) { libraryInfo.name = pathEntryFile.getName().replace(".jar", ""); } return libraryInfo; } } /** * The compiler.jar file was accidentally added to the liquibase tar.gz distribution, and the compiler.jar * file does not contain a completed MANIFEST.MF file. This method loads the version out of the pom.xml * instead of using the manifest, only for the compiler.jar file. */ private static void handleCompilerJarEdgeCase(File pathEntryFile, JarFile jarFile, LibraryInfo libraryInfo) { try { if (pathEntryFile.toString().endsWith("compiler.jar") && StringUtil.isEmpty(libraryInfo.version)) { ZipEntry entry = jarFile.getEntry("META-INF/maven/com.github.spullara.mustache.java/compiler/pom.properties"); InputStream inputStream = jarFile.getInputStream(entry); Properties jarProperties = new Properties(); jarProperties.load(inputStream); libraryInfo.version = jarProperties.getProperty("version"); } } catch (Exception e) { Scope.getCurrentScope().getLog(VersionUtils.class).fine("Failed to load the version of compiler.jar from " + "its pom.properties, this is relatively harmless, but could mean that the version of compiler.jar will " + "not appear in the liquibase --version console output.", e); } } private static String getValue(Manifest manifest, String... keys) { for (String key : keys) { String value = manifest.getMainAttributes().getValue(key); if (value != null) { return value; } } return null; } public static class LibraryInfo implements Comparable<LibraryInfo> { public String vendor; public String name; public File file; public String version; @Override public int compareTo(LibraryInfo o) { return this.file.compareTo(o.file); } } }
List<Version.Library> mdcLibraries = new ArrayList<>(libraryInfo.size()); List<String> libraries = new ArrayList<>(libraryInfo.size()); for (LibraryInfo info : new TreeSet<>(libraryInfo.values())) { String filePath = info.file.getCanonicalPath(); if (liquibaseHomePath != null && info.file.toPath().startsWith(liquibaseHomePath)) { filePath = liquibaseHomePath.relativize(info.file.toPath()).toString(); } if (info.file.toPath().startsWith(workingDirectory)) { filePath = workingDirectory.relativize(info.file.toPath()).toString(); } String libraryDescription = filePath + ":" + " " + info.name + " " + (info.version == null ? "UNKNOWN" : info.version) + (info.vendor == null ? "" : " By " + info.vendor); libraries.add(libraryDescription); mdcLibraries.add(new Version.Library(info.name, filePath)); } if (mdcVersion != null) { mdcVersion.setLiquibaseLibraries(new Version.LiquibaseLibraries(libraryInfo.size(), mdcLibraries)); } return libraries;
1,084
335
1,419
<no_super_class>
liquibase_liquibase
liquibase/liquibase-maven-plugin/src/main/java/org/liquibase/maven/plugins/AbstractLiquibaseChangeLogMojo.java
AbstractLiquibaseChangeLogMojo
getResourceAccessor
class AbstractLiquibaseChangeLogMojo extends AbstractLiquibaseMojo { /** * Specifies the directory where Liquibase can find your <i>changelog</i> file. This is an aliases for searchPath * * @parameter property="liquibase.changeLogDirectory" */ @PropertyElement protected String changeLogDirectory; /** * Specifies the <i>changelog</i> file for Liquibase to use. * * @parameter property="liquibase.changeLogFile" */ @PropertyElement protected String changeLogFile; /** * Specifies which contexts Liquibase will execute, which can be separated by a comma if multiple contexts are required. * If a context is not specified, then ALL contexts will be executed. * * @parameter property="liquibase.contexts" default-value="" */ @PropertyElement protected String contexts; /** * Deprecated version of labelFilter * * @parameter property="liquibase.labels" default-value="" * @deprecated */ @PropertyElement protected String labels; /** * Specifies which Liquibase labels Liquibase will execute, which can be separated by a comma if multiple labels are required or you need to designate a more complex expression. * If a label is not specified, then ALL labels will be executed. * * @parameter property="liquibase.labelFilter" default-value="" */ @PropertyElement protected String labelFilter; /** * How to handle multiple files being found in the search path that have duplicate paths. * Options are WARN (log warning and choose one at random) or ERROR (fail current operation) * * @parameter property="liquibase.duplicateFileMode" default-value="ERROR" */ @PropertyElement protected String duplicateFileMode; @Override protected void checkRequiredParametersAreSpecified() throws MojoFailureException { super.checkRequiredParametersAreSpecified(); if (changeLogFile == null) { throw new MojoFailureException("The changeLogFile must be specified."); } } /** * Performs the actual Liquibase task on the database using the fully configured {@link * liquibase.Liquibase}. * * @param liquibase The {@link liquibase.Liquibase} that has been fully * configured to run the desired database task. */ @Override protected void performLiquibaseTask(Liquibase liquibase) throws LiquibaseException { if (StringUtil.isNotEmpty(duplicateFileMode)) { DeprecatedConfigurationValueProvider.setData(GlobalConfiguration.DUPLICATE_FILE_MODE.getKey(), GlobalConfiguration.DuplicateFileMode.valueOf(duplicateFileMode.toUpperCase(Locale.ROOT))); } } @Override protected void printSettings(String indent) { super.printSettings(indent); getLog().info(indent + "changeLogDirectory: " + changeLogDirectory); getLog().info(indent + "changeLogFile: " + changeLogFile); getLog().info(indent + "context(s): " + contexts); getLog().info(indent + "label(s): " + getLabelFilter()); } @Override protected ResourceAccessor getResourceAccessor(ClassLoader cl) throws IOException, MojoFailureException {<FILL_FUNCTION_BODY>} @Override protected Liquibase createLiquibase(Database db) throws MojoExecutionException { String changeLog = (changeLogFile == null) ? "" : changeLogFile.trim(); return new Liquibase(changeLog, Scope.getCurrentScope().getResourceAccessor(), db); } private void calculateChangeLogDirectoryAbsolutePath() { if (changeLogDirectory != null) { // convert to standard / if using absolute path on windows changeLogDirectory = changeLogDirectory.trim().replace('\\', '/'); // try to know if it's an absolute or relative path : the absolute path case is simpler and don't need more actions File changeLogDirectoryFile = new File(changeLogDirectory); if (!changeLogDirectoryFile.isAbsolute()) { // we are in the relative path case changeLogDirectory = project.getBasedir().getAbsolutePath().replace('\\', '/') + "/" + changeLogDirectory; } } } public String getLabelFilter() { if (labelFilter == null) { return labels; } return labelFilter; } }
List<ResourceAccessor> resourceAccessors = new ArrayList<>(); resourceAccessors.add(new MavenResourceAccessor(cl)); resourceAccessors.add(new DirectoryResourceAccessor(project.getBasedir())); resourceAccessors.add(new ClassLoaderResourceAccessor(getClass().getClassLoader())); String finalSearchPath = searchPath; if (changeLogDirectory != null) { if (searchPath != null) { throw new MojoFailureException("Cannot specify searchPath and changeLogDirectory at the same time"); } calculateChangeLogDirectoryAbsolutePath(); finalSearchPath = changeLogDirectory; } return new SearchPathResourceAccessor(finalSearchPath, resourceAccessors.toArray(new ResourceAccessor[0]));
1,182
191
1,373
<methods>public non-sealed void <init>() ,public void configureFieldsAndValues() throws MojoExecutionException,public boolean databaseConnectionRequired() ,public void execute() throws MojoExecutionException, MojoFailureException,public synchronized Log getLog() ,public void setPassword(java.lang.String) throws java.lang.Exception,public void setUrl(java.lang.String) throws java.lang.Exception,public void setUsername(java.lang.String) throws java.lang.Exception<variables>private static final java.lang.String DEFAULT_FIELD_SUFFIX,private static final Set<java.lang.String> EXCLUDED_CONFIGURATION_PROPERTIES,protected java.lang.String changeExecListenerClass,protected java.lang.String changeExecListenerPropertiesFile,protected java.lang.String changelogCatalogName,protected java.lang.String changelogSchemaName,protected boolean clearCheckSums,protected java.lang.String commandName,private static final java.util.ResourceBundle coreBundle,protected java.lang.String databaseChangeLogLockTableName,protected java.lang.String databaseChangeLogTableName,protected java.lang.Boolean databaseChangelogHistoryCaptureExtensions,protected java.lang.Boolean databaseChangelogHistoryCaptureSql,protected java.lang.Boolean databaseChangelogHistoryEnabled,protected java.lang.String databaseClass,protected java.lang.Boolean dbclHistoryCaptureExtensions,protected java.lang.Boolean dbclHistoryCaptureSql,protected java.lang.Boolean dbclHistoryEnabled,protected java.lang.String defaultCatalogName,protected liquibase.changelog.visitor.DefaultChangeExecListener defaultChangeExecListener,protected java.lang.String defaultSchemaName,protected java.lang.String driver,private java.io.File driverPropertiesFile,protected boolean emptyPassword,private Map#RAW expressionVariables,private java.util.Properties expressionVars,protected boolean includeArtifact,protected boolean includeTestOutputDirectory,private liquibase.Liquibase liquibase,private java.lang.String liquibaseLicenseKey,private java.lang.String liquibaseProLicenseKey,private org.liquibase.maven.plugins.MavenLog logCache,protected java.lang.String logFormat,protected java.lang.String logLevel,protected java.lang.String logging,protected MojoExecution mojoExecution,protected boolean outputDefaultCatalog,protected boolean outputDefaultSchema,protected java.lang.String outputFileEncoding,protected java.lang.String password,protected java.lang.Boolean preserveSchemaCase,protected MavenProject project,protected boolean promptOnNonLocalDatabase,protected java.lang.String propertyFile,protected boolean propertyFileWillOverride,protected java.lang.String propertyProviderClass,protected java.lang.String psqlArgs,protected java.lang.Boolean psqlKeepTemp,protected java.lang.String psqlKeepTempName,protected java.lang.String psqlKeepTempPath,protected java.lang.String psqlLogFile,protected java.lang.String psqlPath,protected java.lang.Integer psqlTimeout,protected java.lang.String searchPath,private java.lang.String server,protected MavenSession session,protected boolean showBanner,protected boolean skip,protected java.lang.String skipOnFileExists,protected java.lang.String sqlPlusArgs,protected java.lang.Boolean sqlPlusKeepTemp,protected java.lang.String sqlPlusKeepTempName,protected java.lang.Boolean sqlPlusKeepTempOverwrite,protected java.lang.String sqlPlusKeepTempPath,protected java.lang.String sqlPlusLogFile,protected java.lang.String sqlPlusPath,protected java.lang.Integer sqlPlusTimeout,protected java.lang.String sqlcmdArgs,protected java.lang.String sqlcmdCatalogName,protected java.lang.Boolean sqlcmdKeepTemp,protected java.lang.String sqlcmdKeepTempName,protected java.lang.Boolean sqlcmdKeepTempOverwrite,protected java.lang.String sqlcmdKeepTempPath,protected java.lang.String sqlcmdLogFile,protected java.lang.String sqlcmdPath,protected java.lang.Integer sqlcmdTimeout,protected java.util.Properties systemProperties,protected java.lang.String url,protected java.lang.String username,protected boolean verbose,protected WagonManager wagonManager
liquibase_liquibase
liquibase/liquibase-maven-plugin/src/main/java/org/liquibase/maven/plugins/AbstractLiquibaseFlowMojo.java
AbstractLiquibaseFlowMojo
performLiquibaseTask
class AbstractLiquibaseFlowMojo extends AbstractLiquibaseMojo { /** * Specifies the <i>flowFile</i> to use. If not specified, the default * checks will be used and no file will be created. * * @parameter property="liquibase.flowFile" */ @PropertyElement protected String flowFile; /** * @parameter property="liquibase.outputFile" */ @PropertyElement protected File outputFile; /** * Arbitrary map of parameters that the underlying liquibase command will use. These arguments will be passed * verbatim to the underlying liquibase command that is being run. * * @parameter property="flowCommandArguments" */ @PropertyElement protected Map<String, Object> flowCommandArguments; @Override public boolean databaseConnectionRequired() { return false; } @Override protected void performLiquibaseTask(Liquibase liquibase) throws LiquibaseException {<FILL_FUNCTION_BODY>} public abstract String[] getCommandName(); }
CommandScope liquibaseCommand = new CommandScope(getCommandName()); liquibaseCommand.addArgumentValue("flowFile", flowFile); liquibaseCommand.addArgumentValue("flowIntegration", "maven"); if (flowCommandArguments != null) { FlowCommandArgumentValueProvider flowCommandArgumentValueProvider = new FlowCommandArgumentValueProvider(flowCommandArguments); Scope.getCurrentScope().getSingleton(LiquibaseConfiguration.class).registerProvider(flowCommandArgumentValueProvider); } if (outputFile != null) { try { liquibaseCommand.setOutput(Files.newOutputStream(outputFile.toPath())); } catch (IOException e) { throw new CommandExecutionException(e); } } liquibaseCommand.execute();
289
194
483
<methods>public non-sealed void <init>() ,public void configureFieldsAndValues() throws MojoExecutionException,public boolean databaseConnectionRequired() ,public void execute() throws MojoExecutionException, MojoFailureException,public synchronized Log getLog() ,public void setPassword(java.lang.String) throws java.lang.Exception,public void setUrl(java.lang.String) throws java.lang.Exception,public void setUsername(java.lang.String) throws java.lang.Exception<variables>private static final java.lang.String DEFAULT_FIELD_SUFFIX,private static final Set<java.lang.String> EXCLUDED_CONFIGURATION_PROPERTIES,protected java.lang.String changeExecListenerClass,protected java.lang.String changeExecListenerPropertiesFile,protected java.lang.String changelogCatalogName,protected java.lang.String changelogSchemaName,protected boolean clearCheckSums,protected java.lang.String commandName,private static final java.util.ResourceBundle coreBundle,protected java.lang.String databaseChangeLogLockTableName,protected java.lang.String databaseChangeLogTableName,protected java.lang.Boolean databaseChangelogHistoryCaptureExtensions,protected java.lang.Boolean databaseChangelogHistoryCaptureSql,protected java.lang.Boolean databaseChangelogHistoryEnabled,protected java.lang.String databaseClass,protected java.lang.Boolean dbclHistoryCaptureExtensions,protected java.lang.Boolean dbclHistoryCaptureSql,protected java.lang.Boolean dbclHistoryEnabled,protected java.lang.String defaultCatalogName,protected liquibase.changelog.visitor.DefaultChangeExecListener defaultChangeExecListener,protected java.lang.String defaultSchemaName,protected java.lang.String driver,private java.io.File driverPropertiesFile,protected boolean emptyPassword,private Map#RAW expressionVariables,private java.util.Properties expressionVars,protected boolean includeArtifact,protected boolean includeTestOutputDirectory,private liquibase.Liquibase liquibase,private java.lang.String liquibaseLicenseKey,private java.lang.String liquibaseProLicenseKey,private org.liquibase.maven.plugins.MavenLog logCache,protected java.lang.String logFormat,protected java.lang.String logLevel,protected java.lang.String logging,protected MojoExecution mojoExecution,protected boolean outputDefaultCatalog,protected boolean outputDefaultSchema,protected java.lang.String outputFileEncoding,protected java.lang.String password,protected java.lang.Boolean preserveSchemaCase,protected MavenProject project,protected boolean promptOnNonLocalDatabase,protected java.lang.String propertyFile,protected boolean propertyFileWillOverride,protected java.lang.String propertyProviderClass,protected java.lang.String psqlArgs,protected java.lang.Boolean psqlKeepTemp,protected java.lang.String psqlKeepTempName,protected java.lang.String psqlKeepTempPath,protected java.lang.String psqlLogFile,protected java.lang.String psqlPath,protected java.lang.Integer psqlTimeout,protected java.lang.String searchPath,private java.lang.String server,protected MavenSession session,protected boolean showBanner,protected boolean skip,protected java.lang.String skipOnFileExists,protected java.lang.String sqlPlusArgs,protected java.lang.Boolean sqlPlusKeepTemp,protected java.lang.String sqlPlusKeepTempName,protected java.lang.Boolean sqlPlusKeepTempOverwrite,protected java.lang.String sqlPlusKeepTempPath,protected java.lang.String sqlPlusLogFile,protected java.lang.String sqlPlusPath,protected java.lang.Integer sqlPlusTimeout,protected java.lang.String sqlcmdArgs,protected java.lang.String sqlcmdCatalogName,protected java.lang.Boolean sqlcmdKeepTemp,protected java.lang.String sqlcmdKeepTempName,protected java.lang.Boolean sqlcmdKeepTempOverwrite,protected java.lang.String sqlcmdKeepTempPath,protected java.lang.String sqlcmdLogFile,protected java.lang.String sqlcmdPath,protected java.lang.Integer sqlcmdTimeout,protected java.util.Properties systemProperties,protected java.lang.String url,protected java.lang.String username,protected boolean verbose,protected WagonManager wagonManager