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
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/canal/Mall4cloudCanalGlue.java
Mall4cloudCanalGlue
process
class Mall4cloudCanalGlue implements CanalGlue { private final CanalBinlogEventProcessorFactory canalBinlogEventProcessorFactory; @Override public void process(String content) {<FILL_FUNCTION_BODY>} private Mall4cloudCanalGlue(CanalBinlogEventProcessorFactory canalBinlogEventProcessorFactory) { this.canalBinlogEventProcessorFactory = canalBinlogEventProcessorFactory; } public static Mall4cloudCanalGlue of(CanalBinlogEventProcessorFactory canalBinlogEventProcessorFactory) { return new Mall4cloudCanalGlue(canalBinlogEventProcessorFactory); } }
CanalBinLogEvent event = (CanalBinLogEvent) SourceAdapterFacade.X.adapt(CanalBinLogEvent.class, content); ModelTable modelTable = ModelTable.of(event.getDatabase(), event.getTable()); List<BaseCanalBinlogEventProcessor<?>> baseCanalBinlogEventProcessors = this.canalBinlogEventProcessorFactory.get(modelTable); if (CollectionUtil.isEmpty(baseCanalBinlogEventProcessors)) { return; } baseCanalBinlogEventProcessors.forEach((processor) -> { processor.process(event); });
172
160
332
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/config/CanalGlueAutoConfiguration.java
CanalGlueAutoConfiguration
afterSingletonsInstantiated
class CanalGlueAutoConfiguration implements SmartInitializingSingleton, BeanFactoryAware { private ConfigurableListableBeanFactory configurableListableBeanFactory; @Bean @ConditionalOnMissingBean public CanalBinlogEventProcessorFactory canalBinlogEventProcessorFactory() { return Mall4cloudCanalBinlogEventProcessorFactory.of(); } @Bean @ConditionalOnMissingBean public ModelTableMetadataManager modelTableMetadataManager(CanalFieldConverterFactory canalFieldConverterFactory) { return InMemoryModelTableMetadataManager.of(canalFieldConverterFactory); } @Bean @ConditionalOnMissingBean public CanalFieldConverterFactory canalFieldConverterFactory() { return InMemoryCanalFieldConverterFactory.of(); } @Bean @ConditionalOnMissingBean public CanalBinLogEventParser canalBinLogEventParser() { return Mall4cloudCanalBinLogEventParser.of(); } @Bean @ConditionalOnMissingBean public ParseResultInterceptorManager parseResultInterceptorManager(ModelTableMetadataManager modelTableMetadataManager) { return InMemoryParseResultInterceptorManager.of(modelTableMetadataManager); } @Bean @Primary public CanalGlue canalGlue(CanalBinlogEventProcessorFactory canalBinlogEventProcessorFactory) { return Mall4cloudCanalGlue.of(canalBinlogEventProcessorFactory); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.configurableListableBeanFactory = (ConfigurableListableBeanFactory) beanFactory; } @SuppressWarnings({"rawtypes", "unchecked"}) @Override public void afterSingletonsInstantiated() {<FILL_FUNCTION_BODY>} }
ParseResultInterceptorManager parseResultInterceptorManager = configurableListableBeanFactory.getBean(ParseResultInterceptorManager.class); ModelTableMetadataManager modelTableMetadataManager = configurableListableBeanFactory.getBean(ModelTableMetadataManager.class); CanalBinlogEventProcessorFactory canalBinlogEventProcessorFactory = configurableListableBeanFactory.getBean(CanalBinlogEventProcessorFactory.class); CanalBinLogEventParser canalBinLogEventParser = configurableListableBeanFactory.getBean(CanalBinLogEventParser.class); Map<String, BaseParseResultInterceptor> interceptors = configurableListableBeanFactory.getBeansOfType(BaseParseResultInterceptor.class); interceptors.forEach((k, interceptor) -> parseResultInterceptorManager.registerParseResultInterceptor(interceptor)); Map<String, BaseCanalBinlogEventProcessor> processors = configurableListableBeanFactory.getBeansOfType(BaseCanalBinlogEventProcessor.class); processors.forEach((k, processor) -> processor.init(canalBinLogEventParser, modelTableMetadataManager, canalBinlogEventProcessorFactory, parseResultInterceptorManager));
458
313
771
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/controller/app/ProductSearchController.java
ProductSearchController
page
class ProductSearchController { @Autowired private ProductSearchManager productSearchManager; @Autowired private ShopDetailFeignClient shopDetailFeignClient; @GetMapping("/page") @Operation(summary = "商品信息列表-包含spu、品牌、分类、属性和店铺信息" , description = "spu列表-包含spu、品牌、分类、属性和店铺信息") public ServerResponseEntity<EsPageVO<ProductSearchVO>> page(@Valid EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {<FILL_FUNCTION_BODY>} @GetMapping("/simple_page") @Operation(summary = "商品信息列表-包含spu信息" , description = "商品信息列表-包含spu信息") public ServerResponseEntity<EsPageVO<ProductSearchVO>> simplePage(@Valid EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) { productSearchDTO.setSpuStatus(StatusEnum.ENABLE.value()); EsPageVO<ProductSearchVO> searchPage = productSearchManager.simplePage(pageDTO, productSearchDTO); loadShopData(searchPage.getList()); return ServerResponseEntity.success(searchPage); } /** * 获取店铺数据 * @param list */ private void loadShopData(List<ProductSearchVO> list) { if (CollUtil.isEmpty(list)) { return; } for (ProductSearchVO productSearchVO : list) { if (Objects.isNull(productSearchVO.getShopInfo()) || Objects.isNull(productSearchVO.getShopInfo().getShopId())) { continue; } ServerResponseEntity<EsShopDetailBO> shopDataResponse = shopDetailFeignClient.shopExtensionData(productSearchVO.getShopInfo().getShopId()); if (Objects.equals(shopDataResponse.getCode(), ResponseEnum.OK.value())) { EsShopDetailBO esShopDetailBO = shopDataResponse.getData(); ShopInfoSearchVO shopInfo = productSearchVO.getShopInfo(); shopInfo.setShopLogo(esShopDetailBO.getShopLogo()); shopInfo.setShopName(esShopDetailBO.getShopName()); shopInfo.setType(esShopDetailBO.getType()); } } } }
productSearchDTO.setSpuStatus(StatusEnum.ENABLE.value()); EsPageVO<ProductSearchVO> searchPage = productSearchManager.page(pageDTO, productSearchDTO); loadShopData(searchPage.getList()); return ServerResponseEntity.success(searchPage);
581
74
655
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/controller/multishop/ProductSearchController.java
ProductSearchController
page
class ProductSearchController { @Autowired private ProductSearchManager productSearchManager; @GetMapping("/page") @Operation(summary = "商品信息列表" , description = "商品信息列表") public ServerResponseEntity<EsPageVO<SpuAdminVO>> page(@Valid EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) {<FILL_FUNCTION_BODY>} }
Long shopId = AuthUserContext.get().getTenantId(); productSearchDTO.setSearchType(SearchTypeEnum.MULTISHOP.value()); productSearchDTO.setShopId(shopId); EsPageVO<SpuAdminVO> searchPage = productSearchManager.adminPage(pageDTO, productSearchDTO); return ServerResponseEntity.success(searchPage);
106
98
204
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/feign/SearchOrderFeignController.java
SearchOrderFeignController
getOrderPage
class SearchOrderFeignController implements SearchOrderFeignClient { @Autowired private OrderSearchManager orderSearchManager; @Override public ServerResponseEntity<EsPageVO<EsOrderVO>> getOrderPage(OrderSearchDTO orderSearch) {<FILL_FUNCTION_BODY>} }
EsPageDTO pageDTO = new EsPageDTO(); pageDTO.setPageNum(orderSearch.getPageNum()); pageDTO.setPageSize(orderSearch.getPageSize()); return ServerResponseEntity.success(orderSearchManager.pageSearchResult(pageDTO, orderSearch));
78
77
155
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/feign/SearchSpuFeignController.java
SearchSpuFeignController
getSpusBySpuIds
class SearchSpuFeignController implements SearchSpuFeignClient { @Autowired private ProductSearchManager productSearchManager; @Override public ServerResponseEntity<EsPageVO<ProductSearchVO>> search(EsPageDTO pageDTO, ProductSearchDTO productSearchDTO) { return ServerResponseEntity.success(productSearchManager.simplePage(pageDTO, productSearchDTO)); } @Override public ServerResponseEntity<List<SpuSearchVO>> getSpusBySpuIds(List<Long> spuIds){<FILL_FUNCTION_BODY>} @Override public ServerResponseEntity<EsPageVO<ProductSearchVO>> spuPage(Integer pageNum, Integer pageSize, Long shopId) { EsPageDTO pageDTO = new EsPageDTO(); pageDTO.setPageNum(pageNum); pageDTO.setPageSize(pageSize); ProductSearchDTO productSearchDTO = new ProductSearchDTO(); // 平台id则搜索整个平台的商品 if (!Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) { productSearchDTO.setShopId(shopId); } EsPageVO<ProductSearchVO> page = productSearchManager.page(pageDTO, productSearchDTO); return ServerResponseEntity.success(page); } @Override public ServerResponseEntity<List<SpuSearchVO>> limitSizeListByShopIds(List<Long> shopIds, Integer size) { if (CollUtil.isEmpty(shopIds)) { return ServerResponseEntity.success(new ArrayList<>()); } List<SpuSearchVO> list = productSearchManager.limitSizeListByShopIds(shopIds, size); return ServerResponseEntity.success(list); } }
if (CollUtil.isEmpty(spuIds)) { return ServerResponseEntity.success(new ArrayList<>()); } ProductSearchDTO productSearchDTO = new ProductSearchDTO(); productSearchDTO.setSpuIds(spuIds); List<SpuSearchVO> list = productSearchManager.list(productSearchDTO); return ServerResponseEntity.success(list);
446
99
545
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/listener/BrandCanalListener.java
BrandCanalListener
processUpdateInternal
class BrandCanalListener extends BaseCanalBinlogEventProcessor<BrandBO> { private static final Logger log = LoggerFactory.getLogger(BrandCanalListener.class); @Autowired private ProductUpdateManager productUpdateManager; @Autowired private ProductFeignClient productFeignClient; /** * 新增品牌 */ @Override protected void processInsertInternal(CanalBinLogResult<BrandBO> brandResult) { } /** * 更新品牌 * @param result */ @Override protected void processUpdateInternal(CanalBinLogResult<BrandBO> result) {<FILL_FUNCTION_BODY>} }
BrandBO beforeData = result.getBeforeData(); if (Objects.isNull(beforeData.getName()) && StrUtil.isBlank(beforeData.getImgUrl())) { return; } BrandBO afterData = result.getAfterData(); EsProductBO esProductBO = new EsProductBO(); if (StrUtil.isNotBlank(beforeData.getName())) { esProductBO.setBrandName(afterData.getName()); } if (Objects.nonNull(beforeData.getImgUrl())) { esProductBO.setBrandImg(afterData.getImgUrl()); } ServerResponseEntity<List<Long>> responseData = productFeignClient.getSpuIdsByBrandId(afterData.getBrandId()); productUpdateManager.esUpdateSpuBySpuIds(responseData.getData(), esProductBO);
184
219
403
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/listener/CanalListener.java
CanalListener
onMessage
class CanalListener implements RocketMQListener<String> { private static final Logger log = LoggerFactory.getLogger(CanalListener.class); @Autowired private CanalGlue canalGlue; @Override public void onMessage(String message) {<FILL_FUNCTION_BODY>} }
Map map = JSON.parseObject(message, Map.class); String table = map.get("table").toString(); String database = map.get("database").toString(); log.info("canal-database: {}, table: {}, mq message:{}", database, table, message); canalGlue.process(message);
83
82
165
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/listener/CategoryCanalListener.java
CategoryCanalListener
getSpuIdsByCategoryId
class CategoryCanalListener extends BaseCanalBinlogEventProcessor<CategoryBO> { private static final Logger log = LoggerFactory.getLogger(CategoryCanalListener.class); @Autowired private CategoryFeignClient categoryFeignClient; @Autowired private ProductUpdateManager productUpdateManager; @Autowired private ProductFeignClient productFeignClient; /** * 插入商品,此时插入es */ @Override protected void processInsertInternal(CanalBinLogResult<CategoryBO> categoryBo) { } /** * 更新分类,删除商品索引,再重新构建一个 * @param result */ @Override protected void processUpdateInternal(CanalBinLogResult<CategoryBO> result) { CategoryBO beforeData = result.getBeforeData(); if (Objects.isNull(beforeData.getName()) && Objects.isNull(beforeData.getStatus())) { return; } CategoryBO afterData = result.getAfterData(); EsProductBO esProductBO = new EsProductBO(); if (StrUtil.isNotBlank(beforeData.getName())) { insertCategoryName(esProductBO, afterData); } // 更新分类列表下商品的状态 if (Objects.nonNull(beforeData.getStatus())) { esProductBO.setSpuStatus(beforeData.getStatus()); } List<Long> spuIds = getSpuIdsByCategoryId(afterData); productUpdateManager.esUpdateSpuBySpuIds(spuIds, esProductBO); } /** * 插入需要修改的分类名称 * @param esProductBO * @param afterData */ private void insertCategoryName(EsProductBO esProductBO, CategoryBO afterData) { // 平台分类 if (Objects.equals(Constant.PLATFORM_SHOP_ID, afterData.getShopId())) { if (afterData.getLevel().equals(CategoryLevel.First.value())) { esProductBO.setPrimaryCategoryName(afterData.getName()); } else if (afterData.getLevel().equals(CategoryLevel.SECOND.value())) { esProductBO.setSecondaryCategoryName(afterData.getName()); } else { esProductBO.setCategoryName(afterData.getName()); } } // 商家分类 else { if (afterData.getLevel().equals(CategoryLevel.First.value())) { esProductBO.setShopPrimaryCategoryName(afterData.getName()); } else if (afterData.getLevel().equals(CategoryLevel.SECOND.value())) { esProductBO.setShopSecondaryCategoryName(afterData.getName()); } } } /** * 根据分类信息,获取分类下的商品Id列表 * @param category * @return */ private List<Long> getSpuIdsByCategoryId(CategoryBO category) {<FILL_FUNCTION_BODY>} }
List<Long> spuIds = new ArrayList<>(); ServerResponseEntity<List<Long>> spuIdResponse = null; List<Long> categoryIds = new ArrayList<>(); Boolean isSearch = (category.getShopId().equals(Constant.PLATFORM_SHOP_ID) && !category.getLevel().equals(CategoryLevel.THIRD.value())) && (!category.getShopId().equals(Constant.PLATFORM_SHOP_ID) && category.getLevel().equals(CategoryLevel.First.value())); // 平台分类 if (isSearch) { ServerResponseEntity<List<Long>> categoryResponse = categoryFeignClient.listCategoryId(category.getCategoryId()); categoryIds.addAll(categoryResponse.getData()); } else { categoryIds.add(category.getCategoryId()); } if (Objects.equals(category.getShopId(), Constant.PLATFORM_SHOP_ID)) { spuIdResponse = productFeignClient.getSpuIdsByCategoryIds(categoryIds); } else { spuIdResponse = productFeignClient.getSpuIdsByShopCategoryIds(categoryIds); } spuIds.addAll(spuIdResponse.getData()); return spuIds;
766
312
1,078
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/listener/OrderCanalListener.java
OrderCanalListener
processUpdateInternal
class OrderCanalListener extends BaseCanalBinlogEventProcessor<OrderBO> { private static final Logger log = LoggerFactory.getLogger(OrderCanalListener.class); @Autowired private OrderFeignClient orderFeignClient; @Autowired private RestHighLevelClient restHighLevelClient; /** * 插入订单,此时插入es */ @Override protected void processInsertInternal(CanalBinLogResult<OrderBO> result) { Long orderId = result.getPrimaryKey(); ServerResponseEntity<EsOrderBO> esOrderResponse = orderFeignClient.getEsOrder(orderId); IndexRequest request = new IndexRequest(EsIndexEnum.ORDER.value()); request.id(String.valueOf(orderId)); request.source(Json.toJsonString(esOrderResponse.getData()), XContentType.JSON); try { IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT); log.info(indexResponse.toString()); } catch (IOException e) { e.printStackTrace(); log.error(e.toString()); throw new Mall4cloudException("保存es信息异常", e); } } /** * 更新订单,删除订单索引,再重新构建一个 */ @Override protected void processUpdateInternal(CanalBinLogResult<OrderBO> result) {<FILL_FUNCTION_BODY>} @Override protected ExceptionHandler exceptionHandler() { return (CanalBinLogEvent event, Throwable throwable) -> { throw new Mall4cloudException("创建索引异常",throwable); }; } }
Long orderId = result.getPrimaryKey(); ServerResponseEntity<EsOrderBO> esOrderResponse = orderFeignClient.getEsOrder(orderId); UpdateRequest request = new UpdateRequest(EsIndexEnum.ORDER.value(), String.valueOf(orderId)); request.doc(Json.toJsonString(esOrderResponse.getData()), XContentType.JSON); request.docAsUpsert(true); try { UpdateResponse updateResponse = restHighLevelClient.update(request, RequestOptions.DEFAULT); log.info(updateResponse.toString()); } catch (IOException e) { log.error(e.toString()); throw new Mall4cloudException("更新订单es信息异常",e); }
432
180
612
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/listener/ShopDetailCanalListener.java
ShopDetailCanalListener
processUpdateInternal
class ShopDetailCanalListener extends BaseCanalBinlogEventProcessor<ShopDetailBO> { private static final Logger log = LoggerFactory.getLogger(ShopDetailCanalListener.class); @Autowired private ProductUpdateManager productUpdateManager; @Autowired private ProductFeignClient productFeignClient; /** * 新增店铺 */ @Override protected void processInsertInternal(CanalBinLogResult<ShopDetailBO> shopDetailResult) { } /** * 更新店铺 * @param result */ @Override protected void processUpdateInternal(CanalBinLogResult<ShopDetailBO> result) {<FILL_FUNCTION_BODY>} }
ShopDetailBO beforeData = result.getBeforeData(); if (Objects.isNull(beforeData.getShopName()) && StrUtil.isBlank(beforeData.getShopLogo()) && !Objects.equals(beforeData.getShopStatus(), StatusEnum.ENABLE.value())) { return; } ShopDetailBO afterData = result.getAfterData(); EsProductBO esProductBO = new EsProductBO(); if (StrUtil.isNotBlank(beforeData.getShopName())) { esProductBO.setShopName(afterData.getShopName()); } if (Objects.nonNull(beforeData.getShopLogo())) { esProductBO.setShopImg(afterData.getShopLogo()); } if (Objects.nonNull(beforeData.getShopStatus()) && Objects.equals(beforeData.getShopId(), StatusEnum.ENABLE.value())) { esProductBO.setSpuStatus(StatusEnum.DISABLE.value()); } ServerResponseEntity<List<Long>> responseData = productFeignClient.getSpuIdsByShopId(afterData.getShopId()); productUpdateManager.esUpdateSpuBySpuIds(responseData.getData(), esProductBO);
188
302
490
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/listener/SpuCanalListener.java
SpuCanalListener
exceptionHandler
class SpuCanalListener extends BaseCanalBinlogEventProcessor<SpuBO> { private static final Logger log = LoggerFactory.getLogger(SpuCanalListener.class); @Autowired private ProductFeignClient productFeignClient; @Autowired private RestHighLevelClient restHighLevelClient; /** * 插入商品,此时插入es */ @Override protected void processInsertInternal(CanalBinLogResult<SpuBO> result) { Long spuId = result.getPrimaryKey(); ServerResponseEntity<EsProductBO> esProductBO = productFeignClient.loadEsProductBO(spuId); if (!esProductBO.isSuccess()) { throw new Mall4cloudException("创建索引异常"); } IndexRequest request = new IndexRequest(EsIndexEnum.PRODUCT.value()); request.id(String.valueOf(spuId)); request.source(Json.toJsonString(esProductBO.getData()), XContentType.JSON); try { IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT); log.info(indexResponse.toString()); } catch (IOException e) { log.error(e.toString()); throw new Mall4cloudException("保存es信息异常", e); } } /** * 更新商品,删除商品索引,再重新构建一个 */ @Override protected void processUpdateInternal(CanalBinLogResult<SpuBO> result) { Long spuId = result.getPrimaryKey(); ServerResponseEntity<EsProductBO> esProductBO = productFeignClient.loadEsProductBO(spuId); String source = Json.toJsonString(esProductBO.getData()); UpdateRequest request = new UpdateRequest(EsIndexEnum.PRODUCT.value(), String.valueOf(spuId)); request.doc(source, XContentType.JSON); request.docAsUpsert(true); try { UpdateResponse updateResponse = restHighLevelClient.update(request, RequestOptions.DEFAULT); log.info(updateResponse.toString()); } catch (IOException e) { log.error(e.toString()); throw new Mall4cloudException("删除es信息异常",e); } } @Override protected ExceptionHandler exceptionHandler() {<FILL_FUNCTION_BODY>} }
return (CanalBinLogEvent event, Throwable throwable) -> { throw new Mall4cloudException("创建索引异常",throwable); };
610
44
654
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/listener/SpuExtensionCanalListener.java
SpuExtensionCanalListener
processUpdateInternal
class SpuExtensionCanalListener extends BaseCanalBinlogEventProcessor<SpuExtensionBO> { private static final Logger log = LoggerFactory.getLogger(SpuExtensionCanalListener.class); @Autowired private CacheManagerUtil cacheManagerUtil; @Autowired private RestHighLevelClient restHighLevelClient; /** * 插入商品,此时插入es */ @Override protected void processInsertInternal(CanalBinLogResult<SpuExtensionBO> result) { System.out.println(); } /** * 更新商品,删除商品索引,再重新构建一个 */ @Override protected void processUpdateInternal(CanalBinLogResult<SpuExtensionBO> result) {<FILL_FUNCTION_BODY>} }
// 更新之后的数据 SpuExtensionBO afterData = result.getAfterData(); // 清除缓存 cacheManagerUtil.evictCache(CacheNames.SPU_EXTENSION_KEY, afterData.getSpuId().toString()); UpdateRequest request = new UpdateRequest(EsIndexEnum.PRODUCT.value(), String.valueOf(afterData.getSpuId())); EsProductBO esProductBO = new EsProductBO(); // 可售库存 esProductBO.setSpuId(afterData.getSpuId()); esProductBO.setStock(afterData.getStock()); esProductBO.setHasStock(afterData.getStock() != 0); esProductBO.setSaleNum(afterData.getSaleNum()); request.doc(Json.toJsonString(esProductBO), XContentType.JSON); try { UpdateResponse updateResponse = restHighLevelClient.update(request, RequestOptions.DEFAULT); log.info(updateResponse.toString()); } catch (IOException e) { log.error(e.toString()); throw new Mall4cloudException("更新es信息异常",e); }
208
298
506
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/manager/ProductUpdateManager.java
ProductUpdateManager
esUpdateSpuBySpuIds
class ProductUpdateManager { @Autowired private RestHighLevelClient restHighLevelClient; /** * 批量更新es中的商品信息 * @param spuIds spuId列表 * @param esProductBO 更新的数据 */ public void esUpdateSpuBySpuIds(List<Long> spuIds, EsProductBO esProductBO) {<FILL_FUNCTION_BODY>} }
String source = Json.toJsonString(esProductBO); try { BulkRequest request = new BulkRequest(); // 准备更新的数据 for (Long spuId : spuIds) { request.add(new UpdateRequest(EsIndexEnum.PRODUCT.value(), String.valueOf(spuId)).doc(source, XContentType.JSON)); } //更新 BulkResponse bulkResponse = restHighLevelClient.bulk(request, RequestOptions.DEFAULT); if (bulkResponse.hasFailures()) { throw new Mall4cloudException(bulkResponse.buildFailureMessage()); } } catch (Exception e) { throw new Mall4cloudException(e.getMessage()); }
111
183
294
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-search/src/main/java/com/mall4j/cloud/search/vo/SpuAdminVO.java
SpuAdminVO
toString
class SpuAdminVO { @Schema(description = "商品id" ) private Long spuId; @Schema(description = "商品名称" ) private String spuName; @Schema(description = "商品介绍主图" ) private String mainImgUrl; @Schema(description = "店铺id" ) private Long shopId; @Schema(description = "店铺名称" ) private String shopName; @Schema(description = "商品售价" ) private Long priceFee; @Schema(description = "市场价,整数方式保存" ) private Long marketPriceFee; @Schema(description = "销量" ) private Integer saleNum; @Schema(description = "状态" ) private Integer spuStatus; @Schema(description = "库存" ) private Integer stock; @Schema(description = "序号" ) private Integer seq; public Long getSpuId() { return spuId; } public void setSpuId(Long spuId) { this.spuId = spuId; } public String getSpuName() { return spuName; } public void setSpuName(String spuName) { this.spuName = spuName; } public String getMainImgUrl() { return mainImgUrl; } public void setMainImgUrl(String mainImgUrl) { this.mainImgUrl = mainImgUrl; } public Long getShopId() { return shopId; } public void setShopId(Long shopId) { this.shopId = shopId; } public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public Long getPriceFee() { return priceFee; } public void setPriceFee(Long priceFee) { this.priceFee = priceFee; } public Long getMarketPriceFee() { return marketPriceFee; } public void setMarketPriceFee(Long marketPriceFee) { this.marketPriceFee = marketPriceFee; } public Integer getSaleNum() { return saleNum; } public void setSaleNum(Integer saleNum) { this.saleNum = saleNum; } public Integer getSpuStatus() { return spuStatus; } public void setSpuStatus(Integer spuStatus) { this.spuStatus = spuStatus; } public Integer getStock() { return stock; } public void setStock(Integer stock) { this.stock = stock; } public Integer getSeq() { return seq; } public void setSeq(Integer seq) { this.seq = seq; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "SpuAdminVO{" + "spuId=" + spuId + ", spuName='" + spuName + '\'' + ", mainImgUrl='" + mainImgUrl + '\'' + ", shopId=" + shopId + ", shopName='" + shopName + '\'' + ", priceFee=" + priceFee + ", marketPriceFee=" + marketPriceFee + ", saleNum=" + saleNum + ", spuStatus=" + spuStatus + ", stock=" + stock + ", seq=" + seq + '}';
824
162
986
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/controller/app/UserAddrController.java
UserAddrController
delete
class UserAddrController { @Autowired private UserAddrService userAddrService; private static final Integer MAX_USER_ADDR = 10; @GetMapping("/list") @Operation(summary = "获取用户地址列表" , description = "获取用户地址列表") public ServerResponseEntity<List<UserAddrVO>> list() { Long userId = AuthUserContext.get().getUserId(); List<UserAddrVO> userAddrPage = userAddrService.list(userId); return ServerResponseEntity.success(userAddrPage); } @GetMapping @Operation(summary = "获取用户地址" , description = "根据addrId获取用户地址") public ServerResponseEntity<UserAddrVO> getByAddrId(@RequestParam Long addrId) { return ServerResponseEntity.success(userAddrService.getUserAddrByUserId(addrId,AuthUserContext.get().getUserId())); } @PostMapping @Operation(summary = "保存用户地址" , description = "保存用户地址") public ServerResponseEntity<Void> save(@Valid @RequestBody UserAddrDTO userAddrDTO) { Long userId = AuthUserContext.get().getUserId(); int userAddrCount = userAddrService.countByUserId(userId); if (userAddrCount >= MAX_USER_ADDR) { return ServerResponseEntity.showFailMsg("收货地址已达到上限,无法再新增地址"); } UserAddr userAddr = BeanUtil.map(userAddrDTO, UserAddr.class); if (userAddrCount == 0) { userAddr.setIsDefault(UserAddr.DEFAULT_ADDR); } else if (!UserAddr.DEFAULT_ADDR.equals(userAddr.getIsDefault())){ userAddr.setIsDefault(UserAddr.NOT_DEFAULT_ADDR); } userAddr.setAddrId(null); userAddr.setUserId(userId); userAddrService.save(userAddr); // 清除默认地址缓存 if (UserAddr.DEFAULT_ADDR.equals(userAddr.getIsDefault())) { userAddrService.removeUserDefaultAddrCacheByUserId(userId); } return ServerResponseEntity.success(); } @PutMapping @Operation(summary = "更新用户地址" , description = "更新用户地址") public ServerResponseEntity<Void> update(@Valid @RequestBody UserAddrDTO userAddrDTO) { Long userId = AuthUserContext.get().getUserId(); UserAddrVO dbUserAddr = userAddrService.getUserAddrByUserId(userAddrDTO.getAddrId(), userId); if (dbUserAddr == null) { throw new Mall4cloudException("该地址已被删除"); } // 默认地址不能修改为普通地址 else if (dbUserAddr.getIsDefault().equals(UserAddr.DEFAULT_ADDR) && userAddrDTO.getIsDefault().equals(UserAddr.NOT_DEFAULT_ADDR)) { throw new Mall4cloudException(ResponseEnum.DATA_ERROR); } UserAddr userAddr = BeanUtil.map(userAddrDTO, UserAddr.class); userAddr.setUserId(userId); userAddrService.update(userAddr); // 清除默认地址缓存 if (userAddr.getIsDefault().equals(UserAddr.DEFAULT_ADDR)) { userAddrService.removeUserDefaultAddrCacheByUserId(userId); } return ServerResponseEntity.success(); } @DeleteMapping @Operation(summary = "删除用户地址" , description = "根据用户地址id删除用户地址") public ServerResponseEntity<Void> delete(@RequestParam Long addrId) {<FILL_FUNCTION_BODY>} }
Long userId = AuthUserContext.get().getUserId(); UserAddrVO dbUserAddr = userAddrService.getUserAddrByUserId(addrId, userId); if (dbUserAddr == null) { throw new Mall4cloudException("该地址已被删除"); } else if (dbUserAddr.getIsDefault().equals(UserAddr.DEFAULT_ADDR)) { throw new Mall4cloudException("默认地址不能删除"); } userAddrService.deleteUserAddrByUserId(addrId, userId); return ServerResponseEntity.success();
947
144
1,091
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/controller/app/UserController.java
UserController
updateUser
class UserController { @Autowired private UserService userService; @GetMapping("/simple_info") @Operation(summary = "用户头像昵称" , description = "用户头像昵称") public ServerResponseEntity<UserSimpleInfoVO> getByAddrId() { Long userId = AuthUserContext.get().getUserId(); UserApiVO userApiVO = userService.getByUserId(userId); UserSimpleInfoVO userSimpleInfoVO = new UserSimpleInfoVO(); userSimpleInfoVO.setNickName(userApiVO.getNickName()); userSimpleInfoVO.setPic(userApiVO.getPic()); return ServerResponseEntity.success(userSimpleInfoVO); } @GetMapping("/ma/user_detail_info") @Operation(summary = "获取用户详细信息" , description = "返回用户详细信息") public ServerResponseEntity<UserApiVO> getUserDetailInfo() { UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get(); if (userInfoInTokenBO == null) { return ServerResponseEntity.fail(ResponseEnum.CLEAN_TOKEN); } Long userId = userInfoInTokenBO.getUserId(); UserApiVO userApiVO = userService.getByUserId(userId); return ServerResponseEntity.success(userApiVO); } @PostMapping ("/ma/update_user") @Operation(summary = "更新用户信息") public ServerResponseEntity<Void> updateUser(@RequestBody UserApiVO userApiVO) {<FILL_FUNCTION_BODY>} }
Long userId = AuthUserContext.get().getUserId(); UserApiVO byUserId = userService.getByUserId(userId); User user = new User(); user.setUserId(userId); user.setNickName(Objects.isNull(userApiVO.getNickName())? byUserId.getNickName() : userApiVO.getNickName()); user.setPic(Objects.isNull(userApiVO.getPic())? byUserId.getPic() : userApiVO.getPic()); userService.update(user); return ServerResponseEntity.success();
413
158
571
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/controller/app/UserRegisterController.java
UserRegisterController
register
class UserRegisterController { @Autowired private UserService userService; @Autowired private AccountFeignClient accountFeignClient; @Operation(summary = "注册") @PostMapping public ServerResponseEntity<TokenInfoVO> register(@Valid @RequestBody UserRegisterDTO param) {<FILL_FUNCTION_BODY>} }
if (StrUtil.isBlank(param.getNickName())) { param.setNickName(param.getUserName()); } // 1. 保存账户信息 Long uid = userService.save(param); // 2. 登录 UserInfoInTokenBO userInfoInTokenBO = new UserInfoInTokenBO(); userInfoInTokenBO.setUid(uid); userInfoInTokenBO.setUserId(param.getUserId()); userInfoInTokenBO.setSysType(SysTypeEnum.ORDINARY.value()); userInfoInTokenBO.setIsAdmin(0); return accountFeignClient.storeTokenAndGetVo(userInfoInTokenBO);
95
185
280
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/dto/UserAddrDTO.java
UserAddrDTO
toString
class UserAddrDTO { private static final long serialVersionUID = 1L; @Schema(description = "ID" ) private Long addrId; @Schema(description = "手机" ) private String mobile; @Schema(description = "是否默认地址 1是" ) private Integer isDefault; @Schema(description = "收货人" ) @Length(min = 2, max = 20, message = "收货人姓名需要在2到20个字符之间") private String consignee; @Schema(description = "省ID" ) private Long provinceId; @Schema(description = "省" ) private String province; @Schema(description = "城市ID" ) private Long cityId; @Schema(description = "城市" ) private String city; @Schema(description = "区ID" ) private Long areaId; @Schema(description = "区" ) private String area; @Schema(description = "邮编" ) private String postCode; @Schema(description = "地址" ) private String addr; @Schema(description = "经度" ) private Double lng; @Schema(description = "纬度" ) private Double lat; public Long getAddrId() { return addrId; } public void setAddrId(Long addrId) { this.addrId = addrId; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public Integer getIsDefault() { return isDefault; } public void setIsDefault(Integer isDefault) { this.isDefault = isDefault; } public String getConsignee() { return consignee; } public void setConsignee(String consignee) { this.consignee = consignee; } public Long getProvinceId() { return provinceId; } public void setProvinceId(Long provinceId) { this.provinceId = provinceId; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public Long getCityId() { return cityId; } public void setCityId(Long cityId) { this.cityId = cityId; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Long getAreaId() { return areaId; } public void setAreaId(Long areaId) { this.areaId = areaId; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public Double getLng() { return lng; } public void setLng(Double lng) { this.lng = lng; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserAddrDTO{" + "addrId=" + addrId + ",mobile=" + mobile + ",isDefault=" + isDefault + ",consignee=" + consignee + ",provinceId=" + provinceId + ",province=" + province + ",cityId=" + cityId + ",city=" + city + ",areaId=" + areaId + ",area=" + area + ",postCode=" + postCode + ",addr=" + addr + ",lng=" + lng + ",lat=" + lat + '}';
917
177
1,094
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/dto/UserDTO.java
UserDTO
toString
class UserDTO{ private static final long serialVersionUID = 1L; @Schema(description = "ID" ) private Long userId; @Schema(description = "用户昵称" ) private String nickName; @Schema(description = "头像图片路径" ) private String pic; @Schema(description = "状态 1 正常 0 无效" ) private Integer status; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserDTO{" + "userId=" + userId + ",nickName=" + nickName + ",pic=" + pic + ",status=" + status + '}';
295
61
356
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/dto/UserRegisterDTO.java
UserRegisterDTO
toString
class UserRegisterDTO { @NotBlank @Schema(description = "密码" ) private String password; @Schema(description = "头像" ) private String img; @Schema(description = "昵称" ) private String nickName; @NotBlank @Schema(description = "用户名" ) private String userName; @Schema(description = "当账户未绑定时,临时的uid" ) private String tempUid; @Schema(description = "用户id" ) private Long userId; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getTempUid() { return tempUid; } public void setTempUid(String tempUid) { this.tempUid = tempUid; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserRegisterDTO{" + "password='" + password + '\'' + ", img='" + img + '\'' + ", nickName='" + nickName + '\'' + ", userName='" + userName + '\'' + ", tempUid='" + tempUid + '\'' + ", userId=" + userId + '}';
410
102
512
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/model/Area.java
Area
toString
class Area extends BaseModel implements Serializable{ private static final long serialVersionUID = 1L; /** * */ private Long areaId; /** * 地址 */ private String areaName; /** * 上级地址 */ private Long parentId; /** * 等级(从1开始) */ private Integer level; public Long getAreaId() { return areaId; } public void setAreaId(Long areaId) { this.areaId = areaId; } public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "Area{" + "areaId=" + areaId + ",areaName=" + areaName + ",parentId=" + parentId + ",level=" + level + ",createTime=" + createTime + ",updateTime=" + updateTime + '}';
293
84
377
<methods>public non-sealed void <init>() ,public java.util.Date getCreateTime() ,public java.util.Date getUpdateTime() ,public void setCreateTime(java.util.Date) ,public void setUpdateTime(java.util.Date) ,public java.lang.String toString() <variables>protected java.util.Date createTime,protected java.util.Date updateTime
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/model/User.java
User
toString
class User extends BaseModel implements Serializable{ private static final long serialVersionUID = 1L; public static final String DISTRIBUTED_ID_KEY = "mall4cloud-user"; /** * ID */ private Long userId; /** * 用户昵称 */ private String nickName; /** * 头像图片路径 */ private String pic; /** * 状态 1 正常 0 无效 */ private Integer status; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "User{" + "userId=" + userId + ",createTime=" + createTime + ",updateTime=" + updateTime + ",nickName=" + nickName + ",pic=" + pic + ",status=" + status + '}';
323
83
406
<methods>public non-sealed void <init>() ,public java.util.Date getCreateTime() ,public java.util.Date getUpdateTime() ,public void setCreateTime(java.util.Date) ,public void setUpdateTime(java.util.Date) ,public java.lang.String toString() <variables>protected java.util.Date createTime,protected java.util.Date updateTime
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/model/UserAddr.java
UserAddr
toString
class UserAddr extends BaseModel implements Serializable{ private static final long serialVersionUID = 1L; public static final Integer DEFAULT_ADDR = 1; public static final Integer NOT_DEFAULT_ADDR = 0; /** * ID */ private Long addrId; /** * 用户ID */ private Long userId; /** * 手机 */ private String mobile; /** * 是否默认地址 1是 */ private Integer isDefault; /** * 收货人 */ private String consignee; /** * 省ID */ private Long provinceId; /** * 省 */ private String province; /** * 城市ID */ private Long cityId; /** * 城市 */ private String city; /** * 区ID */ private Long areaId; /** * 区 */ private String area; /** * 邮编 */ private String postCode; /** * 地址 */ private String addr; /** * 经度 */ private Double lng; /** * 纬度 */ private Double lat; public Long getAddrId() { return addrId; } public void setAddrId(Long addrId) { this.addrId = addrId; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public Integer getIsDefault() { return isDefault; } public void setIsDefault(Integer isDefault) { this.isDefault = isDefault; } public String getConsignee() { return consignee; } public void setConsignee(String consignee) { this.consignee = consignee; } public Long getProvinceId() { return provinceId; } public void setProvinceId(Long provinceId) { this.provinceId = provinceId; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public Long getCityId() { return cityId; } public void setCityId(Long cityId) { this.cityId = cityId; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Long getAreaId() { return areaId; } public void setAreaId(Long areaId) { this.areaId = areaId; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public Double getLng() { return lng; } public void setLng(Double lng) { this.lng = lng; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserAddr{" + "addrId=" + addrId + ",createTime=" + createTime + ",updateTime=" + updateTime + ",userId=" + userId + ",mobile=" + mobile + ",isDefault=" + isDefault + ",consignee=" + consignee + ",provinceId=" + provinceId + ",province=" + province + ",cityId=" + cityId + ",city=" + city + ",areaId=" + areaId + ",area=" + area + ",postCode=" + postCode + ",addr=" + addr + ",lng=" + lng + ",lat=" + lat + '}';
976
211
1,187
<methods>public non-sealed void <init>() ,public java.util.Date getCreateTime() ,public java.util.Date getUpdateTime() ,public void setCreateTime(java.util.Date) ,public void setUpdateTime(java.util.Date) ,public java.lang.String toString() <variables>protected java.util.Date createTime,protected java.util.Date updateTime
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/service/impl/AreaServiceImpl.java
AreaServiceImpl
getAreaListInfo
class AreaServiceImpl implements AreaService { @Autowired private AreaMapper areaMapper; @Override public List<AreaVO> list() { return areaMapper.list(); } @Override @Cacheable(cacheNames = CacheNames.AREA_INFO_KEY, key = "'areaList'", sync = true) public List<AreaVO> getAreaListInfo() {<FILL_FUNCTION_BODY>} @Override public List<AreaVO> listAreaOfEnable() { List<AreaVO> list = areaMapper.listAreaOfEnable(); return list; } @Override public AreaVO getByAreaId(Long areaId) { return areaMapper.getByAreaId(areaId); } @Override public void save(Area area) { areaMapper.save(area); } @Override public void update(Area area) { areaMapper.update(area); } @Override public void deleteById(Long areaId) { int areaNum = areaMapper.countByAreaId(areaId); if (areaNum > 0) { throw new Mall4cloudException("请先删除子地区"); } areaMapper.deleteById(areaId); } @Override @Cacheable(cacheNames = CacheNames.AREA_KEY, key = "'list:' + #pid") public List<AreaVO> listByPid(Long pid) { return areaMapper.listByPid(pid); } @Override @Caching(evict = { @CacheEvict(cacheNames = CacheNames.AREA_INFO_KEY, key = "'areaList'"), @CacheEvict(cacheNames = CacheNames.AREA_KEY, key = "'list:' + #pid") }) public void removeAllCache(Long pid) { } @Override @Caching(evict = { @CacheEvict(cacheNames = CacheNames.AREA_KEY, key = "'list:' + #pid"), @CacheEvict(cacheNames = CacheNames.AREA_INFO_KEY, key = "'areaList'") }) public void removeAreaCacheByParentId(Long pid) { } }
List<AreaVO> areaList = areaMapper.getAreaListInfo(); for (AreaVO province:areaList){ List<Long> cityAll = new ArrayList<>(); for (AreaVO city:province.getAreas()){ cityAll.add(city.getAreaId()); List<Long> areaAll = new ArrayList<>(); for (AreaVO area:city.getAreas()){ areaAll.add(area.getAreaId()); } city.setAreaIds(areaAll); } province.setAreaIds(cityAll); } return areaList;
569
152
721
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/service/impl/UserAddrServiceImpl.java
UserAddrServiceImpl
getUserAddrByUserId
class UserAddrServiceImpl implements UserAddrService { @Autowired private UserAddrMapper userAddrMapper; @Override public List<UserAddrVO> list(Long userId) { return userAddrMapper.list(userId); } @Override @Transactional(rollbackFor = Exception.class) public void save(UserAddr userAddr) { if (userAddr.getIsDefault().equals(UserAddr.DEFAULT_ADDR)) { userAddrMapper.removeDefaultUserAddr(userAddr.getUserId()); } userAddrMapper.save(userAddr); } @Override @Transactional(rollbackFor = Exception.class) public void update(UserAddr userAddr) { if (userAddr.getIsDefault().equals(UserAddr.DEFAULT_ADDR)) { userAddrMapper.removeDefaultUserAddr(userAddr.getUserId()); } userAddrMapper.update(userAddr); } @Override public void deleteUserAddrByUserId(Long addrId, Long userId) { userAddrMapper.deleteById(addrId,userId); } @Override public UserAddrVO getUserAddrByUserId(Long addrId, Long userId) {<FILL_FUNCTION_BODY>} @Override public int countByUserId(Long userId) { return userAddrMapper.countByUserId(userId); } @Override @CacheEvict(cacheNames = UserCacheNames.USER_DEFAULT_ADDR, key = "#userId") public void removeUserDefaultAddrCacheByUserId(Long userId) { } }
// 获取用户默认地址 if (addrId == 0) { return userAddrMapper.getUserDefaultAddrByUserId(userId); } return userAddrMapper.getByAddrId(addrId,userId);
415
61
476
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/service/impl/UserServiceImpl.java
UserServiceImpl
save
class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Autowired private AccountFeignClient accountFeignClient; @Autowired private SegmentFeignClient segmentFeignClient; @Override public PageVO<UserApiVO> page(PageDTO pageDTO) { return PageUtil.doPage(pageDTO, () -> userMapper.list()); } @Override @Cacheable(cacheNames = UserCacheNames.USER_INFO, key = "#userId") public UserApiVO getByUserId(Long userId) { return userMapper.getByUserId(userId); } @Override @CacheEvict(cacheNames = UserCacheNames.USER_INFO, key = "#user.userId") public void update(User user) { userMapper.update(user); } @Override public List<UserApiVO> getUserByUserIds(List<Long> userIds) { if (CollUtil.isEmpty(userIds)) { return new ArrayList<>(); } return userMapper.getUserByUserIds(userIds); } @Override @GlobalTransactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class) public Long save(UserRegisterDTO param) {<FILL_FUNCTION_BODY>} private void checkRegisterInfo(UserRegisterDTO userRegisterDTO) { ServerResponseEntity<AuthAccountVO> responseEntity = accountFeignClient.getByUsernameAndSysType(userRegisterDTO.getUserName(), SysTypeEnum.ORDINARY); if (!responseEntity.isSuccess()) { throw new Mall4cloudException(responseEntity.getMsg()); } if (Objects.nonNull(responseEntity.getData())) { throw new Mall4cloudException("用户名已存在"); } } }
this.checkRegisterInfo(param); ServerResponseEntity<Long> segmentIdResponse = segmentFeignClient.getSegmentId(User.DISTRIBUTED_ID_KEY); if (!segmentIdResponse.isSuccess()) { throw new Mall4cloudException(ResponseEnum.EXCEPTION); } Long userId = segmentIdResponse.getData(); param.setUserId(userId); AuthAccountDTO authAccountDTO = new AuthAccountDTO(); authAccountDTO.setCreateIp(IpHelper.getIpAddr()); authAccountDTO.setPassword(param.getPassword()); authAccountDTO.setIsAdmin(0); authAccountDTO.setSysType(SysTypeEnum.ORDINARY.value()); authAccountDTO.setUsername(param.getUserName()); authAccountDTO.setStatus(1); authAccountDTO.setUserId(userId); // 保存统一账户信息 ServerResponseEntity<Long> serverResponse = accountFeignClient.save(authAccountDTO); // 抛异常回滚 if (!serverResponse.isSuccess()) { throw new Mall4cloudException(serverResponse.getMsg()); } User user = new User(); user.setUserId(userId); user.setPic(param.getImg()); user.setNickName(param.getNickName()); user.setStatus(1); // 这里保存之后才有用户id userMapper.save(user); return serverResponse.getData();
485
398
883
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/vo/UserSimpleInfoVO.java
UserSimpleInfoVO
toString
class UserSimpleInfoVO { @Schema(description = "用户昵称" ,requiredMode = Schema.RequiredMode.REQUIRED) private String nickName; @Schema(description = "用户头像" ,requiredMode = Schema.RequiredMode.REQUIRED) private String pic; public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserCenterInfoVO{" + "nickName='" + nickName + '\'' + ", pic='" + pic + '\'' + '}';
193
45
238
<no_super_class>
gz-yami_mall4cloud
mall4cloud/mall4cloud-user/src/main/java/com/mall4j/cloud/user/vo/UserVO.java
UserVO
toString
class UserVO extends BaseVO{ private static final long serialVersionUID = 1L; @Schema(description = "ID" ) private Long userId; @Schema(description = "用户昵称" ) private String nickName; @Schema(description = "头像图片路径" ) private String pic; @Schema(description = "状态 1 正常 0 无效" ) private Integer status; /** * openId list */ private List<String> bizUserIdList; public List<String> getBizUserIdList() { return bizUserIdList; } public void setBizUserIdList(List<String> bizUserIdList) { this.bizUserIdList = bizUserIdList; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserApiVO{" + "userId=" + userId + ",createTime=" + createTime + ",updateTime=" + updateTime + ",nickName=" + nickName + ",pic=" + pic + ",status=" + status + '}';
387
85
472
<methods>public non-sealed void <init>() ,public java.util.Date getCreateTime() ,public java.util.Date getUpdateTime() ,public void setCreateTime(java.util.Date) ,public void setUpdateTime(java.util.Date) ,public java.lang.String toString() <variables>protected java.util.Date createTime,protected java.util.Date updateTime
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/config/SwaggerConfiguration.java
SwaggerConfiguration
springShopOpenApi
class SwaggerConfiguration { @Bean public GroupedOpenApi baseRestApi() { return GroupedOpenApi.builder() .group("接口文档") .packagesToScan("com.yami").build(); } @Bean public OpenAPI springShopOpenApi() {<FILL_FUNCTION_BODY>} }
return new OpenAPI() .info(new Info().title("Mall4j接口文档") .description("Mall4j接口文档,openapi3.0 接口,用于前端对接") .version("v0.0.1") .license(new License().name("使用请遵守AGPL3.0授权协议").url("https://www.mall4j.com")));
86
107
193
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/AdminLoginController.java
AdminLoginController
login
class AdminLoginController { @Autowired private TokenStore tokenStore; @Autowired private SysUserService sysUserService; @Autowired private SysMenuService sysMenuService; @Autowired private PasswordCheckManager passwordCheckManager; @Autowired private CaptchaService captchaService; @Autowired private PasswordManager passwordManager; @PostMapping("/adminLogin") @Operation(summary = "账号密码 + 验证码登录(用于后台登录)" , description = "通过账号/手机号/用户名密码登录") public ServerResponseEntity<?> login( @Valid @RequestBody CaptchaAuthenticationDTO captchaAuthenticationDTO) {<FILL_FUNCTION_BODY>} private Set<String> getUserPermissions(Long userId) { List<String> permsList; //系统管理员,拥有最高权限 if(userId == Constant.SUPER_ADMIN_ID){ List<SysMenu> menuList = sysMenuService.list(Wrappers.emptyWrapper()); permsList = menuList.stream().map(SysMenu::getPerms).collect(Collectors.toList()); }else{ permsList = sysUserService.queryAllPerms(userId); } return permsList.stream().flatMap((perms)->{ if (StrUtil.isBlank(perms)) { return null; } return Arrays.stream(perms.trim().split(StrUtil.COMMA)); } ).collect(Collectors.toSet()); } }
// 登陆后台登录需要再校验一遍验证码 CaptchaVO captchaVO = new CaptchaVO(); captchaVO.setCaptchaVerification(captchaAuthenticationDTO.getCaptchaVerification()); ResponseModel response = captchaService.verification(captchaVO); if (!response.isSuccess()) { return ServerResponseEntity.showFailMsg("验证码有误或已过期"); } SysUser sysUser = sysUserService.getByUserName(captchaAuthenticationDTO.getUserName()); if (sysUser == null) { throw new YamiShopBindException("账号或密码不正确"); } // 半小时内密码输入错误十次,已限制登录30分钟 String decryptPassword = passwordManager.decryptPassword(captchaAuthenticationDTO.getPassWord()); passwordCheckManager.checkPassword(SysTypeEnum.ADMIN,captchaAuthenticationDTO.getUserName(), decryptPassword, sysUser.getPassword()); // 不是店铺超级管理员,并且是禁用状态,无法登录 if (Objects.equals(sysUser.getStatus(),0)) { // 未找到此用户信息 throw new YamiShopBindException("未找到此用户信息"); } UserInfoInTokenBO userInfoInToken = new UserInfoInTokenBO(); userInfoInToken.setUserId(String.valueOf(sysUser.getUserId())); userInfoInToken.setSysType(SysTypeEnum.ADMIN.value()); userInfoInToken.setEnabled(sysUser.getStatus() == 1); userInfoInToken.setPerms(getUserPermissions(sysUser.getUserId())); userInfoInToken.setNickName(sysUser.getUsername()); userInfoInToken.setShopId(sysUser.getShopId()); // 存储token返回vo TokenInfoVO tokenInfoVO = tokenStore.storeAndGetVo(userInfoInToken); return ServerResponseEntity.success(tokenInfoVO);
426
514
940
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/AreaController.java
AreaController
save
class AreaController { @Autowired private AreaService areaService; /** * 分页获取 */ @GetMapping("/page") @PreAuthorize("@pms.hasPermission('admin:area:page')") public ServerResponseEntity<IPage<Area>> page(Area area,PageParam<Area> page) { IPage<Area> sysUserPage = areaService.page(page, new LambdaQueryWrapper<Area>()); return ServerResponseEntity.success(sysUserPage); } /** * 获取省市 */ @GetMapping("/list") @PreAuthorize("@pms.hasPermission('admin:area:list')") public ServerResponseEntity<List<Area>> list(Area area) { List<Area> areas = areaService.list(new LambdaQueryWrapper<Area>() .like(area.getAreaName() != null, Area::getAreaName, area.getAreaName())); return ServerResponseEntity.success(areas); } /** * 通过父级id获取区域列表 */ @GetMapping("/listByPid") public ServerResponseEntity<List<Area>> listByPid(Long pid) { List<Area> list = areaService.listByPid(pid); return ServerResponseEntity.success(list); } /** * 获取信息 */ @GetMapping("/info/{id}") @PreAuthorize("@pms.hasPermission('admin:area:info')") public ServerResponseEntity<Area> info(@PathVariable("id") Long id) { Area area = areaService.getById(id); return ServerResponseEntity.success(area); } /** * 保存 */ @PostMapping @PreAuthorize("@pms.hasPermission('admin:area:save')") public ServerResponseEntity<Void> save(@Valid @RequestBody Area area) {<FILL_FUNCTION_BODY>} /** * 修改 */ @PutMapping @PreAuthorize("@pms.hasPermission('admin:area:update')") public ServerResponseEntity<Void> update(@Valid @RequestBody Area area) { Area areaDb = areaService.getById(area.getAreaId()); // 判断当前省市区级别,如果是1级、2级则不能修改级别,不能修改成别人的下级 if(Objects.equals(areaDb.getLevel(), AreaLevelEnum.FIRST_LEVEL.value()) && !Objects.equals(area.getLevel(),AreaLevelEnum.FIRST_LEVEL.value())){ throw new YamiShopBindException("不能改变一级行政地区的级别"); } if(Objects.equals(areaDb.getLevel(),AreaLevelEnum.SECOND_LEVEL.value()) && !Objects.equals(area.getLevel(),AreaLevelEnum.SECOND_LEVEL.value())){ throw new YamiShopBindException("不能改变二级行政地区的级别"); } hasSameName(area); areaService.updateById(area); areaService.removeAreaCacheByParentId(area.getParentId()); return ServerResponseEntity.success(); } /** * 删除 */ @DeleteMapping("/{id}") @PreAuthorize("@pms.hasPermission('admin:area:delete')") public ServerResponseEntity<Void> delete(@PathVariable Long id) { Area area = areaService.getById(id); areaService.removeById(id); areaService.removeAreaCacheByParentId(area.getParentId()); return ServerResponseEntity.success(); } private void hasSameName(Area area) { long count = areaService.count(new LambdaQueryWrapper<Area>() .eq(Area::getParentId, area.getParentId()) .eq(Area::getAreaName, area.getAreaName()) .ne(Objects.nonNull(area.getAreaId()) && !Objects.equals(area.getAreaId(), 0L), Area::getAreaId, area.getAreaId()) ); if (count > 0) { throw new YamiShopBindException("该地区已存在"); } } }
if (area.getParentId() != null) { Area parentArea = areaService.getById(area.getParentId()); area.setLevel(parentArea.getLevel() + 1); areaService.removeAreaCacheByParentId(area.getParentId()); } areaService.save(area); return ServerResponseEntity.success();
1,061
91
1,152
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/AttributeController.java
AttributeController
update
class AttributeController { @Autowired private ProdPropService prodPropService; /** * 分页获取 */ @GetMapping("/page") @PreAuthorize("@pms.hasPermission('admin:attribute:page')") public ServerResponseEntity<IPage<ProdProp>> page(ProdProp prodProp,PageParam<ProdProp> page){ prodProp.setRule(ProdPropRule.ATTRIBUTE.value()); prodProp.setShopId(SecurityUtils.getSysUser().getShopId()); IPage<ProdProp> prodPropPage = prodPropService.pagePropAndValue(prodProp,page); return ServerResponseEntity.success(prodPropPage); } /** * 获取信息 */ @GetMapping("/info/{id}") @PreAuthorize("@pms.hasPermission('admin:attribute:info')") public ServerResponseEntity<ProdProp> info(@PathVariable("id") Long id){ ProdProp prodProp = prodPropService.getById(id); return ServerResponseEntity.success(prodProp); } /** * 保存 */ @PostMapping @PreAuthorize("@pms.hasPermission('admin:attribute:save')") public ServerResponseEntity<Void> save(@Valid ProdProp prodProp){ prodProp.setRule(ProdPropRule.ATTRIBUTE.value()); prodProp.setShopId(SecurityUtils.getSysUser().getShopId()); prodPropService.saveProdPropAndValues(prodProp); return ServerResponseEntity.success(); } /** * 修改 */ @PutMapping @PreAuthorize("@pms.hasPermission('admin:attribute:update')") public ServerResponseEntity<Void> update(@Valid ProdProp prodProp){<FILL_FUNCTION_BODY>} /** * 删除 */ @DeleteMapping("/{id}") @PreAuthorize("@pms.hasPermission('admin:attribute:delete')") public ServerResponseEntity<Void> delete(@PathVariable Long id){ prodPropService.deleteProdPropAndValues(id,ProdPropRule.ATTRIBUTE.value(),SecurityUtils.getSysUser().getShopId()); return ServerResponseEntity.success(); } }
ProdProp dbProdProp = prodPropService.getById(prodProp.getPropId()); if (!Objects.equals(dbProdProp.getShopId(), SecurityUtils.getSysUser().getShopId())) { throw new YamiShopBindException("没有权限获取该商品规格信息"); } prodProp.setRule(ProdPropRule.ATTRIBUTE.value()); prodProp.setShopId(SecurityUtils.getSysUser().getShopId()); prodPropService.updateProdPropAndValues(prodProp); return ServerResponseEntity.success();
574
150
724
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/BrandController.java
BrandController
page
class BrandController { @Autowired private BrandService brandService; /** * 分页获取 */ @GetMapping("/page") @PreAuthorize("@pms.hasPermission('admin:brand:page')") public ServerResponseEntity<IPage<Brand>> page(Brand brand,PageParam<Brand> page) {<FILL_FUNCTION_BODY>} /** * 获取信息 */ @GetMapping("/info/{id}") @PreAuthorize("@pms.hasPermission('admin:brand:info')") public ServerResponseEntity<Brand> info(@PathVariable("id") Long id) { Brand brand = brandService.getById(id); return ServerResponseEntity.success(brand); } /** * 保存 */ @PostMapping @PreAuthorize("@pms.hasPermission('admin:brand:save')") public ServerResponseEntity<Void> save(@Valid Brand brand) { Brand dbBrand = brandService.getByBrandName(brand.getBrandName()); if (dbBrand != null) { throw new YamiShopBindException("该品牌名称已存在"); } brandService.save(brand); return ServerResponseEntity.success(); } /** * 修改 */ @PutMapping @PreAuthorize("@pms.hasPermission('admin:brand:update')") public ServerResponseEntity<Void> update(@Valid Brand brand) { Brand dbBrand = brandService.getByBrandName(brand.getBrandName()); if (dbBrand != null && !Objects.equals(dbBrand.getBrandId(), brand.getBrandId())) { throw new YamiShopBindException("该品牌名称已存在"); } brandService.updateById(brand); return ServerResponseEntity.success(); } /** * 删除 */ @DeleteMapping("/{id}") @PreAuthorize("@pms.hasPermission('admin:brand:delete')") public ServerResponseEntity<Void> delete(@PathVariable Long id) { brandService.deleteByBrand(id); return ServerResponseEntity.success(); } }
IPage<Brand> brands = brandService.page(page, new LambdaQueryWrapper<Brand>() .like(StrUtil.isNotBlank(brand.getBrandName()), Brand::getBrandName, brand.getBrandName()).orderByAsc(Brand::getFirstChar)); return ServerResponseEntity.success(brands);
571
90
661
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/CategoryController.java
CategoryController
delete
class CategoryController { @Autowired private CategoryService categoryService; /** * 获取菜单页面的表 * @return */ @GetMapping("/table") @PreAuthorize("@pms.hasPermission('prod:category:page')") public ServerResponseEntity<List<Category>> table(){ List<Category> categoryMenuList = categoryService.tableCategory(SecurityUtils.getSysUser().getShopId()); return ServerResponseEntity.success(categoryMenuList); } /** * 获取分类信息 */ @GetMapping("/info/{categoryId}") public ServerResponseEntity<Category> info(@PathVariable("categoryId") Long categoryId){ Category category = categoryService.getById(categoryId); return ServerResponseEntity.success(category); } /** * 保存分类 */ @SysLog("保存分类") @PostMapping @PreAuthorize("@pms.hasPermission('prod:category:save')") public ServerResponseEntity<Void> save(@RequestBody Category category){ category.setShopId(SecurityUtils.getSysUser().getShopId()); category.setRecTime(new Date()); Category categoryName = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName,category.getCategoryName()) .eq(Category::getShopId,category.getShopId())); if(categoryName != null){ throw new YamiShopBindException("类目名称已存在!"); } categoryService.saveCategory(category); return ServerResponseEntity.success(); } /** * 更新分类 */ @SysLog("更新分类") @PutMapping @PreAuthorize("@pms.hasPermission('prod:category:update')") public ServerResponseEntity<String> update(@RequestBody Category category){ category.setShopId(SecurityUtils.getSysUser().getShopId()); if (Objects.equals(category.getParentId(),category.getCategoryId())) { return ServerResponseEntity.showFailMsg("分类的上级不能是自己本身"); } Category categoryName = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName,category.getCategoryName()) .eq(Category::getShopId,category.getShopId()).ne(Category::getCategoryId,category.getCategoryId())); if(categoryName != null){ throw new YamiShopBindException("类目名称已存在!"); } Category categoryDb = categoryService.getById(category.getCategoryId()); // 如果从下线改成正常,则需要判断上级的状态 if (Objects.equals(categoryDb.getStatus(),0) && Objects.equals(category.getStatus(),1) && !Objects.equals(category.getParentId(),0L)){ Category parentCategory = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryId, category.getParentId())); if(Objects.isNull(parentCategory) || Objects.equals(parentCategory.getStatus(),0)){ // 修改失败,上级分类不存在或者不为正常状态 throw new YamiShopBindException("修改失败,上级分类不存在或者不为正常状态"); } } categoryService.updateCategory(category); return ServerResponseEntity.success(); } /** * 删除分类 */ @SysLog("删除分类") @DeleteMapping("/{categoryId}") @PreAuthorize("@pms.hasPermission('prod:category:delete')") public ServerResponseEntity<String> delete(@PathVariable("categoryId") Long categoryId){<FILL_FUNCTION_BODY>} /** * 所有的 */ @GetMapping("/listCategory") public ServerResponseEntity<List<Category>> listCategory(){ return ServerResponseEntity.success(categoryService.list(new LambdaQueryWrapper<Category>() .le(Category::getGrade, 2) .eq(Category::getShopId, SecurityUtils.getSysUser().getShopId()) .orderByAsc(Category::getSeq))); } /** * 所有的产品分类 */ @GetMapping("/listProdCategory") public ServerResponseEntity<List<Category>> listProdCategory(){ List<Category> categories = categoryService.treeSelect(SecurityUtils.getSysUser().getShopId(),2); return ServerResponseEntity.success(categories); } }
if (categoryService.count(new LambdaQueryWrapper<Category>().eq(Category::getParentId,categoryId)) >0) { return ServerResponseEntity.showFailMsg("请删除子分类,再删除该分类"); } categoryService.deleteCategory(categoryId); return ServerResponseEntity.success();
1,118
83
1,201
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/FileController.java
FileController
uploadElementFile
class FileController { @Autowired private AttachFileService attachFileService; @Autowired private Qiniu qiniu; @Autowired private ImgUploadUtil imgUploadUtil; @PostMapping("/upload/element") public ServerResponseEntity<String> uploadElementFile(@RequestParam("file") MultipartFile file) throws IOException{<FILL_FUNCTION_BODY>} @PostMapping("/upload/tinymceEditor") public ServerResponseEntity<String> uploadTinymceEditorImages(@RequestParam("editorFile") MultipartFile editorFile) throws IOException{ String fileName = attachFileService.uploadFile(editorFile); String data = ""; if (Objects.equals(imgUploadUtil.getUploadType(), 1)) { data = imgUploadUtil.getUploadPath() + fileName; } else if (Objects.equals(imgUploadUtil.getUploadType(), 2)) { data = qiniu.getResourcesUrl() + fileName; } return ServerResponseEntity.success(data); } }
if(file.isEmpty()){ return ServerResponseEntity.success(); } String fileName = attachFileService.uploadFile(file); return ServerResponseEntity.success(fileName);
263
51
314
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/HotSearchController.java
HotSearchController
page
class HotSearchController { @Autowired private HotSearchService hotSearchService; /** * 分页获取 */ @GetMapping("/page") @PreAuthorize("@pms.hasPermission('admin:hotSearch:page')") public ServerResponseEntity<IPage<HotSearch>> page(HotSearch hotSearch,PageParam<HotSearch> page){<FILL_FUNCTION_BODY>} /** * 获取信息 */ @GetMapping("/info/{id}") public ServerResponseEntity<HotSearch> info(@PathVariable("id") Long id){ HotSearch hotSearch = hotSearchService.getById(id); return ServerResponseEntity.success(hotSearch); } /** * 保存 */ @PostMapping @PreAuthorize("@pms.hasPermission('admin:hotSearch:save')") public ServerResponseEntity<Void> save(@RequestBody @Valid HotSearch hotSearch){ hotSearch.setRecDate(new Date()); hotSearch.setShopId(SecurityUtils.getSysUser().getShopId()); hotSearchService.save(hotSearch); //清除缓存 hotSearchService.removeHotSearchDtoCacheByShopId(SecurityUtils.getSysUser().getShopId()); return ServerResponseEntity.success(); } /** * 修改 */ @PutMapping @PreAuthorize("@pms.hasPermission('admin:hotSearch:update')") public ServerResponseEntity<Void> update(@RequestBody @Valid HotSearch hotSearch){ hotSearchService.updateById(hotSearch); //清除缓存 hotSearchService.removeHotSearchDtoCacheByShopId(SecurityUtils.getSysUser().getShopId()); return ServerResponseEntity.success(); } /** * 删除 */ @DeleteMapping @PreAuthorize("@pms.hasPermission('admin:hotSearch:delete')") public ServerResponseEntity<Void> delete(@RequestBody List<Long> ids){ hotSearchService.removeByIds(ids); //清除缓存 hotSearchService.removeHotSearchDtoCacheByShopId(SecurityUtils.getSysUser().getShopId()); return ServerResponseEntity.success(); } }
IPage<HotSearch> hotSearchs = hotSearchService.page(page,new LambdaQueryWrapper<HotSearch>() .eq(HotSearch::getShopId, SecurityUtils.getSysUser().getShopId()) .like(StrUtil.isNotBlank(hotSearch.getContent()), HotSearch::getContent,hotSearch.getContent()) .like(StrUtil.isNotBlank(hotSearch.getTitle()), HotSearch::getTitle,hotSearch.getTitle()) .eq(hotSearch.getStatus()!=null, HotSearch::getStatus,hotSearch.getStatus()) .orderByAsc(HotSearch::getSeq) ); return ServerResponseEntity.success(hotSearchs);
564
179
743
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/IndexImgController.java
IndexImgController
page
class IndexImgController { @Autowired private IndexImgService indexImgService; @Autowired private ProductService productService; /** * 分页获取 */ @GetMapping("/page") @PreAuthorize("@pms.hasPermission('admin:indexImg:page')") public ServerResponseEntity<IPage<IndexImg>> page(IndexImg indexImg, PageParam<IndexImg> page) {<FILL_FUNCTION_BODY>} /** * 获取信息 */ @GetMapping("/info/{imgId}") @PreAuthorize("@pms.hasPermission('admin:indexImg:info')") public ServerResponseEntity<IndexImg> info(@PathVariable("imgId") Long imgId) { Long shopId = SecurityUtils.getSysUser().getShopId(); IndexImg indexImg = indexImgService.getOne(new LambdaQueryWrapper<IndexImg>().eq(IndexImg::getShopId, shopId).eq(IndexImg::getImgId, imgId)); if (Objects.nonNull(indexImg.getRelation())) { Product product = productService.getProductByProdId(indexImg.getRelation()); indexImg.setPic(product.getPic()); indexImg.setProdName(product.getProdName()); } return ServerResponseEntity.success(indexImg); } /** * 保存 */ @PostMapping @PreAuthorize("@pms.hasPermission('admin:indexImg:save')") public ServerResponseEntity<Void> save(@RequestBody @Valid IndexImg indexImg) { Long shopId = SecurityUtils.getSysUser().getShopId(); indexImg.setShopId(shopId); indexImg.setUploadTime(new Date()); checkProdStatus(indexImg); indexImgService.save(indexImg); indexImgService.removeIndexImgCache(); return ServerResponseEntity.success(); } /** * 修改 */ @PutMapping @PreAuthorize("@pms.hasPermission('admin:indexImg:update')") public ServerResponseEntity<Void> update(@RequestBody @Valid IndexImg indexImg) { checkProdStatus(indexImg); indexImgService.saveOrUpdate(indexImg); indexImgService.removeIndexImgCache(); return ServerResponseEntity.success(); } /** * 删除 */ @DeleteMapping @PreAuthorize("@pms.hasPermission('admin:indexImg:delete')") public ServerResponseEntity<Void> delete(@RequestBody Long[] ids) { indexImgService.deleteIndexImgByIds(ids); indexImgService.removeIndexImgCache(); return ServerResponseEntity.success(); } private void checkProdStatus(IndexImg indexImg) { if (!Objects.equals(indexImg.getType(), 0)) { return; } if (Objects.isNull(indexImg.getRelation())) { throw new YamiShopBindException("请选择商品"); } Product product = productService.getById(indexImg.getRelation()); if (Objects.isNull(product)) { throw new YamiShopBindException("商品信息不存在"); } if (!Objects.equals(product.getStatus(), 1)) { throw new YamiShopBindException("该商品未上架,请选择别的商品"); } } }
IPage<IndexImg> indexImgPage = indexImgService.page(page, new LambdaQueryWrapper<IndexImg>() .eq(indexImg.getStatus() != null, IndexImg::getStatus, indexImg.getStatus()) .orderByAsc(IndexImg::getSeq)); return ServerResponseEntity.success(indexImgPage);
922
99
1,021
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/MessageController.java
MessageController
page
class MessageController { @Autowired private MessageService messageService; /** * 分页获取 */ @GetMapping("/page") @PreAuthorize("@pms.hasPermission('admin:message:page')") public ServerResponseEntity<IPage<Message>> page(Message message,PageParam<Message> page) {<FILL_FUNCTION_BODY>} /** * 获取信息 */ @GetMapping("/info/{id}") @PreAuthorize("@pms.hasPermission('admin:message:info')") public ServerResponseEntity<Message> info(@PathVariable("id") Long id) { Message message = messageService.getById(id); return ServerResponseEntity.success(message); } /** * 保存 */ @PostMapping @PreAuthorize("@pms.hasPermission('admin:message:save')") public ServerResponseEntity<Void> save(@RequestBody Message message) { messageService.save(message); return ServerResponseEntity.success(); } /** * 修改 */ @PutMapping @PreAuthorize("@pms.hasPermission('admin:message:update')") public ServerResponseEntity<Void> update(@RequestBody Message message) { messageService.updateById(message); return ServerResponseEntity.success(); } /** * 公开留言 */ @PutMapping("/release/{id}") @PreAuthorize("@pms.hasPermission('admin:message:release')") public ServerResponseEntity<Void> release(@PathVariable("id") Long id) { Message message = new Message(); message.setId(id); message.setStatus(MessageStatus.RELEASE.value()); messageService.updateById(message); return ServerResponseEntity.success(); } /** * 取消公开留言 */ @PutMapping("/cancel/{id}") @PreAuthorize("@pms.hasPermission('admin:message:cancel')") public ServerResponseEntity<Void> cancel(@PathVariable("id") Long id) { Message message = new Message(); message.setId(id); message.setStatus(MessageStatus.CANCEL.value()); messageService.updateById(message); return ServerResponseEntity.success(); } /** * 删除 */ @DeleteMapping("/{ids}") @PreAuthorize("@pms.hasPermission('admin:message:delete')") public ServerResponseEntity<Void> delete(@PathVariable Long[] ids) { messageService.removeByIds(Arrays.asList(ids)); return ServerResponseEntity.success(); } }
IPage<Message> messages = messageService.page(page, new LambdaQueryWrapper<Message>() .like(StrUtil.isNotBlank(message.getUserName()), Message::getUserName, message.getUserName()) .eq(message.getStatus() != null, Message::getStatus, message.getStatus())); return ServerResponseEntity.success(messages);
686
94
780
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/NoticeController.java
NoticeController
updateById
class NoticeController { private final NoticeService noticeService; /** * 分页查询 * * @param page 分页对象 * @param notice 公告管理 * @return 分页数据 */ @GetMapping("/page") public ServerResponseEntity<IPage<Notice>> getNoticePage(PageParam<Notice> page, Notice notice) { IPage<Notice> noticePage = noticeService.page(page, new LambdaQueryWrapper<Notice>() .eq(notice.getStatus() != null, Notice::getStatus, notice.getStatus()) .eq(notice.getIsTop()!=null,Notice::getIsTop,notice.getIsTop()) .like(notice.getTitle() != null, Notice::getTitle, notice.getTitle()).orderByDesc(Notice::getUpdateTime)); return ServerResponseEntity.success(noticePage); } /** * 通过id查询公告管理 * * @param id id * @return 单个数据 */ @GetMapping("/info/{id}") public ServerResponseEntity<Notice> getById(@PathVariable("id") Long id) { return ServerResponseEntity.success(noticeService.getById(id)); } /** * 新增公告管理 * * @param notice 公告管理 * @return 是否新增成功 */ @SysLog("新增公告管理") @PostMapping @PreAuthorize("@pms.hasPermission('shop:notice:save')") public ServerResponseEntity<Boolean> save(@RequestBody @Valid Notice notice) { notice.setShopId(SecurityUtils.getSysUser().getShopId()); if (notice.getStatus() == 1) { notice.setPublishTime(new Date()); } notice.setUpdateTime(new Date()); noticeService.removeNoticeList(); return ServerResponseEntity.success(noticeService.save(notice)); } /** * 修改公告管理 * * @param notice 公告管理 * @return 是否修改成功 */ @SysLog("修改公告管理") @PutMapping @PreAuthorize("@pms.hasPermission('shop:notice:update')") public ServerResponseEntity<Boolean> updateById(@RequestBody @Valid Notice notice) {<FILL_FUNCTION_BODY>} /** * 通过id删除公告管理 * * @param id id * @return 是否删除成功 */ @SysLog("删除公告管理") @DeleteMapping("/{id}") @PreAuthorize("@pms.hasPermission('shop:notice:delete')") public ServerResponseEntity<Boolean> removeById(@PathVariable Long id) { noticeService.removeNoticeList(); noticeService.removeNoticeById(id); return ServerResponseEntity.success(noticeService.removeById(id)); } }
Notice oldNotice = noticeService.getById(notice.getId()); if (oldNotice.getStatus() == 0 && notice.getStatus() == 1) { notice.setPublishTime(new Date()); } notice.setUpdateTime(new Date()); noticeService.removeNoticeList(); noticeService.removeNoticeById(notice.getId()); return ServerResponseEntity.success(noticeService.updateById(notice));
751
110
861
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/PickAddrController.java
PickAddrController
update
class PickAddrController { @Autowired private PickAddrService pickAddrService; /** * 分页获取 */ @GetMapping("/page") @PreAuthorize("@pms.hasPermission('shop:pickAddr:page')") public ServerResponseEntity<IPage<PickAddr>> page(PickAddr pickAddr,PageParam<PickAddr> page){ IPage<PickAddr> pickAddrs = pickAddrService.page(page,new LambdaQueryWrapper<PickAddr>() .like(StrUtil.isNotBlank(pickAddr.getAddrName()),PickAddr::getAddrName,pickAddr.getAddrName()) .orderByDesc(PickAddr::getAddrId)); return ServerResponseEntity.success(pickAddrs); } /** * 获取信息 */ @GetMapping("/info/{id}") @PreAuthorize("@pms.hasPermission('shop:pickAddr:info')") public ServerResponseEntity<PickAddr> info(@PathVariable("id") Long id){ PickAddr pickAddr = pickAddrService.getById(id); return ServerResponseEntity.success(pickAddr); } /** * 保存 */ @PostMapping @PreAuthorize("@pms.hasPermission('shop:pickAddr:save')") public ServerResponseEntity<Void> save(@Valid @RequestBody PickAddr pickAddr){ pickAddr.setShopId(SecurityUtils.getSysUser().getShopId()); pickAddrService.save(pickAddr); return ServerResponseEntity.success(); } /** * 修改 */ @PutMapping @PreAuthorize("@pms.hasPermission('shop:pickAddr:update')") public ServerResponseEntity<Void> update(@Valid @RequestBody PickAddr pickAddr){<FILL_FUNCTION_BODY>} /** * 删除 */ @DeleteMapping @PreAuthorize("@pms.hasPermission('shop:pickAddr:delete')") public ServerResponseEntity<Void> delete(@RequestBody Long[] ids){ pickAddrService.removeByIds(Arrays.asList(ids)); return ServerResponseEntity.success(); } }
PickAddr dbPickAddr = pickAddrService.getById(pickAddr.getAddrId()); if (!Objects.equals(dbPickAddr.getShopId(),SecurityUtils.getSysUser().getShopId())) { throw new YamiShopBindException(ResponseEnum.UNAUTHORIZED); } pickAddrService.updateById(pickAddr); return ServerResponseEntity.success();
559
107
666
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/ProdTagController.java
ProdTagController
removeById
class ProdTagController { @Autowired private ProdTagService prodTagService; /** * 分页查询 * * @param page 分页对象 * @param prodTag 商品分组标签 * @return 分页数据 */ @GetMapping("/page") public ServerResponseEntity<IPage<ProdTag>> getProdTagPage(PageParam<ProdTag> page, ProdTag prodTag) { IPage<ProdTag> tagPage = prodTagService.page( page, new LambdaQueryWrapper<ProdTag>() .eq(prodTag.getStatus() != null, ProdTag::getStatus, prodTag.getStatus()) .like(prodTag.getTitle() != null, ProdTag::getTitle, prodTag.getTitle()) .orderByDesc(ProdTag::getSeq, ProdTag::getCreateTime)); return ServerResponseEntity.success(tagPage); } /** * 通过id查询商品分组标签 * * @param id id * @return 单个数据 */ @GetMapping("/info/{id}") public ServerResponseEntity<ProdTag> getById(@PathVariable("id") Long id) { return ServerResponseEntity.success(prodTagService.getById(id)); } /** * 新增商品分组标签 * * @param prodTag 商品分组标签 * @return 是否新增成功 */ @SysLog("新增商品分组标签") @PostMapping @PreAuthorize("@pms.hasPermission('prod:prodTag:save')") public ServerResponseEntity<Boolean> save(@RequestBody @Valid ProdTag prodTag) { // 查看是否相同的标签 List<ProdTag> list = prodTagService.list(new LambdaQueryWrapper<ProdTag>().like(ProdTag::getTitle, prodTag.getTitle())); if (CollectionUtil.isNotEmpty(list)) { throw new YamiShopBindException("标签名称已存在,不能添加相同的标签"); } prodTag.setIsDefault(0); prodTag.setProdCount(0L); prodTag.setCreateTime(new Date()); prodTag.setUpdateTime(new Date()); prodTag.setShopId(SecurityUtils.getSysUser().getShopId()); prodTagService.removeProdTag(); return ServerResponseEntity.success(prodTagService.save(prodTag)); } /** * 修改商品分组标签 * * @param prodTag 商品分组标签 * @return 是否修改成功 */ @SysLog("修改商品分组标签") @PutMapping @PreAuthorize("@pms.hasPermission('prod:prodTag:update')") public ServerResponseEntity<Boolean> updateById(@RequestBody @Valid ProdTag prodTag) { prodTag.setUpdateTime(new Date()); prodTagService.removeProdTag(); return ServerResponseEntity.success(prodTagService.updateById(prodTag)); } /** * 通过id删除商品分组标签 * * @param id id * @return 是否删除成功 */ @SysLog("删除商品分组标签") @DeleteMapping("/{id}") @PreAuthorize("@pms.hasPermission('prod:prodTag:delete')") public ServerResponseEntity<Boolean> removeById(@PathVariable Long id) {<FILL_FUNCTION_BODY>} @GetMapping("/listTagList") public ServerResponseEntity<List<ProdTag>> listTagList() { return ServerResponseEntity.success(prodTagService.listProdTag()); } }
ProdTag prodTag = prodTagService.getById(id); if (prodTag.getIsDefault() != 0) { throw new YamiShopBindException("默认标签不能删除"); } prodTagService.removeProdTag(); return ServerResponseEntity.success(prodTagService.removeById(id));
968
86
1,054
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/ProductController.java
ProductController
checkParam
class ProductController { @Autowired private ProductService productService; @Autowired private SkuService skuService; @Autowired private ProdTagReferenceService prodTagReferenceService; @Autowired private BasketService basketService; /** * 分页获取商品信息 */ @GetMapping("/page") @PreAuthorize("@pms.hasPermission('prod:prod:page')") public ServerResponseEntity<IPage<Product>> page(ProductParam product, PageParam<Product> page) { IPage<Product> products = productService.page(page, new LambdaQueryWrapper<Product>() .like(StrUtil.isNotBlank(product.getProdName()), Product::getProdName, product.getProdName()) .eq(Product::getShopId, SecurityUtils.getSysUser().getShopId()) .eq(product.getStatus() != null, Product::getStatus, product.getStatus()) .orderByDesc(Product::getPutawayTime)); return ServerResponseEntity.success(products); } /** * 获取信息 */ @GetMapping("/info/{prodId}") @PreAuthorize("@pms.hasPermission('prod:prod:info')") public ServerResponseEntity<Product> info(@PathVariable("prodId") Long prodId) { Product prod = productService.getProductByProdId(prodId); if (!Objects.equals(prod.getShopId(), SecurityUtils.getSysUser().getShopId())) { throw new YamiShopBindException("没有权限获取该商品规格信息"); } List<Sku> skuList = skuService.listByProdId(prodId); prod.setSkuList(skuList); //获取分组标签 List<Long> listTagId = prodTagReferenceService.listTagIdByProdId(prodId); prod.setTagList(listTagId); return ServerResponseEntity.success(prod); } /** * 保存 */ @PostMapping @PreAuthorize("@pms.hasPermission('prod:prod:save')") public ServerResponseEntity<String> save(@Valid @RequestBody ProductParam productParam) { checkParam(productParam); Product product = BeanUtil.copyProperties(productParam, Product.class); product.setDeliveryMode(Json.toJsonString(productParam.getDeliveryModeVo())); product.setShopId(SecurityUtils.getSysUser().getShopId()); product.setUpdateTime(new Date()); if (product.getStatus() == 1) { product.setPutawayTime(new Date()); } product.setCreateTime(new Date()); productService.saveProduct(product); return ServerResponseEntity.success(); } /** * 修改 */ @PutMapping @PreAuthorize("@pms.hasPermission('prod:prod:update')") public ServerResponseEntity<String> update(@Valid @RequestBody ProductParam productParam) { checkParam(productParam); Product dbProduct = productService.getProductByProdId(productParam.getProdId()); if (!Objects.equals(dbProduct.getShopId(), SecurityUtils.getSysUser().getShopId())) { return ServerResponseEntity.showFailMsg("无法修改非本店铺商品信息"); } List<Sku> dbSkus = skuService.listByProdId(dbProduct.getProdId()); Product product = BeanUtil.copyProperties(productParam, Product.class); product.setDeliveryMode(Json.toJsonString(productParam.getDeliveryModeVo())); product.setUpdateTime(new Date()); if (dbProduct.getStatus() == 0 || productParam.getStatus() == 1) { product.setPutawayTime(new Date()); } dbProduct.setSkuList(dbSkus); productService.updateProduct(product, dbProduct); List<String> userIds = basketService.listUserIdByProdId(product.getProdId()); for (String userId : userIds) { basketService.removeShopCartItemsCacheByUserId(userId); } for (Sku sku : dbSkus) { skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId()); } return ServerResponseEntity.success(); } /** * 删除 */ public ServerResponseEntity<Void> delete(Long prodId) { Product dbProduct = productService.getProductByProdId(prodId); if (!Objects.equals(dbProduct.getShopId(), SecurityUtils.getSysUser().getShopId())) { throw new YamiShopBindException("无法获取非本店铺商品信息"); } List<Sku> dbSkus = skuService.listByProdId(dbProduct.getProdId()); // 删除商品 productService.removeProductByProdId(prodId); for (Sku sku : dbSkus) { skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId()); } List<String> userIds = basketService.listUserIdByProdId(prodId); for (String userId : userIds) { basketService.removeShopCartItemsCacheByUserId(userId); } return ServerResponseEntity.success(); } /** * 批量删除 */ @DeleteMapping @PreAuthorize("@pms.hasPermission('prod:prod:delete')") public ServerResponseEntity<Void> batchDelete(@RequestBody Long[] prodIds) { for (Long prodId : prodIds) { delete(prodId); } return ServerResponseEntity.success(); } /** * 更新商品状态 */ @PutMapping("/prodStatus") @PreAuthorize("@pms.hasPermission('prod:prod:status')") public ServerResponseEntity<Void> shopStatus(@RequestParam Long prodId, @RequestParam Integer prodStatus) { Product product = new Product(); product.setProdId(prodId); product.setStatus(prodStatus); if (prodStatus == 1) { product.setPutawayTime(new Date()); } productService.updateById(product); productService.removeProductCacheByProdId(prodId); List<String> userIds = basketService.listUserIdByProdId(prodId); for (String userId : userIds) { basketService.removeShopCartItemsCacheByUserId(userId); } return ServerResponseEntity.success(); } private void checkParam(ProductParam productParam) {<FILL_FUNCTION_BODY>} }
if (CollectionUtil.isEmpty(productParam.getTagList())) { throw new YamiShopBindException("请选择产品分组"); } Product.DeliveryModeVO deliveryMode = productParam.getDeliveryModeVo(); boolean hasDeliverMode = deliveryMode != null && (deliveryMode.getHasShopDelivery() || deliveryMode.getHasUserPickUp()); if (!hasDeliverMode) { throw new YamiShopBindException("请选择配送方式"); } List<Sku> skuList = productParam.getSkuList(); boolean isAllUnUse = true; for (Sku sku : skuList) { if (sku.getStatus() == 1) { isAllUnUse = false; } } if (isAllUnUse) { throw new YamiShopBindException("至少要启用一种商品规格"); }
1,753
232
1,985
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/ShopDetailController.java
ShopDetailController
listShopName
class ShopDetailController { @Autowired private ShopDetailService shopDetailService; /** * 修改分销开关 */ @PutMapping("/isDistribution") public ServerResponseEntity<Void> updateIsDistribution(@RequestParam Integer isDistribution){ ShopDetail shopDetail=new ShopDetail(); shopDetail.setShopId(SecurityUtils.getSysUser().getShopId()); shopDetail.setIsDistribution(isDistribution); shopDetailService.updateById(shopDetail); // 更新完成后删除缓存 shopDetailService.removeShopDetailCacheByShopId(shopDetail.getShopId()); return ServerResponseEntity.success(); } /** * 获取信息 */ @GetMapping("/info") @PreAuthorize("@pms.hasPermission('shop:shopDetail:info')") public ServerResponseEntity<ShopDetail> info(){ ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(SecurityUtils.getSysUser().getShopId()); return ServerResponseEntity.success(shopDetail); } /** * 分页获取 */ @GetMapping("/page") @PreAuthorize("@pms.hasPermission('shop:shopDetail:page')") public ServerResponseEntity<IPage<ShopDetail>> page(ShopDetail shopDetail,PageParam<ShopDetail> page){ IPage<ShopDetail> shopDetails = shopDetailService.page(page, new LambdaQueryWrapper<ShopDetail>() .like(StrUtil.isNotBlank(shopDetail.getShopName()),ShopDetail::getShopName,shopDetail.getShopName()) .orderByDesc(ShopDetail::getShopId)); return ServerResponseEntity.success(shopDetails); } /** * 获取信息 */ @GetMapping("/info/{shopId}") @PreAuthorize("@pms.hasPermission('shop:shopDetail:info')") public ServerResponseEntity<ShopDetail> info(@PathVariable("shopId") Long shopId){ ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId); // 店铺图片 return ServerResponseEntity.success(shopDetail); } /** * 保存 */ @PostMapping @PreAuthorize("@pms.hasPermission('shop:shopDetail:save')") public ServerResponseEntity<Void> save(@Valid ShopDetailParam shopDetailParam){ ShopDetail shopDetail = BeanUtil.copyProperties(shopDetailParam, ShopDetail.class); shopDetail.setCreateTime(new Date()); shopDetail.setShopStatus(1); shopDetailService.save(shopDetail); return ServerResponseEntity.success(); } /** * 修改 */ @PutMapping @PreAuthorize("@pms.hasPermission('shop:shopDetail:update')") public ServerResponseEntity<Void> update(@Valid ShopDetailParam shopDetailParam){ ShopDetail daShopDetail = shopDetailService.getShopDetailByShopId(shopDetailParam.getShopId()); ShopDetail shopDetail = BeanUtil.copyProperties(shopDetailParam, ShopDetail.class); shopDetail.setUpdateTime(new Date()); shopDetailService.updateShopDetail(shopDetail,daShopDetail); return ServerResponseEntity.success(); } /** * 删除 */ @DeleteMapping("/{id}") @PreAuthorize("@pms.hasPermission('shop:shopDetail:delete')") public ServerResponseEntity<Void> delete(@PathVariable Long id){ shopDetailService.deleteShopDetailByShopId(id); return ServerResponseEntity.success(); } /** * 更新店铺状态 */ @PutMapping("/shopStatus") @PreAuthorize("@pms.hasPermission('shop:shopDetail:shopStatus')") public ServerResponseEntity<Void> shopStatus(@RequestParam Long shopId,@RequestParam Integer shopStatus){ ShopDetail shopDetail = new ShopDetail(); shopDetail.setShopId(shopId); shopDetail.setShopStatus(shopStatus); shopDetailService.updateById(shopDetail); // 更新完成后删除缓存 shopDetailService.removeShopDetailCacheByShopId(shopDetail.getShopId()); return ServerResponseEntity.success(); } /** * 获取所有的店铺名称 */ @GetMapping("/listShopName") public ServerResponseEntity<List<ShopDetail>> listShopName(){<FILL_FUNCTION_BODY>} }
List<ShopDetail> list = shopDetailService.list().stream().map((dbShopDetail) ->{ ShopDetail shopDetail = new ShopDetail(); shopDetail.setShopId(dbShopDetail.getShopId()); shopDetail.setShopName(dbShopDetail.getShopName()); return shopDetail; }).collect(Collectors.toList()); return ServerResponseEntity.success(list);
1,127
107
1,234
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/SpecController.java
SpecController
page
class SpecController { @Autowired private ProdPropService prodPropService; @Autowired private ProdPropValueService prodPropValueService; /** * 分页获取 */ @GetMapping("/page") @PreAuthorize("@pms.hasPermission('prod:spec:page')") public ServerResponseEntity<IPage<ProdProp>> page(ProdProp prodProp,PageParam<ProdProp> page) {<FILL_FUNCTION_BODY>} /** * 获取所有的规格 */ @GetMapping("/list") public ServerResponseEntity<List<ProdProp>> list() { List<ProdProp> list = prodPropService.list(new LambdaQueryWrapper<ProdProp>().eq(ProdProp::getRule, ProdPropRule.SPEC.value()).eq(ProdProp::getShopId, SecurityUtils.getSysUser().getShopId())); return ServerResponseEntity.success(list); } /** * 根据规格id获取规格值 */ @GetMapping("/listSpecValue/{specId}") public ServerResponseEntity<List<ProdPropValue>> listSpecValue(@PathVariable("specId") Long specId) { List<ProdPropValue> list = prodPropValueService.list(new LambdaQueryWrapper<ProdPropValue>().eq(ProdPropValue::getPropId, specId)); return ServerResponseEntity.success(list); } /** * 保存 */ @PostMapping @PreAuthorize("@pms.hasPermission('prod:spec:save')") public ServerResponseEntity<Void> save(@Valid @RequestBody ProdProp prodProp) { prodProp.setRule(ProdPropRule.SPEC.value()); prodProp.setShopId(SecurityUtils.getSysUser().getShopId()); prodPropService.saveProdPropAndValues(prodProp); return ServerResponseEntity.success(); } /** * 修改 */ @PutMapping @PreAuthorize("@pms.hasPermission('prod:spec:update')") public ServerResponseEntity<Void> update(@Valid @RequestBody ProdProp prodProp) { ProdProp dbProdProp = prodPropService.getById(prodProp.getPropId()); if (!Objects.equals(dbProdProp.getShopId(), SecurityUtils.getSysUser().getShopId())) { throw new YamiShopBindException("没有权限获取该商品规格信息"); } prodProp.setRule(ProdPropRule.SPEC.value()); prodProp.setShopId(SecurityUtils.getSysUser().getShopId()); prodPropService.updateProdPropAndValues(prodProp); return ServerResponseEntity.success(); } /** * 删除 */ @DeleteMapping("/{id}") @PreAuthorize("@pms.hasPermission('prod:spec:delete')") public ServerResponseEntity<Void> delete(@PathVariable Long id) { prodPropService.deleteProdPropAndValues(id, ProdPropRule.SPEC.value(), SecurityUtils.getSysUser().getShopId()); return ServerResponseEntity.success(); } /** * 根据获取规格值最大的自增id */ @GetMapping("/listSpecMaxValueId") public ServerResponseEntity<Long> listSpecMaxValueId() { ProdPropValue propValue = prodPropValueService.getOne(new LambdaQueryWrapper<ProdPropValue>() .orderByDesc(ProdPropValue::getValueId).last("limit 1")); return ServerResponseEntity.success(Objects.isNull(propValue) ? 0L : propValue.getValueId()); } }
prodProp.setRule(ProdPropRule.SPEC.value()); prodProp.setShopId(SecurityUtils.getSysUser().getShopId()); IPage<ProdProp> list = prodPropService.pagePropAndValue(prodProp, page); return ServerResponseEntity.success(list);
953
79
1,032
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/TransportController.java
TransportController
save
class TransportController { @Autowired private TransportService transportService; /** * 分页获取 */ @GetMapping("/page") @PreAuthorize("@pms.hasPermission('shop:transport:page')") public ServerResponseEntity<IPage<Transport>> page(Transport transport,PageParam<Transport> page) { Long shopId = SecurityUtils.getSysUser().getShopId(); IPage<Transport> transports = transportService.page(page, new LambdaQueryWrapper<Transport>() .eq(Transport::getShopId, shopId) .like(StringUtils.isNotBlank(transport.getTransName()), Transport::getTransName, transport.getTransName())); return ServerResponseEntity.success(transports); } /** * 获取信息 */ @GetMapping("/info/{id}") @PreAuthorize("@pms.hasPermission('shop:transport:info')") public ServerResponseEntity<Transport> info(@PathVariable("id") Long id) { Transport transport = transportService.getTransportAndAllItems(id); return ServerResponseEntity.success(transport); } /** * 保存 */ @PostMapping @PreAuthorize("@pms.hasPermission('shop:transport:save')") public ServerResponseEntity<Void> save(@RequestBody Transport transport) {<FILL_FUNCTION_BODY>} /** * 修改 */ @PutMapping @PreAuthorize("@pms.hasPermission('shop:transport:update')") public ServerResponseEntity<Void> update(@RequestBody Transport transport) { transportService.updateTransportAndTransfee(transport); return ServerResponseEntity.success(); } /** * 删除 */ @DeleteMapping @PreAuthorize("@pms.hasPermission('shop:transport:delete')") public ServerResponseEntity<Void> delete(@RequestBody Long[] ids) { transportService.deleteTransportAndTransfeeAndTranscity(ids); // 删除运费模板的缓存 for (Long id : ids) { transportService.removeTransportAndAllItemsCache(id); } return ServerResponseEntity.success(); } /** * 获取运费模板列表 */ @GetMapping("/list") public ServerResponseEntity<List<Transport>> list() { Long shopId = SecurityUtils.getSysUser().getShopId(); List<Transport> list = transportService.list(new LambdaQueryWrapper<Transport>().eq(Transport::getShopId, shopId)); return ServerResponseEntity.success(list); } }
Long shopId = SecurityUtils.getSysUser().getShopId(); transport.setShopId(shopId); Date createTime = new Date(); transport.setCreateTime(createTime); transportService.insertTransportAndTransfee(transport); return ServerResponseEntity.success();
680
75
755
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/controller/UserController.java
UserController
page
class UserController { @Autowired private UserService userService; /** * 分页获取 */ @GetMapping("/page") @PreAuthorize("@pms.hasPermission('admin:user:page')") public ServerResponseEntity<IPage<User>> page(User user,PageParam<User> page) {<FILL_FUNCTION_BODY>} /** * 获取信息 */ @GetMapping("/info/{userId}") @PreAuthorize("@pms.hasPermission('admin:user:info')") public ServerResponseEntity<User> info(@PathVariable("userId") String userId) { User user = userService.getById(userId); user.setNickName(user.getNickName() == null ? "" : user.getNickName()); return ServerResponseEntity.success(user); } /** * 修改 */ @PutMapping @PreAuthorize("@pms.hasPermission('admin:user:update')") public ServerResponseEntity<Void> update(@RequestBody User user) { user.setModifyTime(new Date()); user.setNickName(user.getNickName() == null ? "" : user.getNickName()); userService.updateById(user); return ServerResponseEntity.success(); } /** * 删除 */ @DeleteMapping @PreAuthorize("@pms.hasPermission('admin:user:delete')") public ServerResponseEntity<Void> delete(@RequestBody String[] userIds) { userService.removeByIds(Arrays.asList(userIds)); return ServerResponseEntity.success(); } }
IPage<User> userPage = userService.page(page, new LambdaQueryWrapper<User>() .like(StrUtil.isNotBlank(user.getNickName()), User::getNickName, user.getNickName()) .eq(user.getStatus() != null, User::getStatus, user.getStatus())); for (User userResult : userPage.getRecords()) { userResult.setNickName(userResult.getNickName() == null ? "" : userResult.getNickName()); } return ServerResponseEntity.success(userPage);
434
149
583
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-admin/src/main/java/com/yami/shop/admin/task/OrderTask.java
OrderTask
confirmOrder
class OrderTask { private static final Logger logger = LoggerFactory.getLogger(OrderTask.class); @Autowired private OrderService orderService; @Autowired private ProductService productService; @Autowired private SkuService skuService; @XxlJob("cancelOrder") public void cancelOrder(){ Date now = new Date(); logger.info("取消超时未支付订单。。。"); // 获取30分钟之前未支付的订单 List<Order> orders = orderService.listOrderAndOrderItems(OrderStatus.UNPAY.value(),DateUtil.offsetMinute(now, -30)); if (CollectionUtil.isEmpty(orders)) { return; } orderService.cancelOrders(orders); for (Order order : orders) { List<OrderItem> orderItems = order.getOrderItems(); for (OrderItem orderItem : orderItems) { productService.removeProductCacheByProdId(orderItem.getProdId()); skuService.removeSkuCacheBySkuId(orderItem.getSkuId(),orderItem.getProdId()); } } } /** * 确认收货 */ @XxlJob("confirmOrder") public void confirmOrder(){<FILL_FUNCTION_BODY>} }
Date now = new Date(); logger.info("系统自动确认收货订单。。。"); // 获取15天之前未支付的订单 List<Order> orders = orderService.listOrderAndOrderItems(OrderStatus.CONSIGNMENT.value(),DateUtil.offsetDay(now, -15)); if (CollectionUtil.isEmpty(orders)) { return; } orderService.confirmOrder(orders); for (Order order : orders) { List<OrderItem> orderItems = order.getOrderItems(); for (OrderItem orderItem : orderItems) { productService.removeProductCacheByProdId(orderItem.getProdId()); skuService.removeSkuCacheBySkuId(orderItem.getSkuId(),orderItem.getProdId()); } }
348
208
556
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/config/SwaggerConfiguration.java
SwaggerConfiguration
springShopOpenApi
class SwaggerConfiguration { @Bean public GroupedOpenApi createRestApi() { return GroupedOpenApi.builder() .group("接口文档") .packagesToScan("com.yami.shop.api").build(); } @Bean public OpenAPI springShopOpenApi() {<FILL_FUNCTION_BODY>} }
return new OpenAPI() .info(new Info().title("Mall4j接口文档") .description("Mall4j接口文档,openapi3.0 接口,用于前端对接") .version("v0.0.1") .license(new License().name("使用请遵守AGPL3.0授权协议").url("https://www.mall4j.com")));
90
107
197
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/AddrController.java
AddrController
dvyList
class AddrController { @Autowired private UserAddrService userAddrService; /** * 选择订单配送地址 */ @GetMapping("/list") @Operation(summary = "用户地址列表" , description = "获取用户的所有地址信息") public ServerResponseEntity<List<UserAddrDto>> dvyList() {<FILL_FUNCTION_BODY>} @PostMapping("/addAddr") @Operation(summary = "新增用户地址" , description = "新增用户地址") public ServerResponseEntity<String> addAddr(@Valid @RequestBody AddrParam addrParam) { String userId = SecurityUtils.getUser().getUserId(); if (addrParam.getAddrId() != null && addrParam.getAddrId() != 0) { return ServerResponseEntity.showFailMsg("该地址已存在"); } long addrCount = userAddrService.count(new LambdaQueryWrapper<UserAddr>().eq(UserAddr::getUserId, userId)); UserAddr userAddr = BeanUtil.copyProperties(addrParam, UserAddr.class); if (addrCount == 0) { userAddr.setCommonAddr(1); } else { userAddr.setCommonAddr(0); } userAddr.setUserId(userId); userAddr.setStatus(1); userAddr.setCreateTime(new Date()); userAddr.setUpdateTime(new Date()); userAddrService.save(userAddr); if (userAddr.getCommonAddr() == 1) { // 清除默认地址缓存 userAddrService.removeUserAddrByUserId(0L, userId); } return ServerResponseEntity.success("添加地址成功"); } /** * 修改订单配送地址 */ @PutMapping("/updateAddr") @Operation(summary = "修改订单用户地址" , description = "修改用户地址") public ServerResponseEntity<String> updateAddr(@Valid @RequestBody AddrParam addrParam) { String userId = SecurityUtils.getUser().getUserId(); UserAddr dbUserAddr = userAddrService.getUserAddrByUserId(addrParam.getAddrId(), userId); if (dbUserAddr == null) { return ServerResponseEntity.showFailMsg("该地址已被删除"); } UserAddr userAddr = BeanUtil.copyProperties(addrParam, UserAddr.class); userAddr.setUserId(userId); userAddr.setUpdateTime(new Date()); userAddrService.updateById(userAddr); // 清除当前地址缓存 userAddrService.removeUserAddrByUserId(addrParam.getAddrId(), userId); // 清除默认地址缓存 userAddrService.removeUserAddrByUserId(0L, userId); return ServerResponseEntity.success("修改地址成功"); } /** * 删除订单配送地址 */ @DeleteMapping("/deleteAddr/{addrId}") @Operation(summary = "删除订单用户地址" , description = "根据地址id,删除用户地址") @Parameter(name = "addrId", description = "地址ID" , required = true) public ServerResponseEntity<String> deleteDvy(@PathVariable("addrId") Long addrId) { String userId = SecurityUtils.getUser().getUserId(); UserAddr userAddr = userAddrService.getUserAddrByUserId(addrId, userId); if (userAddr == null) { return ServerResponseEntity.showFailMsg("该地址已被删除"); } if (userAddr.getCommonAddr() == 1) { return ServerResponseEntity.showFailMsg("默认地址无法删除"); } userAddrService.removeById(addrId); userAddrService.removeUserAddrByUserId(addrId, userId); return ServerResponseEntity.success("删除地址成功"); } /** * 设置默认地址 */ @PutMapping("/defaultAddr/{addrId}") @Operation(summary = "设置默认地址" , description = "根据地址id,设置默认地址") public ServerResponseEntity<String> defaultAddr(@PathVariable("addrId") Long addrId) { String userId = SecurityUtils.getUser().getUserId(); userAddrService.updateDefaultUserAddr(addrId, userId); userAddrService.removeUserAddrByUserId(0L, userId); userAddrService.removeUserAddrByUserId(addrId, userId); return ServerResponseEntity.success("修改地址成功"); } /** * 获取地址信息订单配送地址 */ @GetMapping("/addrInfo/{addrId}") @Operation(summary = "获取地址信息" , description = "根据地址id,获取地址信息") @Parameter(name = "addrId", description = "地址ID" , required = true) public ServerResponseEntity<UserAddrDto> addrInfo(@PathVariable("addrId") Long addrId) { String userId = SecurityUtils.getUser().getUserId(); UserAddr userAddr = userAddrService.getUserAddrByUserId(addrId, userId); if (userAddr == null) { throw new YamiShopBindException("该地址已被删除"); } return ServerResponseEntity.success(BeanUtil.copyProperties(userAddr, UserAddrDto.class)); } }
String userId = SecurityUtils.getUser().getUserId(); List<UserAddr> userAddrs = userAddrService.list(new LambdaQueryWrapper<UserAddr>().eq(UserAddr::getUserId, userId).orderByDesc(UserAddr::getCommonAddr).orderByDesc(UserAddr::getUpdateTime)); return ServerResponseEntity.success(BeanUtil.copyToList(userAddrs, UserAddrDto.class));
1,360
107
1,467
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/CategoryController.java
CategoryController
categoryInfo
class CategoryController { @Autowired private CategoryService categoryService; /** * 分类信息列表接口 */ @GetMapping("/categoryInfo") @Operation(summary = "分类信息列表" , description = "获取所有的产品分类信息,顶级分类的parentId为0,默认为顶级分类") @Parameter(name = "parentId", description = "分类ID", required = false) public ServerResponseEntity<List<CategoryDto>> categoryInfo(@RequestParam(value = "parentId", defaultValue = "0") Long parentId) {<FILL_FUNCTION_BODY>} }
List<Category> categories = categoryService.listByParentId(parentId); List<CategoryDto> categoryDtos = BeanUtil.copyToList(categories, CategoryDto.class); return ServerResponseEntity.success(categoryDtos);
158
66
224
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/DeliveryController.java
DeliveryController
checkDelivery
class DeliveryController { @Autowired private DeliveryService deliveryService; @Autowired private OrderService orderService; /** * 查看物流接口 */ @GetMapping("/check") @Operation(summary = "查看物流" , description = "根据订单号查看物流") @Parameter(name = "orderNumber", description = "订单号" , required = true) public ServerResponseEntity<DeliveryDto> checkDelivery(String orderNumber) {<FILL_FUNCTION_BODY>} }
Order order = orderService.getOrderByOrderNumber(orderNumber); Delivery delivery = deliveryService.getById(order.getDvyId()); String url = delivery.getQueryUrl().replace("{dvyFlowId}", order.getDvyFlowId()); String deliveryJson = HttpUtil.get(url); DeliveryDto deliveryDto = Json.parseObject(deliveryJson, DeliveryDto.class); deliveryDto.setDvyFlowId(order.getDvyFlowId()); deliveryDto.setCompanyHomeUrl(delivery.getCompanyHomeUrl()); deliveryDto.setCompanyName(delivery.getDvyName()); return ServerResponseEntity.success(deliveryDto);
135
188
323
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/IndexImgController.java
IndexImgController
indexImgs
class IndexImgController { @Autowired private IndexImgService indexImgService; /** * 首页轮播图接口 */ @GetMapping("/indexImgs") @Operation(summary = "首页轮播图" , description = "获取首页轮播图列表信息") public ServerResponseEntity<List<IndexImgDto>> indexImgs() {<FILL_FUNCTION_BODY>} }
List<IndexImg> indexImgList = indexImgService.listIndexImg(); List<IndexImgDto> indexImgDtos = BeanUtil.copyToList(indexImgList, IndexImgDto.class); return ServerResponseEntity.success(indexImgDtos);
116
80
196
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/NoticeController.java
NoticeController
getTopNoticeList
class NoticeController { private NoticeService noticeService; /** * 置顶公告列表接口 */ @GetMapping("/topNoticeList") @Operation(summary = "置顶公告列表信息" , description = "获取所有置顶公告列表信息") public ServerResponseEntity<List<NoticeDto>> getTopNoticeList() {<FILL_FUNCTION_BODY>} /** * 获取公告详情 */ @GetMapping("/info/{id}") @Operation(summary = "公告详情" , description = "获取公告id公告详情") public ServerResponseEntity<NoticeDto> getNoticeById(@PathVariable("id") Long id) { Notice notice = noticeService.getNoticeById(id); NoticeDto noticeDto = BeanUtil.copyProperties(notice, NoticeDto.class); return ServerResponseEntity.success(noticeDto); } /** * 公告列表 */ @GetMapping("/noticeList") @Operation(summary = "公告列表信息" , description = "获取所有公告列表信息") @Parameters({ }) public ServerResponseEntity<IPage<NoticeDto>> pageNotice(PageParam<NoticeDto> page) { return ServerResponseEntity.success(noticeService.pageNotice(page)); } }
List<Notice> noticeList = noticeService.listNotice(); List<NoticeDto> noticeDtoList = BeanUtil.copyToList(noticeList, NoticeDto.class); return ServerResponseEntity.success(noticeDtoList);
340
64
404
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/OrderController.java
OrderController
submitOrders
class OrderController { @Autowired private OrderService orderService; @Autowired private SkuService skuService; @Autowired private ProductService productService; @Autowired private UserAddrService userAddrService; @Autowired private BasketService basketService; @Autowired private ApplicationContext applicationContext; /** * 生成订单 */ @PostMapping("/confirm") @Operation(summary = "结算,生成订单信息" , description = "传入下单所需要的参数进行下单") public ServerResponseEntity<ShopCartOrderMergerDto> confirm(@Valid @RequestBody OrderParam orderParam) { String userId = SecurityUtils.getUser().getUserId(); // 订单的地址信息 UserAddr userAddr = userAddrService.getUserAddrByUserId(orderParam.getAddrId(), userId); UserAddrDto userAddrDto = BeanUtil.copyProperties(userAddr, UserAddrDto.class); // 组装获取用户提交的购物车商品项 List<ShopCartItemDto> shopCartItems = basketService.getShopCartItemsByOrderItems(orderParam.getBasketIds(),orderParam.getOrderItem(),userId); if (CollectionUtil.isEmpty(shopCartItems)) { throw new YamiShopBindException("请选择您需要的商品加入购物车"); } // 根据店铺组装购车中的商品信息,返回每个店铺中的购物车商品信息 List<ShopCartDto> shopCarts = basketService.getShopCarts(shopCartItems); // 将要返回给前端的完整的订单信息 ShopCartOrderMergerDto shopCartOrderMergerDto = new ShopCartOrderMergerDto(); shopCartOrderMergerDto.setUserAddr(userAddrDto); // 所有店铺的订单信息 List<ShopCartOrderDto> shopCartOrders = new ArrayList<>(); double actualTotal = 0.0; double total = 0.0; int totalCount = 0; double orderReduce = 0.0; for (ShopCartDto shopCart : shopCarts) { // 每个店铺的订单信息 ShopCartOrderDto shopCartOrder = new ShopCartOrderDto(); shopCartOrder.setShopId(shopCart.getShopId()); shopCartOrder.setShopName(shopCart.getShopName()); List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCart.getShopCartItemDiscounts(); // 店铺中的所有商品项信息 List<ShopCartItemDto> shopAllShopCartItems = new ArrayList<>(); for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartItemDiscounts) { List<ShopCartItemDto> discountShopCartItems = shopCartItemDiscount.getShopCartItems(); shopAllShopCartItems.addAll(discountShopCartItems); } shopCartOrder.setShopCartItemDiscounts(shopCartItemDiscounts); applicationContext.publishEvent(new ConfirmOrderEvent(shopCartOrder,orderParam,shopAllShopCartItems)); actualTotal = Arith.add(actualTotal,shopCartOrder.getActualTotal()); total = Arith.add(total,shopCartOrder.getTotal()); totalCount = totalCount + shopCartOrder.getTotalCount(); orderReduce = Arith.add(orderReduce,shopCartOrder.getShopReduce()); shopCartOrders.add(shopCartOrder); } shopCartOrderMergerDto.setActualTotal(actualTotal); shopCartOrderMergerDto.setTotal(total); shopCartOrderMergerDto.setTotalCount(totalCount); shopCartOrderMergerDto.setShopCartOrders(shopCartOrders); shopCartOrderMergerDto.setOrderReduce(orderReduce); shopCartOrderMergerDto = orderService.putConfirmOrderCache(userId, shopCartOrderMergerDto); return ServerResponseEntity.success(shopCartOrderMergerDto); } /** * 购物车/立即购买 提交订单,根据店铺拆单 */ @PostMapping("/submit") @Operation(summary = "提交订单,返回支付流水号" , description = "根据传入的参数判断是否为购物车提交订单,同时对购物车进行删除,用户开始进行支付") public ServerResponseEntity<OrderNumbersDto> submitOrders(@Valid @RequestBody SubmitOrderParam submitOrderParam) {<FILL_FUNCTION_BODY>} }
String userId = SecurityUtils.getUser().getUserId(); ShopCartOrderMergerDto mergerOrder = orderService.getConfirmOrderCache(userId); if (mergerOrder == null) { throw new YamiShopBindException("订单已过期,请重新下单"); } List<OrderShopParam> orderShopParams = submitOrderParam.getOrderShopParam(); List<ShopCartOrderDto> shopCartOrders = mergerOrder.getShopCartOrders(); // 设置备注 if (CollectionUtil.isNotEmpty(orderShopParams)) { for (ShopCartOrderDto shopCartOrder : shopCartOrders) { for (OrderShopParam orderShopParam : orderShopParams) { if (Objects.equals(shopCartOrder.getShopId(), orderShopParam.getShopId())) { shopCartOrder.setRemarks(orderShopParam.getRemarks()); } } } } List<Order> orders = orderService.submit(userId,mergerOrder); StringBuilder orderNumbers = new StringBuilder(); for (Order order : orders) { orderNumbers.append(order.getOrderNumber()).append(","); } orderNumbers.deleteCharAt(orderNumbers.length() - 1); boolean isShopCartOrder = false; // 移除缓存 for (ShopCartOrderDto shopCartOrder : shopCartOrders) { for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartOrder.getShopCartItemDiscounts()) { for (ShopCartItemDto shopCartItem : shopCartItemDiscount.getShopCartItems()) { Long basketId = shopCartItem.getBasketId(); if (basketId != null && basketId != 0) { isShopCartOrder = true; } skuService.removeSkuCacheBySkuId(shopCartItem.getSkuId(),shopCartItem.getProdId()); productService.removeProductCacheByProdId(shopCartItem.getProdId()); } } } // 购物车提交订单时(即有购物车ID时) if (isShopCartOrder) { basketService.removeShopCartItemsCacheByUserId(userId); } orderService.removeConfirmOrderCache(userId); return ServerResponseEntity.success(new OrderNumbersDto(orderNumbers.toString()));
1,197
615
1,812
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/PayController.java
PayController
normalPay
class PayController { private final PayService payService; /** * 支付接口 */ @PostMapping("/pay") @Operation(summary = "根据订单号进行支付" , description = "根据订单号进行支付") public ServerResponseEntity<Void> pay(@RequestBody PayParam payParam) { YamiUser user = SecurityUtils.getUser(); String userId = user.getUserId(); PayInfoDto payInfo = payService.pay(userId, payParam); payService.paySuccess(payInfo.getPayNo(), ""); return ServerResponseEntity.success(); } /** * 普通支付接口 */ @PostMapping("/normalPay") @Operation(summary = "根据订单号进行支付" , description = "根据订单号进行支付") public ServerResponseEntity<Boolean> normalPay(@RequestBody PayParam payParam) {<FILL_FUNCTION_BODY>} }
YamiUser user = SecurityUtils.getUser(); String userId = user.getUserId(); PayInfoDto pay = payService.pay(userId, payParam); // 根据内部订单号更新order settlement payService.paySuccess(pay.getPayNo(), ""); return ServerResponseEntity.success(true);
243
89
332
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/ProdCommController.java
ProdCommController
saveProdCommPage
class ProdCommController { private final ProdCommService prodCommService; @GetMapping("/prodCommData") @Operation(summary = "返回商品评论数据(好评率 好评数量 中评数 差评数)" , description = "根据商品id获取") public ServerResponseEntity<ProdCommDataDto> getProdCommData(Long prodId) { return ServerResponseEntity.success(prodCommService.getProdCommDataByProdId(prodId)); } @GetMapping("/prodCommPageByUser") @Operation(summary = "根据用户返回评论分页数据" , description = "传入页码") public ServerResponseEntity<IPage<ProdCommDto>> getProdCommPage(PageParam page) { return ServerResponseEntity.success(prodCommService.getProdCommDtoPageByUserId(page, SecurityUtils.getUser().getUserId())); } @GetMapping("/prodCommPageByProd") @Operation(summary = "根据商品返回评论分页数据" , description = "传入商品id和页码") @Parameters({ @Parameter(name = "prodId", description = "商品id" , required = true), @Parameter(name = "evaluate", description = "-1或null 全部,0好评 1中评 2差评 3有图" , required = true), }) public ServerResponseEntity<IPage<ProdCommDto>> getProdCommPageByProdId(PageParam page, Long prodId, Integer evaluate) { return ServerResponseEntity.success(prodCommService.getProdCommDtoPageByProdId(page, prodId, evaluate)); } @PostMapping @Operation(summary = "添加评论") public ServerResponseEntity<Void> saveProdCommPage(ProdCommParam prodCommParam) {<FILL_FUNCTION_BODY>} @DeleteMapping @Operation(summary = "删除评论" , description = "根据id删除") public ServerResponseEntity<Void> deleteProdComm(Long prodCommId) { prodCommService.removeById(prodCommId); return ServerResponseEntity.success(); } }
ProdComm prodComm = new ProdComm(); prodComm.setProdId(prodCommParam.getProdId()); prodComm.setOrderItemId(prodCommParam.getOrderItemId()); prodComm.setUserId(SecurityUtils.getUser().getUserId()); prodComm.setScore(prodCommParam.getScore()); prodComm.setContent(prodCommParam.getContent()); prodComm.setPics(prodCommParam.getPics()); prodComm.setIsAnonymous(prodCommParam.getIsAnonymous()); prodComm.setRecTime(new Date()); prodComm.setStatus(0); prodComm.setEvaluate(prodCommParam.getEvaluate()); prodCommService.save(prodComm); return ServerResponseEntity.success();
546
200
746
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/ProdController.java
ProdController
prodInfo
class ProdController { @Autowired private ProductService prodService; @Autowired private SkuService skuService; @Autowired private TransportService transportService; @GetMapping("/pageProd") @Operation(summary = "通过分类id商品列表信息" , description = "根据分类ID获取该分类下所有的商品列表信息") @Parameters({ @Parameter(name = "categoryId", description = "分类ID" , required = true), }) public ServerResponseEntity<IPage<ProductDto>> prodList( @RequestParam(value = "categoryId") Long categoryId,PageParam<ProductDto> page) { IPage<ProductDto> productPage = prodService.pageByCategoryId(page, categoryId); return ServerResponseEntity.success(productPage); } @GetMapping("/prodInfo") @Operation(summary = "商品详情信息" , description = "根据商品ID(prodId)获取商品信息") @Parameter(name = "prodId", description = "商品ID" , required = true) public ServerResponseEntity<ProductDto> prodInfo(Long prodId) {<FILL_FUNCTION_BODY>} @GetMapping("/lastedProdPage") @Operation(summary = "新品推荐" , description = "获取新品推荐商品列表") @Parameters({ }) public ServerResponseEntity<IPage<ProductDto>> lastedProdPage(PageParam<ProductDto> page) { IPage<ProductDto> productPage = prodService.pageByPutAwayTime(page); return ServerResponseEntity.success(productPage); } @GetMapping("/prodListByTagId") @Operation(summary = "通过分组标签获取商品列表" , description = "通过分组标签id(tagId)获取商品列表") @Parameters({ @Parameter(name = "tagId", description = "当前页,默认为1" , required = true), }) public ServerResponseEntity<IPage<ProductDto>> prodListByTagId( @RequestParam(value = "tagId") Long tagId,PageParam<ProductDto> page) { IPage<ProductDto> productPage = prodService.pageByTagId(page, tagId); return ServerResponseEntity.success(productPage); } @GetMapping("/moreBuyProdList") @Operation(summary = "每日疯抢" , description = "获取销量最多的商品列表") @Parameters({}) public ServerResponseEntity<IPage<ProductDto>> moreBuyProdList(PageParam<ProductDto> page) { IPage<ProductDto> productPage = prodService.moreBuyProdList(page); return ServerResponseEntity.success(productPage); } @GetMapping("/tagProdList") @Operation(summary = "首页所有标签商品接口" , description = "获取首页所有标签商品接口") public ServerResponseEntity<List<TagProductDto>> getTagProdList() { List<TagProductDto> productDtoList = prodService.tagProdList(); return ServerResponseEntity.success(productDtoList); } }
Product product = prodService.getProductByProdId(prodId); if (product == null) { return ServerResponseEntity.success(); } List<Sku> skuList = skuService.listByProdId(prodId); // 启用的sku列表 List<Sku> useSkuList = skuList.stream().filter(sku -> sku.getStatus() == 1).collect(Collectors.toList()); product.setSkuList(useSkuList); ProductDto productDto = BeanUtil.copyProperties(product, ProductDto.class); // 商品的配送方式 Product.DeliveryModeVO deliveryModeVO = Json.parseObject(product.getDeliveryMode(), Product.DeliveryModeVO.class); // 有店铺配送的方式, 且存在运费模板,才返回运费模板的信息,供前端查阅 if (deliveryModeVO.getHasShopDelivery() && product.getDeliveryTemplateId() != null) { Transport transportAndAllItems = transportService.getTransportAndAllItems(product.getDeliveryTemplateId()); productDto.setTransport(transportAndAllItems); } return ServerResponseEntity.success(productDto);
806
321
1,127
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/ProdTagController.java
ProdTagController
getProdTagList
class ProdTagController { private ProdTagService prodTagService; /** * 商品分组标签列表接口 */ @GetMapping("/prodTagList") @Operation(summary = "商品分组标签列表" , description = "获取所有的商品分组列表") public ServerResponseEntity<List<ProdTagDto>> getProdTagList() {<FILL_FUNCTION_BODY>} }
List<ProdTag> prodTagList = prodTagService.listProdTag(); List<ProdTagDto> prodTagDtoList = BeanUtil.copyToList(prodTagList, ProdTagDto.class); return ServerResponseEntity.success(prodTagDtoList);
117
75
192
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/SearchController.java
SearchController
getListResponseEntity
class SearchController { private final HotSearchService hotSearchService; private final ProductService productService; @GetMapping("/hotSearchByShopId") @Operation(summary = "查看店铺热搜" , description = "根据店铺id,热搜数量获取热搜") @Parameters({ @Parameter(name = "shopId", description = "店铺id" , required = true), @Parameter(name = "number", description = "取数" , required = true), @Parameter(name = "sort", description = "是否按照顺序(0 否 1是)"), }) public ServerResponseEntity<List<HotSearchDto>> hotSearchByShopId(Long shopId,Integer number,Integer sort) { List<HotSearchDto> list = hotSearchService.getHotSearchDtoByShopId(shopId); return getListResponseEntity(number, sort, list); } @GetMapping("/hotSearch") @Operation(summary = "查看全局热搜" , description = "根据店铺id,热搜数量获取热搜") @Parameters({ @Parameter(name = "number", description = "取数" , required = true), @Parameter(name = "sort", description = "是否按照顺序(0 否 1是)", required = false ), }) public ServerResponseEntity<List<HotSearchDto>> hotSearch(Integer number,Integer sort) { List<HotSearchDto> list = hotSearchService.getHotSearchDtoByShopId(0L); return getListResponseEntity(number, sort, list); } private ServerResponseEntity<List<HotSearchDto>> getListResponseEntity(Integer number, Integer sort, List<HotSearchDto> list) {<FILL_FUNCTION_BODY>} @GetMapping("/searchProdPage") @Operation(summary = "分页排序搜索商品" , description = "根据商品名搜索") @Parameters({ @Parameter(name = "prodName", description = "商品名" , required = true), @Parameter(name = "sort", description = "排序(0 默认排序 1销量排序 2价格排序)"), @Parameter(name = "orderBy", description = "排序(0升序 1降序)"), @Parameter(name = "shopId", description = "店铺id" , required = true), }) public ServerResponseEntity<IPage<SearchProdDto>> searchProdPage(PageParam page, String prodName, Integer sort, Integer orderBy, Long shopId) { return ServerResponseEntity.success(productService.getSearchProdDtoPageByProdName(page,prodName,sort,orderBy)); } }
if(sort == null || sort == 0){ Collections.shuffle(list); } if(!CollectionUtil.isNotEmpty(list) || list.size()< number){ return ServerResponseEntity.success(list); } return ServerResponseEntity.success(list.subList(0, number));
672
81
753
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/SkuController.java
SkuController
getSkuListByProdId
class SkuController { private final SkuService skuService; @GetMapping("/getSkuList") @Operation(summary = "通过prodId获取商品全部规格列表" , description = "通过prodId获取商品全部规格列表") @Parameter(name = "prodId", description = "商品id" ) public ServerResponseEntity<List<SkuDto>> getSkuListByProdId(Long prodId) {<FILL_FUNCTION_BODY>} }
List<Sku> skus = skuService.list(new LambdaQueryWrapper<Sku>() .eq(Sku::getStatus, 1) .eq(Sku::getIsDelete, 0) .eq(Sku::getProdId, prodId) ); List<SkuDto> skuDtoList = BeanUtil.copyToList(skus, SkuDto.class); return ServerResponseEntity.success(skuDtoList);
127
125
252
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/SmsController.java
SmsController
audit
class SmsController { @Autowired private SmsLogService smsLogService; /** * 发送验证码接口 */ @PostMapping("/send") @Operation(summary = "发送验证码" , description = "用户的发送验证码") public ServerResponseEntity<Void> audit(@RequestBody SendSmsParam sendSmsParam) {<FILL_FUNCTION_BODY>} }
String userId = SecurityUtils.getUser().getUserId(); smsLogService.sendSms(SmsType.VALID, userId, sendSmsParam.getMobile(),Maps.newHashMap()); return ServerResponseEntity.success();
111
65
176
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/UserCollectionController.java
UserCollectionController
addOrCancel
class UserCollectionController { private final UserCollectionService userCollectionService; private final ProductService productService; @GetMapping("/page") @Operation(summary = "分页返回收藏数据" , description = "根据用户id获取") public ServerResponseEntity<IPage<UserCollectionDto>> getUserCollectionDtoPageByUserId(PageParam page) { return ServerResponseEntity.success(userCollectionService.getUserCollectionDtoPageByUserId(page, SecurityUtils.getUser().getUserId())); } @GetMapping("isCollection") @Operation(summary = "根据商品id获取该商品是否在收藏夹中" , description = "传入收藏商品id") public ServerResponseEntity<Boolean> isCollection(Long prodId) { if (productService.count(new LambdaQueryWrapper<Product>() .eq(Product::getProdId, prodId)) < 1) { throw new YamiShopBindException("该商品不存在"); } return ServerResponseEntity.success(userCollectionService.count(new LambdaQueryWrapper<UserCollection>() .eq(UserCollection::getProdId, prodId) .eq(UserCollection::getUserId, SecurityUtils.getUser().getUserId())) > 0); } @PostMapping("/addOrCancel") @Operation(summary = "添加/取消收藏" , description = "传入收藏商品id,如果商品未收藏则收藏商品,已收藏则取消收藏") @Parameter(name = "prodId", description = "商品id" , required = true) public ServerResponseEntity<Void> addOrCancel(@RequestBody Long prodId) {<FILL_FUNCTION_BODY>} /** * 查询用户收藏商品数量 */ @GetMapping("count") @Operation(summary = "查询用户收藏商品数量" , description = "查询用户收藏商品数量") public ServerResponseEntity<Long> findUserCollectionCount() { String userId = SecurityUtils.getUser().getUserId(); return ServerResponseEntity.success(userCollectionService.count(new LambdaQueryWrapper<UserCollection>().eq(UserCollection::getUserId, userId))); } @GetMapping("/prods") @Operation(summary = "获取用户收藏商品列表" , description = "获取用户收藏商品列表") public ServerResponseEntity<IPage<ProductDto>> collectionProds(PageParam page) { String userId = SecurityUtils.getUser().getUserId(); IPage<ProductDto> productDtoPage = productService.collectionProds(page, userId); return ServerResponseEntity.success(productDtoPage); } }
if (Objects.isNull(productService.getProductByProdId(prodId))) { throw new YamiShopBindException("该商品不存在"); } String userId = SecurityUtils.getUser().getUserId(); if (userCollectionService.count(new LambdaQueryWrapper<UserCollection>() .eq(UserCollection::getProdId, prodId) .eq(UserCollection::getUserId, userId)) > 0) { userCollectionService.remove(new LambdaQueryWrapper<UserCollection>() .eq(UserCollection::getProdId, prodId) .eq(UserCollection::getUserId, userId)); } else { UserCollection userCollection = new UserCollection(); userCollection.setCreateTime(new Date()); userCollection.setUserId(userId); userCollection.setProdId(prodId); userCollectionService.save(userCollection); } return ServerResponseEntity.success();
656
240
896
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/UserController.java
UserController
userInfo
class UserController { private final UserService userService; /** * 查看用户接口 */ @GetMapping("/userInfo") @Operation(summary = "查看用户信息" , description = "根据用户ID(userId)获取用户信息") public ServerResponseEntity<UserDto> userInfo() {<FILL_FUNCTION_BODY>} @PutMapping("/setUserInfo") @Operation(summary = "设置用户信息" , description = "设置用户信息") public ServerResponseEntity<Void> setUserInfo(@RequestBody UserInfoParam userInfoParam) { String userId = SecurityUtils.getUser().getUserId(); User user = new User(); user.setUserId(userId); user.setPic(userInfoParam.getAvatarUrl()); user.setNickName(userInfoParam.getNickName()); userService.updateById(user); return ServerResponseEntity.success(); } }
String userId = SecurityUtils.getUser().getUserId(); User user = userService.getById(userId); UserDto userDto = BeanUtil.copyProperties(user, UserDto.class); return ServerResponseEntity.success(userDto);
242
72
314
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/controller/UserRegisterController.java
UserRegisterController
updatePwd
class UserRegisterController { private final UserService userService; private final PasswordEncoder passwordEncoder; private final TokenStore tokenStore; private final PasswordManager passwordManager; @PostMapping("/register") @Operation(summary = "注册" , description = "用户注册或绑定手机号接口") public ServerResponseEntity<TokenInfoVO> register(@Valid @RequestBody UserRegisterParam userRegisterParam) { if (StrUtil.isBlank(userRegisterParam.getNickName())) { userRegisterParam.setNickName(userRegisterParam.getUserName()); } // 正在进行申请注册 if (userService.count(new LambdaQueryWrapper<User>().eq(User::getNickName, userRegisterParam.getNickName())) > 0) { // 该用户名已注册,无法重新注册 throw new YamiShopBindException("该用户名已注册,无法重新注册"); } Date now = new Date(); User user = new User(); user.setModifyTime(now); user.setUserRegtime(now); user.setStatus(1); user.setNickName(userRegisterParam.getNickName()); user.setUserMail(userRegisterParam.getUserMail()); String decryptPassword = passwordManager.decryptPassword(userRegisterParam.getPassWord()); user.setLoginPassword(passwordEncoder.encode(decryptPassword)); String userId = IdUtil.simpleUUID(); user.setUserId(userId); userService.save(user); // 2. 登录 UserInfoInTokenBO userInfoInTokenBO = new UserInfoInTokenBO(); userInfoInTokenBO.setUserId(user.getUserId()); userInfoInTokenBO.setSysType(SysTypeEnum.ORDINARY.value()); userInfoInTokenBO.setIsAdmin(0); userInfoInTokenBO.setEnabled(true); return ServerResponseEntity.success(tokenStore.storeAndGetVo(userInfoInTokenBO)); } @PutMapping("/updatePwd") @Operation(summary = "修改密码" , description = "修改密码") public ServerResponseEntity<Void> updatePwd(@Valid @RequestBody UserRegisterParam userPwdUpdateParam) {<FILL_FUNCTION_BODY>} }
User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getNickName, userPwdUpdateParam.getNickName())); if (user == null) { // 无法获取用户信息 throw new YamiShopBindException("无法获取用户信息"); } String decryptPassword = passwordManager.decryptPassword(userPwdUpdateParam.getPassWord()); if (StrUtil.isBlank(decryptPassword)) { // 新密码不能为空 throw new YamiShopBindException("新密码不能为空"); } String password = passwordEncoder.encode(decryptPassword); if (StrUtil.equals(password, user.getLoginPassword())) { // 新密码不能与原密码相同 throw new YamiShopBindException("新密码不能与原密码相同"); } user.setModifyTime(new Date()); user.setLoginPassword(password); userService.updateById(user); return ServerResponseEntity.success();
591
258
849
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/listener/ConfirmOrderListener.java
ConfirmOrderListener
defaultConfirmOrderEvent
class ConfirmOrderListener { private final UserAddrService userAddrService; private final TransportManagerService transportManagerService; private final ProductService productService; private final SkuService skuService; /** * 计算订单金额 */ @EventListener(ConfirmOrderEvent.class) @Order(ConfirmOrderOrder.DEFAULT) public void defaultConfirmOrderEvent(ConfirmOrderEvent event) {<FILL_FUNCTION_BODY>} }
ShopCartOrderDto shopCartOrderDto = event.getShopCartOrderDto(); OrderParam orderParam = event.getOrderParam(); String userId = SecurityUtils.getUser().getUserId(); // 订单的地址信息 UserAddr userAddr = userAddrService.getUserAddrByUserId(orderParam.getAddrId(), userId); double total = 0.0; int totalCount = 0; double transfee = 0.0; for (ShopCartItemDto shopCartItem : event.getShopCartItems()) { // 获取商品信息 Product product = productService.getProductByProdId(shopCartItem.getProdId()); // 获取sku信息 Sku sku = skuService.getSkuBySkuId(shopCartItem.getSkuId()); if (product == null || sku == null) { throw new YamiShopBindException("购物车包含无法识别的商品"); } if (product.getStatus() != 1 || sku.getStatus() != 1) { throw new YamiShopBindException("商品[" + sku.getProdName() + "]已下架"); } totalCount = shopCartItem.getProdCount() + totalCount; total = Arith.add(shopCartItem.getProductTotalAmount(), total); // 用户地址如果为空,则表示该用户从未设置过任何地址相关信息 if (userAddr != null) { // 每个产品的运费相加 transfee = Arith.add(transfee, transportManagerService.calculateTransfee(shopCartItem, userAddr)); } shopCartItem.setActualTotal(shopCartItem.getProductTotalAmount()); shopCartOrderDto.setActualTotal(Arith.add(total, transfee)); shopCartOrderDto.setTotal(total); shopCartOrderDto.setTotalCount(totalCount); shopCartOrderDto.setTransfee(transfee); }
123
511
634
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-api/src/main/java/com/yami/shop/api/listener/ShopCartListener.java
ShopCartListener
defaultShopCartEvent
class ShopCartListener { /** * 将店铺下的所有商品归属到该店铺的购物车当中 * @param event#getShopCart() 购物车 * @param event#shopCartItemDtoList 该购物车的商品 * @return 是否继续组装 */ @EventListener(ShopCartEvent.class) @Order(ShopCartEventOrder.DEFAULT) public void defaultShopCartEvent(ShopCartEvent event) {<FILL_FUNCTION_BODY>} }
ShopCartDto shopCart = event.getShopCartDto(); List<ShopCartItemDto> shopCartItemDtoList = event.getShopCartItemDtoList(); // 对数据进行组装 List<ShopCartItemDiscountDto> shopCartItemDiscountDtoList = Lists.newArrayList(); ShopCartItemDiscountDto shopCartItemDiscountDto = new ShopCartItemDiscountDto(); shopCartItemDiscountDto.setShopCartItems(shopCartItemDtoList); shopCartItemDiscountDtoList.add(shopCartItemDiscountDto); shopCart.setShopCartItemDiscounts(shopCartItemDiscountDtoList);
128
176
304
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-bean/src/main/java/com/yami/shop/bean/SmsInfoContext.java
SmsInfoContext
put
class SmsInfoContext { /** The request holder. */ private static ThreadLocal<List<SmsInfoBo>> smsInfoHolder = new ThreadLocal<List<SmsInfoBo>>(); public static List<SmsInfoBo> get(){ List<SmsInfoBo> list = smsInfoHolder.get(); if (CollectionUtil.isEmpty(list)) { return new ArrayList<>(); } return smsInfoHolder.get(); } public static void set(List<SmsInfoBo> smsInfoBos){ smsInfoHolder.set(smsInfoBos); } public static void put(SmsInfoBo smsInfoBo){<FILL_FUNCTION_BODY>} public static void clean() { if (smsInfoHolder.get() != null) { smsInfoHolder.remove(); } } }
List<SmsInfoBo> smsInfoBos = smsInfoHolder.get(); if (CollectionUtil.isEmpty(smsInfoBos)) { smsInfoBos = new ArrayList<>(); } smsInfoBos.add(smsInfoBo); smsInfoHolder.set(smsInfoBos);
220
87
307
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/aspect/RedisLockAspect.java
RedisLockAspect
around
class RedisLockAspect { @Autowired private RedissonClient redissonClient; private static final String REDISSON_LOCK_PREFIX = "redisson_lock:"; @Around("@annotation(redisLock)") public Object around(ProceedingJoinPoint joinPoint, RedisLock redisLock) throws Throwable {<FILL_FUNCTION_BODY>} /** * 将spel表达式转换为字符串 * @param joinPoint 切点 * @return redisKey */ private String getRedisKey(ProceedingJoinPoint joinPoint,String lockName,String spel) { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method targetMethod = methodSignature.getMethod(); Object target = joinPoint.getTarget(); Object[] arguments = joinPoint.getArgs(); return REDISSON_LOCK_PREFIX + lockName + StrUtil.COLON + SpelUtil.parse(target,spel, targetMethod, arguments); } }
String spel = redisLock.key(); String lockName = redisLock.lockName(); RLock rLock = redissonClient.getLock(getRedisKey(joinPoint,lockName,spel)); rLock.lock(redisLock.expire(),redisLock.timeUnit()); Object result = null; try { //执行方法 result = joinPoint.proceed(); } finally { rLock.unlock(); } return result;
269
133
402
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/config/DefaultExceptionHandlerConfig.java
DefaultExceptionHandlerConfig
unauthorizedExceptionHandler
class DefaultExceptionHandlerConfig { @ExceptionHandler({ MethodArgumentNotValidException.class, BindException.class }) public ResponseEntity<ServerResponseEntity<List<String>>> methodArgumentNotValidExceptionHandler(Exception e) { log.error("methodArgumentNotValidExceptionHandler", e); List<FieldError> fieldErrors = null; if (e instanceof MethodArgumentNotValidException) { fieldErrors = ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors(); } if (e instanceof BindException) { fieldErrors = ((BindException) e).getBindingResult().getFieldErrors(); } if (fieldErrors == null) { return ResponseEntity.status(HttpStatus.OK) .body(ServerResponseEntity.fail(ResponseEnum.METHOD_ARGUMENT_NOT_VALID)); } List<String> defaultMessages = new ArrayList<>(fieldErrors.size()); for (FieldError fieldError : fieldErrors) { defaultMessages.add(fieldError.getField() + ":" + fieldError.getDefaultMessage()); } return ResponseEntity.status(HttpStatus.OK) .body(ServerResponseEntity.fail(ResponseEnum.METHOD_ARGUMENT_NOT_VALID, defaultMessages)); } @ExceptionHandler(YamiShopBindException.class) public ResponseEntity<ServerResponseEntity<?>> unauthorizedExceptionHandler(YamiShopBindException e){<FILL_FUNCTION_BODY>} @ExceptionHandler(Exception.class) public ResponseEntity<ServerResponseEntity<Object>> exceptionHandler(Exception e){ if (e instanceof NoResourceFoundException) { return ResponseEntity.status(HttpStatus.OK).body(ServerResponseEntity.showFailMsg(e.getMessage())); } log.error("exceptionHandler", e); return ResponseEntity.status(HttpStatus.OK).body(ServerResponseEntity.fail(ResponseEnum.EXCEPTION)); } }
log.error("mall4jExceptionHandler", e); ServerResponseEntity<?> serverResponseEntity = e.getServerResponseEntity(); if (serverResponseEntity!=null) { return ResponseEntity.status(HttpStatus.OK).body(serverResponseEntity); } // 失败返回消息 状态码固定为直接显示消息的状态码 return ResponseEntity.status(HttpStatus.OK).body(ServerResponseEntity.fail(e.getCode(),e.getMessage()));
471
121
592
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/config/FileUploadConfig.java
FileUploadConfig
qiniuConfig
class FileUploadConfig { @Autowired private Qiniu qiniu; /** * 根据配置文件选择机房 */ @Bean public com.qiniu.storage.Configuration qiniuConfig() {<FILL_FUNCTION_BODY>} /** * 构建一个七牛上传工具实例 */ @Bean public UploadManager uploadManager() { return new UploadManager(qiniuConfig()); } /** * 认证信息实例 * @return */ @Bean public Auth auth() { return Auth.create(qiniu.getAccessKey(), qiniu.getSecretKey()); } /** * 构建七牛空间管理实例 */ @Bean public BucketManager bucketManager() { return new BucketManager(auth(), qiniuConfig()); } }
Zone zone = null; if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_BEI)) { zone = Zone.huabei(); } else if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_DONG)) { zone = Zone.huadong(); } else if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_NAN)) { zone = Zone.huanan(); } else if (Objects.equals(qiniu.getZone(), QiniuZone.BEI_MEI)) { zone = Zone.beimei(); } else if (Objects.equals(qiniu.getZone(), QiniuZone.XIN_JIA_PO)) { zone = Zone.xinjiapo(); } return new com.qiniu.storage.Configuration(zone);
232
226
458
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/config/MybatisPlusConfig.java
MybatisPlusConfig
optimisticLockerInterceptor
class MybatisPlusConfig { /** * 逻辑删除插件 * @return LogicSqlInjector */ @Bean @ConditionalOnMissingBean public ISqlInjector sqlInjector() { return new DefaultSqlInjector(); } /** * mybatis-plus插件 */ @Bean public MybatisPlusInterceptor optimisticLockerInterceptor() {<FILL_FUNCTION_BODY>} }
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return mybatisPlusInterceptor;
128
97
225
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/config/RedisCacheConfig.java
RedisCacheConfig
redisSerializer
class RedisCacheConfig { @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory, RedisSerializer<Object> redisSerializer) { RedisCacheManager redisCacheManager = new RedisCacheManager( RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), // 默认策略,未配置的 key 会使用这个 this.getRedisCacheConfigurationWithTtl(3600,redisSerializer), // 指定 key 策略 this.getRedisCacheConfigurationMap(redisSerializer) ); redisCacheManager.setTransactionAware(true); return redisCacheManager; } private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap(RedisSerializer<Object> redisSerializer) { Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>(16); redisCacheConfigurationMap.put("product", this.getRedisCacheConfigurationWithTtl(1800, redisSerializer)); return redisCacheConfigurationMap; } private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds,RedisSerializer<Object> redisSerializer) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith( RedisSerializationContext .SerializationPair .fromSerializer(redisSerializer) ).entryTtl(Duration.ofSeconds(seconds)); return redisCacheConfiguration; } @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory,RedisSerializer<Object> redisSerializer) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(redisSerializer); redisTemplate.setHashValueSerializer(redisSerializer); redisTemplate.setEnableTransactionSupport(false); redisTemplate.afterPropertiesSet(); return redisTemplate; } /** * 自定义redis序列化的机制,重新定义一个ObjectMapper.防止和MVC的冲突 * https://juejin.im/post/5e869d426fb9a03c6148c97e */ @Bean public RedisSerializer<Object> redisSerializer() {<FILL_FUNCTION_BODY>} @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory){ StringRedisTemplate redisTemplate = new StringRedisTemplate(redisConnectionFactory); redisTemplate.setEnableTransactionSupport(false); return redisTemplate; } }
ObjectMapper objectMapper = JsonMapper.builder().disable(MapperFeature.USE_ANNOTATIONS).build(); // 反序列化时候遇到不匹配的属性并不抛出异常 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 序列化时候遇到空对象不抛出异常 objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); // 反序列化的时候如果是无效子类型,不抛出异常 objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false); // 不使用默认的dateTime进行序列化, objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false); // 使用JSR310提供的序列化类,里面包含了大量的JDK8时间序列化类 objectMapper.registerModule(new JavaTimeModule()); // 启用反序列化所需的类型信息,在属性中添加@class objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); // 配置null值的序列化器 GenericJackson2JsonRedisSerializer.registerNullValueSerializer(objectMapper, null); return new GenericJackson2JsonRedisSerializer(objectMapper);
737
369
1,106
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/filter/XssFilter.java
XssFilter
doFilter
class XssFilter implements Filter { Logger logger = LoggerFactory.getLogger(getClass().getName()); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{<FILL_FUNCTION_BODY>} @Override public void destroy() { } }
HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; logger.info("uri:{}",req.getRequestURI()); // xss 过滤 chain.doFilter(new XssWrapper(req), resp);
113
74
187
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/handler/HttpHandler.java
HttpHandler
printServerResponseToWeb
class HttpHandler { private static final Logger logger = LoggerFactory.getLogger(HttpHandler.class); @Autowired private ObjectMapper objectMapper; public <T> void printServerResponseToWeb(ServerResponseEntity<T> serverResponseEntity) { if (serverResponseEntity == null) { logger.info("print obj is null"); return; } ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); if (requestAttributes == null) { logger.error("requestAttributes is null, can not print to web"); return; } HttpServletResponse response = requestAttributes.getResponse(); if (response == null) { logger.error("httpServletResponse is null, can not print to web"); return; } logger.error("response error: " + serverResponseEntity.getMsg()); response.setCharacterEncoding(CharsetUtil.UTF_8); response.setContentType(MediaType.APPLICATION_JSON_VALUE); PrintWriter printWriter = null; try { printWriter = response.getWriter(); printWriter.write(objectMapper.writeValueAsString(serverResponseEntity)); } catch (IOException e) { throw new YamiShopBindException("io 异常", e); } } public <T> void printServerResponseToWeb(YamiShopBindException yamiShopBindException) {<FILL_FUNCTION_BODY>} }
if (yamiShopBindException == null) { logger.info("print obj is null"); return; } if (Objects.nonNull(yamiShopBindException.getServerResponseEntity())) { printServerResponseToWeb(yamiShopBindException.getServerResponseEntity()); return; } ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>(); serverResponseEntity.setCode(yamiShopBindException.getCode()); serverResponseEntity.setMsg(yamiShopBindException.getMessage()); printServerResponseToWeb(serverResponseEntity);
370
148
518
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/response/ServerResponseEntity.java
ServerResponseEntity
fail
class ServerResponseEntity<T> implements Serializable { /** * 状态码 */ private String code; /** * 信息 */ private String msg; /** * 数据 */ private T data; /** * 版本 */ private String version; /** * 时间 */ private Long timestamp; private String sign; public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public ServerResponseEntity setData(T data) { this.data = data; return this; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public Long getTimestamp() { return timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } public boolean isSuccess() { return Objects.equals(ResponseEnum.OK.value(), this.code); } public boolean isFail() { return !Objects.equals(ResponseEnum.OK.value(), this.code); } public ServerResponseEntity() { // 版本号 this.version = "mall4j.v230424"; } public static <T> ServerResponseEntity<T> success(T data) { ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>(); serverResponseEntity.setData(data); serverResponseEntity.setCode(ResponseEnum.OK.value()); return serverResponseEntity; } public static <T> ServerResponseEntity<T> success() { ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>(); serverResponseEntity.setCode(ResponseEnum.OK.value()); serverResponseEntity.setMsg(ResponseEnum.OK.getMsg()); return serverResponseEntity; } public static <T> ServerResponseEntity<T> success(Integer code, T data) { return success(String.valueOf(code), data); } public static <T> ServerResponseEntity<T> success(String code, T data) { ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>(); serverResponseEntity.setCode(code); serverResponseEntity.setData(data); return serverResponseEntity; } /** * 前端显示失败消息 * @param msg 失败消息 * @return */ public static <T> ServerResponseEntity<T> showFailMsg(String msg) { log.error(msg); ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>(); serverResponseEntity.setMsg(msg); serverResponseEntity.setCode(ResponseEnum.SHOW_FAIL.value()); return serverResponseEntity; } public static <T> ServerResponseEntity<T> fail(ResponseEnum responseEnum) {<FILL_FUNCTION_BODY>} public static <T> ServerResponseEntity<T> fail(ResponseEnum responseEnum, T data) { log.error(responseEnum.toString()); ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>(); serverResponseEntity.setMsg(responseEnum.getMsg()); serverResponseEntity.setCode(responseEnum.value()); serverResponseEntity.setData(data); return serverResponseEntity; } public static <T> ServerResponseEntity<T> fail(String code, String msg, T data) { log.error(msg); ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>(); serverResponseEntity.setMsg(msg); serverResponseEntity.setCode(code); serverResponseEntity.setData(data); return serverResponseEntity; } public static <T> ServerResponseEntity<T> fail(String code, String msg) { return fail(code, msg, null); } public static <T> ServerResponseEntity<T> fail(Integer code, T data) { ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>(); serverResponseEntity.setCode(String.valueOf(code)); serverResponseEntity.setData(data); return serverResponseEntity; } @Override public String toString() { return "ServerResponseEntity{" + "code='" + code + '\'' + ", msg='" + msg + '\'' + ", data=" + data + ", version='" + version + '\'' + ", timestamp=" + timestamp + ", sign='" + sign + '\'' + '}'; } }
log.error(responseEnum.toString()); ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>(); serverResponseEntity.setMsg(responseEnum.getMsg()); serverResponseEntity.setCode(responseEnum.value()); return serverResponseEntity;
1,286
68
1,354
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/serializer/json/ImgJsonSerializer.java
ImgJsonSerializer
serialize
class ImgJsonSerializer extends JsonSerializer<String> { @Autowired private Qiniu qiniu; @Autowired private ImgUploadUtil imgUploadUtil; @Override public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {<FILL_FUNCTION_BODY>} }
if (StrUtil.isBlank(value)) { gen.writeString(StrUtil.EMPTY); return; } String[] imgs = value.split(StrUtil.COMMA); StringBuilder sb = new StringBuilder(); String resourceUrl = ""; if (Objects.equals(imgUploadUtil.getUploadType(), 2)) { resourceUrl = qiniu.getResourcesUrl(); } else if (Objects.equals(imgUploadUtil.getUploadType(), 1)) { resourceUrl = imgUploadUtil.getResourceUrl(); } for (String img : imgs) { sb.append(resourceUrl).append(img).append(StrUtil.COMMA); } sb.deleteCharAt(sb.length()-1); gen.writeString(sb.toString());
89
203
292
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/util/Arith.java
Arith
div
class Arith { /** * 默认除法运算精度 */ private static final int DEF_DIV_SCALE = 2; /** * 这个类不能实例化 */ private Arith() { } /** * 提供精确的加法运算。. * * @param v1 被加数 * @param v2 加数 * @return 两个参数的和 */ public static double add(double v1, double v2) { // 必须转换成String String s1 = Double.toString(v1); String s2 = Double.toString(v2); BigDecimal b1 = new BigDecimal(s1); BigDecimal b2 = new BigDecimal(s2); return b1.add(b2).doubleValue(); } /** * 提供精确的减法运算。. * * @param v1 被减数 * @param v2 减数 * @return 两个参数的差 */ public static double sub(double v1, double v2) { String s1 = Double.toString(v1); String s2 = Double.toString(v2); BigDecimal b1 = new BigDecimal(s1); BigDecimal b2 = new BigDecimal(s2); return b1.subtract(b2).doubleValue(); } /** * 提供精确的乘法运算。. * * @param v1 被乘数 * @param v2 乘数 * @return 两个参数的积 */ public static double mul(double v1, double v2) { String s1 = Double.toString(v1); String s2 = Double.toString(v2); BigDecimal b1 = new BigDecimal(s1); BigDecimal b2 = new BigDecimal(s2); return b1.multiply(b2).doubleValue(); } /** * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入。. * * @param v1 被除数 * @param v2 除数 * @return 两个参数的商 */ public static double div(double v1, double v2) { return div(v1, v2, DEF_DIV_SCALE); } /** * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。. * * @param v1 被除数 * @param v2 除数 * @param scale 表示表示需要精确到小数点以后几位。 * @return 两个参数的商 */ public static double div(double v1, double v2, int scale) {<FILL_FUNCTION_BODY>} /** * 提供精确的小数位四舍五入处理。. * * @param v 需要四舍五入的数字 * @param scale 小数点后保留几位 * @return 四舍五入后的结果 */ public static double round(double v, int scale) { if (scale < 0) { throw new IllegalArgumentException("The scale must be a positive integer or zero"); } String s = Double.toString(v); BigDecimal b = new BigDecimal(s); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, RoundingMode.HALF_EVEN).doubleValue(); } /** * @param bigDecimal * @param bigDecimal2 * @param bigDecimal3 * @return */ public static double add(BigDecimal bigDecimal, BigDecimal bigDecimal2, BigDecimal bigDecimal3) { return bigDecimal.add(bigDecimal2).add(bigDecimal3).doubleValue(); } /** * @param preDepositPrice * @param finalPrice * @return */ public static double add(BigDecimal preDepositPrice, BigDecimal finalPrice) { return preDepositPrice.add(finalPrice).doubleValue(); } }
if (scale < 0) { throw new IllegalArgumentException("The scale must be a positive integer or zero"); } String s1 = Double.toString(v1); String s2 = Double.toString(v2); BigDecimal b1 = new BigDecimal(s1); BigDecimal b2 = new BigDecimal(s2); return b1.divide(b2, scale, RoundingMode.HALF_EVEN).doubleValue();
1,137
119
1,256
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/util/CacheManagerUtil.java
CacheManagerUtil
getCache
class CacheManagerUtil { private CacheManager cacheManager; @SuppressWarnings({"unchecked"}) public <T> T getCache(String cacheName,String key) {<FILL_FUNCTION_BODY>} public void putCache(String cacheName,String key, Object value) { Cache cache = cacheManager.getCache(cacheName); if (cache != null) { cache.put(key, value); } } public void evictCache(String cacheName,String key) { Cache cache = cacheManager.getCache(cacheName); if (cache != null) { cache.evict(key); } } }
Cache cache = cacheManager.getCache(cacheName); if (cache == null) { return null; } Cache.ValueWrapper valueWrapper = cache.get(key); if (valueWrapper == null) { return null; } return (T)valueWrapper.get();
177
78
255
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/util/HttpContextUtils.java
HttpContextUtils
getDomain
class HttpContextUtils { public static HttpServletRequest getHttpServletRequest() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } public static String getDomain(){<FILL_FUNCTION_BODY>} public static String getOrigin(){ HttpServletRequest request = getHttpServletRequest(); return request.getHeader("Origin"); } }
HttpServletRequest request = getHttpServletRequest(); StringBuffer url = request.getRequestURL(); return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
95
54
149
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/util/IdUtil.java
IdUtil
encode
class IdUtil { @Autowired private Snowflake snowflake; private static final String DICT = "0123456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; private static final int SEED = DICT.length(); private static final int ID_MIN_LENGTH = 6; /** * 数字->字符映射 */ private static final char[] CHARS = DICT.toCharArray(); /** * 字符->数字映射 */ private static final Map<Character, Integer> NUMBERS = new HashMap<>(); static { int len = CHARS.length; for (int i = 0; i<len; i++) { NUMBERS.put(CHARS[i], i); } } /** * 根据从数据库中返回的记录ID生成对应的短网址编码 * @param id (1-56.8billion) * @return */ public static String encode(long id) {<FILL_FUNCTION_BODY>} /** * 根据获得的短网址编码解析出数据库中对应的记录ID * @param key 短网址 eg. RwTji8, GijT7Y等等 * @return */ public static long decode(String key) { char[] shorts = key.toCharArray(); int len = shorts.length; long id = 0L; for (int i = 0; i < len; i++) { id = id + (long) (NUMBERS.get(shorts[i]) * Math.pow(SEED, len-i-1)); } return id; } public String nextShortId() { return encode(snowflake.nextId()); } }
StringBuilder shortUrl = new StringBuilder(); while (id > 0) { int r = (int) (id % SEED); shortUrl.insert(0, CHARS[r]); id = id / SEED; } int len = shortUrl.length(); while (len < ID_MIN_LENGTH) { shortUrl.insert(0, CHARS[0]); len++; } return shortUrl.toString();
498
117
615
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/util/ImgUploadUtil.java
ImgUploadUtil
getUploadPath
class ImgUploadUtil { @Autowired private ImgUpload imgUpload; public Integer getUploadType() { Integer uploadType = imgUpload.getUploadType(); if (Objects.isNull(uploadType)) { throw new YamiShopBindException("请配置图片存储方式"); } return uploadType; } public String getUploadPath() {<FILL_FUNCTION_BODY>} public String getResourceUrl() { String resourceUrl = imgUpload.getResourceUrl(); if (Objects.isNull(resourceUrl) || StrUtil.isBlank(resourceUrl)) { throw new YamiShopBindException("请配置图片路径"); } return resourceUrl; } public String upload(MultipartFile img, String fileName) { String filePath = imgUpload.getImagePath(); File file = new File(filePath + fileName); if (!file.exists()) { boolean result = file.mkdirs(); if (!result) { throw new YamiShopBindException("创建目录:" + filePath + "失败"); } } try { img.transferTo(file); } catch (IOException e) { throw new YamiShopBindException("图片上传失败"); } return fileName; } public void delete(String fileName) { String filePath = imgUpload.getImagePath(); File file = new File(filePath + fileName); file.deleteOnExit(); } }
String imagePath = imgUpload.getImagePath(); if (Objects.isNull(imagePath) || StrUtil.isBlank(imagePath)) { throw new YamiShopBindException("请配置图片存储路径"); } return imagePath;
387
67
454
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/util/IpHelper.java
IpHelper
getIpAddr
class IpHelper { private static final String UNKNOWN = "unknown"; /** * 得到用户的真实地址,如果有多个就取第一个 * * @return */ public static String getIpAddr() {<FILL_FUNCTION_BODY>} }
HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); if (request == null) { return null; } String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } String[] ips = ip.split(","); return ips[0].trim();
78
209
287
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/util/Json.java
Json
parseArray
class Json { private static ObjectMapper objectMapper = new ObjectMapper(); static { // 如果为空则不输出 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); // 对于空的对象转json的时候不抛出错误 objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); // 禁用序列化日期为timestamps objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // 禁用遇到未知属性抛出异常 objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // 取消对非ASCII字符的转码 objectMapper.configure(JsonWriteFeature.ESCAPE_NON_ASCII.mappedFeature(), false); } /** * 对象转json * @param object * @return */ public static String toJsonString(Object object) { try { return objectMapper.writeValueAsString(object); } catch (JsonProcessingException e) { log.error("对象转json错误:", e); } return null; } /** * json转换换成对象 * @param json * @param clazz * @return */ public static <T> T parseObject(String json, Class<T> clazz) { T result = null; try { result = objectMapper.readValue(json, clazz); } catch (Exception e) { log.error("对象转json错误:", e); } return result; } public static ObjectMapper getObjectMapper() { return objectMapper; } /** * * https://stackoverflow.com/questions/6349421/how-to-use-jackson-to-deserialise-an-array-of-objects * * List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class)) * * works up to 10 time faster than TypeRefence. * @return */ public static <T> List<T> parseArray(String json, Class<T[]> clazz){<FILL_FUNCTION_BODY>} /** * 转换成json节点,即map * @param jsonStr * @return */ public static JsonNode parseJson(String jsonStr) { JsonNode jsonNode = null; try { jsonNode = objectMapper.readTree(jsonStr); } catch (Exception e) { log.error("Json转换错误:", e); } return jsonNode; } }
T[] result = null; try { result = objectMapper.readValue(json, clazz); } catch (Exception e) { log.error("Json转换错误:", e); } if (result == null) { return Collections.emptyList(); } return Arrays.asList(result);
709
93
802
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/util/PageParam.java
PageParam
setSize
class PageParam<T> extends Page<T> { /** * 每页显示条数,默认 10 */ @Schema(description = "每页大小,默认10") private long size = 10; /** * 当前页 */ @Schema(description = "当前页,默认1") private long current = 1; /** * 查询数据列表 */ @Hidden private List<T> records; /** * 总数 */ @Hidden private long total = 0; /** * 是否进行 count 查询 */ @JsonIgnore private boolean isSearchCount = true; @JsonIgnore private String countId; @JsonIgnore private Long maxLimit; @JsonIgnore private boolean optimizeCountSql; @Override public List<T> getRecords() { return this.records; } @Override public Page<T> setRecords(List<T> records) { this.records = records; return this; } @Override public long getTotal() { return this.total; } @Override public Page<T> setTotal(long total) { this.total = total; return this; } @JsonIgnore public boolean getSearchCount() { if (total < 0) { return false; } return isSearchCount; } @Override public Page<T> setSearchCount(boolean isSearchCount) { this.isSearchCount = isSearchCount; return this; } @Override public long getSize() { return this.size; } @Override public Page<T> setSize(long size) {<FILL_FUNCTION_BODY>} @Override public long getCurrent() { return this.current; } @Override public Page<T> setCurrent(long current) { this.current = current; return this; } }
int maxSize = 100; if (size > maxSize) { this.size = maxSize; } else { this.size = size; } return this;
548
53
601
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/util/PrincipalUtil.java
PrincipalUtil
isMatching
class PrincipalUtil { /** * 以1开头,后面跟10位数 */ public static final String MOBILE_REGEXP = "1[0-9]{10}"; /** * 数字字母下划线 4-16位 */ public static final String USER_NAME_REGEXP = "([a-zA-Z0-9_]{4,16})"; /** * 由简单的字母数字拼接而成的字符串 不含有下划线,大写字母 */ public static final String SIMPLE_CHAR_REGEXP = "([a-z0-9]+)"; public static boolean isMobile(String value) { if(StrUtil.isBlank(value)) { return false; } return Pattern.matches(MOBILE_REGEXP, value); } public static boolean isUserName(String value) { if(StrUtil.isBlank(value)) { return false; } return Pattern.matches(USER_NAME_REGEXP, value); } public static boolean isMatching(String regexp, String value) {<FILL_FUNCTION_BODY>} /** * 是否是由简单的字母数字拼接而成的字符串 * @param value 输入值 * @return 匹配结果 */ public static boolean isSimpleChar(String value) { return isMatching(SIMPLE_CHAR_REGEXP, value); } }
if (StrUtil.isBlank(value)) { return false; } return Pattern.matches(regexp, value);
396
39
435
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/util/RedisUtil.java
RedisUtil
set
class RedisUtil { private static RedisTemplate<String, Object> redisTemplate = SpringContextUtils.getBean("redisTemplate", RedisTemplate.class); public static final StringRedisTemplate STRING_REDIS_TEMPLATE = SpringContextUtils.getBean("stringRedisTemplate",StringRedisTemplate.class); //=============================common============================ /** * 指定缓存失效时间 * * @param key 键 * @param time 时间(秒) * @return */ public static boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { log.error("设置redis指定key失效时间错误:", e); return false; } } /** * 根据key 获取过期时间 * * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 失效时间为负数,说明该主键未设置失效时间(失效时间默认为-1) */ public static Long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 判断key是否存在 * * @param key 键 * @return true 存在 false 不存在 */ public static Boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { log.error("redis判断key是否存在错误:", e); return false; } } /** * 删除缓存 * * @param key 可以传一个值 或多个 */ @SuppressWarnings("unchecked") public static void del(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete(Arrays.asList(key)); } } } //============================String============================= /** * 普通缓存获取 * * @param key 键 * @return 值 */ @SuppressWarnings("unchecked") public static <T> T get(String key) { return key == null ? null : (T) redisTemplate.opsForValue().get(key); } /** * 普通缓存放入 * * @param key 键 * @param value 值 * @return true成功 false失败 */ public static boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { log.error("设置redis缓存错误:", e); return false; } } /** * 普通缓存放入并设置时间 * * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 * @return true成功 false 失败 */ public static boolean set(String key, Object value, long time) {<FILL_FUNCTION_BODY>} /** * 递增 此时value值必须为int类型 否则报错 * * @param key 键 * @param delta 要增加几(大于0) * @return */ public static Long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递增因子必须大于0"); } return STRING_REDIS_TEMPLATE.opsForValue().increment(key, delta); } /** * 递减 * * @param key 键 * @param delta 要减少几(小于0) * @return */ public static Long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return STRING_REDIS_TEMPLATE.opsForValue().increment(key, -delta); } }
try { if (time > 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; }
1,151
87
1,238
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/util/SpelUtil.java
SpelUtil
parse
class SpelUtil { /** * 支持 #p0 参数索引的表达式解析 * @param rootObject 根对象,method 所在的对象 * @param spel 表达式 * @param method ,目标方法 * @param args 方法入参 * @return 解析后的字符串 */ public static String parse(Object rootObject,String spel, Method method, Object[] args) {<FILL_FUNCTION_BODY>} }
if (StrUtil.isBlank(spel)) { return StrUtil.EMPTY; } //获取被拦截方法参数名列表(使用Spring支持类库) StandardReflectionParameterNameDiscoverer standardReflectionParameterNameDiscoverer = new StandardReflectionParameterNameDiscoverer(); String[] paraNameArr = standardReflectionParameterNameDiscoverer.getParameterNames(method); if (ArrayUtil.isEmpty(paraNameArr)) { return spel; } //使用SPEL进行key的解析 ExpressionParser parser = new SpelExpressionParser(); //SPEL上下文 StandardEvaluationContext context = new MethodBasedEvaluationContext(rootObject,method,args,standardReflectionParameterNameDiscoverer); //把方法参数放入SPEL上下文中 for (int i = 0; i < paraNameArr.length; i++) { context.setVariable(paraNameArr[i], args[i]); } return parser.parseExpression(spel).getValue(context, String.class);
125
268
393
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-common/src/main/java/com/yami/shop/common/xss/XssWrapper.java
XssWrapper
getParameterValues
class XssWrapper extends HttpServletRequestWrapper { /** * Constructs a request object wrapping the given request. * * @param request The request to wrap * @throws IllegalArgumentException if the request is null */ public XssWrapper(HttpServletRequest request) { super(request); } /** * 对数组参数进行特殊字符过滤 */ @Override public String[] getParameterValues(String name) {<FILL_FUNCTION_BODY>} /** * 对参数中特殊字符进行过滤 */ @Override public String getParameter(String name) { String value = super.getParameter(name); if (StrUtil.isBlank(value)) { return value; } return cleanXss(value); } /** * 获取attribute,特殊字符过滤 */ @Override public Object getAttribute(String name) { Object value = super.getAttribute(name); if (value instanceof String && StrUtil.isNotBlank((String) value)) { return cleanXss((String) value); } return value; } /** * 对请求头部进行特殊字符过滤 */ @Override public String getHeader(String name) { String value = super.getHeader(name); if (StrUtil.isBlank(value)) { return value; } return cleanXss(value); } private String cleanXss(String value) { return XssUtil.clean(value); } }
String[] values = super.getParameterValues(name); if (values == null) { return null; } int count = values.length; String[] encodedValues = new String[count]; for (int i = 0; i < count; i++) { encodedValues[i] = cleanXss(values[i]); } return encodedValues;
409
97
506
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-security/yami-shop-security-admin/src/main/java/com/yami/shop/security/admin/util/SecurityUtils.java
SecurityUtils
getSysUser
class SecurityUtils { /** * 获取用户 */ public YamiSysUser getSysUser() {<FILL_FUNCTION_BODY>} }
UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get(); YamiSysUser details = new YamiSysUser(); details.setUserId(Long.valueOf(userInfoInTokenBO.getUserId())); details.setEnabled(userInfoInTokenBO.getEnabled()); details.setUsername(userInfoInTokenBO.getNickName()); details.setAuthorities(userInfoInTokenBO.getPerms()); details.setShopId(userInfoInTokenBO.getShopId()); return details;
45
138
183
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-security/yami-shop-security-api/src/main/java/com/yami/shop/security/api/controller/LoginController.java
LoginController
login
class LoginController { @Autowired private TokenStore tokenStore; @Autowired private UserMapper userMapper; @Autowired private PasswordCheckManager passwordCheckManager; @Autowired private PasswordManager passwordManager; @PostMapping("/login") @Operation(summary = "账号密码(用于前端登录)" , description = "通过账号/手机号/用户名密码登录,还要携带用户的类型,也就是用户所在的系统") public ServerResponseEntity<TokenInfoVO> login( @Valid @RequestBody AuthenticationDTO authenticationDTO) {<FILL_FUNCTION_BODY>} private User getUser(String mobileOrUserName) { User user = null; // 手机验证码登陆,或传过来的账号很像手机号 if (PrincipalUtil.isMobile(mobileOrUserName)) { user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserMobile, mobileOrUserName)); } // 如果不是手机验证码登陆, 找不到手机号就找用户名 if (user == null) { user = userMapper.selectOneByUserName(mobileOrUserName); } if (user == null) { throw new YamiShopBindException("账号或密码不正确"); } return user; } }
String mobileOrUserName = authenticationDTO.getUserName(); User user = getUser(mobileOrUserName); String decryptPassword = passwordManager.decryptPassword(authenticationDTO.getPassWord()); // 半小时内密码输入错误十次,已限制登录30分钟 passwordCheckManager.checkPassword(SysTypeEnum.ORDINARY,authenticationDTO.getUserName(), decryptPassword, user.getLoginPassword()); UserInfoInTokenBO userInfoInToken = new UserInfoInTokenBO(); userInfoInToken.setUserId(user.getUserId()); userInfoInToken.setSysType(SysTypeEnum.ORDINARY.value()); userInfoInToken.setEnabled(user.getStatus() == 1); // 存储token返回vo TokenInfoVO tokenInfoVO = tokenStore.storeAndGetVo(userInfoInToken); return ServerResponseEntity.success(tokenInfoVO);
357
240
597
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-security/yami-shop-security-api/src/main/java/com/yami/shop/security/api/util/SecurityUtils.java
SecurityUtils
getUser
class SecurityUtils { private static final String USER_REQUEST = "/p/"; /** * 获取用户 */ public YamiUser getUser() {<FILL_FUNCTION_BODY>} }
if (!HttpContextUtils.getHttpServletRequest().getRequestURI().startsWith(USER_REQUEST)) { // 用户相关的请求,应该以/p开头!!! throw new RuntimeException("yami.user.request.error"); } UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get(); YamiUser yamiUser = new YamiUser(); yamiUser.setUserId(userInfoInTokenBO.getUserId()); yamiUser.setBizUserId(userInfoInTokenBO.getBizUserId()); yamiUser.setEnabled(userInfoInTokenBO.getEnabled()); yamiUser.setShopId(userInfoInTokenBO.getShopId()); yamiUser.setStationId(userInfoInTokenBO.getOtherId()); return yamiUser;
58
209
267
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-security/yami-shop-security-common/src/main/java/com/yami/shop/security/common/adapter/MallWebSecurityConfigurerAdapter.java
MallWebSecurityConfigurerAdapter
filterChain
class MallWebSecurityConfigurerAdapter { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{<FILL_FUNCTION_BODY>} }
// We don't need CSRF for token based authentication return http.csrf().disable().cors() .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and().authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll() .and() .authorizeRequests().requestMatchers( "/**").permitAll().and().build();
45
111
156
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-security/yami-shop-security-common/src/main/java/com/yami/shop/security/common/config/AuthConfig.java
AuthConfig
filterRegistration
class AuthConfig { @Autowired private AuthFilter authFilter; @Bean @ConditionalOnMissingBean public AuthConfigAdapter authConfigAdapter() { return new DefaultAuthConfigAdapter(); } @Bean @Lazy public FilterRegistrationBean<AuthFilter> filterRegistration(AuthConfigAdapter authConfigAdapter) {<FILL_FUNCTION_BODY>} }
FilterRegistrationBean<AuthFilter> registration = new FilterRegistrationBean<>(); // 添加过滤器 registration.setFilter(authFilter); // 设置过滤路径,/*所有路径 registration.addUrlPatterns(ArrayUtil.toArray(authConfigAdapter.pathPatterns(), String.class)); registration.setName("authFilter"); // 设置优先级 registration.setOrder(0); registration.setDispatcherTypes(DispatcherType.REQUEST); return registration;
105
127
232
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-security/yami-shop-security-common/src/main/java/com/yami/shop/security/common/config/CaptchaConfig.java
CaptchaConfig
getResourcesImagesFile
class CaptchaConfig { @Bean public CaptchaService captchaService() { Properties config = new Properties(); config.put(Const.CAPTCHA_CACHETYPE, "redis"); config.put(Const.CAPTCHA_WATER_MARK, ""); // 滑动验证 config.put(Const.CAPTCHA_TYPE, CaptchaTypeEnum.BLOCKPUZZLE.getCodeValue()); config.put(Const.CAPTCHA_INIT_ORIGINAL, "true"); initializeBaseMap(); return CaptchaServiceFactory.getInstance(config); } private static void initializeBaseMap() { ImageUtils.cacheBootImage(getResourcesImagesFile("classpath:captcha" + "/original/*.png"), getResourcesImagesFile("classpath:captcha" + "/slidingBlock/*.png"), Collections.emptyMap()); } public static Map<String, String> getResourcesImagesFile(String path) {<FILL_FUNCTION_BODY>} }
Map<String, String> imgMap = new HashMap<>(16); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { Resource[] resources = resolver.getResources(path); Resource[] var4 = resources; int var5 = resources.length; for(int var6 = 0; var6 < var5; ++var6) { Resource resource = var4[var6]; byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream()); String string = Base64Utils.encodeToString(bytes); String filename = resource.getFilename(); imgMap.put(filename, string); } } catch (Exception var11) { var11.printStackTrace(); } return imgMap;
263
203
466
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-security/yami-shop-security-common/src/main/java/com/yami/shop/security/common/config/CorsConfig.java
CorsConfig
corsConfigurationSource
class CorsConfig { /** * 修改为添加而不是设置,* 最好生产环境改为实际的需要, 这里可以用多个add配置多个域名 * configuration.addAllowedOrigin("http://localhost:8080"); * configuration.addAllowedOrigin("http://192.168.1.6:8080"); * @return CorsConfigurationSource */ @Bean public CorsConfigurationSource corsConfigurationSource() {<FILL_FUNCTION_BODY>} }
CorsConfiguration configuration = new CorsConfiguration(); configuration.addAllowedOriginPattern("*"); //修改为添加而不是设置 configuration.addAllowedMethod("*"); //这里很重要,起码需要允许 Access-Control-Allow-Origin configuration.addAllowedHeader("*"); configuration.setAllowCredentials(true); configuration.setMaxAge(3600 * 24L); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source;
136
144
280
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-security/yami-shop-security-common/src/main/java/com/yami/shop/security/common/controller/CaptchaController.java
CaptchaController
check
class CaptchaController { private final CaptchaService captchaService; public CaptchaController(CaptchaService captchaService) { this.captchaService = captchaService; } @PostMapping({ "/get" }) public ServerResponseEntity<ResponseModel> get(@RequestBody CaptchaVO captchaVO) { return ServerResponseEntity.success(captchaService.get(captchaVO)); } @PostMapping({ "/check" }) public ServerResponseEntity<ResponseModel> check(@RequestBody CaptchaVO captchaVO) {<FILL_FUNCTION_BODY>} }
ResponseModel responseModel; try { responseModel = captchaService.check(captchaVO); }catch (Exception e) { return ServerResponseEntity.success(ResponseModel.errorMsg(RepCodeEnum.API_CAPTCHA_COORDINATE_ERROR)); } return ServerResponseEntity.success(responseModel);
158
86
244
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-security/yami-shop-security-common/src/main/java/com/yami/shop/security/common/controller/LogoutController.java
LogoutController
logOut
class LogoutController { @Autowired private TokenStore tokenStore; @PostMapping("/logOut") @Operation(summary = "退出登陆" , description = "点击退出登陆,清除token,清除菜单缓存") public ServerResponseEntity<Void> logOut(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
String accessToken = request.getHeader("Authorization"); if (StrUtil.isBlank(accessToken)) { return ServerResponseEntity.success(); } // 删除该用户在该系统当前的token tokenStore.deleteCurrentToken(accessToken); return ServerResponseEntity.success();
99
79
178
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-security/yami-shop-security-common/src/main/java/com/yami/shop/security/common/controller/TokenController.java
TokenController
refreshToken
class TokenController { @Autowired private TokenStore tokenStore; @PostMapping("/token/refresh") public ServerResponseEntity<TokenInfoVO> refreshToken(@Valid @RequestBody RefreshTokenDTO refreshTokenDTO) {<FILL_FUNCTION_BODY>} }
TokenInfoBO tokenInfoServerResponseEntity = tokenStore .refreshToken(refreshTokenDTO.getRefreshToken()); return ServerResponseEntity .success(BeanUtil.copyProperties(tokenInfoServerResponseEntity, TokenInfoVO.class));
79
65
144
<no_super_class>
gz-yami_mall4j
mall4j/yami-shop-security/yami-shop-security-common/src/main/java/com/yami/shop/security/common/dto/RefreshTokenDTO.java
RefreshTokenDTO
toString
class RefreshTokenDTO { /** * refreshToken */ @NotBlank(message = "refreshToken不能为空") @Schema(description = "refreshToken" , required = true) private String refreshToken; public String getRefreshToken() { return refreshToken; } public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "RefreshTokenDTO{" + "refreshToken='" + refreshToken + '\'' + '}';
138
30
168
<no_super_class>