package com.rainbowforest.productcatalogservice.controller; import com.rainbowforest.productcatalogservice.entity.Product; import com.rainbowforest.productcatalogservice.http.header.HeaderGenerator; import com.rainbowforest.productcatalogservice.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; @RestController @RequestMapping("/admin") public class AdminProductController { @Autowired private ProductService productService; @Autowired private HeaderGenerator headerGenerator; @PostMapping(value = "/products") private ResponseEntity<Product> addProduct(@RequestBody Product product, HttpServletRequest request){ if(product != null) { try { productService.addProduct(product); return new ResponseEntity<Product>( product, headerGenerator.getHeadersForSuccessPostMethod(request, product.getId()), HttpStatus.CREATED); }catch (Exception e) { e.printStackTrace(); return new ResponseEntity<Product>( headerGenerator.getHeadersForError(), HttpStatus.INTERNAL_SERVER_ERROR); } } return new ResponseEntity<Product>( headerGenerator.getHeadersForError(), HttpStatus.BAD_REQUEST); } @DeleteMapping(value = "/products/{id}") private ResponseEntity<Void> deleteProduct(@PathVariable("id") Long id){ Product product = productService.getProductById(id); if(product != null) { try { productService.deleteProduct(id); return new ResponseEntity<Void>( headerGenerator.getHeadersForSuccessGetMethod(), HttpStatus.OK); }catch (Exception e) { e.printStackTrace(); return new ResponseEntity<Void>( headerGenerator.getHeadersForError(), HttpStatus.INTERNAL_SERVER_ERROR); } } return new ResponseEntity<Void>(headerGenerator.getHeadersForError(), HttpStatus.NOT_FOUND); } }
package com.rainbowforest.recommendationservice.controller; import com.rainbowforest.recommendationservice.feignClient.ProductClient; import com.rainbowforest.recommendationservice.feignClient.UserClient; import com.rainbowforest.recommendationservice.http.header.HeaderGenerator; import com.rainbowforest.recommendationservice.model.Product; import com.rainbowforest.recommendationservice.model.Recommendation; import com.rainbowforest.recommendationservice.model.User; import com.rainbowforest.recommendationservice.service.RecommendationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; @RestController public class RecommendationController { @Autowired private RecommendationService recommendationService; @Autowired private ProductClient productClient; @Autowired private UserClient userClient; @Autowired private HeaderGenerator headerGenerator; @GetMapping(value = "/recommendations") private ResponseEntity<List<Recommendation>> getAllRating(@RequestParam("name") String productName){ List<Recommendation> recommendations = recommendationService.getAllRecommendationByProductName(productName); if(!recommendations.isEmpty()) { return new ResponseEntity<List<Recommendation>>( recommendations, headerGenerator.getHeadersForSuccessGetMethod(), HttpStatus.OK); } return new ResponseEntity<List<Recommendation>>( headerGenerator.getHeadersForError(), HttpStatus.NOT_FOUND); } @PostMapping(value = "/{userId}/recommendations/{productId}") private ResponseEntity<Recommendation> saveRecommendations( @PathVariable ("userId") Long userId, @PathVariable ("productId") Long productId, @RequestParam ("rating") int rating, HttpServletRequest request){ Product product = productClient.getProductById(productId); User user = userClient.getUserById(userId); if(product != null && user != null) { try { Recommendation recommendation = new Recommendation(); recommendation.setProduct(product); recommendation.setUser(user); recommendation.setRating(rating); recommendationService.saveRecommendation(recommendation); return new ResponseEntity<Recommendation>( recommendation, headerGenerator.getHeadersForSuccessPostMethod(request, recommendation.getId()), HttpStatus.CREATED); }catch (Exception e) { e.printStackTrace(); return new ResponseEntity<Recommendation>( headerGenerator.getHeadersForError(), HttpStatus.INTERNAL_SERVER_ERROR); } } return new ResponseEntity<Recommendation>( headerGenerator.getHeadersForError(), HttpStatus.BAD_REQUEST); } @DeleteMapping(value = "/recommendations/{id}") private ResponseEntity<Void> deleteRecommendations(@PathVariable("id") Long id){ Recommendation recommendation = recommendationService.getRecommendationById(id); if(recommendation != null) { try { recommendationService.deleteRecommendation(id); return new ResponseEntity<Void>( headerGenerator.getHeadersForSuccessGetMethod(), HttpStatus.OK); }catch (Exception e) { e.printStackTrace(); return new ResponseEntity<Void>( headerGenerator.getHeadersForError(), HttpStatus.INTERNAL_SERVER_ERROR); } } return new ResponseEntity<Void>( headerGenerator.getHeadersForError(), HttpStatus.NOT_FOUND); } }
package com.macro.mall.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.dto.PmsBrandParam; import com.macro.mall.model.PmsBrand; import com.macro.mall.service.PmsBrandService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 品牌功能Controller * Created by macro on 2018/4/26. */ @Controller @Api(tags = "PmsBrandController", description = "商品品牌管理") @RequestMapping("/brand") public class PmsBrandController { @Autowired private PmsBrandService brandService; @ApiOperation(value = "获取全部品牌列表") @RequestMapping(value = "/listAll", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsBrand>> getList() { return CommonResult.success(brandService.listAllBrand()); } @ApiOperation(value = "添加品牌") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@Validated @RequestBody PmsBrandParam pmsBrand) { CommonResult commonResult; int count = brandService.createBrand(pmsBrand); if (count == 1) { commonResult = CommonResult.success(count); } else { commonResult = CommonResult.failed(); } return commonResult; } @ApiOperation(value = "更新品牌") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable("id") Long id, @Validated @RequestBody PmsBrandParam pmsBrandParam) { CommonResult commonResult; int count = brandService.updateBrand(id, pmsBrandParam); if (count == 1) { commonResult = CommonResult.success(count); } else { commonResult = CommonResult.failed(); } return commonResult; } @ApiOperation(value = "删除品牌") @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult delete(@PathVariable("id") Long id) { int count = brandService.deleteBrand(id); if (count == 1) { return CommonResult.success(null); } else { return CommonResult.failed(); } } @ApiOperation(value = "根据品牌名称分页获取品牌列表") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsBrand>> getList(@RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) { List<PmsBrand> brandList = brandService.listBrand(keyword, pageNum, pageSize); return CommonResult.success(CommonPage.restPage(brandList)); } @ApiOperation(value = "根据编号查询品牌信息") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsBrand> getItem(@PathVariable("id") Long id) { return CommonResult.success(brandService.getBrand(id)); } @ApiOperation(value = "批量删除品牌") @RequestMapping(value = "/delete/batch", method = RequestMethod.POST) @ResponseBody public CommonResult deleteBatch(@RequestParam("ids") List<Long> ids) { int count = brandService.deleteBrand(ids); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation(value = "批量更新显示状态") @RequestMapping(value = "/update/showStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateShowStatus(@RequestParam("ids") List<Long> ids, @RequestParam("showStatus") Integer showStatus) { int count = brandService.updateShowStatus(ids, showStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation(value = "批量更新厂家制造商状态") @RequestMapping(value = "/update/factoryStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateFactoryStatus(@RequestParam("ids") List<Long> ids, @RequestParam("factoryStatus") Integer factoryStatus) { int count = brandService.updateFactoryStatus(ids, factoryStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } }
package com.macro.mall.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.dto.PmsProductAttributeCategoryItem; import com.macro.mall.model.PmsProductAttributeCategory; import com.macro.mall.service.PmsProductAttributeCategoryService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 商品属性分类Controller * Created by macro on 2018/4/26. */ @Controller @Api(tags = "PmsProductAttributeCategoryController", description = "商品属性分类管理") @RequestMapping("/productAttribute/category") public class PmsProductAttributeCategoryController { @Autowired private PmsProductAttributeCategoryService productAttributeCategoryService; @ApiOperation("添加商品属性分类") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestParam String name) { int count = productAttributeCategoryService.create(name); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改商品属性分类") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestParam String name) { int count = productAttributeCategoryService.update(id, name); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("删除单个商品属性分类") @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = productAttributeCategoryService.delete(id); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("获取单个商品属性分类信息") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsProductAttributeCategory> getItem(@PathVariable Long id) { PmsProductAttributeCategory productAttributeCategory = productAttributeCategoryService.getItem(id); return CommonResult.success(productAttributeCategory); } @ApiOperation("分页获取所有商品属性分类") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsProductAttributeCategory>> getList(@RequestParam(defaultValue = "5") Integer pageSize, @RequestParam(defaultValue = "1") Integer pageNum) { List<PmsProductAttributeCategory> productAttributeCategoryList = productAttributeCategoryService.getList(pageSize, pageNum); return CommonResult.success(CommonPage.restPage(productAttributeCategoryList)); } @ApiOperation("获取所有商品属性分类及其下属性") @RequestMapping(value = "/list/withAttr", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProductAttributeCategoryItem>> getListWithAttr() { List<PmsProductAttributeCategoryItem> productAttributeCategoryResultList = productAttributeCategoryService.getListWithAttr(); return CommonResult.success(productAttributeCategoryResultList); } }
package com.macro.mall.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.dto.PmsProductAttributeParam; import com.macro.mall.dto.ProductAttrInfo; import com.macro.mall.model.PmsProductAttribute; import com.macro.mall.service.PmsProductAttributeService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 商品属性管理Controller * Created by macro on 2018/4/26. */ @Controller @Api(tags = "PmsProductAttributeController", description = "商品属性管理") @RequestMapping("/productAttribute") public class PmsProductAttributeController { @Autowired private PmsProductAttributeService productAttributeService; @ApiOperation("根据分类查询属性列表或参数列表") @ApiImplicitParams({@ApiImplicitParam(name = "type", value = "0表示属性,1表示参数", required = true, paramType = "query", dataType = "integer")}) @RequestMapping(value = "/list/{cid}", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsProductAttribute>> getList(@PathVariable Long cid, @RequestParam(value = "type") Integer type, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<PmsProductAttribute> productAttributeList = productAttributeService.getList(cid, type, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(productAttributeList)); } @ApiOperation("添加商品属性信息") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody PmsProductAttributeParam productAttributeParam) { int count = productAttributeService.create(productAttributeParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改商品属性信息") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody PmsProductAttributeParam productAttributeParam) { int count = productAttributeService.update(id, productAttributeParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("查询单个商品属性") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsProductAttribute> getItem(@PathVariable Long id) { PmsProductAttribute productAttribute = productAttributeService.getItem(id); return CommonResult.success(productAttribute); } @ApiOperation("批量删除商品属性") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = productAttributeService.delete(ids); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("根据商品分类的id获取商品属性及属性分类") @RequestMapping(value = "/attrInfo/{productCategoryId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<ProductAttrInfo>> getAttrInfo(@PathVariable Long productCategoryId) { List<ProductAttrInfo> productAttrInfoList = productAttributeService.getProductAttrInfo(productCategoryId); return CommonResult.success(productAttrInfoList); } }
package com.macro.mall.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.dto.PmsProductCategoryParam; import com.macro.mall.dto.PmsProductCategoryWithChildrenItem; import com.macro.mall.model.PmsProductCategory; import com.macro.mall.service.PmsProductCategoryService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 商品分类模块Controller * Created by macro on 2018/4/26. */ @Controller @Api(tags = "PmsProductCategoryController", description = "商品分类管理") @RequestMapping("/productCategory") public class PmsProductCategoryController { @Autowired private PmsProductCategoryService productCategoryService; @ApiOperation("添加产品分类") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@Validated @RequestBody PmsProductCategoryParam productCategoryParam) { int count = productCategoryService.create(productCategoryParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改商品分类") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @Validated @RequestBody PmsProductCategoryParam productCategoryParam) { int count = productCategoryService.update(id, productCategoryParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("分页查询商品分类") @RequestMapping(value = "/list/{parentId}", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsProductCategory>> getList(@PathVariable Long parentId, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<PmsProductCategory> productCategoryList = productCategoryService.getList(parentId, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(productCategoryList)); } @ApiOperation("根据id获取商品分类") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsProductCategory> getItem(@PathVariable Long id) { PmsProductCategory productCategory = productCategoryService.getItem(id); return CommonResult.success(productCategory); } @ApiOperation("删除商品分类") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = productCategoryService.delete(id); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改导航栏显示状态") @RequestMapping(value = "/update/navStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateNavStatus(@RequestParam("ids") List<Long> ids, @RequestParam("navStatus") Integer navStatus) { int count = productCategoryService.updateNavStatus(ids, navStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改显示状态") @RequestMapping(value = "/update/showStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateShowStatus(@RequestParam("ids") List<Long> ids, @RequestParam("showStatus") Integer showStatus) { int count = productCategoryService.updateShowStatus(ids, showStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("查询所有一级分类及子分类") @RequestMapping(value = "/list/withChildren", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProductCategoryWithChildrenItem>> listWithChildren() { List<PmsProductCategoryWithChildrenItem> list = productCategoryService.listWithChildren(); return CommonResult.success(list); } }
package com.macro.mall.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.dto.PmsProductParam; import com.macro.mall.dto.PmsProductQueryParam; import com.macro.mall.dto.PmsProductResult; import com.macro.mall.model.PmsProduct; import com.macro.mall.service.PmsProductService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 商品管理Controller * Created by macro on 2018/4/26. */ @Controller @Api(tags = "PmsProductController", description = "商品管理") @RequestMapping("/product") public class PmsProductController { @Autowired private PmsProductService productService; @ApiOperation("创建商品") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody PmsProductParam productParam) { int count = productService.create(productParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("根据商品id获取商品编辑信息") @RequestMapping(value = "/updateInfo/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsProductResult> getUpdateInfo(@PathVariable Long id) { PmsProductResult productResult = productService.getUpdateInfo(id); return CommonResult.success(productResult); } @ApiOperation("更新商品") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody PmsProductParam productParam) { int count = productService.update(id, productParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("查询商品") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsProduct>> getList(PmsProductQueryParam productQueryParam, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<PmsProduct> productList = productService.list(productQueryParam, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(productList)); } @ApiOperation("根据商品名称或货号模糊查询") @RequestMapping(value = "/simpleList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProduct>> getList(String keyword) { List<PmsProduct> productList = productService.list(keyword); return CommonResult.success(productList); } @ApiOperation("批量修改审核状态") @RequestMapping(value = "/update/verifyStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateVerifyStatus(@RequestParam("ids") List<Long> ids, @RequestParam("verifyStatus") Integer verifyStatus, @RequestParam("detail") String detail) { int count = productService.updateVerifyStatus(ids, verifyStatus, detail); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("批量上下架") @RequestMapping(value = "/update/publishStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updatePublishStatus(@RequestParam("ids") List<Long> ids, @RequestParam("publishStatus") Integer publishStatus) { int count = productService.updatePublishStatus(ids, publishStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("批量推荐商品") @RequestMapping(value = "/update/recommendStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateRecommendStatus(@RequestParam("ids") List<Long> ids, @RequestParam("recommendStatus") Integer recommendStatus) { int count = productService.updateRecommendStatus(ids, recommendStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("批量设为新品") @RequestMapping(value = "/update/newStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateNewStatus(@RequestParam("ids") List<Long> ids, @RequestParam("newStatus") Integer newStatus) { int count = productService.updateNewStatus(ids, newStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("批量修改删除状态") @RequestMapping(value = "/update/deleteStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateDeleteStatus(@RequestParam("ids") List<Long> ids, @RequestParam("deleteStatus") Integer deleteStatus) { int count = productService.updateDeleteStatus(ids, deleteStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } }
package com.macro.mall.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.dto.UmsMenuNode; import com.macro.mall.model.UmsMenu; import com.macro.mall.service.UmsMenuService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 后台菜单管理Controller * Created by macro on 2020/2/4. */ @Controller @Api(tags = "UmsMenuController", description = "后台菜单管理") @RequestMapping("/menu") public class UmsMenuController { @Autowired private UmsMenuService menuService; @ApiOperation("添加后台菜单") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody UmsMenu umsMenu) { int count = menuService.create(umsMenu); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改后台菜单") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody UmsMenu umsMenu) { int count = menuService.update(id, umsMenu); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("根据ID获取菜单详情") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<UmsMenu> getItem(@PathVariable Long id) { UmsMenu umsMenu = menuService.getItem(id); return CommonResult.success(umsMenu); } @ApiOperation("根据ID删除后台菜单") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = menuService.delete(id); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("分页查询后台菜单") @RequestMapping(value = "/list/{parentId}", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<UmsMenu>> list(@PathVariable Long parentId, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<UmsMenu> menuList = menuService.list(parentId, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(menuList)); } @ApiOperation("树形结构返回所有菜单列表") @RequestMapping(value = "/treeList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsMenuNode>> treeList() { List<UmsMenuNode> list = menuService.treeList(); return CommonResult.success(list); } @ApiOperation("修改菜单显示状态") @RequestMapping(value = "/updateHidden/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateHidden(@PathVariable Long id, @RequestParam("hidden") Integer hidden) { int count = menuService.updateHidden(id, hidden); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } }
package com.macro.mall.controller; import com.macro.mall.common.api.CommonResult; import com.macro.mall.model.UmsResourceCategory; import com.macro.mall.service.UmsResourceCategoryService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 后台资源分类管理Controller * Created by macro on 2020/2/5. */ @Controller @Api(tags = "UmsResourceCategoryController", description = "后台资源分类管理") @RequestMapping("/resourceCategory") public class UmsResourceCategoryController { @Autowired private UmsResourceCategoryService resourceCategoryService; @ApiOperation("查询所有后台资源分类") @RequestMapping(value = "/listAll", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsResourceCategory>> listAll() { List<UmsResourceCategory> resourceList = resourceCategoryService.listAll(); return CommonResult.success(resourceList); } @ApiOperation("添加后台资源分类") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody UmsResourceCategory umsResourceCategory) { int count = resourceCategoryService.create(umsResourceCategory); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改后台资源分类") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody UmsResourceCategory umsResourceCategory) { int count = resourceCategoryService.update(id, umsResourceCategory); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("根据ID删除后台资源") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = resourceCategoryService.delete(id); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } }
package com.macro.mall.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.model.UmsResource; import com.macro.mall.service.UmsResourceService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; /** * 后台资源管理Controller * Created by macro on 2020/2/4. */ @Controller @Api(tags = "UmsResourceController", description = "后台资源管理") @RequestMapping("/resource") public class UmsResourceController { @Autowired private UmsResourceService resourceService; @ApiOperation("添加后台资源") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody UmsResource umsResource) { int count = resourceService.create(umsResource); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改后台资源") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody UmsResource umsResource) { int count = resourceService.update(id, umsResource); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("根据ID获取资源详情") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<UmsResource> getItem(@PathVariable Long id) { UmsResource umsResource = resourceService.getItem(id); return CommonResult.success(umsResource); } @ApiOperation("根据ID删除后台资源") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = resourceService.delete(id); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("分页模糊查询后台资源") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<UmsResource>> list(@RequestParam(required = false) Long categoryId, @RequestParam(required = false) String nameKeyword, @RequestParam(required = false) String urlKeyword, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<UmsResource> resourceList = resourceService.list(categoryId,nameKeyword, urlKeyword, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(resourceList)); } @ApiOperation("查询所有后台资源") @RequestMapping(value = "/listAll", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsResource>> listAll() { List<UmsResource> resourceList = resourceService.listAll(); return CommonResult.success(resourceList); } @ApiOperation("初始化资源角色关联数据") @RequestMapping(value = "/initResourceRolesMap", method = RequestMethod.GET) @ResponseBody public CommonResult initResourceRolesMap() { Map<String, List<String>> resourceRolesMap = resourceService.initResourceRolesMap(); return CommonResult.success(resourceRolesMap); } }
package com.macro.mall.demo.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.demo.dto.PmsBrandDto; import com.macro.mall.demo.service.DemoService; import com.macro.mall.model.PmsBrand; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 商品管理示例Controller */ @Api(tags = "DemoController", description = "商品管理示例接口") @Controller public class DemoController { @Autowired private DemoService demoService; private static final Logger LOGGER = LoggerFactory.getLogger(DemoController.class); @ApiOperation(value = "获取全部品牌列表") @RequestMapping(value = "/brand/listAll", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsBrand>> getBrandList() { return CommonResult.success(demoService.listAllBrand()); } @ApiOperation(value = "添加品牌") @RequestMapping(value = "/brand/create", method = RequestMethod.POST) @ResponseBody public CommonResult createBrand(@Validated @RequestBody PmsBrandDto pmsBrand) { CommonResult commonResult; int count = demoService.createBrand(pmsBrand); if (count == 1) { commonResult = CommonResult.success(pmsBrand); LOGGER.debug("createBrand success:{}", pmsBrand); } else { commonResult = CommonResult.failed("操作失败"); LOGGER.debug("createBrand failed:{}", pmsBrand); } return commonResult; } @ApiOperation(value = "更新品牌") @RequestMapping(value = "/brand/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateBrand(@PathVariable("id") Long id, @Validated @RequestBody PmsBrandDto pmsBrandDto) { CommonResult commonResult; int count = demoService.updateBrand(id, pmsBrandDto); if (count == 1) { commonResult = CommonResult.success(pmsBrandDto); LOGGER.debug("updateBrand success:{}", pmsBrandDto); } else { commonResult = CommonResult.failed("操作失败"); LOGGER.debug("updateBrand failed:{}", pmsBrandDto); } return commonResult; } @ApiOperation(value = "删除品牌") @RequestMapping(value = "/brand/delete/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult deleteBrand(@PathVariable("id") Long id) { int count = demoService.deleteBrand(id); if (count == 1) { LOGGER.debug("deleteBrand success :id={}", id); return CommonResult.success(null); } else { LOGGER.debug("deleteBrand failed :id={}", id); return CommonResult.failed("操作失败"); } } @ApiOperation(value = "分页获取品牌列表") @RequestMapping(value = "/brand/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize) { List<PmsBrand> brandList = demoService.listBrand(pageNum, pageSize); return CommonResult.success(CommonPage.restPage(brandList)); } @ApiOperation(value = "根据编号查询品牌信息") @RequestMapping(value = "/brand/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsBrand> brand(@PathVariable("id") Long id) { return CommonResult.success(demoService.getBrand(id)); } }
package com.macro.mall.portal.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.portal.domain.MemberBrandAttention; import com.macro.mall.portal.domain.MemberProductCollection; import com.macro.mall.portal.service.MemberAttentionService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 会员关注品牌管理Controller * Created by macro on 2018/8/2. */ @Controller @Api(tags = "MemberAttentionController", description = "会员关注品牌管理") @RequestMapping("/member/attention") public class MemberAttentionController { @Autowired private MemberAttentionService memberAttentionService; @ApiOperation("添加品牌关注") @RequestMapping(value = "/add", method = RequestMethod.POST) @ResponseBody public CommonResult add(@RequestBody MemberBrandAttention memberBrandAttention) { int count = memberAttentionService.add(memberBrandAttention); if(count>0){ return CommonResult.success(count); }else{ return CommonResult.failed(); } } @ApiOperation("取消关注") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(Long brandId) { int count = memberAttentionService.delete(brandId); if(count>0){ return CommonResult.success(count); }else{ return CommonResult.failed(); } } @ApiOperation("显示关注列表") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<MemberBrandAttention>> list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) { Page<MemberBrandAttention> page = memberAttentionService.list(pageNum,pageSize); return CommonResult.success(CommonPage.restPage(page)); } @ApiOperation("显示关注品牌详情") @RequestMapping(value = "/detail", method = RequestMethod.GET) @ResponseBody public CommonResult<MemberBrandAttention> detail(@RequestParam Long brandId) { MemberBrandAttention memberBrandAttention = memberAttentionService.detail(brandId); return CommonResult.success(memberBrandAttention); } @ApiOperation("清空关注列表") @RequestMapping(value = "/clear", method = RequestMethod.POST) @ResponseBody public CommonResult clear() { memberAttentionService.clear(); return CommonResult.success(null); } }
package com.macro.mall.portal.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.portal.domain.MemberProductCollection; import com.macro.mall.portal.service.MemberCollectionService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 会员收藏管理Controller * Created by macro on 2018/8/2. */ @Controller @Api(tags = "MemberCollectionController", description = "会员收藏管理") @RequestMapping("/member/productCollection") public class MemberProductCollectionController { @Autowired private MemberCollectionService memberCollectionService; @ApiOperation("添加商品收藏") @RequestMapping(value = "/add", method = RequestMethod.POST) @ResponseBody public CommonResult add(@RequestBody MemberProductCollection productCollection) { int count = memberCollectionService.add(productCollection); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("删除收藏商品") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(Long productId) { int count = memberCollectionService.delete(productId); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("显示收藏列表") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<MemberProductCollection>> list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) { Page<MemberProductCollection> page = memberCollectionService.list(pageNum,pageSize); return CommonResult.success(CommonPage.restPage(page)); } @ApiOperation("显示收藏商品详情") @RequestMapping(value = "/detail", method = RequestMethod.GET) @ResponseBody public CommonResult<MemberProductCollection> detail(@RequestParam Long productId) { MemberProductCollection memberProductCollection = memberCollectionService.detail(productId); return CommonResult.success(memberProductCollection); } @ApiOperation("清空收藏列表") @RequestMapping(value = "/clear", method = RequestMethod.POST) @ResponseBody public CommonResult clear() { memberCollectionService.clear(); return CommonResult.success(null); } }
package com.macro.mall.portal.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.portal.domain.MemberReadHistory; import com.macro.mall.portal.service.MemberReadHistoryService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 会员商品浏览记录管理Controller * Created by macro on 2018/8/3. */ @Controller @Api(tags = "MemberReadHistoryController", description = "会员商品浏览记录管理") @RequestMapping("/member/readHistory") public class MemberReadHistoryController { @Autowired private MemberReadHistoryService memberReadHistoryService; @ApiOperation("创建浏览记录") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody MemberReadHistory memberReadHistory) { int count = memberReadHistoryService.create(memberReadHistory); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("删除浏览记录") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<String> ids) { int count = memberReadHistoryService.delete(ids); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("清空除浏览记录") @RequestMapping(value = "/clear", method = RequestMethod.POST) @ResponseBody public CommonResult clear() { memberReadHistoryService.clear(); return CommonResult.success(null); } @ApiOperation("分页获取用户浏览记录") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<MemberReadHistory>> list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) { Page<MemberReadHistory> page = memberReadHistoryService.list(pageNum, pageSize); return CommonResult.success(CommonPage.restPage(page)); } }
package com.macro.mall.portal.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.model.PmsProduct; import com.macro.mall.portal.domain.PmsPortalProductDetail; import com.macro.mall.portal.domain.PmsProductCategoryNode; import com.macro.mall.portal.service.PmsPortalProductService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 前台商品管理Controller * Created by macro on 2020/4/6. */ @Controller @Api(tags = "PmsPortalProductController", description = "前台商品管理") @RequestMapping("/product") public class PmsPortalProductController { @Autowired private PmsPortalProductService portalProductService; @ApiOperation(value = "综合搜索、筛选、排序") @ApiImplicitParam(name = "sort", value = "排序字段:0->按相关度;1->按新品;2->按销量;3->价格从低到高;4->价格从高到低", defaultValue = "0", allowableValues = "0,1,2,3,4", paramType = "query", dataType = "integer") @RequestMapping(value = "/search", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsProduct>> search(@RequestParam(required = false) String keyword, @RequestParam(required = false) Long brandId, @RequestParam(required = false) Long productCategoryId, @RequestParam(required = false, defaultValue = "0") Integer pageNum, @RequestParam(required = false, defaultValue = "5") Integer pageSize, @RequestParam(required = false, defaultValue = "0") Integer sort) { List<PmsProduct> productList = portalProductService.search(keyword, brandId, productCategoryId, pageNum, pageSize, sort); return CommonResult.success(CommonPage.restPage(productList)); } @ApiOperation("以树形结构获取所有商品分类") @RequestMapping(value = "/categoryTreeList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProductCategoryNode>> categoryTreeList() { List<PmsProductCategoryNode> list = portalProductService.categoryTreeList(); return CommonResult.success(list); } @ApiOperation("获取前台商品详情") @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsPortalProductDetail> detail(@PathVariable Long id) { PmsPortalProductDetail productDetail = portalProductService.detail(id); return CommonResult.success(productDetail); } }
package com.macro.mall.search.controller; import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonResult; import com.macro.mall.search.domain.EsProduct; import com.macro.mall.search.domain.EsProductRelatedInfo; import com.macro.mall.search.service.EsProductService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 搜索商品管理Controller * Created by macro on 2018/6/19. */ @Controller @Api(tags = "EsProductController", description = "搜索商品管理") @RequestMapping("/esProduct") public class EsProductController { @Autowired private EsProductService esProductService; @ApiOperation(value = "导入所有数据库中商品到ES") @RequestMapping(value = "/importAll", method = RequestMethod.POST) @ResponseBody public CommonResult<Integer> importAllList() { int count = esProductService.importAll(); return CommonResult.success(count); } @ApiOperation(value = "根据id删除商品") @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<Object> delete(@PathVariable Long id) { esProductService.delete(id); return CommonResult.success(null); } @ApiOperation(value = "根据id批量删除商品") @RequestMapping(value = "/delete/batch", method = RequestMethod.POST) @ResponseBody public CommonResult<Object> delete(@RequestParam("ids") List<Long> ids) { esProductService.delete(ids); return CommonResult.success(null); } @ApiOperation(value = "根据id创建商品") @RequestMapping(value = "/create/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult<EsProduct> create(@PathVariable Long id) { EsProduct esProduct = esProductService.create(id); if (esProduct != null) { return CommonResult.success(esProduct); } else { return CommonResult.failed(); } } @ApiOperation(value = "简单搜索") @RequestMapping(value = "/search/simple", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<EsProduct>> search(@RequestParam(required = false) String keyword, @RequestParam(required = false, defaultValue = "0") Integer pageNum, @RequestParam(required = false, defaultValue = "5") Integer pageSize) { Page<EsProduct> esProductPage = esProductService.search(keyword, pageNum, pageSize); return CommonResult.success(CommonPage.restPage(esProductPage)); } @ApiOperation(value = "综合搜索、筛选、排序") @ApiImplicitParam(name = "sort", value = "排序字段:0->按相关度;1->按新品;2->按销量;3->价格从低到高;4->价格从高到低", defaultValue = "0", allowableValues = "0,1,2,3,4", paramType = "query", dataType = "integer") @RequestMapping(value = "/search", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<EsProduct>> search(@RequestParam(required = false) String keyword, @RequestParam(required = false) Long brandId, @RequestParam(required = false) Long productCategoryId, @RequestParam(required = false, defaultValue = "0") Integer pageNum, @RequestParam(required = false, defaultValue = "5") Integer pageSize, @RequestParam(required = false, defaultValue = "0") Integer sort) { Page<EsProduct> esProductPage = esProductService.search(keyword, brandId, productCategoryId, pageNum, pageSize, sort); return CommonResult.success(CommonPage.restPage(esProductPage)); } @ApiOperation(value = "根据商品id推荐商品") @RequestMapping(value = "/recommend/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<EsProduct>> recommend(@PathVariable Long id, @RequestParam(required = false, defaultValue = "0") Integer pageNum, @RequestParam(required = false, defaultValue = "5") Integer pageSize) { Page<EsProduct> esProductPage = esProductService.recommend(id, pageNum, pageSize); return CommonResult.success(CommonPage.restPage(esProductPage)); } @ApiOperation(value = "获取搜索的相关品牌、分类及筛选属性") @RequestMapping(value = "/search/relate", method = RequestMethod.GET) @ResponseBody public CommonResult<EsProductRelatedInfo> searchRelatedInfo(@RequestParam(required = false) String keyword) { EsProductRelatedInfo productRelatedInfo = esProductService.searchRelatedInfo(keyword); return CommonResult.success(productRelatedInfo); } }
/** * @(#)FacadeController.java, 2018-12-31. * * Copyright 2018 Stalary. */ package com.stalary.pf.outside.controller; import com.stalary.pf.outside.data.Email; import com.stalary.pf.outside.data.ResponseMessage; import com.stalary.pf.outside.service.MailService; import com.stalary.pf.outside.service.SmsService; import com.stalary.pf.outside.service.UserService; import com.stalary.pf.outside.util.UserUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; /** * OutsideController * * @description 外部调用接口 * @author lirongqian * @since 2018/12/31 */ @RestController @RequestMapping("/outside") public class OutsideController { @Resource private SmsService smsService; @Resource private UserService userService; @Resource private MailService mailService; /** * @method code 发送短信验证码的接口 * @param phone 手机号 **/ @GetMapping("/code") public ResponseMessage code( @RequestParam String phone) { String code = smsService.sendCode(phone); if (StringUtils.isNotEmpty(code)) { return ResponseMessage.successMessage("发送成功"); } else { return ResponseMessage.failedMessage("发送失败"); } } /** * @method upload 上传用户头像 * @param avatar 头像 **/ @PostMapping("/avatar") public ResponseMessage upload( HttpServletRequest request, @RequestParam("avatar") MultipartFile avatar) { Long userId = UserUtil.getUserId(request); return userService.uploadAvatar(userId, avatar); } @PostMapping("/email") public ResponseMessage sendEmail( @RequestBody Email email) { mailService.sendEmail(email.getEmail(), email.getTitle(), email.getContent()); return ResponseMessage.successMessage("邮件发送成功"); } }
package com.stalary.pf.user.controller; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.stalary.pf.user.annotation.LoginRequired; import com.stalary.pf.user.client.MessageClient; import com.stalary.pf.user.data.constant.Constant; import com.stalary.pf.user.data.dto.*; import com.stalary.pf.user.data.entity.UserInfoEntity; import com.stalary.pf.user.data.vo.LoginVo; import com.stalary.pf.user.data.vo.ResponseMessage; import com.stalary.pf.user.holder.IpHolder; import com.stalary.pf.user.holder.UserHolder; import com.stalary.pf.user.service.ClientService; import com.stalary.pf.user.service.UserInfoService; import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.List; import java.util.Map; /** * UserController * @description 用户相关接口 * @author lirongqian * @since 2019/01/01 */ @RestController @RequestMapping("/user") public class UserController { @Resource private UserInfoService userInfoService; @Resource private ClientService clientService; @Resource private MessageClient messageClient; /** * @method register 求职者注册 * @param applicant 求职者对象 * @return 0 token **/ @PostMapping public ResponseMessage register( @RequestBody Applicant applicant) { return clientService.postUser(applicant, Constant.REGISTER); } /** * @method login 传入登陆对象,仅需要用户名和密码 * @param user 用户对象 * @return LoginVo 登陆对象 **/ @PostMapping("/login") public ResponseMessage login(@RequestBody User user) { ResponseMessage responseMessage = clientService.postUser(user, Constant.LOGIN); if (!responseMessage.isSuccess()) { return responseMessage; } String token = responseMessage.getData().toString(); User getUser = clientService.getUser(token); LoginVo loginVo = new LoginVo(token, getUser.getRole(), getUser.getId(), getUser.getFirstId()); messageClient.sendCount(getUser.getId()); return ResponseMessage.successMessage(loginVo); } /** * @method hrRegister hr注册 * @param hr hr对象 * @return 0 token **/ @PostMapping("/hr") public ResponseMessage hrRegister( @RequestBody HR hr) { return clientService.postUser(hr, Constant.REGISTER); } /** * @method logout 退出登录 * @return 0 退出成功 **/ @GetMapping("/logout") @LoginRequired public ResponseMessage logout() { return ResponseMessage.successMessage("退出成功"); } /** * @method getInfo header中带入token获取用户信息 * @return UserInfo 用户信息 **/ @GetMapping @LoginRequired public ResponseMessage getInfo() { return ResponseMessage.successMessage(userInfoService.getInfo()); } @GetMapping("/info") public ResponseMessage getInfoByUserId( @RequestParam Long userId) { return ResponseMessage.successMessage(userInfoService.getInfoByUserId(userId)); } /** * @method updateInfo 修改用户信息 * @param userInfo 用户信息对象 * @return UserInfo 用户信息 **/ @PutMapping("/info") @LoginRequired public ResponseMessage updateInfo( @RequestBody UserInfoEntity userInfo) { User user = UserHolder.get(); userInfo.setUserId(user.getId()); userInfo.setUsername(user.getUsername()); return ResponseMessage.successMessage(userInfoService.save(userInfo)); } /** * @method updatePhone 修改手机号 * @param params 手机号 */ @PutMapping("/phone") @LoginRequired public ResponseMessage updatePhone( @RequestBody Map<String, String> params) { User user = UserHolder.get(); user.setPhone(params.get("phone")); return clientService.postUser(user, Constant.UPDATE); } /** * @method updatePassword 修改密码,通过新密码进行修改 * @param params 新密码 */ @PutMapping("/password") @LoginRequired public ResponseMessage updatePassword( @RequestBody Map<String, String> params) { User user = UserHolder.get(); user.setPassword(params.get("password")); return clientService.postUser(user, Constant.UPDATE_PASSWORD); } /** * @method forgetPassword 忘记密码,通过用户名,手机号,新密码进行修改 * @param params 参数 **/ @PostMapping("/password") public ResponseMessage forgetPassword( @RequestBody Map<String, String> params) { User user = new User(); user.setPassword(params.get("password")); user.setUsername(params.get("username")); user.setPhone(params.get("phone")); return clientService.postUser(user, Constant.UPDATE_PASSWORD); } /** * @method updateEmail 修改邮箱 * @param params 邮箱 */ @PutMapping("/email") @LoginRequired public ResponseMessage updateEmail( @RequestBody Map<String, String> params) { User user = UserHolder.get(); user.setEmail(params.get("email")); return clientService.postUser(user, Constant.UPDATE); } /** * @method token 使用token获取用户信息 * @param token token * @return User 用户信息 **/ @GetMapping("/token") public ResponseMessage token( @RequestParam String token) { return ResponseMessage.successMessage(clientService.getUser(token)); } /** * @method getSendList 查看个人投递列表 * @return SendInfo 投递信息 **/ @GetMapping("/send") @LoginRequired public ResponseMessage getSendList() { return ResponseMessage.successMessage(userInfoService.getSendList()); } /** * @method getReceiveList 查看获取的简历列表 * @return ReceiveInfo 简历信息 **/ @GetMapping("/receive") @LoginRequired public ResponseMessage getReceiveList() { return ResponseMessage.successMessage(userInfoService.getReceiveList()); } ///////////////////////// 内部服务使用的接口 ////////////////////////////////// @PostMapping("/avatar") public ResponseMessage uploadAvatar( @RequestBody UploadAvatar uploadAvatar) { boolean flag = userInfoService.uploadAvatar(uploadAvatar); if (flag) { return ResponseMessage.successMessage("上传头像成功"); } else { return ResponseMessage.failedMessage("上传头像失败"); } } @GetMapping("/recommend") public ResponseMessage getRecommendUser( @RequestParam String param) { List<CompanyAndJob> companyAndJobList = JSONObject.parseObject(param, new TypeReference<List<CompanyAndJob>>() { }); return ResponseMessage.successMessage(userInfoService.getRecommendUser(companyAndJobList)); } @GetMapping("/email") public ResponseMessage getEmail( @RequestParam Long userId) { return ResponseMessage.successMessage(clientService.getUser(userId).getEmail()); } @GetMapping("/userId") public ResponseMessage getUserById(@RequestParam Long userId) { return ResponseMessage.successMessage(clientService.getUser(userId)); } }
package top.quhailong.pan.core.page.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StopWatch; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import top.quhailong.pan.core.page.provider.PageProvider; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @Controller @CrossOrigin public class PageController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private HttpServletRequest httpServletRequest; @Autowired private PageProvider pageProvider; /** * 首页跳转 * * @author: quhailong * @date: 2019/9/27 */ @RequestMapping("/") public String index() { logger.info("首页跳转请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("首页跳转数据处理开始"); String resultUrl = pageProvider.indexHandle(); logger.info("首页跳转数据处理结束,resultUrl:{}", resultUrl); stopWatch.stop(); logger.info("首页跳转调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return resultUrl; } /** * 跳转到主页面 * * @author: quhailong * @date: 2019/9/27 */ @RequestMapping("/disk/home") public String home(Model model) { logger.info("跳转到主页面请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("跳转到主页面数据处理开始"); String resultUrl = pageProvider.homeHandle(model); logger.info("跳转到主页面数据处理结束,resultUrl:{}", resultUrl); stopWatch.stop(); logger.info("跳转到主页面调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return resultUrl; } /** * 跳转到分享管理页面 * * @author: quhailong * @date: 2019/9/27 */ @RequestMapping("/share/manage") public String share(Model model) { logger.info("跳转到分享管理页面请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("跳转到分享管理页面数据处理开始"); String resultUrl = pageProvider.shareHandle(model); logger.info("跳转到分享管理页面数据处理结束,resultUrl:{}", resultUrl); stopWatch.stop(); logger.info("跳转到分享管理页面调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return resultUrl; } /** * 查看分享页面 * * @author: quhailong * @date: 2019/9/27 */ @RequestMapping("/s/{shareId}") public String s(Model model, @PathVariable String shareId) { logger.info("查看分享页面请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("查看分享页面数据处理开始"); String resultUrl = pageProvider.sHandle(model, shareId); logger.info("查看分享页面数据处理结束,resultUrl:{}", resultUrl); stopWatch.stop(); logger.info("查看分享页面调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return resultUrl; } }
package top.quhailong.pan.core.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StopWatch; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import top.quhailong.pan.core.provider.CapacityProvider; import top.quhailong.pan.utils.RestAPIResult; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; /** * 容量服务 * * @author: quhailong * @date: 2019/9/24 */ @RestController public class CapacityController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private HttpServletRequest httpServletRequest; @Autowired private CapacityProvider capacityProvider; /** * 查询使用容量 * * @author: quhailong * @date: 2019/9/24 */ //@RequestMapping(value = "use", method = {RequestMethod.POST}) @RequestMapping(value = "usecapacity", method = RequestMethod.GET) public RestAPIResult<String> useCapacity(String uid) { logger.info("查询使用容量请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("查询使用容量数据处理开始,uid:{}", uid); RestAPIResult<String> result = capacityProvider.useCapacityHandle(uid); logger.info("查询使用容量数据处理结束,result:{}", result); stopWatch.stop(); logger.info("查询使用容量调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 初始化容量 * * @author: quhailong * @date: 2019/9/25 */ @RequestMapping(value = "initcapacity", method = RequestMethod.POST) public RestAPIResult<Integer> initCapacity(@RequestParam("userId") String userId) { logger.info("初始化容量请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("初始化容量数据处理开始,userId:{}", userId); RestAPIResult<Integer> result = capacityProvider.initCapacityHandle(userId); logger.info("初始化容量数据处理结束,result:{}", result); stopWatch.stop(); logger.info("初始化容量调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } }
package top.quhailong.pan.core.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.util.StopWatch; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import top.quhailong.pan.core.provider.QueryContentProvider; import top.quhailong.pan.request.CheckDirWhetherRequest; import top.quhailong.pan.request.ListFileRequest; import top.quhailong.pan.request.ListFolderRequest; import top.quhailong.pan.request.SearchFileRequest; import top.quhailong.pan.response.VirtualAddressDTO; import top.quhailong.pan.utils.RestAPIResult; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; /** * 查询服务 * * @author: quhailong * @date: 2019/9/24 */ @RestController //@RequestMapping("api") public class QueryContentController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private HttpServletRequest httpServletRequest; @Autowired private QueryContentProvider queryContentProvider; /** * 查询文件列表 * * @author: quhailong * @date: 2019/9/24 */ //@RequestMapping(value = "list", method = { RequestMethod.POST }) @RequestMapping(value = "listfile", method = RequestMethod.GET) public RestAPIResult<String> listFile(ListFileRequest request) throws UnsupportedEncodingException { logger.info("查询文件列表请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("查询文件列表数据处理开始,request:{}", request); RestAPIResult<String> result = queryContentProvider.listFileHandle(request); logger.info("查询文件列表数据处理结束,result:{}", result); stopWatch.stop(); logger.info("查询文件列表调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 展示文件夹列表 * * @author: quhailong * @date: 2019/9/24 */ //@RequestMapping(value = "folderList", method = {RequestMethod.POST}) @RequestMapping(value = "listfolder", method = RequestMethod.GET) public RestAPIResult<String> listFolder(ListFolderRequest request) throws Exception { logger.info("展示文件夹列表请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("展示文件夹列表数据处理开始,request:{}", request); RestAPIResult<String> result = queryContentProvider.listFolderHandle(request); logger.info("展示文件夹列表数据处理结束,result:{}", result); stopWatch.stop(); logger.info("展示文件夹列表调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 搜索文件 * * @author: quhailong * @date: 2019/9/24 */ //@RequestMapping(value = "search", method = {RequestMethod.POST}) @RequestMapping(value = "searchfile", method = RequestMethod.GET) public RestAPIResult<String> searchFile(SearchFileRequest request) { logger.info("搜索文件请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("搜索文件数据处理开始,request:{}", request); RestAPIResult<String> result = queryContentProvider.searchFileHandle(request); logger.info("搜索文件数据处理结束,result:{}", result); stopWatch.stop(); logger.info("搜索文件调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 查询文件夹是否存在(调用) * * @author: quhailong * @date: 2019/9/25 */ @RequestMapping(value = "checkdirwhether", method = RequestMethod.GET) public RestAPIResult<Integer> checkDirWhether(CheckDirWhetherRequest request) { logger.info("查询文件夹是否存在请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("查询文件夹是否存在数据处理开始,request:{}", request); RestAPIResult<Integer> result = queryContentProvider.checkDirWhetherHandle(request); logger.info("查询文件夹是否存在数据处理结束,result:{}", result); stopWatch.stop(); logger.info("查询文件夹是否存在调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 根据虚拟地址ID获取文件名称(调用) * * @author: quhailong * @date: 2019/9/25 */ @RequestMapping(value = "getfilenamebyvid", method = RequestMethod.GET) public RestAPIResult<String> getFileNameByVid(String vid, String uid) { logger.info("根据虚拟地址ID获取文件名称请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("根据虚拟地址ID获取文件名称数据处理开始,vid:{}", vid); RestAPIResult<String> result = queryContentProvider.getFileNameByVidHandle(vid, uid); logger.info("根据虚拟地址ID获取文件名称数据处理结束,result:{}", result); stopWatch.stop(); logger.info("根据虚拟地址ID获取文件名称调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 根据虚拟地址ID获取实体 * * @author: quhailong * @date: 2019/9/25 */ @RequestMapping(value = "getvirtualaddress", method = RequestMethod.GET) public RestAPIResult<VirtualAddressDTO> getVirtualaddress(String vid, String uid) { logger.info("根据虚拟地址ID获取实体请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("根据虚拟地址ID获取实体数据处理开始,vid:{}", vid); RestAPIResult<VirtualAddressDTO> result = queryContentProvider.getVirtualaddressHandle(vid, uid); logger.info("根据虚拟地址ID获取实体数据处理结束,result:{}", result); stopWatch.stop(); logger.info("根据虚拟地址ID获取实体调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } }
package top.quhailong.pan.core.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StopWatch; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import top.quhailong.pan.core.provider.UpdateContentProvider; import top.quhailong.pan.request.CopyOrMoveFileRequest; import top.quhailong.pan.request.CreateDirRequest; import top.quhailong.pan.request.CreateVirtualAddressRequest; import top.quhailong.pan.request.RenameFileOrDirRequest; import top.quhailong.pan.utils.RestAPIResult; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; /** * 更新服务 * * @author: quhailong * @date: 2019/9/24 */ @RestController public class UpdateContentController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private HttpServletRequest httpServletRequest; @Autowired private UpdateContentProvider updateContentProvider; /** * 文件或文件夹重命名 * * @author: quhailong * @date: 2019/9/24 */ //@RequestMapping(value = "rename", method = { RequestMethod.POST }) @RequestMapping(value = "renamefileordir", method = RequestMethod.PUT) public RestAPIResult<String> renameFileOrDir(@RequestBody RenameFileOrDirRequest request) { logger.info("文件或文件夹重命名请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("文件或文件夹重命名数据处理开始,request:{}", request); RestAPIResult<String> result = updateContentProvider.renameFileOrDirHandle(request); logger.info("文件或文件夹重命名数据处理结束,result:{}", result); stopWatch.stop(); logger.info("文件或文件夹重命名调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 删除文件 * * @author: quhailong * @date: 2019/9/24 */ //@RequestMapping(value = "del", method = { RequestMethod.POST }) @RequestMapping(value = "deletefile", method = RequestMethod.DELETE) public RestAPIResult<String> deleteFile(String uid, String vids) throws Exception { logger.info("删除文件请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("删除文件数据处理开始,vids:{}", vids); RestAPIResult<String> result = updateContentProvider.deleteFileHandle(vids); logger.info("删除文件数据处理结束,result:{}", result); stopWatch.stop(); logger.info("删除文件调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 创建文件夹 * * @author: quhailong * @date: 2019/9/24 */ //@RequestMapping("/createDir") @RequestMapping(value = "createdir", method = RequestMethod.POST) public RestAPIResult<String> createDir(@RequestBody CreateDirRequest request) { logger.info("创建文件夹请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("创建文件夹数据处理开始,request:{}", request); RestAPIResult<String> result = updateContentProvider.createDirHandle(request); logger.info("创建文件夹数据处理结束,result:{}", result); stopWatch.stop(); logger.info("创建文件夹调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 文件复制或移动 * * @author: quhailong * @date: 2019/9/24 */ //@RequestMapping(value = "filemanager", method = { RequestMethod.POST }) @RequestMapping(value = "copyormovefile", method = RequestMethod.PUT) public RestAPIResult<String> copyOrMoveFile(@RequestBody CopyOrMoveFileRequest request) { logger.info("文件复制或移动请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("文件复制或移动数据处理开始,request:{}", request); RestAPIResult<String> result = updateContentProvider.copyOrMoveFileHandle(request); logger.info("文件复制或移动数据处理结束,result:{}", result); stopWatch.stop(); logger.info("文件复制或移动调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 创建文件(调用) * * @author: quhailong * @date: 2019/9/25 */ @RequestMapping(value = "createvirtualaddress", method = RequestMethod.POST) public RestAPIResult<Integer> createVirtualAddress(@RequestBody CreateVirtualAddressRequest request) { logger.info("创建文件请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("创建文件数据处理开始,request:{}", request); RestAPIResult<Integer> result = updateContentProvider.createVirtualAddressHandle(request); logger.info("创建文件数据处理结束,result:{}", result); stopWatch.stop(); logger.info("创建文件调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } }
package top.quhailong.pan.edge.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StopWatch; import org.springframework.web.bind.annotation.*; import top.quhailong.pan.edge.provider.EdgeServiceProvider; import top.quhailong.pan.utils.RestAPIResult; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.UUID; @RestController public class EdgeServiceController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private HttpServletRequest httpServletRequest; @Autowired private EdgeServiceProvider edgeServiceProvider; /** * 生成公钥 * * @author: quhailong * @date: 2019/9/26 */ //@RequestMapping(value = "getPublickKey", method = {RequestMethod.GET}) @RequestMapping(value = "getpublickey", method = RequestMethod.GET) public RestAPIResult<String> getPublicKey() throws Exception { logger.info("生成公钥请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("生成公钥数据处理开始"); RestAPIResult<String> result = edgeServiceProvider.getPublicKeyHandle(); logger.info("生成公钥数据处理结束,result:{}", result); stopWatch.stop(); logger.info("生成公钥调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 生成验证码 * * @author: quhailong * @date: 2019/9/26 */ @RequestMapping(value = "getverfyimg/{vcodestr}", method = RequestMethod.GET) public void getVerfyImg(@PathVariable(value = "vcodestr") String vcodestr, HttpServletResponse response) { logger.info("生成验证码请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("生成验证码数据处理开始"); edgeServiceProvider.getVerfyImgHandle(vcodestr, response); logger.info("生成验证码数据处理结束"); stopWatch.stop(); logger.info("生成验证码调用时间,millies:{}", stopWatch.getTotalTimeMillis()); } /** * 检查密码格式 * * @author: quhailong * @date: 2019/9/26 */ @RequestMapping(value = "regcheckpwd", method = RequestMethod.POST) public RestAPIResult<String> regCheckPwd(@RequestParam("password") String password, @RequestParam("RSAKey") String RSAKey) { logger.info("检查密码格式请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("检查密码格式数据处理开始"); RestAPIResult<String> result = edgeServiceProvider.regCheckPwdHandle(password, RSAKey); logger.info("检查密码格式数据处理结束,result:{}", result); stopWatch.stop(); logger.info("检查密码格式调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 变换图片的UUID * * @author: quhailong * @date: 2019/9/26 */ //@RequestMapping("/regsmscodestr") @RequestMapping(value = "/regsmscodestr", method = RequestMethod.GET) public RestAPIResult<String> regsmscodestr() { RestAPIResult<String> panResult = new RestAPIResult<>(); logger.info("变换图片的UUID请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); panResult.setRespCode(1); panResult.setRespData(UUID.randomUUID().toString().replaceAll("-", "")); stopWatch.stop(); logger.info("变换图片的UUID调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return panResult; } }
package top.quhailong.pan.edge.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StopWatch; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import top.quhailong.pan.edge.provider.SendSmsProvider; import top.quhailong.pan.request.SendSmsRequest; import top.quhailong.pan.utils.RestAPIResult; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @RestController public class SendSmsController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private HttpServletRequest httpServletRequest; @Autowired private SendSmsProvider sendSmsProvider; /** * 发送短信 * * @author: quhailong * @date: 2019/9/26 */ //@RequestMapping("/api/sendSms") @RequestMapping(value = "sendSms", method = RequestMethod.POST) public RestAPIResult<String> sendSms(@RequestBody SendSmsRequest request) { logger.info("发送短信请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("发送短信数据处理开始"); RestAPIResult<String> result = sendSmsProvider.sendSmsHandle(request); logger.info("发送短信数据处理结束,result:{}", result); stopWatch.stop(); logger.info("发送短信调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } }
package top.quhailong.pan.file.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StopWatch; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import top.quhailong.pan.file.provider.DownloadProvider; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 下载文件 * * @author: quhailong * @date: 2019/9/25 */ @RestController public class DownloadController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private HttpServletRequest httpServletRequest; @Autowired private DownloadProvider downloadProvider; /** * 下载文件 * * @author: quhailong * @date: 2019/9/25 */ //@RequestMapping(value = "/download", method = RequestMethod.POST) @RequestMapping(value = "download", method = RequestMethod.GET) public void download(String uid, String vids, HttpServletResponse res) throws IOException { logger.info("下载文件请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("下载文件数据处理开始,vids:{}", vids); downloadProvider.downloadHandle(uid, vids, res); logger.info("下载文件数据处理结束"); stopWatch.stop(); logger.info("下载文件调用时间,millies:{}", stopWatch.getTotalTimeMillis()); } /** * 下载分享文件 * * @author: quhailong * @date: 2019/9/26 */ //@RequestMapping(value = "/downloadShare", method = RequestMethod.POST) @RequestMapping(value = "downloadshare", method = RequestMethod.GET) public void downloadShare(String lockPassword, String shareId, HttpServletResponse res) throws IOException { logger.info("下载分享文件请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("下载分享文件数据处理开始,shareId:{}", shareId); downloadProvider.downloadShareHandle(lockPassword, shareId, res); logger.info("下载分享文件数据处理结束"); stopWatch.stop(); logger.info("下载分享文件调用时间,millies:{}", stopWatch.getTotalTimeMillis()); } }
package top.quhailong.pan.file.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StopWatch; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import top.quhailong.pan.file.provider.Md5Provider; import top.quhailong.pan.utils.RestAPIResult; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; /** * Md5服务 * * @author: quhailong * @date: 2019/9/25 */ @RestController public class Md5Controller { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private HttpServletRequest httpServletRequest; @Autowired private Md5Provider md5Provider; /** * Md5校验服务 * * @author: quhailong * @date: 2019/9/25 */ //@RequestMapping(value = "md5check" , method = { RequestMethod.POST }) @RequestMapping(value = "md5check", method = RequestMethod.GET) public RestAPIResult<String> md5Check(String fid, String md5) { logger.info("Md5校验服务请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("Md5校验服务数据处理开始,md5:{}", md5); RestAPIResult<String> result = md5Provider.md5CheckHandle(fid, md5); logger.info("Md5校验服务数据处理结束,result:{}", result); stopWatch.stop(); logger.info("Md5校验服务调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } }
package top.quhailong.pan.file.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StopWatch; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import top.quhailong.pan.file.provider.UploadFileProvider; import top.quhailong.pan.request.QuickUploadFileRequest; import top.quhailong.pan.request.UploadFileRequest; import top.quhailong.pan.utils.RestAPIResult; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.UnsupportedEncodingException; /** * 上传文件服务 * * @author: quhailong * @date: 2019/9/25 */ @RestController public class UploadFileController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private HttpServletRequest httpServletRequest; @Autowired private UploadFileProvider uploadFileProvider; /** * 上传文件 * * @author: quhailong * @date: 2019/9/25 */ //@RequestMapping("/uploadFile") // new annotation since 4.3 @RequestMapping(value = "uploadfile", method = RequestMethod.POST) public RestAPIResult<String> uploadFile(UploadFileRequest request) throws IOException { logger.info("上传文件请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("上传文件数据处理开始,request:{}", request); RestAPIResult<String> result = uploadFileProvider.uploadFileHandle(request); logger.info("上传文件数据处理结束,result:{}", result); stopWatch.stop(); logger.info("上传文件调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 秒传文件 * * @author: quhailong * @date: 2019/9/25 */ //@RequestMapping("/uploadFileSpe") // new annotation since 4.3 @RequestMapping(value = "quickuploadfile", method = RequestMethod.POST) public RestAPIResult<String> quickUploadFile(QuickUploadFileRequest request) throws UnsupportedEncodingException { logger.info("秒传文件请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("秒传文件数据处理开始,request:{}", request); RestAPIResult<String> result = uploadFileProvider.quickUploadFileHandle(request); logger.info("秒传文件数据处理结束,result:{}", result); stopWatch.stop(); logger.info("秒传文件调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 上传文件(内部调用) * * @author: quhailong * @date: 2019/9/26 */ @RequestMapping(value = "upload", method = RequestMethod.POST) public RestAPIResult<String> upload(MultipartFile file) throws IOException { logger.info("上传文件(内部调用)请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("上传文件(内部调用)数据处理开始"); RestAPIResult<String> result = uploadFileProvider.uploadHandle(file); logger.info("上传文件(内部调用)数据处理结束,result:{}", result); stopWatch.stop(); logger.info("上传文件调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } }
package top.quhailong.pan.share.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StopWatch; import org.springframework.web.bind.annotation.*; import top.quhailong.pan.request.AddShareViewCountRequest; import top.quhailong.pan.request.SaveShareRequest; import top.quhailong.pan.request.ShareListRequest; import top.quhailong.pan.request.ShareRequest; import top.quhailong.pan.share.provider.ShareProvider; import top.quhailong.pan.utils.RestAPIResult; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @RestController public class ShareController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private HttpServletRequest httpServletRequest; @Autowired private ShareProvider shareProvider; /** * 分享文件 * * @author: quhailong * @date: 2019/9/26 */ @RequestMapping(value = "share", method = RequestMethod.POST) public RestAPIResult<String> share(@RequestBody ShareRequest request) { logger.info("分享文件请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("分享文件数据处理开始,request:{}", request); RestAPIResult<String> result = shareProvider.shareHandle(request); logger.info("分享文件数据处理结束,result:{}", result); stopWatch.stop(); logger.info("分享文件调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 获取分享列表 * * @author: quhailong * @date: 2019/9/26 */ //@RequestMapping(value = "shareList", method = {RequestMethod.POST}) @RequestMapping(value = "sharelist", method = RequestMethod.GET) public RestAPIResult<String> shareList(ShareListRequest request) { logger.info("获取分享列表请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("获取分享列表数据处理开始,request:{}", request); RestAPIResult<String> result = shareProvider.shareListHandle(request); logger.info("获取分享列表数据处理结束,result:{}", result); stopWatch.stop(); logger.info("获取分享列表调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 取消分享 * * @author: quhailong * @date: 2019/9/26 */ //@RequestMapping(value = "unShare", method = {RequestMethod.POST}) @RequestMapping(value = "unshare", method = RequestMethod.GET) public RestAPIResult<String> unShare(String uid, String vids) { logger.info("取消分享请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("取消分享数据处理开始,vids:{}", vids); RestAPIResult<String> result = shareProvider.unShareHandle(uid, vids); logger.info("取消分享数据处理结束,result:{}", result); stopWatch.stop(); logger.info("取消分享调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 获取分享用户信息 * * @author: quhailong * @date: 2019/9/26 */ //@RequestMapping(value = "getShareUser", method = {RequestMethod.POST}) @RequestMapping(value = "getshareuser", method = RequestMethod.GET) public RestAPIResult<String> getShareUser(String shareId) { logger.info("获取分享用户信息请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("获取分享用户信息数据处理开始,shareId:{}", shareId); RestAPIResult<String> result = shareProvider.getShareUserHandle(shareId); logger.info("获取分享用户信息数据处理结束,result:{}", result); stopWatch.stop(); logger.info("获取分享用户信息调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 保存分享 * * @author: quhailong * @date: 2019/9/26 */ //@RequestMapping(value = "saveShare", method = {RequestMethod.POST}) @RequestMapping(value = "saveshare", method = RequestMethod.POST) public RestAPIResult<String> saveShare(@RequestBody SaveShareRequest request) { logger.info("保存分享请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("保存分享数据处理开始,request:{}", request); RestAPIResult<String> result = shareProvider.saveShareHandle(request); logger.info("保存分享数据处理结束,result:{}", result); stopWatch.stop(); logger.info("保存分享调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 查询分享是否带密码 * * @author: quhailong * @date: 2019/9/26 */ //@RequestMapping(value = "checkLock", method = {RequestMethod.POST}) @RequestMapping(value = "checklock", method = RequestMethod.GET) public RestAPIResult<String> checkLock(@RequestParam("shareId") String shareId) { logger.info("查询分享是否带密码请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("查询分享是否带密码数据处理开始,shareId:{}", shareId); RestAPIResult<String> result = shareProvider.checkLockHandle(shareId); logger.info("查询分享是否带密码数据处理结束,result:{}", result); stopWatch.stop(); logger.info("查询分享是否带密码调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 验证分享密码 * * @author: quhailong * @date: 2019/9/26 */ //@RequestMapping(value = "verifykLock", method = {RequestMethod.POST}) @RequestMapping(value = "verifyklock", method = RequestMethod.GET) public RestAPIResult<String> verifykLock(@RequestParam("lockPassword") String lockPassword, @RequestParam("shareId") String shareId) { logger.info("验证分享密码请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("验证分享密码数据处理开始,shareId:{}", shareId); RestAPIResult<String> result = shareProvider.verifykLockHandle(lockPassword, shareId); logger.info("验证分享密码数据处理结束,result:{}", result); stopWatch.stop(); logger.info("验证分享密码调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 获取分享虚拟地址信息 * * @author: quhailong * @date: 2019/9/26 */ //@RequestMapping(value = "getVinfo", method = {RequestMethod.POST}) @RequestMapping(value = "getvinfo", method = RequestMethod.GET) public RestAPIResult<String> getUid(@RequestParam("shareId") String shareId, @RequestParam("lockPassword") String lockPassword) { logger.info("获取分享虚拟地址信息请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("获取分享虚拟地址信息数据处理开始,shareId:{}", shareId); RestAPIResult<String> result = shareProvider.getVinfoHandle(shareId, lockPassword); logger.info("获取分享虚拟地址信息数据处理结束,result:{}", result); stopWatch.stop(); logger.info("获取分享虚拟地址信息调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 增加分享访问量 * * @author: quhailong * @date: 2019/9/26 */ //@RequestMapping(value = "addShareView", method = {RequestMethod.POST}) @RequestMapping(value = "addshareview", method = RequestMethod.POST) public void addShareView(@RequestBody AddShareViewCountRequest request) { logger.info("增加分享访问量请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("增加分享访问量数据处理开始,request:{}", request); shareProvider.addShareViewCountHandle(request); logger.info("增加分享访问量数据处理结束"); stopWatch.stop(); logger.info("增加分享访问量调用时间,millies:{}", stopWatch.getTotalTimeMillis()); } /** * 增加分享下载量 * * @author: quhailong * @date: 2019/9/26 */ //@RequestMapping(value = "addShareDownload", method = {RequestMethod.POST}) @RequestMapping(value = "addsharedownload", method = {RequestMethod.POST}) public void addShareDownload(@RequestParam("shareId") String shareId) { logger.info("增加分享下载量请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("增加分享下载量数据处理开始,shareId:{}", shareId); shareProvider.addShareDownloadCountHandle(shareId); logger.info("增加分享下载量数据处理结束"); stopWatch.stop(); logger.info("增加分享下载量调用时间,millies:{}", stopWatch.getTotalTimeMillis()); } }
package top.quhailong.pan.user.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StopWatch; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import top.quhailong.pan.response.UserInfoDTO; import top.quhailong.pan.user.service.PassportService; import top.quhailong.pan.utils.RestAPIResult; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @RestController public class PassportController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private HttpServletRequest httpServletRequest; @Autowired private PassportService passportService; /** * 登录请求 * * @author: quhailong * @date: 2019/9/25 */ @RequestMapping(value = "login", method = RequestMethod.POST) public RestAPIResult<String> login(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("RSAKey") String RSAKey) throws Exception { logger.info("登录请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("登录数据处理开始,username:{}", username); RestAPIResult<String> result = passportService.loginHandle(username, password, RSAKey); logger.info("登录数据处理结束,result:{}", result); stopWatch.stop(); logger.info("登录调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 退出 * * @param token * @return */ @RequestMapping(value = "logout", method = RequestMethod.GET) public RestAPIResult<String> logout(@RequestParam("token") String token) { logger.info("退出请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("退出数据处理开始,token:{}", token); RestAPIResult<String> result = passportService.logoutHandle(token); logger.info("退出数据处理结束,result:{}", result); stopWatch.stop(); logger.info("退出调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 根据用户ID获取用户信息 * * @author: quhailong * @date: 2019/9/26 */ @RequestMapping(value = "getuserinfo", method = RequestMethod.POST) public RestAPIResult<UserInfoDTO> getUserInfo(@RequestParam("userId") String userId) { logger.info("根据用户ID获取用户信息请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("根据用户ID获取用户信息数据处理开始,userId:{}", userId); RestAPIResult<UserInfoDTO> result = passportService.getUserInfoHandle(userId); logger.info("根据用户ID获取用户信息数据处理结束,result:{}", result); stopWatch.stop(); logger.info("根据用户ID获取用户信息调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } }
package top.quhailong.pan.user.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StopWatch; import org.springframework.web.bind.annotation.*; import top.quhailong.pan.request.ForgetPhoneSendRequest; import top.quhailong.pan.request.ModifyPassRequest; import top.quhailong.pan.user.service.PasswordService; import top.quhailong.pan.utils.RestAPIResult; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; /** * 密码服务 * * @author: quhailong * @date: 2019/9/26 */ @RestController public class PasswordController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private HttpServletRequest httpServletRequest; @Autowired private PasswordService passwordService; /** * 忘记密码短信服务 * * @author: quhailong * @date: 2019/9/26 */ @RequestMapping(value = "forgetphonesend", method = RequestMethod.POST) public RestAPIResult<String> forgetPhoneSend(@RequestBody ForgetPhoneSendRequest request) { logger.info("忘记密码短信服务请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("忘记密码短信服务数据处理开始,request:{}", request); RestAPIResult<String> result = passwordService.forgetPhoneSendHandle(request); logger.info("忘记密码短信服务数据处理结束,result:{}", result); stopWatch.stop(); logger.info("忘记密码短信服务调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 手机号/用户名校验 * * @author: quhailong * @date: 2019/9/26 */ @RequestMapping(value = "checkphonesend", method = {RequestMethod.GET}) public RestAPIResult<String> checkPhoneSend(@RequestParam("username") String username) { logger.info("手机号/用户名校验服务请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("手机号/用户名校验数据处理开始,username:{}", username); RestAPIResult<String> result = passwordService.checkPhoneSendHandle(username); logger.info("手机号/用户名校验数据处理结束,result:{}", result); stopWatch.stop(); logger.info("手机号/用户名校验调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 忘记密码的修改 * * @author: quhailong * @date: 2019/9/26 */ @RequestMapping(value = "modifypass", method = {RequestMethod.POST}) public RestAPIResult<String> modifyPass(@RequestBody ModifyPassRequest request) { logger.info("忘记密码的修改服务请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("忘记密码的修改数据处理开始,request:{}", request); RestAPIResult<String> result = passwordService.modifyPassHandle(request); logger.info("忘记密码的修改数据处理结束,result:{}", result); stopWatch.stop(); logger.info("忘记密码的修改调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } }
package top.quhailong.pan.user.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StopWatch; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import top.quhailong.pan.request.ChangePwdRequest; import top.quhailong.pan.request.RegPhoneSendRequest; import top.quhailong.pan.request.UserRegistRequest; import top.quhailong.pan.user.service.RegisterService; import top.quhailong.pan.utils.RestAPIResult; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * 注册服务 * * @author: quhailong * @date: 2019/9/25 */ @RestController public class RegisterController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private HttpServletRequest httpServletRequest; @Autowired private RegisterService registerService; /** * 用户名查重 * * @author: quhailong * @date: 2019/9/25 */ @RequestMapping(value = "regcheckusername", method = RequestMethod.GET) public RestAPIResult<String> checkUserName(@RequestParam("userName") String userName) { logger.info("用户名查重请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("用户名查重数据处理开始,userName:{}", userName); RestAPIResult<String> result = registerService.checkUserNameHandle(userName); logger.info("用户名查重数据处理结束,result:{}", result); stopWatch.stop(); logger.info("用户名查重调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 手机号查重 * * @author: quhailong * @date: 2019/9/25 */ @RequestMapping(value = "regcheckphone", method = RequestMethod.GET) public RestAPIResult<String> checkPhone(@RequestParam("phoneNum") String phoneNum) { logger.info("手机号查重请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("手机号查重数据处理开始,phoneNum:{}", phoneNum); RestAPIResult<String> result = registerService.checkPhoneHandle(phoneNum); logger.info("手机号查重数据处理结束,result:{}", result); stopWatch.stop(); logger.info("手机号查重调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 用户注册 * * @author: quhailong * @date: 2019/9/25 */ @RequestMapping(value = "regphone", method = RequestMethod.POST) public RestAPIResult<String> userRegist(@RequestBody UserRegistRequest request) throws Exception { logger.info("用户注册请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("用户注册数据处理开始,request:{}", request); RestAPIResult<String> result = registerService.userRegistHandle(request); logger.info("用户注册数据处理结束,result:{}", result); stopWatch.stop(); logger.info("用户注册调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 注册发送短信 * * @author: quhailong * @date: 2019/9/26 */ @RequestMapping(value = "regphonesend", method = RequestMethod.POST) public RestAPIResult<String> regPhoneSend(@RequestBody RegPhoneSendRequest request) { logger.info("注册发送短信请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("注册发送短信数据处理开始,request:{}", request); RestAPIResult<String> result = registerService.regPhoneSendHandle(request); logger.info("注册发送短信数据处理结束,result:{}", result); stopWatch.stop(); logger.info("注册发送短信调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 修改密码 * * @author: quhailong * @date: 2019/9/26 */ @RequestMapping(value = "changepwd", method = RequestMethod.POST) public RestAPIResult<String> changePwd(@RequestBody ChangePwdRequest request) { logger.info("修改密码请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("修改密码数据处理开始,request:{}", request); RestAPIResult<String> result = registerService.changePwdHandle(request); logger.info("修改密码数据处理结束,result:{}", result); stopWatch.stop(); logger.info("修改密码调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 加载用户头像 * * @author: quhailong * @date: 2019/9/26 */ @RequestMapping(value = "loadimg", method = RequestMethod.GET) public RestAPIResult<String> loadImg(@RequestParam("uid") String uid) { logger.info("加载用户头像请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("加载用户头像数据处理开始,uid:{}", uid); RestAPIResult<String> result = registerService.loadImgHandle(uid); logger.info("加载用户头像数据处理结束,result:{}", result); stopWatch.stop(); logger.info("加载用户头像调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } /** * 上传用户头像 * * @author: quhailong * @date: 2019/9/26 */ @RequestMapping(value = "uploadpic", method = RequestMethod.POST) public RestAPIResult<String> uploadPic(@RequestParam("uid") String uid, @RequestParam("file") MultipartFile file) throws IOException { logger.info("上传用户头像请求URL:{}", httpServletRequest.getRequestURL()); StopWatch stopWatch = new StopWatch(); stopWatch.start(); logger.info("上传用户头像数据处理开始,uid:{}", uid); RestAPIResult<String> result = registerService.uploadPicHandle(uid, file); logger.info("上传用户头像数据处理结束,result:{}", result); stopWatch.stop(); logger.info("上传用户头像调用时间,millies:{}", stopWatch.getTotalTimeMillis()); return result; } }
package com.zheng.cms.admin.controller.manage; import com.baidu.unbiz.fluentvalidator.ComplexResult; import com.baidu.unbiz.fluentvalidator.FluentValidator; import com.baidu.unbiz.fluentvalidator.ResultCollectors; import com.zheng.cms.common.constant.CmsResult; import com.zheng.cms.common.constant.CmsResultConstant; import com.zheng.cms.dao.model.CmsArticle; import com.zheng.cms.dao.model.CmsArticleExample; import com.zheng.cms.dao.model.CmsTopic; import com.zheng.cms.dao.model.CmsTopicExample; import com.zheng.cms.rpc.api.CmsArticleService; import com.zheng.cms.rpc.api.CmsTopicService; import com.zheng.common.base.BaseController; import com.zheng.common.validator.LengthValidator; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 文章控制器 * Created by shuzheng on 2016/11/14. */ @Controller @Api(value = "文章管理", description = "文章管理") @RequestMapping("/manage/article") public class CmsArticleController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(CmsArticleController.class); @Autowired private CmsArticleService cmsArticleService; @Autowired private CmsTopicService cmsTopicService; @ApiOperation(value = "文章首页") @RequiresPermissions("cms:article:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/article/index.jsp"; } @ApiOperation(value = "文章列表") @RequiresPermissions("cms:article:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { CmsArticleExample cmsArticleExample = new CmsArticleExample(); if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { cmsArticleExample.setOrderByClause(sort + " " + order); } List<CmsArticle> rows = cmsArticleService.selectByExampleForOffsetPage(cmsArticleExample, offset, limit); long total = cmsArticleService.countByExample(cmsArticleExample); Map<String, Object> result = new HashMap<>(2); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "新增文章") @RequiresPermissions("cms:article:create") @RequestMapping(value = "/create", method = RequestMethod.GET) public String create(ModelMap modelMap) { CmsTopicExample cmsTopicExample = new CmsTopicExample(); cmsTopicExample.setOrderByClause("ctime desc"); List<CmsTopic> cmsTopics = cmsTopicService.selectByExample(cmsTopicExample); modelMap.put("cmsTopics", cmsTopics); return "/manage/article/create.jsp"; } @ApiOperation(value = "新增文章") @RequiresPermissions("cms:article:create") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public Object create(CmsArticle cmsArticle) { ComplexResult result = FluentValidator.checkAll() .on(cmsArticle.getTitle(), new LengthValidator(1, 200, "标题")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } long time = System.currentTimeMillis(); cmsArticle.setCtime(time); cmsArticle.setOrders(time); cmsArticle.setReadnumber(0); int count = cmsArticleService.insertSelective(cmsArticle); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "删除文章") @RequiresPermissions("cms:article:delete") @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = cmsArticleService.deleteByPrimaryKeys(ids); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "修改文章") @RequiresPermissions("cms:article:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") int id, ModelMap modelMap) { CmsTopicExample cmsTopicExample = new CmsTopicExample(); cmsTopicExample.setOrderByClause("ctime desc"); List<CmsTopic> cmsTopics = cmsTopicService.selectByExample(cmsTopicExample); CmsArticle article = cmsArticleService.selectByPrimaryKey(id); modelMap.put("cmsTopics", cmsTopics); modelMap.put("article", article); return "/manage/article/update.jsp"; } @ApiOperation(value = "修改文章") @RequiresPermissions("cms:article:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable("id") int id, CmsArticle cmsArticle) { ComplexResult result = FluentValidator.checkAll() .on(cmsArticle.getTitle(), new LengthValidator(1, 200, "标题")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } cmsArticle.setArticleId(id); int count = cmsArticleService.updateByPrimaryKeySelective(cmsArticle); return new CmsResult(CmsResultConstant.SUCCESS, count); } }
package com.zheng.cms.admin.controller.manage; import com.baidu.unbiz.fluentvalidator.ComplexResult; import com.baidu.unbiz.fluentvalidator.FluentValidator; import com.baidu.unbiz.fluentvalidator.ResultCollectors; import com.zheng.cms.common.constant.CmsResult; import com.zheng.cms.common.constant.CmsResultConstant; import com.zheng.cms.dao.model.CmsCategory; import com.zheng.cms.dao.model.CmsCategoryExample; import com.zheng.cms.rpc.api.CmsCategoryService; import com.zheng.common.base.BaseController; import com.zheng.common.validator.LengthValidator; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 类目控制器 * Created by shuzheng on 2016/11/14. */ @Controller @Api(value = "类目管理", description = "类目管理") @RequestMapping("/manage/category") public class CmsCategoryController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(CmsCategoryController.class); @Autowired private CmsCategoryService cmsCategoryService; @ApiOperation(value = "类目首页") @RequiresPermissions("cms:category:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/category/index.jsp"; } @ApiOperation(value = "类目列表") @RequiresPermissions("cms:category:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { CmsCategoryExample cmsCategoryExample = new CmsCategoryExample(); if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { cmsCategoryExample.setOrderByClause(sort + " " + order); } List<CmsCategory> rows = cmsCategoryService.selectByExampleForOffsetPage(cmsCategoryExample, offset, limit); long total = cmsCategoryService.countByExample(cmsCategoryExample); Map<String, Object> result = new HashMap<>(2); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "新增类目") @RequiresPermissions("cms:category:create") @RequestMapping(value = "/create", method = RequestMethod.GET) public String create() { return "/manage/category/create.jsp"; } @ApiOperation(value = "新增类目") @RequiresPermissions("cms:category:create") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public Object create(CmsCategory cmsCategory) { ComplexResult result = FluentValidator.checkAll() .on(cmsCategory.getName(), new LengthValidator(1, 20, "名称")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } long time = System.currentTimeMillis(); cmsCategory.setCtime(time); cmsCategory.setOrders(time); int count = cmsCategoryService.insertSelective(cmsCategory); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "删除类目") @RequiresPermissions("cms:category:delete") @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = cmsCategoryService.deleteByPrimaryKeys(ids); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "修改类目") @RequiresPermissions("cms:category:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") int id, ModelMap modelMap) { CmsCategory category = cmsCategoryService.selectByPrimaryKey(id); modelMap.put("category", category); return "/manage/category/update.jsp"; } @ApiOperation(value = "修改类目") @RequiresPermissions("cms:category:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable("id") int id, CmsCategory cmsCategory) { ComplexResult result = FluentValidator.checkAll() .on(cmsCategory.getName(), new LengthValidator(1, 20, "名称")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } cmsCategory.setCategoryId(id); int count = cmsCategoryService.updateByPrimaryKeySelective(cmsCategory); return new CmsResult(CmsResultConstant.SUCCESS, count); } }
package com.zheng.cms.admin.controller.manage; import com.zheng.cms.common.constant.CmsResult; import com.zheng.cms.common.constant.CmsResultConstant; import com.zheng.cms.dao.model.CmsComment; import com.zheng.cms.dao.model.CmsCommentExample; import com.zheng.cms.rpc.api.CmsCommentService; import com.zheng.common.base.BaseController; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 评论控制器 * Created by shuzheng on 2016/11/14. */ @Controller @Api(value = "评论管理", description = "评论管理") @RequestMapping("/manage/comment") public class CmsCommentController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(CmsCommentController.class); @Autowired private CmsCommentService cmsCommentService; @ApiOperation(value = "评论首页") @RequiresPermissions("cms:comment:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/comment/index.jsp"; } @ApiOperation(value = "评论列表") @RequiresPermissions("cms:comment:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { CmsCommentExample cmsCommentExample = new CmsCommentExample(); if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { cmsCommentExample.setOrderByClause(sort + " " + order); } List<CmsComment> rows = cmsCommentService.selectByExampleWithBLOBsForOffsetPage(cmsCommentExample, offset, limit); long total = cmsCommentService.countByExample(cmsCommentExample); Map<String, Object> result = new HashMap<>(2); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "新增评论") @RequiresPermissions("cms:comment:create") @RequestMapping(value = "/create", method = RequestMethod.GET) public String create() { return "/manage/comment/create.jsp"; } @ApiOperation(value = "新增评论") @RequiresPermissions("cms:comment:create") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public Object create(CmsComment cmsComment) { long time = System.currentTimeMillis(); cmsComment.setCtime(time); int count = cmsCommentService.insertSelective(cmsComment); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "删除评论") @RequiresPermissions("cms:comment:delete") @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = cmsCommentService.deleteByPrimaryKeys(ids); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "修改评论") @RequiresPermissions("cms:comment:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") int id, ModelMap modelMap) { CmsComment comment = cmsCommentService.selectByPrimaryKey(id); modelMap.put("comment", comment); return "/manage/comment/update.jsp"; } @ApiOperation(value = "修改评论") @RequiresPermissions("cms:comment:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable("id") int id, CmsComment cmsComment) { cmsComment.setCommentId(id); int count = cmsCommentService.updateByPrimaryKeySelective(cmsComment); return new CmsResult(CmsResultConstant.SUCCESS, count); } }
package com.zheng.cms.admin.controller.manage; import com.baidu.unbiz.fluentvalidator.ComplexResult; import com.baidu.unbiz.fluentvalidator.FluentValidator; import com.baidu.unbiz.fluentvalidator.ResultCollectors; import com.zheng.cms.common.constant.CmsResult; import com.zheng.cms.common.constant.CmsResultConstant; import com.zheng.cms.dao.model.CmsMenu; import com.zheng.cms.dao.model.CmsMenuExample; import com.zheng.cms.rpc.api.CmsMenuService; import com.zheng.common.base.BaseController; import com.zheng.common.validator.LengthValidator; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 菜单控制器 * Created by shuzheng on 2017/3/18. */ @Controller @Api(value = "菜单管理", description = "菜单管理") @RequestMapping("/manage/menu") public class CmsMenuController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(CmsMenuController.class); @Autowired private CmsMenuService cmsMenuService; @ApiOperation(value = "评论首页") @RequiresPermissions("cms:menu:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/menu/index.jsp"; } @ApiOperation(value = "评论列表") @RequiresPermissions("cms:menu:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { CmsMenuExample cmsMenuExample = new CmsMenuExample(); if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { cmsMenuExample.setOrderByClause(sort + " " + order); } List<CmsMenu> rows = cmsMenuService.selectByExampleForOffsetPage(cmsMenuExample, offset, limit); long total = cmsMenuService.countByExample(cmsMenuExample); Map<String, Object> result = new HashMap<>(2); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "新增菜单") @RequiresPermissions("cms:menu:create") @RequestMapping(value = "/create", method = RequestMethod.GET) public String create() { return "/manage/menu/create.jsp"; } @ApiOperation(value = "新增菜单") @RequiresPermissions("cms:menu:create") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public Object create(CmsMenu cmsMenu) { ComplexResult result = FluentValidator.checkAll() .on(cmsMenu.getName(), new LengthValidator(1, 20, "名称")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } long time = System.currentTimeMillis(); cmsMenu.setOrders(time); int count = cmsMenuService.insertSelective(cmsMenu); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "删除菜单") @RequiresPermissions("cms:menu:delete") @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = cmsMenuService.deleteByPrimaryKeys(ids); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "修改菜单") @RequiresPermissions("cms:menu:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") int id, ModelMap modelMap) { CmsMenu menu = cmsMenuService.selectByPrimaryKey(id); modelMap.put("menu", menu); return "/manage/menu/update.jsp"; } @ApiOperation(value = "修改菜单") @RequiresPermissions("cms:menu:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable("id") int id, CmsMenu cmsMenu) { ComplexResult result = FluentValidator.checkAll() .on(cmsMenu.getName(), new LengthValidator(1, 20, "名称")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } cmsMenu.setMenuId(id); int count = cmsMenuService.updateByPrimaryKeySelective(cmsMenu); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "上移菜单") @RequiresPermissions("cms:menu:up") @RequestMapping(value = "/up/{id}", method = RequestMethod.GET) @ResponseBody public Object up(@PathVariable("id") int id) { CmsMenu cmsMenu = cmsMenuService.selectByPrimaryKey(id); if (null == cmsMenu) { return new CmsResult(CmsResultConstant.INVALID_PARAMETER, "无效参数!"); } CmsMenuExample cmsMenuExample = new CmsMenuExample(); CmsMenuExample.Criteria criteria = cmsMenuExample.createCriteria(); if (null == cmsMenu.getPid()) { criteria.andPidIsNull(); } else { criteria.andPidEqualTo(cmsMenu.getPid()); } criteria.andOrdersLessThan(cmsMenu.getOrders()); cmsMenuExample.setOrderByClause("orders desc"); CmsMenu upCmsMenu = cmsMenuService.selectFirstByExample(cmsMenuExample); if (null == upCmsMenu) { return new CmsResult(CmsResultConstant.FAILED, "不能上移了!"); } long tempOrders = upCmsMenu.getOrders(); upCmsMenu.setOrders(cmsMenu.getOrders()); cmsMenu.setOrders(tempOrders); cmsMenuService.updateByPrimaryKeySelective(cmsMenu); cmsMenuService.updateByPrimaryKeySelective(upCmsMenu); return new CmsResult(CmsResultConstant.SUCCESS, 1); } @ApiOperation(value = "下移菜单") @RequiresPermissions("cms:menu:down") @RequestMapping(value = "/down/{id}", method = RequestMethod.GET) @ResponseBody public Object down(@PathVariable("id") int id) { CmsMenu cmsMenu = cmsMenuService.selectByPrimaryKey(id); if (null == cmsMenu) { return new CmsResult(CmsResultConstant.INVALID_PARAMETER, "无效参数!"); } CmsMenuExample cmsMenuExample = new CmsMenuExample(); CmsMenuExample.Criteria criteria = cmsMenuExample.createCriteria(); if (null == cmsMenu.getPid()) { criteria.andPidIsNull(); } else { criteria.andPidEqualTo(cmsMenu.getPid()); } criteria.andOrdersGreaterThan(cmsMenu.getOrders()); cmsMenuExample.setOrderByClause("orders asc"); CmsMenu upCmsMenu = cmsMenuService.selectFirstByExample(cmsMenuExample); if (null == upCmsMenu) { return new CmsResult(CmsResultConstant.FAILED, "不能下移了!"); } long tempOrders = upCmsMenu.getOrders(); upCmsMenu.setOrders(cmsMenu.getOrders()); cmsMenu.setOrders(tempOrders); cmsMenuService.updateByPrimaryKeySelective(cmsMenu); cmsMenuService.updateByPrimaryKeySelective(upCmsMenu); return new CmsResult(CmsResultConstant.SUCCESS, 1); } }
package com.zheng.cms.admin.controller.manage; import com.baidu.unbiz.fluentvalidator.ComplexResult; import com.baidu.unbiz.fluentvalidator.FluentValidator; import com.baidu.unbiz.fluentvalidator.ResultCollectors; import com.zheng.cms.common.constant.CmsResult; import com.zheng.cms.common.constant.CmsResultConstant; import com.zheng.cms.dao.model.CmsPage; import com.zheng.cms.dao.model.CmsPageExample; import com.zheng.cms.rpc.api.CmsPageService; import com.zheng.common.base.BaseController; import com.zheng.common.validator.LengthValidator; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 单页控制器 * Created by shuzheng on 2017/3/18. */ @Controller @Api(value = "单页管理", description = "单页管理") @RequestMapping("/manage/page") public class CmsPageController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(CmsPageController.class); @Autowired private CmsPageService cmsPageService; @ApiOperation(value = "评论首页") @RequiresPermissions("cms:page:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/page/index.jsp"; } @ApiOperation(value = "评论列表") @RequiresPermissions("cms:page:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { CmsPageExample cmsPageExample = new CmsPageExample(); if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { cmsPageExample.setOrderByClause(sort + " " + order); } List<CmsPage> rows = cmsPageService.selectByExampleForOffsetPage(cmsPageExample, offset, limit); long total = cmsPageService.countByExample(cmsPageExample); Map<String, Object> result = new HashMap<>(2); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "新增单页") @RequiresPermissions("cms:page:create") @RequestMapping(value = "/create", method = RequestMethod.GET) public String create() { return "/manage/page/create.jsp"; } @ApiOperation(value = "新增单页") @RequiresPermissions("cms:page:create") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public Object create(CmsPage cmsPage) { ComplexResult result = FluentValidator.checkAll() .on(cmsPage.getTitle(), new LengthValidator(1, 20, "标题")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } long time = System.currentTimeMillis(); cmsPage.setCtime(time); cmsPage.setOrders(time); int count = cmsPageService.insertSelective(cmsPage); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "删除单页") @RequiresPermissions("cms:page:delete") @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = cmsPageService.deleteByPrimaryKeys(ids); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "修改单页") @RequiresPermissions("cms:page:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") int id, ModelMap modelMap) { CmsPage page = cmsPageService.selectByPrimaryKey(id); modelMap.put("page", page); return "/manage/page/update.jsp"; } @ApiOperation(value = "修改单页") @RequiresPermissions("cms:page:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable("id") int id, CmsPage cmsPage) { ComplexResult result = FluentValidator.checkAll() .on(cmsPage.getTitle(), new LengthValidator(1, 20, "标题")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } cmsPage.setPageId(id); int count = cmsPageService.updateByPrimaryKeySelective(cmsPage); return new CmsResult(CmsResultConstant.SUCCESS, count); } }
package com.zheng.cms.admin.controller.manage; import com.baidu.unbiz.fluentvalidator.ComplexResult; import com.baidu.unbiz.fluentvalidator.FluentValidator; import com.baidu.unbiz.fluentvalidator.ResultCollectors; import com.zheng.cms.common.constant.CmsResult; import com.zheng.cms.common.constant.CmsResultConstant; import com.zheng.cms.dao.model.CmsSetting; import com.zheng.cms.dao.model.CmsSettingExample; import com.zheng.cms.rpc.api.CmsSettingService; import com.zheng.common.base.BaseController; import com.zheng.common.util.StringUtil; import com.zheng.common.validator.LengthValidator; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 设置控制器 * Created by shuzheng on 2017/3/18. */ @Controller @Api(value = "设置管理", description = "设置管理") @RequestMapping("/manage/setting") public class CmsSettingController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(CmsSettingController.class); @Autowired private CmsSettingService cmsSettingService; @ApiOperation(value = "评论首页") @RequiresPermissions("cms:setting:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/setting/index.jsp"; } @ApiOperation(value = "评论列表") @RequiresPermissions("cms:setting:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { CmsSettingExample cmsSettingExample = new CmsSettingExample(); if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { cmsSettingExample.setOrderByClause(StringUtil.humpToLine(sort) + " " + order); } List<CmsSetting> rows = cmsSettingService.selectByExampleForOffsetPage(cmsSettingExample, offset, limit); long total = cmsSettingService.countByExample(cmsSettingExample); Map<String, Object> result = new HashMap<>(2); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "新增设置") @RequiresPermissions("cms:setting:create") @RequestMapping(value = "/create", method = RequestMethod.GET) public String create() { return "/manage/setting/create.jsp"; } @ApiOperation(value = "新增设置") @RequiresPermissions("cms:setting:create") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public Object create(CmsSetting cmsSetting) { ComplexResult result = FluentValidator.checkAll() .on(cmsSetting.getSettingKey(), new LengthValidator(1, 20, "键")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } int count = cmsSettingService.insertSelective(cmsSetting); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "删除设置") @RequiresPermissions("cms:setting:delete") @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = cmsSettingService.deleteByPrimaryKeys(ids); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "修改设置") @RequiresPermissions("cms:setting:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") int id, ModelMap modelMap) { CmsSetting setting = cmsSettingService.selectByPrimaryKey(id); modelMap.put("setting", setting); return "/manage/setting/update.jsp"; } @ApiOperation(value = "修改设置") @RequiresPermissions("cms:setting:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable("id") int id, CmsSetting cmsSetting) { ComplexResult result = FluentValidator.checkAll() .on(cmsSetting.getSettingKey(), new LengthValidator(1, 20, "键")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } cmsSetting.setSettingId(id); int count = cmsSettingService.updateByPrimaryKeySelective(cmsSetting); return new CmsResult(CmsResultConstant.SUCCESS, count); } }
package com.zheng.cms.admin.controller.manage; import com.baidu.unbiz.fluentvalidator.ComplexResult; import com.baidu.unbiz.fluentvalidator.FluentValidator; import com.baidu.unbiz.fluentvalidator.ResultCollectors; import com.zheng.cms.common.constant.CmsResult; import com.zheng.cms.common.constant.CmsResultConstant; import com.zheng.cms.dao.model.CmsTag; import com.zheng.cms.dao.model.CmsTagExample; import com.zheng.cms.rpc.api.CmsTagService; import com.zheng.common.base.BaseController; import com.zheng.common.validator.LengthValidator; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 标签控制器 * Created by shuzheng on 2016/11/14. */ @Controller @Api(value = "标签管理", description = "标签管理") @RequestMapping("/manage/tag") public class CmsTagController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(CmsTagController.class); @Autowired private CmsTagService cmsTagService; @ApiOperation(value = "评论首页") @RequiresPermissions("cms:tag:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/tag/index.jsp"; } @ApiOperation(value = "评论列表") @RequiresPermissions("cms:tag:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { CmsTagExample cmsTagExample = new CmsTagExample(); if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { cmsTagExample.setOrderByClause(sort + " " + order); } List<CmsTag> rows = cmsTagService.selectByExampleForOffsetPage(cmsTagExample, offset, limit); long total = cmsTagService.countByExample(cmsTagExample); Map<String, Object> result = new HashMap<>(2); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "新增标签") @RequiresPermissions("cms:tag:create") @RequestMapping(value = "/create", method = RequestMethod.GET) public String create() { return "/manage/tag/create.jsp"; } @ApiOperation(value = "新增标签") @RequiresPermissions("cms:tag:create") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public Object create(CmsTag cmsTag) { ComplexResult result = FluentValidator.checkAll() .on(cmsTag.getName(), new LengthValidator(1, 20, "名称")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } long time = System.currentTimeMillis(); cmsTag.setCtime(time); cmsTag.setOrders(time); int count = cmsTagService.insertSelective(cmsTag); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "删除标签") @RequiresPermissions("cms:tag:delete") @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = cmsTagService.deleteByPrimaryKeys(ids); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "修改标签") @RequiresPermissions("cms:tag:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") int id, ModelMap modelMap) { CmsTag tag = cmsTagService.selectByPrimaryKey(id); modelMap.put("tag", tag); return "/manage/tag/update.jsp"; } @ApiOperation(value = "修改标签") @RequiresPermissions("cms:tag:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable("id") int id, CmsTag cmsTag) { ComplexResult result = FluentValidator.checkAll() .on(cmsTag.getName(), new LengthValidator(1, 20, "名称")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } cmsTag.setTagId(id); int count = cmsTagService.updateByPrimaryKeySelective(cmsTag); return new CmsResult(CmsResultConstant.SUCCESS, count); } }
package com.zheng.cms.admin.controller.manage; import com.baidu.unbiz.fluentvalidator.ComplexResult; import com.baidu.unbiz.fluentvalidator.FluentValidator; import com.baidu.unbiz.fluentvalidator.ResultCollectors; import com.zheng.cms.common.constant.CmsResult; import com.zheng.cms.common.constant.CmsResultConstant; import com.zheng.cms.dao.model.CmsTopic; import com.zheng.cms.dao.model.CmsTopicExample; import com.zheng.cms.rpc.api.CmsTopicService; import com.zheng.common.base.BaseController; import com.zheng.common.validator.LengthValidator; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 专题控制器 * Created by shuzheng on 2017/3/18. */ @Controller @Api(value = "专题管理", description = "专题管理") @RequestMapping("/manage/topic") public class CmsTopicController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(CmsTopicController.class); @Autowired private CmsTopicService cmsTopicService; @ApiOperation(value = "评论首页") @RequiresPermissions("cms:topic:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/topic/index.jsp"; } @ApiOperation(value = "评论列表") @RequiresPermissions("cms:topic:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { CmsTopicExample cmsTopicExample = new CmsTopicExample(); if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { cmsTopicExample.setOrderByClause(sort + " " + order); } List<CmsTopic> rows = cmsTopicService.selectByExampleForOffsetPage(cmsTopicExample, offset, limit); long total = cmsTopicService.countByExample(cmsTopicExample); Map<String, Object> result = new HashMap<>(2); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "新增专题") @RequiresPermissions("cms:topic:create") @RequestMapping(value = "/create", method = RequestMethod.GET) public String create() { return "/manage/topic/create.jsp"; } @ApiOperation(value = "新增专题") @RequiresPermissions("cms:topic:create") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public Object create(CmsTopic cmsTopic) { ComplexResult result = FluentValidator.checkAll() .on(cmsTopic.getTitle(), new LengthValidator(1, 100, "标题")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } long time = System.currentTimeMillis(); cmsTopic.setCtime(time); int count = cmsTopicService.insertSelective(cmsTopic); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "删除专题") @RequiresPermissions("cms:topic:delete") @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = cmsTopicService.deleteByPrimaryKeys(ids); return new CmsResult(CmsResultConstant.SUCCESS, count); } @ApiOperation(value = "修改专题") @RequiresPermissions("cms:topic:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") int id, ModelMap modelMap) { CmsTopic topic = cmsTopicService.selectByPrimaryKey(id); modelMap.put("topic", topic); return "/manage/topic/update.jsp"; } @ApiOperation(value = "修改专题") @RequiresPermissions("cms:topic:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable("id") int id, CmsTopic cmsTopic) { ComplexResult result = FluentValidator.checkAll() .on(cmsTopic.getTitle(), new LengthValidator(1, 100, "标题")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new CmsResult(CmsResultConstant.INVALID_LENGTH, result.getErrors()); } cmsTopic.setTopicId(id); int count = cmsTopicService.updateByPrimaryKeySelective(cmsTopic); return new CmsResult(CmsResultConstant.SUCCESS, count); } }
package com.zheng.upms.server.controller.manage; import com.zheng.common.base.BaseController; import com.zheng.common.util.StringUtil; import com.zheng.upms.common.constant.UpmsResult; import com.zheng.upms.common.constant.UpmsResultConstant; import com.zheng.upms.dao.model.UpmsLog; import com.zheng.upms.dao.model.UpmsLogExample; import com.zheng.upms.rpc.api.UpmsLogService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 日志controller * Created by shuzheng on 2017/3/14. */ @Controller @Api(value = "日志管理", description = "日志管理") @RequestMapping("/manage/log") public class UpmsLogController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(UpmsLogController.class); @Autowired private UpmsLogService upmsLogService; @ApiOperation(value = "日志首页") @RequiresPermissions("upms:log:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/log/index.jsp"; } @ApiOperation(value = "日志列表") @RequiresPermissions("upms:log:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, defaultValue = "", value = "search") String search, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { UpmsLogExample upmsLogExample = new UpmsLogExample(); if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { upmsLogExample.setOrderByClause(StringUtil.humpToLine(sort) + " " + order); } if (StringUtils.isNotBlank(search)) { upmsLogExample.or() .andDescriptionLike("%" + search + "%"); } List<UpmsLog> rows = upmsLogService.selectByExampleForOffsetPage(upmsLogExample, offset, limit); long total = upmsLogService.countByExample(upmsLogExample); Map<String, Object> result = new HashMap<>(); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "删除日志") @RequiresPermissions("upms:log:delete") @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = upmsLogService.deleteByPrimaryKeys(ids); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } }
package com.zheng.upms.server.controller.manage; import com.baidu.unbiz.fluentvalidator.ComplexResult; import com.baidu.unbiz.fluentvalidator.FluentValidator; import com.baidu.unbiz.fluentvalidator.ResultCollectors; import com.zheng.common.base.BaseController; import com.zheng.common.validator.LengthValidator; import com.zheng.upms.common.constant.UpmsResult; import com.zheng.upms.common.constant.UpmsResultConstant; import com.zheng.upms.dao.model.UpmsOrganization; import com.zheng.upms.dao.model.UpmsOrganizationExample; import com.zheng.upms.rpc.api.UpmsOrganizationService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 组织controller * Created by shuzheng on 2017/2/6. */ @Controller @Api(value = "组织管理", description = "组织管理") @RequestMapping("/manage/organization") public class UpmsOrganizationController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(UpmsOrganizationController.class); @Autowired private UpmsOrganizationService upmsOrganizationService; @ApiOperation(value = "组织首页") @RequiresPermissions("upms:organization:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/organization/index.jsp"; } @ApiOperation(value = "组织列表") @RequiresPermissions("upms:organization:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, defaultValue = "", value = "search") String search, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { UpmsOrganizationExample upmsOrganizationExample = new UpmsOrganizationExample(); if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { upmsOrganizationExample.setOrderByClause(sort + " " + order); } if (StringUtils.isNotBlank(search)) { upmsOrganizationExample.or() .andNameLike("%" + search + "%"); } List<UpmsOrganization> rows = upmsOrganizationService.selectByExampleForOffsetPage(upmsOrganizationExample, offset, limit); long total = upmsOrganizationService.countByExample(upmsOrganizationExample); Map<String, Object> result = new HashMap<>(); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "新增组织") @RequiresPermissions("upms:organization:create") @RequestMapping(value = "/create", method = RequestMethod.GET) public String create() { return "/manage/organization/create.jsp"; } @ApiOperation(value = "新增组织") @RequiresPermissions("upms:organization:create") @ResponseBody @RequestMapping(value = "/create", method = RequestMethod.POST) public Object create(UpmsOrganization upmsOrganization) { ComplexResult result = FluentValidator.checkAll() .on(upmsOrganization.getName(), new LengthValidator(1, 20, "名称")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors()); } long time = System.currentTimeMillis(); upmsOrganization.setCtime(time); int count = upmsOrganizationService.insertSelective(upmsOrganization); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } @ApiOperation(value = "删除组织") @RequiresPermissions("upms:organization:delete") @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = upmsOrganizationService.deleteByPrimaryKeys(ids); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } @ApiOperation(value = "修改组织") @RequiresPermissions("upms:organization:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") int id, ModelMap modelMap) { UpmsOrganization organization = upmsOrganizationService.selectByPrimaryKey(id); modelMap.put("organization", organization); return "/manage/organization/update.jsp"; } @ApiOperation(value = "修改组织") @RequiresPermissions("upms:organization:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable("id") int id, UpmsOrganization upmsOrganization) { ComplexResult result = FluentValidator.checkAll() .on(upmsOrganization.getName(), new LengthValidator(1, 20, "名称")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors()); } upmsOrganization.setOrganizationId(id); int count = upmsOrganizationService.updateByPrimaryKeySelective(upmsOrganization); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } }
package com.zheng.upms.server.controller.manage; import com.baidu.unbiz.fluentvalidator.ComplexResult; import com.baidu.unbiz.fluentvalidator.FluentValidator; import com.baidu.unbiz.fluentvalidator.ResultCollectors; import com.zheng.common.base.BaseController; import com.zheng.common.validator.LengthValidator; import com.zheng.upms.common.constant.UpmsResult; import com.zheng.upms.common.constant.UpmsResultConstant; import com.zheng.upms.dao.model.UpmsPermission; import com.zheng.upms.dao.model.UpmsPermissionExample; import com.zheng.upms.dao.model.UpmsSystem; import com.zheng.upms.dao.model.UpmsSystemExample; import com.zheng.upms.rpc.api.UpmsApiService; import com.zheng.upms.rpc.api.UpmsPermissionService; import com.zheng.upms.rpc.api.UpmsSystemService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 权限controller * Created by shuzheng on 2017/2/6. */ @Controller @Api(value = "权限管理", description = "权限管理") @RequestMapping("/manage/permission") public class UpmsPermissionController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(UpmsPermissionController.class); @Autowired private UpmsPermissionService upmsPermissionService; @Autowired private UpmsSystemService upmsSystemService; @Autowired private UpmsApiService upmsApiService; @ApiOperation(value = "权限首页") @RequiresPermissions("upms:permission:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/permission/index.jsp"; } @ApiOperation(value = "权限列表") @RequiresPermissions("upms:permission:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, defaultValue = "", value = "search") String search, @RequestParam(required = false, defaultValue = "0", value = "type") int type, @RequestParam(required = false, defaultValue = "0", value = "systemId") int systemId, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { UpmsPermissionExample upmsPermissionExample = new UpmsPermissionExample(); UpmsPermissionExample.Criteria criteria = upmsPermissionExample.createCriteria(); if (0 != type) { criteria.andTypeEqualTo((byte) type); } if (0 != systemId) { criteria.andSystemIdEqualTo(systemId); } if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { upmsPermissionExample.setOrderByClause(sort + " " + order); } if (StringUtils.isNotBlank(search)) { upmsPermissionExample.or() .andNameLike("%" + search + "%"); } List<UpmsPermission> rows = upmsPermissionService.selectByExampleForOffsetPage(upmsPermissionExample, offset, limit); long total = upmsPermissionService.countByExample(upmsPermissionExample); Map<String, Object> result = new HashMap<>(); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "角色权限列表") @RequiresPermissions("upms:permission:read") @RequestMapping(value = "/role/{id}", method = RequestMethod.POST) @ResponseBody public Object role(@PathVariable("id") int id) { return upmsPermissionService.getTreeByRoleId(id); } @ApiOperation(value = "用户权限列表") @RequiresPermissions("upms:permission:read") @RequestMapping(value = "/user/{id}", method = RequestMethod.POST) @ResponseBody public Object user(@PathVariable("id") int id, HttpServletRequest request) { return upmsPermissionService.getTreeByUserId(id, NumberUtils.toByte(request.getParameter("type"))); } @ApiOperation(value = "新增权限") @RequiresPermissions("upms:permission:create") @RequestMapping(value = "/create", method = RequestMethod.GET) public String create(ModelMap modelMap) { UpmsSystemExample upmsSystemExample = new UpmsSystemExample(); upmsSystemExample.createCriteria() .andStatusEqualTo((byte) 1); List<UpmsSystem> upmsSystems = upmsSystemService.selectByExample(upmsSystemExample); modelMap.put("upmsSystems", upmsSystems); return "/manage/permission/create.jsp"; } @ApiOperation(value = "新增权限") @RequiresPermissions("upms:permission:create") @ResponseBody @RequestMapping(value = "/create", method = RequestMethod.POST) public Object create(UpmsPermission upmsPermission) { ComplexResult result = FluentValidator.checkAll() .on(upmsPermission.getName(), new LengthValidator(1, 20, "名称")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors()); } long time = System.currentTimeMillis(); upmsPermission.setCtime(time); upmsPermission.setOrders(time); int count = upmsPermissionService.insertSelective(upmsPermission); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } @ApiOperation(value = "删除权限") @RequiresPermissions("upms:permission:delete") @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = upmsPermissionService.deleteByPrimaryKeys(ids); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } @ApiOperation(value = "修改权限") @RequiresPermissions("upms:permission:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") int id, ModelMap modelMap) { UpmsSystemExample upmsSystemExample = new UpmsSystemExample(); upmsSystemExample.createCriteria() .andStatusEqualTo((byte) 1); List<UpmsSystem> upmsSystems = upmsSystemService.selectByExample(upmsSystemExample); UpmsPermission permission = upmsPermissionService.selectByPrimaryKey(id); modelMap.put("permission", permission); modelMap.put("upmsSystems", upmsSystems); return "/manage/permission/update.jsp"; } @ApiOperation(value = "修改权限") @RequiresPermissions("upms:permission:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable("id") int id, UpmsPermission upmsPermission) { ComplexResult result = FluentValidator.checkAll() .on(upmsPermission.getName(), new LengthValidator(1, 20, "名称")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors()); } upmsPermission.setPermissionId(id); int count = upmsPermissionService.updateByPrimaryKeySelective(upmsPermission); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } }
package com.zheng.upms.server.controller.manage; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baidu.unbiz.fluentvalidator.ComplexResult; import com.baidu.unbiz.fluentvalidator.FluentValidator; import com.baidu.unbiz.fluentvalidator.ResultCollectors; import com.zheng.common.base.BaseController; import com.zheng.common.validator.LengthValidator; import com.zheng.upms.common.constant.UpmsResult; import com.zheng.upms.common.constant.UpmsResultConstant; import com.zheng.upms.dao.model.UpmsRole; import com.zheng.upms.dao.model.UpmsRoleExample; import com.zheng.upms.dao.model.UpmsRolePermission; import com.zheng.upms.dao.model.UpmsRolePermissionExample; import com.zheng.upms.rpc.api.UpmsRolePermissionService; import com.zheng.upms.rpc.api.UpmsRoleService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 角色controller * Created by shuzheng on 2017/2/6. */ @Controller @Api(value = "角色管理", description = "角色管理") @RequestMapping("/manage/role") public class UpmsRoleController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(UpmsRoleController.class); @Autowired private UpmsRoleService upmsRoleService; @Autowired private UpmsRolePermissionService upmsRolePermissionService; @ApiOperation(value = "角色首页") @RequiresPermissions("upms:role:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/role/index.jsp"; } @ApiOperation(value = "角色权限") @RequiresPermissions("upms:role:permission") @RequestMapping(value = "/permission/{id}", method = RequestMethod.GET) public String permission(@PathVariable("id") int id, ModelMap modelMap) { UpmsRole role = upmsRoleService.selectByPrimaryKey(id); modelMap.put("role", role); return "/manage/role/permission.jsp"; } @ApiOperation(value = "角色权限") @RequiresPermissions("upms:role:permission") @RequestMapping(value = "/permission/{id}", method = RequestMethod.POST) @ResponseBody public Object permission(@PathVariable("id") int id, HttpServletRequest request) { JSONArray datas = JSONArray.parseArray(request.getParameter("datas")); int result = upmsRolePermissionService.rolePermission(datas, id); return new UpmsResult(UpmsResultConstant.SUCCESS, result); } @ApiOperation(value = "角色列表") @RequiresPermissions("upms:role:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, defaultValue = "", value = "search") String search, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { UpmsRoleExample upmsRoleExample = new UpmsRoleExample(); if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { upmsRoleExample.setOrderByClause(sort + " " + order); } if (StringUtils.isNotBlank(search)) { upmsRoleExample.or() .andTitleLike("%" + search + "%"); } List<UpmsRole> rows = upmsRoleService.selectByExampleForOffsetPage(upmsRoleExample, offset, limit); long total = upmsRoleService.countByExample(upmsRoleExample); Map<String, Object> result = new HashMap<>(); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "新增角色") @RequiresPermissions("upms:role:create") @RequestMapping(value = "/create", method = RequestMethod.GET) public String create() { return "/manage/role/create.jsp"; } @ApiOperation(value = "新增角色") @RequiresPermissions("upms:role:create") @ResponseBody @RequestMapping(value = "/create", method = RequestMethod.POST) public Object create(UpmsRole upmsRole) { ComplexResult result = FluentValidator.checkAll() .on(upmsRole.getName(), new LengthValidator(1, 20, "名称")) .on(upmsRole.getTitle(), new LengthValidator(1, 20, "标题")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors()); } long time = System.currentTimeMillis(); upmsRole.setCtime(time); upmsRole.setOrders(time); int count = upmsRoleService.insertSelective(upmsRole); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } @ApiOperation(value = "删除角色") @RequiresPermissions("upms:role:delete") @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = upmsRoleService.deleteByPrimaryKeys(ids); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } @ApiOperation(value = "修改角色") @RequiresPermissions("upms:role:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") int id, ModelMap modelMap) { UpmsRole role = upmsRoleService.selectByPrimaryKey(id); modelMap.put("role", role); return "/manage/role/update.jsp"; } @ApiOperation(value = "修改角色") @RequiresPermissions("upms:role:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable("id") int id, UpmsRole upmsRole) { ComplexResult result = FluentValidator.checkAll() .on(upmsRole.getName(), new LengthValidator(1, 20, "名称")) .on(upmsRole.getTitle(), new LengthValidator(1, 20, "标题")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors()); } upmsRole.setRoleId(id); int count = upmsRoleService.updateByPrimaryKeySelective(upmsRole); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } }
package com.zheng.upms.server.controller.manage; import com.baidu.unbiz.fluentvalidator.ComplexResult; import com.baidu.unbiz.fluentvalidator.FluentValidator; import com.baidu.unbiz.fluentvalidator.ResultCollectors; import com.zheng.common.base.BaseController; import com.zheng.common.validator.LengthValidator; import com.zheng.upms.common.constant.UpmsResult; import com.zheng.upms.common.constant.UpmsResultConstant; import com.zheng.upms.dao.model.UpmsSystem; import com.zheng.upms.dao.model.UpmsSystemExample; import com.zheng.upms.rpc.api.UpmsSystemService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 系统controller * Created by shuzheng on 2016/12/18. */ @Controller @Api(value = "系统管理", description = "系统管理") @RequestMapping("/manage/system") public class UpmsSystemController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(UpmsSystemController.class); @Autowired private UpmsSystemService upmsSystemService; @ApiOperation(value = "系统首页") @RequiresPermissions("upms:system:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/system/index.jsp"; } @ApiOperation(value = "系统列表") @RequiresPermissions("upms:system:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, defaultValue = "", value = "search") String search, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { UpmsSystemExample upmsSystemExample = new UpmsSystemExample(); if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { upmsSystemExample.setOrderByClause(sort + " " + order); } if (StringUtils.isNotBlank(search)) { upmsSystemExample.or() .andTitleLike("%" + search + "%"); } List<UpmsSystem> rows = upmsSystemService.selectByExampleForOffsetPage(upmsSystemExample, offset, limit); long total = upmsSystemService.countByExample(upmsSystemExample); Map<String, Object> result = new HashMap<>(); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "新增系统") @RequiresPermissions("upms:system:create") @RequestMapping(value = "/create", method = RequestMethod.GET) public String create() { return "/manage/system/create.jsp"; } @ApiOperation(value = "新增系统") @RequiresPermissions("upms:system:create") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public Object create(UpmsSystem upmsSystem) { ComplexResult result = FluentValidator.checkAll() .on(upmsSystem.getTitle(), new LengthValidator(1, 20, "标题")) .on(upmsSystem.getName(), new LengthValidator(1, 20, "名称")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors()); } long time = System.currentTimeMillis(); upmsSystem.setCtime(time); upmsSystem.setOrders(time); int count = upmsSystemService.insertSelective(upmsSystem); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } @ApiOperation(value = "删除系统") @RequiresPermissions("upms:system:delete") @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = upmsSystemService.deleteByPrimaryKeys(ids); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } @ApiOperation(value = "修改系统") @RequiresPermissions("upms:system:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") int id, ModelMap modelMap) { UpmsSystem system = upmsSystemService.selectByPrimaryKey(id); modelMap.put("system", system); return "/manage/system/update.jsp"; } @ApiOperation(value = "修改系统") @RequiresPermissions("upms:system:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable("id") int id, UpmsSystem upmsSystem) { ComplexResult result = FluentValidator.checkAll() .on(upmsSystem.getTitle(), new LengthValidator(1, 20, "标题")) .on(upmsSystem.getName(), new LengthValidator(1, 20, "名称")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors()); } upmsSystem.setSystemId(id); int count = upmsSystemService.updateByPrimaryKeySelective(upmsSystem); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } }
package com.zheng.upms.server.controller.manage; import com.alibaba.fastjson.JSONArray; import com.baidu.unbiz.fluentvalidator.ComplexResult; import com.baidu.unbiz.fluentvalidator.FluentValidator; import com.baidu.unbiz.fluentvalidator.ResultCollectors; import com.zheng.common.base.BaseController; import com.zheng.common.util.MD5Util; import com.zheng.common.validator.LengthValidator; import com.zheng.common.validator.NotNullValidator; import com.zheng.upms.common.constant.UpmsResult; import com.zheng.upms.common.constant.UpmsResultConstant; import com.zheng.upms.dao.model.*; import com.zheng.upms.rpc.api.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /** * 用户controller * Created by shuzheng on 2017/2/6. */ @Controller @Api(value = "用户管理", description = "用户管理") @RequestMapping("/manage/user") public class UpmsUserController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(UpmsUserController.class); @Autowired private UpmsUserService upmsUserService; @Autowired private UpmsRoleService upmsRoleService; @Autowired private UpmsOrganizationService upmsOrganizationService; @Autowired private UpmsUserOrganizationService upmsUserOrganizationService; @Autowired private UpmsUserRoleService upmsUserRoleService; @Autowired private UpmsUserPermissionService upmsUserPermissionService; @ApiOperation(value = "用户首页") @RequiresPermissions("upms:user:read") @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/user/index.jsp"; } @ApiOperation(value = "用户组织") @RequiresPermissions("upms:user:organization") @RequestMapping(value = "/organization/{id}", method = RequestMethod.GET) public String organization(@PathVariable("id") int id, ModelMap modelMap) { // 所有组织 List<UpmsOrganization> upmsOrganizations = upmsOrganizationService.selectByExample(new UpmsOrganizationExample()); // 用户拥有组织 UpmsUserOrganizationExample upmsUserOrganizationExample = new UpmsUserOrganizationExample(); upmsUserOrganizationExample.createCriteria() .andUserIdEqualTo(id); List<UpmsUserOrganization> upmsUserOrganizations = upmsUserOrganizationService.selectByExample(upmsUserOrganizationExample); modelMap.put("upmsOrganizations", upmsOrganizations); modelMap.put("upmsUserOrganizations", upmsUserOrganizations); return "/manage/user/organization.jsp"; } @ApiOperation(value = "用户组织") @RequiresPermissions("upms:user:organization") @RequestMapping(value = "/organization/{id}", method = RequestMethod.POST) @ResponseBody public Object organization(@PathVariable("id") int id, HttpServletRequest request) { String[] organizationIds = request.getParameterValues("organizationId"); upmsUserOrganizationService.organization(organizationIds, id); return new UpmsResult(UpmsResultConstant.SUCCESS, ""); } @ApiOperation(value = "用户角色") @RequiresPermissions("upms:user:role") @RequestMapping(value = "/role/{id}", method = RequestMethod.GET) public String role(@PathVariable("id") int id, ModelMap modelMap) { // 所有角色 List<UpmsRole> upmsRoles = upmsRoleService.selectByExample(new UpmsRoleExample()); // 用户拥有角色 UpmsUserRoleExample upmsUserRoleExample = new UpmsUserRoleExample(); upmsUserRoleExample.createCriteria() .andUserIdEqualTo(id); List<UpmsUserRole> upmsUserRoles = upmsUserRoleService.selectByExample(upmsUserRoleExample); modelMap.put("upmsRoles", upmsRoles); modelMap.put("upmsUserRoles", upmsUserRoles); return "/manage/user/role.jsp"; } @ApiOperation(value = "用户角色") @RequiresPermissions("upms:user:role") @RequestMapping(value = "/role/{id}", method = RequestMethod.POST) @ResponseBody public Object role(@PathVariable("id") int id, HttpServletRequest request) { String[] roleIds = request.getParameterValues("roleId"); upmsUserRoleService.role(roleIds, id); return new UpmsResult(UpmsResultConstant.SUCCESS, ""); } @ApiOperation(value = "用户权限") @RequiresPermissions("upms:user:permission") @RequestMapping(value = "/permission/{id}", method = RequestMethod.GET) public String permission(@PathVariable("id") int id, ModelMap modelMap) { UpmsUser user = upmsUserService.selectByPrimaryKey(id); modelMap.put("user", user); return "/manage/user/permission.jsp"; } @ApiOperation(value = "用户权限") @RequiresPermissions("upms:user:permission") @RequestMapping(value = "/permission/{id}", method = RequestMethod.POST) @ResponseBody public Object permission(@PathVariable("id") int id, HttpServletRequest request) { JSONArray datas = JSONArray.parseArray(request.getParameter("datas")); upmsUserPermissionService.permission(datas, id); return new UpmsResult(UpmsResultConstant.SUCCESS, datas.size()); } @ApiOperation(value = "用户列表") @RequiresPermissions("upms:user:read") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object list( @RequestParam(required = false, defaultValue = "0", value = "offset") int offset, @RequestParam(required = false, defaultValue = "10", value = "limit") int limit, @RequestParam(required = false, defaultValue = "", value = "search") String search, @RequestParam(required = false, value = "sort") String sort, @RequestParam(required = false, value = "order") String order) { UpmsUserExample upmsUserExample = new UpmsUserExample(); if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) { upmsUserExample.setOrderByClause(sort + " " + order); } if (StringUtils.isNotBlank(search)) { upmsUserExample.or() .andRealnameLike("%" + search + "%"); upmsUserExample.or() .andUsernameLike("%" + search + "%"); } List<UpmsUser> rows = upmsUserService.selectByExampleForOffsetPage(upmsUserExample, offset, limit); long total = upmsUserService.countByExample(upmsUserExample); Map<String, Object> result = new HashMap<>(); result.put("rows", rows); result.put("total", total); return result; } @ApiOperation(value = "新增用户") @RequiresPermissions("upms:user:create") @RequestMapping(value = "/create", method = RequestMethod.GET) public String create() { return "/manage/user/create.jsp"; } @ApiOperation(value = "新增用户") @RequiresPermissions("upms:user:create") @ResponseBody @RequestMapping(value = "/create", method = RequestMethod.POST) public Object create(UpmsUser upmsUser) { ComplexResult result = FluentValidator.checkAll() .on(upmsUser.getUsername(), new LengthValidator(1, 20, "帐号")) .on(upmsUser.getPassword(), new LengthValidator(5, 32, "密码")) .on(upmsUser.getRealname(), new NotNullValidator("姓名")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors()); } long time = System.currentTimeMillis(); String salt = UUID.randomUUID().toString().replaceAll("-", ""); upmsUser.setSalt(salt); upmsUser.setPassword(MD5Util.md5(upmsUser.getPassword() + upmsUser.getSalt())); upmsUser.setCtime(time); upmsUser = upmsUserService.createUser(upmsUser); if (null == upmsUser) { return new UpmsResult(UpmsResultConstant.FAILED, "帐号名已存在!"); } LOGGER.info("新增用户,主键:userId={}", upmsUser.getUserId()); return new UpmsResult(UpmsResultConstant.SUCCESS, 1); } @ApiOperation(value = "删除用户") @RequiresPermissions("upms:user:delete") @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET) @ResponseBody public Object delete(@PathVariable("ids") String ids) { int count = upmsUserService.deleteByPrimaryKeys(ids); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } @ApiOperation(value = "修改用户") @RequiresPermissions("upms:user:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String update(@PathVariable("id") int id, ModelMap modelMap) { UpmsUser user = upmsUserService.selectByPrimaryKey(id); modelMap.put("user", user); return "/manage/user/update.jsp"; } @ApiOperation(value = "修改用户") @RequiresPermissions("upms:user:update") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable("id") int id, UpmsUser upmsUser) { ComplexResult result = FluentValidator.checkAll() .on(upmsUser.getUsername(), new LengthValidator(1, 20, "帐号")) .on(upmsUser.getRealname(), new NotNullValidator("姓名")) .doValidate() .result(ResultCollectors.toComplex()); if (!result.isSuccess()) { return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors()); } // 不允许直接改密码 upmsUser.setPassword(null); upmsUser.setUserId(id); int count = upmsUserService.updateByPrimaryKeySelective(upmsUser); return new UpmsResult(UpmsResultConstant.SUCCESS, count); } }
package com.mall4j.cloud.multishop.controller; import com.mall4j.cloud.api.auth.vo.AuthAccountVO; import com.mall4j.cloud.common.response.ResponseEnum; import com.mall4j.cloud.common.response.ServerResponseEntity; import com.mall4j.cloud.common.security.AuthUserContext; import com.mall4j.cloud.multishop.dto.ChangeAccountDTO; import com.mall4j.cloud.multishop.service.ShopUserAccountService; import com.mall4j.cloud.multishop.service.ShopUserService; import com.mall4j.cloud.multishop.vo.ShopUserVO; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.Objects; /** * @author FrozenWatermelon * @date 2020/09/02 */ @RequestMapping(value = "/shop_user/account") @RestController @Api(tags = "店铺用户账号信息") public class ShopUserAccountController { private final ShopUserAccountService shopUserAccountService; private final ShopUserService shopUserService; public ShopUserAccountController(ShopUserAccountService shopUserAccountService, ShopUserService shopUserService) { this.shopUserAccountService = shopUserAccountService; this.shopUserService = shopUserService; } @GetMapping @ApiOperation(value = "获取账号信息", notes = "获取账号信息") public ServerResponseEntity<AuthAccountVO> getAccount(Long shopUserId) { return shopUserAccountService.getByUserIdAndSysType(shopUserId, AuthUserContext.get().getSysType()); } @PostMapping @ApiOperation(value = "添加账号", notes = "添加账号") public ServerResponseEntity<Void> addAccount(@Valid @RequestBody ChangeAccountDTO changeAccountDTO) { ShopUserVO shopUserVO = shopUserService.getByUserId(changeAccountDTO.getUserId()); if (shopUserVO == null) { return ServerResponseEntity.showFailMsg("无法获取账户信息"); } if (Objects.equals(shopUserVO.getHasAccount(), 1)) { return ServerResponseEntity.showFailMsg("已有账号,无需重复添加"); } if (!Objects.equals(shopUserVO.getShopId(), AuthUserContext.get().getTenantId())) { return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED); } return shopUserAccountService.save(changeAccountDTO); } @PutMapping @ApiOperation(value = "修改账号", notes = "修改账号") public ServerResponseEntity<Void> updateAccount(@Valid @RequestBody ChangeAccountDTO changeAccountDTO) { ShopUserVO shopUserVO = shopUserService.getByUserId(changeAccountDTO.getUserId()); if (shopUserVO == null || Objects.equals(shopUserVO.getHasAccount(), 0)) { return ServerResponseEntity.showFailMsg("无法获取账户信息"); } if (!Objects.equals(shopUserVO.getShopId(), AuthUserContext.get().getTenantId())) { return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED); } return shopUserAccountService.update(changeAccountDTO); } }
package com.mall4j.cloud.platform.controller; import com.mall4j.cloud.api.auth.vo.AuthAccountVO; import com.mall4j.cloud.common.response.ServerResponseEntity; import com.mall4j.cloud.common.security.AuthUserContext; import com.mall4j.cloud.platform.dto.ChangeAccountDTO; import com.mall4j.cloud.platform.service.SysUserAccountService; import com.mall4j.cloud.platform.service.SysUserService; import com.mall4j.cloud.platform.vo.SysUserVO; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.Objects; /** * @author lhd * @date 2020/12/21 */ @RequestMapping(value = "/sys_user/account") @RestController @Api(tags = "平台用户账号信息") public class SysUserAccountController { private final SysUserAccountService SysUserAccountService; private final SysUserService SysUserService; public SysUserAccountController(SysUserAccountService sysUserAccountService, SysUserService sysUserService) { this.SysUserAccountService = sysUserAccountService; this.SysUserService = sysUserService; } @GetMapping @ApiOperation(value = "获取账号信息", notes = "获取账号信息") public ServerResponseEntity<AuthAccountVO> getAccount(Long userId) { return SysUserAccountService.getByUserIdAndSysType(userId, AuthUserContext.get().getSysType()); } @PostMapping @ApiOperation(value = "添加账号", notes = "添加账号") public ServerResponseEntity<Void> addAccount(@Valid @RequestBody ChangeAccountDTO changeAccountDTO) { SysUserVO sysUserVO = SysUserService.getByUserId(changeAccountDTO.getUserId()); if (sysUserVO == null) { return ServerResponseEntity.showFailMsg("无法获取账户信息"); } if (Objects.equals(sysUserVO.getHasAccount(), 1)) { return ServerResponseEntity.showFailMsg("已有账号,无需重复添加"); } return SysUserAccountService.save(changeAccountDTO); } @PutMapping @ApiOperation(value = "修改账号", notes = "修改账号") public ServerResponseEntity<Void> updateAccount(@Valid @RequestBody ChangeAccountDTO changeAccountDTO) { SysUserVO sysUserVO = SysUserService.getByUserId(changeAccountDTO.getUserId()); if (sysUserVO == null || Objects.equals(sysUserVO.getHasAccount(), 0)) { return ServerResponseEntity.showFailMsg("无法获取账户信息"); } return SysUserAccountService.update(changeAccountDTO); } }
package com.metamagic.ms.controller.write; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.metamagic.ms.bean.ResponseBean; import com.metamagic.ms.dto.UserDTO; import com.metamagic.ms.exception.BussinessException; import com.metamagic.ms.exception.RepositoryException; import com.metamagic.ms.service.write.UserWriteService; import ch.qos.logback.classic.Logger; /** * @author sagar * * THIS CONTROLLER USED FOR USER OPERATION */ @RestController @RequestMapping("/user") public class UserController { private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(UserController.class); @Autowired private UserWriteService userWriteService; /** * THIS METHOD USED FOR CREATE USER */ @PostMapping(value = "/create", produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity<ResponseBean> createUser(@RequestBody UserDTO userDTO) { try { userWriteService.createUser(userDTO); ResponseBean responseBean = new ResponseBean(true, "User saved successfully.", "success", null); return new ResponseEntity<ResponseBean>(responseBean, HttpStatus.OK); } catch (RepositoryException e) { ResponseBean responseBean = new ResponseBean(false, e.getMessage(), "failure", null); LOGGER.error("User creation failed:" + e.getMessage()); return new ResponseEntity<ResponseBean>(responseBean, HttpStatus.OK); } catch (BussinessException e) { ResponseBean responseBean = new ResponseBean(false, e.getMessage(), "failure", null); LOGGER.error("User creation failed:" + e.getMessage()); return new ResponseEntity<ResponseBean>(responseBean, HttpStatus.OK); } } }
package com.metamagic.ms.controller.read; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.metamagic.ms.aspect.LoginInfoHelperBean; import com.metamagic.ms.bean.ResponseBean; import com.metamagic.ms.exception.RepositoryException; import com.metamagic.ms.service.read.OrderReadService; /** * @author sagar * * THIS CONTROLLER IS USED FOR READ ORDER * */ @RestController @RequestMapping("/order/query") @Scope("request") public class OrderQueryController { @Autowired private OrderReadService orderReadService; @Autowired private LoginInfoHelperBean infoHelperBean; /** * THIS METHOD IS USED FOR GET ORDER HISTORY */ @RequestMapping(value = "/orderhistory", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity<ResponseBean> findAll() { try { ResponseBean response = new ResponseBean(true, "Data retrieved successfully", "success", orderReadService.findAll(infoHelperBean.getUserId())); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } catch (RepositoryException e) { ResponseBean response = new ResponseBean(false, e.getMessage(), "failed", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } } /** * THIS METHOD RETURN ORDER ID OF LOGGED IN USER */ @RequestMapping(value = "/getOrderDetails", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity<ResponseBean> getOrderDetails() { try { ResponseBean response = new ResponseBean(true, "Data retrieved successfully", "success", orderReadService.getOrderDetails(infoHelperBean.getUserId())); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } catch (RepositoryException e) { ResponseBean response = new ResponseBean(false, e.getMessage(), "failed", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } } }
package com.metamagic.ms.controller.write; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.metamagic.ms.bean.ResponseBean; import com.metamagic.ms.dto.PaymentDTO; import com.metamagic.ms.dto.ShippingAddressDTO; import com.metamagic.ms.exception.BussinessException; import com.metamagic.ms.exception.RepositoryException; import com.metamagic.ms.service.write.OrderWriteService; /** * @author sagar * * THIS CONTROLLER IS USED FOR ADDING SHIPPING ADDDRESS AND PAYMENT * DETAILS OD ORDER */ @RestController @RequestMapping("/order/write") @Scope("request") public class OrderWriteController { @Autowired private OrderWriteService orderWriteService; /** * THIS METHOD IS USED FOR ADD SHIPPING ADDRESS */ @PostMapping(value = "/addshippingaddress", produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity<ResponseBean> addShippingAddress(@RequestBody ShippingAddressDTO addressDTO) { try { orderWriteService.addShippingAddressDetails(addressDTO); ResponseBean responseBean = new ResponseBean(true, "Shipping address added successfully.", "success", null); return new ResponseEntity<ResponseBean>(responseBean, HttpStatus.OK); } catch (RepositoryException e) { ResponseBean responseBean = new ResponseBean(false, e.getMessage(), "failure", null); return new ResponseEntity<ResponseBean>(responseBean, HttpStatus.OK); } catch (BussinessException e) { ResponseBean responseBean = new ResponseBean(false, e.getMessage(), "failure", null); return new ResponseEntity<ResponseBean>(responseBean, HttpStatus.OK); } catch (Exception e) { ResponseBean responseBean = new ResponseBean(false, e.getMessage(), "failure", null); return new ResponseEntity<ResponseBean>(responseBean, HttpStatus.OK); } } /** * THIS METHOD IS USED FOR ADD PAYMENT DETAILS */ @PostMapping(value = "/addpaymentdetails", produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity<ResponseBean> addPaymentDetails(@RequestBody PaymentDTO paymentDTO) { try { orderWriteService.addPaymentDetails(paymentDTO); ResponseBean responseBean = new ResponseBean(true, "Payment done successfully.", "success", null); return new ResponseEntity<ResponseBean>(responseBean, HttpStatus.OK); } catch (RepositoryException e) { ResponseBean responseBean = new ResponseBean(false, e.getMessage(), "failure", null); return new ResponseEntity<ResponseBean>(responseBean, HttpStatus.OK); } catch (BussinessException e) { ResponseBean responseBean = new ResponseBean(false, e.getMessage(), "failure", null); return new ResponseEntity<ResponseBean>(responseBean, HttpStatus.OK); } catch (Exception e) { ResponseBean responseBean = new ResponseBean(false, e.getMessage(), "failure", null); return new ResponseEntity<ResponseBean>(responseBean, HttpStatus.OK); } } }
package com.metamagic.ms.controller.read; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.metamagic.ms.bean.ResponseBean; import com.metamagic.ms.exception.RepositoryException; import com.metamagic.ms.service.read.ProductReadService; /** * @author sagar * * THIS CONTROLLER USED FOR PRODUCT READ */ @RestController @RequestMapping("/product/query") public class ProductQueryController { @Autowired private ProductReadService productService; /** * ThIS METHOD IS USED FOR FINDING ALL PRODUCT */ @RequestMapping(value = "/findall", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity<ResponseBean> findAll() { try { ResponseBean response = new ResponseBean(true, "Data retrieved successfully", "success", productService.getProducts()); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } catch (RepositoryException e) { ResponseBean response = new ResponseBean(false, e.getMessage(), "failed", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } } }
package com.metamagic.ms.controller.write; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.metamagic.ms.bean.ResponseBean; import com.metamagic.ms.entity.Product; import com.metamagic.ms.exception.RepositoryException; import com.metamagic.ms.service.write.ProductWriteService; /** * @author sagar * * THIS CONTROLLER USED FOR WRITE PRODUCT OPERATION */ @RestController @RequestMapping("/product/write") public class ProductWriteController { @Autowired private ProductWriteService productService; /** * THIS METHOD IS USED FOR SAVE PRODUCT */ @RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity<ResponseBean> save(@RequestBody Product product) { try { productService.save(product); ResponseBean response = new ResponseBean(true, "Data retrieved successfully", "success", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } catch (RepositoryException e) { ResponseBean response = new ResponseBean(false, e.getMessage(), "failed", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } } }
package com.metamagic.ms.controller.write; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.metamagic.ms.aspect.LoginInfoHelperBean; import com.metamagic.ms.bean.ResponseBean; import com.metamagic.ms.dto.CartDTO; import com.metamagic.ms.exception.IllegalArgumentCustomException; import com.metamagic.ms.service.write.ShoppingCartWriteService; import ch.qos.logback.classic.Logger; /** * @author sagar THIS CONTROLLER IS USED FOR WRTIE CART OPERATION */ @RestController @RequestMapping("/shoppingcart/write") @Scope("request") public class ShoppingCartWriteController { @Autowired private LoginInfoHelperBean loginInfoHelperBean; @Autowired private ShoppingCartWriteService shoppingCartService; /** * THIS METHOD IS USED FOR CREATE CART * @throws IllegalArgumentCustomException */ @PostMapping("/create") public @ResponseBody ResponseEntity<ResponseBean> createCart(@RequestBody CartDTO cart) throws IllegalArgumentCustomException { cart.setCartId(loginInfoHelperBean.getUserId()); cart.setCustomerId(loginInfoHelperBean.getUserId()); shoppingCartService.createCart(cart); ResponseBean response = new ResponseBean(true, "Cart created.", "success", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } @PostMapping("/additem") public @ResponseBody ResponseEntity<ResponseBean> addItem(@RequestBody CartDTO cart) throws IllegalArgumentCustomException { cart.setCartId(loginInfoHelperBean.getUserId()); cart.setCustomerId(loginInfoHelperBean.getUserId()); shoppingCartService.addItem(cart); ResponseBean response = new ResponseBean(true, "Item added.", "success", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } @PostMapping("/removeitem") public @ResponseBody ResponseEntity<ResponseBean> removeItem(@RequestBody CartDTO cart) { try { cart.setCartId(loginInfoHelperBean.getUserId()); cart.setCustomerId(loginInfoHelperBean.getUserId()); shoppingCartService.removeItem(cart); ResponseBean response = new ResponseBean(true, "Item removed.", "success", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } catch (IllegalArgumentCustomException e) { ResponseBean response = new ResponseBean(false, "Item removed failed", "failed", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } } @PostMapping("/placeorder") public @ResponseBody ResponseEntity<ResponseBean> placeOrder(@RequestBody CartDTO cart) { try { cart.setCartId(loginInfoHelperBean.getUserId()); cart.setCustomerId(loginInfoHelperBean.getUserId()); shoppingCartService.placeOrder(cart); ResponseBean response = new ResponseBean(true, "order placed.", "success", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } catch (IllegalArgumentCustomException e) { ResponseBean response = new ResponseBean(false, "order placed failed", "failed", null); return new ResponseEntity<ResponseBean>(response, HttpStatus.OK); } } }
package com.own.file.controller; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.own.face.util.Resp; import com.own.face.util.base.BaseController; import io.swagger.annotations.ApiOperation; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; @RestController @RequestMapping("/file") public class FileController extends BaseController { private static final String tTmpInfoFilePath = "/opt/temp/"; private static final String tRealInfofilePath = "/opt/real/"; @ApiOperation(value = "图片上传接口") @PostMapping("/picture") public @ResponseBody Resp uploadFile(MultipartHttpServletRequest request) { File fileUploadPath = new File(tTmpInfoFilePath);//tme if (!fileUploadPath.exists()) fileUploadPath.mkdirs(); List<MultipartFile> files = request.getFiles("file"); String realFileName = null; if (!files.get(0).isEmpty()) { String originalFileName = files.get(0).getOriginalFilename(); UUID uuid = UUID.randomUUID(); realFileName = uuid + originalFileName.substring(originalFileName.lastIndexOf(".")); try { byte[] bytes = files.get(0).getBytes(); FileOutputStream fos = new FileOutputStream( tTmpInfoFilePath + File.separator + realFileName);// 写入文件 fos.write(bytes); fos.close(); } catch (IOException e) { e.printStackTrace(); } } return new Resp(realFileName,HttpStatus.ACCEPTED.value(),"success"); } @ApiOperation(value = "下载临时文件图片 根据imgUri获得图片并输出到response") @GetMapping("/tmpPicture/{fileName}/{fileSuffix}") public @ResponseBody void downloadTmpFile(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileName, @PathVariable String fileSuffix) { response.setHeader("Content-Disposition", "attachment; filename=" + fileName); String filePath = tTmpInfoFilePath + "/" + fileName + "." + fileSuffix; try { FileInputStream imageIn = new FileInputStream(filePath); BufferedInputStream bis = new BufferedInputStream(imageIn); BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream()); byte data[] = new byte[4096]; int size = 0; size = bis.read(data); while (size != -1) { bos.write(data, 0, size); size = bis.read(data); } bis.close(); bos.flush(); bos.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 下载图片 根据imgUri获得图片并输出到response * * @param request * @param response * @param fileName * @param fileSuffix */ @RequestMapping(value = "/Picture/{fileName}/{fileSuffix}", method = RequestMethod.GET) public @ResponseBody void downloadFile(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileName, @PathVariable String fileSuffix) { response.setHeader("Content-Disposition", "attachment; filename=" + fileName); String filePath = tRealInfofilePath + "/" + fileName + "." + fileSuffix; try { FileInputStream imageIn = new FileInputStream(filePath); BufferedInputStream bis = new BufferedInputStream(imageIn); BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream()); byte data[] = new byte[4096]; int size = 0; size = bis.read(data); while (size != -1) { bos.write(data, 0, size); size = bis.read(data); } bis.close(); bos.flush(); bos.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } /** * * * @param fileNames 移动图片的名称数组 例如 [a.png,b.jpb,c.png] */ @ApiOperation(value = "将图片从临时目录移动到真实目录,并删除临时路径图片") @PostMapping("/Copy/{fileNames}") public @ResponseBody void Copy(@PathVariable String[] fileNames) { File file = null; FileInputStream fis = null; BufferedInputStream bis = null; FileOutputStream fos = null; for (String fileName : fileNames) { try { file = new File(tTmpInfoFilePath + "/" + fileName); if (!file.exists()) { continue; } fis = new FileInputStream(file); bis = new BufferedInputStream(fis); fos = new FileOutputStream(tRealInfofilePath + "/" + fileName);// 写入文件 byte data[] = new byte[4096]; int size = 0; size = bis.read(data); while (size != -1) { fos.write(data, 0, size); size = bis.read(data); } fos.flush(); } catch (IOException e) { e.printStackTrace(); // throw new IFException("500","将图片从临时路径拷贝到真实路径出错..."); } finally { try { if (fis != null) fis.close(); if (bis != null) bis.close(); if (fos != null) fos.close(); if (file.exists()) file.delete();// 删除临时路径图片 } catch (Exception e) { e.printStackTrace(); } } } } }
package com.moxi.mogublog.web.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.moxi.mogublog.commons.entity.Blog; import com.moxi.mogublog.commons.entity.BlogSort; import com.moxi.mogublog.commons.entity.SystemConfig; import com.moxi.mogublog.commons.entity.Tag; import com.moxi.mogublog.commons.feign.PictureFeignClient; import com.moxi.mogublog.utils.ResultUtil; import com.moxi.mogublog.utils.StringUtils; import com.moxi.mogublog.web.global.SQLConf; import com.moxi.mogublog.web.global.SysConf; import com.moxi.mogublog.xo.service.*; import com.moxi.mogublog.xo.utils.WebUtil; import com.moxi.mougblog.base.enums.ELevel; import com.moxi.mougblog.base.enums.EPublish; import com.moxi.mougblog.base.enums.EStatus; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Controller; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; /** * FreemarkController * * @author: 陌溪 * @create: 2020-03-04-11:23 */ @RequestMapping("freemarker") @RefreshScope @Controller public class FreemarkerController { @Autowired WebUtil webUtil; @Autowired WebConfigService webConfigService; @Autowired SystemConfigService systemConfigService; @Autowired BlogService blogService; @Autowired TagService tagService; @Autowired BlogSortService blogSortService; @Autowired LinkService linkService; @Autowired private PictureFeignClient pictureFeignClient; @Value(value = "${file.upload.path}") private String fileUploadPath; @Value(value = "${data.webSite.url}") private String webSiteUrl; @Value(value = "${data.web.url}") private String webUrl; @RequestMapping("/info/{uid}") public String index(Map<String, Object> map, @PathVariable("uid") String uid) { // fc98d2ae7756d2587390ae441b82f52d List<Blog> sameBlog = blogService.getSameBlogByBlogUid(uid); sameBlog = setBlog(sameBlog); List<Blog> thirdBlog = blogService.getBlogListByLevel(ELevel.THIRD); thirdBlog = setBlog(thirdBlog); List<Blog> fourthBlog = blogService.getBlogListByLevel(ELevel.FOURTH); fourthBlog = setBlog(fourthBlog); SystemConfig systemConfig = systemConfigService.getConfig(); if (systemConfig == null) { return ResultUtil.result(SysConf.ERROR, "系统配置为空"); } map.put("vueWebBasePath", webSiteUrl); map.put("webBasePath", webUrl); map.put("staticBasePath", systemConfig.getLocalPictureBaseUrl()); map.put("webConfig", webConfigService.getWebConfig()); map.put("blog", blogService.getBlogByUid(uid)); map.put("sameBlog", sameBlog); map.put("thirdBlogList", thirdBlog); map.put("fourthBlogList", fourthBlog); map.put("fourthBlogList", fourthBlog); map.put("hotBlogList", blogService.getBlogListByTop(SysConf.FIVE)); return "info"; } /** * 生成静态文件 * * @throws IOException * @throws TemplateException */ public void generateHtml(String uid) { try { //创建配置类 Configuration configuration = new Configuration(Configuration.getVersion()); String classpath = this.getClass().getResource("/").getPath(); //设置模板路径 configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/")); //设置字符集 configuration.setDefaultEncoding("utf-8"); //加载模板 Template template = configuration.getTemplate("info.ftl"); //数据模型 Map map = new HashMap(); List<Blog> sameBlog = blogService.getSameBlogByBlogUid(uid); sameBlog = setBlog(sameBlog); List<Blog> thirdBlog = blogService.getBlogListByLevel(ELevel.THIRD); thirdBlog = setBlog(thirdBlog); List<Blog> fourthBlog = blogService.getBlogListByLevel(ELevel.FOURTH); fourthBlog = setBlog(fourthBlog); map.put("vueWebBasePath", "http://localhost:9527/#/"); map.put("webBasePath", "http://localhost:8603"); map.put("staticBasePath", "http://localhost:8600"); map.put("webConfig", webConfigService.getWebConfig()); map.put("blog", blogService.getBlogByUid(uid)); map.put("sameBlog", sameBlog); map.put("hotBlogList", blogService.getBlogListByTop(SysConf.FIVE)); //静态化 String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map); InputStream inputStream = IOUtils.toInputStream(content); //输出文件 String savePath = fileUploadPath + "/blog/page/" + uid + ".html"; FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath)); int copy = IOUtils.copy(inputStream, fileOutputStream); } catch (Exception e) { e.getMessage(); } } /** * 生成所有博客的静态文件 */ @RequestMapping("/getAllHtml") @ResponseBody public String getAllHtml() throws IOException { FileOutputStream fileOutputStream = null; InputStream inputStream = null; try { //创建配置类 Configuration configuration = new Configuration(Configuration.getVersion()); String classpath = this.getClass().getResource("/").getPath(); //设置模板路径 configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/")); //设置字符集 configuration.setDefaultEncoding("utf-8"); //加载模板 Template template = configuration.getTemplate("info.ftl"); QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); queryWrapper.eq(SQLConf.IS_PUBLISH, EPublish.PUBLISH); List<Blog> blogList = blogService.list(queryWrapper); blogList = setBlog(blogList); Map<String, List<Blog>> blogMap = new HashMap<>(); List<Blog> thirdBlog = new ArrayList<>(); List<Blog> fourthBlog = new ArrayList<>(); List<Blog> hotBlogList = blogService.getBlogListByTop(SysConf.FIVE); blogList.forEach(item -> { if (item.getLevel() == ELevel.THIRD) { thirdBlog.add(item); } else if (item.getLevel() == ELevel.FOURTH) { fourthBlog.add(item); } List<Blog> tempList = blogMap.get(item.getBlogSortUid()); if (tempList != null && tempList.size() > 0) { tempList.add(item); blogMap.put(item.getBlogSortUid(), tempList); } else { List<Blog> temp = new ArrayList<>(); temp.add(item); blogMap.put(item.getBlogSortUid(), temp); } }); SystemConfig systemConfig = systemConfigService.getConfig(); if (systemConfig == null) { return ResultUtil.result(SysConf.ERROR, "系统配置为空"); } for (int a = 0; a < blogList.size(); a++) { //数据模型 Map map = new HashMap(); List<Blog> sameBlog = blogMap.get(blogList.get(a).getBlogSortUid()); map.put("vueWebBasePath", webSiteUrl); map.put("webBasePath", webUrl); map.put("staticBasePath", systemConfig.getLocalPictureBaseUrl()); map.put("webConfig", webConfigService.getWebConfig()); map.put("blog", blogList.get(a)); map.put("sameBlog", sameBlog); map.put("thirdBlogList", thirdBlog); map.put("fourthBlogList", fourthBlog); map.put("hotBlogList", hotBlogList); //静态化 String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map); inputStream = IOUtils.toInputStream(content); //输出文件 String savePath = fileUploadPath + "/blog/page/" + blogList.get(a).getUid() + ".html"; fileOutputStream = new FileOutputStream(new File(savePath)); IOUtils.copy(inputStream, fileOutputStream); } return ResultUtil.result(SysConf.SUCCESS, "生成成功"); } catch (Exception e) { e.getMessage(); } finally { inputStream.close(); fileOutputStream.close(); } return ResultUtil.result(SysConf.SUCCESS, "生成失败"); } /** * 设置博客的分类标签和内容 * * @param list * @return */ private List<Blog> setBlog(List<Blog> list) { final StringBuffer fileUids = new StringBuffer(); List<String> sortUids = new ArrayList<>(); List<String> tagUids = new ArrayList<>(); list.forEach(item -> { if (StringUtils.isNotEmpty(item.getFileUid())) { fileUids.append(item.getFileUid() + SysConf.FILE_SEGMENTATION); } if (StringUtils.isNotEmpty(item.getBlogSortUid())) { sortUids.add(item.getBlogSortUid()); } if (StringUtils.isNotEmpty(item.getTagUid())) { tagUids.add(item.getTagUid()); } }); String pictureList = null; if (fileUids != null) { pictureList = this.pictureFeignClient.getPicture(fileUids.toString(), SysConf.FILE_SEGMENTATION); } List<Map<String, Object>> picList = webUtil.getPictureMap(pictureList); Collection<BlogSort> sortList = new ArrayList<>(); Collection<Tag> tagList = new ArrayList<>(); if (sortUids.size() > 0) { sortList = blogSortService.listByIds(sortUids); } if (tagUids.size() > 0) { tagList = tagService.listByIds(tagUids); } Map<String, BlogSort> sortMap = new HashMap<>(); Map<String, Tag> tagMap = new HashMap<>(); Map<String, String> pictureMap = new HashMap<>(); sortList.forEach(item -> { sortMap.put(item.getUid(), item); }); tagList.forEach(item -> { tagMap.put(item.getUid(), item); }); picList.forEach(item -> { pictureMap.put(item.get(SQLConf.UID).toString(), item.get(SQLConf.URL).toString()); }); for (Blog item : list) { //设置分类 if (StringUtils.isNotEmpty(item.getBlogSortUid())) { item.setBlogSort(sortMap.get(item.getBlogSortUid())); } //获取标签 if (StringUtils.isNotEmpty(item.getTagUid())) { List<String> tagUidsTemp = StringUtils.changeStringToString(item.getTagUid(), SysConf.FILE_SEGMENTATION); List<Tag> tagListTemp = new ArrayList<Tag>(); tagUidsTemp.forEach(tag -> { tagListTemp.add(tagMap.get(tag)); }); item.setTagList(tagListTemp); } //获取图片 if (StringUtils.isNotEmpty(item.getFileUid())) { List<String> pictureUidsTemp = StringUtils.changeStringToString(item.getFileUid(), SysConf.FILE_SEGMENTATION); List<String> pictureListTemp = new ArrayList<>(); pictureUidsTemp.forEach(picture -> { pictureListTemp.add(pictureMap.get(picture)); }); item.setPhotoList(pictureListTemp); } } return list; } }
package com.macro.mall.service.impl; import com.github.pagehelper.PageHelper; import com.macro.mall.dao.PmsProductCategoryAttributeRelationDao; import com.macro.mall.dao.PmsProductCategoryDao; import com.macro.mall.dto.PmsProductCategoryParam; import com.macro.mall.dto.PmsProductCategoryWithChildrenItem; import com.macro.mall.mapper.PmsProductCategoryAttributeRelationMapper; import com.macro.mall.mapper.PmsProductCategoryMapper; import com.macro.mall.mapper.PmsProductMapper; import com.macro.mall.model.*; import com.macro.mall.service.PmsProductCategoryService; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * PmsProductCategoryService实现类 * Created by macro on 2018/4/26. */ @Service public class PmsProductCategoryServiceImpl implements PmsProductCategoryService { @Autowired private PmsProductCategoryMapper productCategoryMapper; @Autowired private PmsProductMapper productMapper; @Autowired private PmsProductCategoryAttributeRelationDao productCategoryAttributeRelationDao; @Autowired private PmsProductCategoryAttributeRelationMapper productCategoryAttributeRelationMapper; @Autowired private PmsProductCategoryDao productCategoryDao; @Override public int create(PmsProductCategoryParam pmsProductCategoryParam) { PmsProductCategory productCategory = new PmsProductCategory(); productCategory.setProductCount(0); BeanUtils.copyProperties(pmsProductCategoryParam, productCategory); //没有父分类时为一级分类 setCategoryLevel(productCategory); int count = productCategoryMapper.insertSelective(productCategory); //创建筛选属性关联 List<Long> productAttributeIdList = pmsProductCategoryParam.getProductAttributeIdList(); if(!CollectionUtils.isEmpty(productAttributeIdList)){ insertRelationList(productCategory.getId(), productAttributeIdList); } return count; } /** * 批量插入商品分类与筛选属性关系表 * @param productCategoryId 商品分类id * @param productAttributeIdList 相关商品筛选属性id集合 */ private void insertRelationList(Long productCategoryId, List<Long> productAttributeIdList) { List<PmsProductCategoryAttributeRelation> relationList = new ArrayList<>(); for (Long productAttrId : productAttributeIdList) { PmsProductCategoryAttributeRelation relation = new PmsProductCategoryAttributeRelation(); relation.setProductAttributeId(productAttrId); relation.setProductCategoryId(productCategoryId); relationList.add(relation); } productCategoryAttributeRelationDao.insertList(relationList); } @Override public int update(Long id, PmsProductCategoryParam pmsProductCategoryParam) { PmsProductCategory productCategory = new PmsProductCategory(); productCategory.setId(id); BeanUtils.copyProperties(pmsProductCategoryParam, productCategory); setCategoryLevel(productCategory); //更新商品分类时要更新商品中的名称 PmsProduct product = new PmsProduct(); product.setProductCategoryName(productCategory.getName()); PmsProductExample example = new PmsProductExample(); example.createCriteria().andProductCategoryIdEqualTo(id); productMapper.updateByExampleSelective(product,example); //同时更新筛选属性的信息 if(!CollectionUtils.isEmpty(pmsProductCategoryParam.getProductAttributeIdList())){ PmsProductCategoryAttributeRelationExample relationExample = new PmsProductCategoryAttributeRelationExample(); relationExample.createCriteria().andProductCategoryIdEqualTo(id); productCategoryAttributeRelationMapper.deleteByExample(relationExample); insertRelationList(id,pmsProductCategoryParam.getProductAttributeIdList()); }else{ PmsProductCategoryAttributeRelationExample relationExample = new PmsProductCategoryAttributeRelationExample(); relationExample.createCriteria().andProductCategoryIdEqualTo(id); productCategoryAttributeRelationMapper.deleteByExample(relationExample); } return productCategoryMapper.updateByPrimaryKeySelective(productCategory); } @Override public List<PmsProductCategory> getList(Long parentId, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); PmsProductCategoryExample example = new PmsProductCategoryExample(); example.setOrderByClause("sort desc"); example.createCriteria().andParentIdEqualTo(parentId); return productCategoryMapper.selectByExample(example); } @Override public int delete(Long id) { return productCategoryMapper.deleteByPrimaryKey(id); } @Override public PmsProductCategory getItem(Long id) { return productCategoryMapper.selectByPrimaryKey(id); } @Override public int updateNavStatus(List<Long> ids, Integer navStatus) { PmsProductCategory productCategory = new PmsProductCategory(); productCategory.setNavStatus(navStatus); PmsProductCategoryExample example = new PmsProductCategoryExample(); example.createCriteria().andIdIn(ids); return productCategoryMapper.updateByExampleSelective(productCategory, example); } @Override public int updateShowStatus(List<Long> ids, Integer showStatus) { PmsProductCategory productCategory = new PmsProductCategory(); productCategory.setShowStatus(showStatus); PmsProductCategoryExample example = new PmsProductCategoryExample(); example.createCriteria().andIdIn(ids); return productCategoryMapper.updateByExampleSelective(productCategory, example); } @Override public List<PmsProductCategoryWithChildrenItem> listWithChildren() { return productCategoryDao.listWithChildren(); } /** * 根据分类的parentId设置分类的level */ private void setCategoryLevel(PmsProductCategory productCategory) { //没有父分类时为一级分类 if (productCategory.getParentId() == 0) { productCategory.setLevel(0); } else { //有父分类时选择根据父分类level设置 PmsProductCategory parentCategory = productCategoryMapper.selectByPrimaryKey(productCategory.getParentId()); if (parentCategory != null) { productCategory.setLevel(parentCategory.getLevel() + 1); } else { productCategory.setLevel(0); } } } }
package com.macro.mall.service.impl; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.crypto.digest.BCrypt; import cn.hutool.json.JSONUtil; import com.github.pagehelper.PageHelper; import com.macro.mall.common.api.CommonResult; import com.macro.mall.common.api.ResultCode; import com.macro.mall.common.constant.AuthConstant; import com.macro.mall.common.domain.UserDto; import com.macro.mall.common.exception.Asserts; import com.macro.mall.dao.UmsAdminRoleRelationDao; import com.macro.mall.dto.UmsAdminParam; import com.macro.mall.dto.UpdateAdminPasswordParam; import com.macro.mall.mapper.UmsAdminLoginLogMapper; import com.macro.mall.mapper.UmsAdminMapper; import com.macro.mall.mapper.UmsAdminRoleRelationMapper; import com.macro.mall.model.*; import com.macro.mall.service.AuthService; import com.macro.mall.service.UmsAdminCacheService; import com.macro.mall.service.UmsAdminService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.*; import java.util.stream.Collectors; /** * UmsAdminService实现类 * Created by macro on 2018/4/26. */ @Service public class UmsAdminServiceImpl implements UmsAdminService { private static final Logger LOGGER = LoggerFactory.getLogger(UmsAdminServiceImpl.class); @Autowired private UmsAdminMapper adminMapper; @Autowired private UmsAdminRoleRelationMapper adminRoleRelationMapper; @Autowired private UmsAdminRoleRelationDao adminRoleRelationDao; @Autowired private UmsAdminLoginLogMapper loginLogMapper; @Autowired private AuthService authService; @Autowired private UmsAdminCacheService adminCacheService; @Autowired private HttpServletRequest request; @Override public UmsAdmin getAdminByUsername(String username) { UmsAdminExample example = new UmsAdminExample(); example.createCriteria().andUsernameEqualTo(username); List<UmsAdmin> adminList = adminMapper.selectByExample(example); if (adminList != null && adminList.size() > 0) { return adminList.get(0); } return null; } @Override public UmsAdmin register(UmsAdminParam umsAdminParam) { UmsAdmin umsAdmin = new UmsAdmin(); BeanUtils.copyProperties(umsAdminParam, umsAdmin); umsAdmin.setCreateTime(new Date()); umsAdmin.setStatus(1); //查询是否有相同用户名的用户 UmsAdminExample example = new UmsAdminExample(); example.createCriteria().andUsernameEqualTo(umsAdmin.getUsername()); List<UmsAdmin> umsAdminList = adminMapper.selectByExample(example); if (umsAdminList.size() > 0) { return null; } //将密码进行加密操作 String encodePassword = BCrypt.hashpw(umsAdmin.getPassword()); umsAdmin.setPassword(encodePassword); adminMapper.insert(umsAdmin); return umsAdmin; } @Override public CommonResult login(String username, String password) { if(StrUtil.isEmpty(username)||StrUtil.isEmpty(password)){ Asserts.fail("用户名或密码不能为空!"); } Map<String, String> params = new HashMap<>(); params.put("client_id", AuthConstant.ADMIN_CLIENT_ID); params.put("client_secret","123456"); params.put("grant_type","password"); params.put("username",username); params.put("password",password); CommonResult restResult = authService.getAccessToken(params); if(ResultCode.SUCCESS.getCode()==restResult.getCode()&&restResult.getData()!=null){ // updateLoginTimeByUsername(username); insertLoginLog(username); } return restResult; } /** * 添加登录记录 * @param username 用户名 */ private void insertLoginLog(String username) { UmsAdmin admin = getAdminByUsername(username); if(admin==null) return; UmsAdminLoginLog loginLog = new UmsAdminLoginLog(); loginLog.setAdminId(admin.getId()); loginLog.setCreateTime(new Date()); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); loginLog.setIp(request.getRemoteAddr()); loginLogMapper.insert(loginLog); } /** * 根据用户名修改登录时间 */ private void updateLoginTimeByUsername(String username) { UmsAdmin record = new UmsAdmin(); record.setLoginTime(new Date()); UmsAdminExample example = new UmsAdminExample(); example.createCriteria().andUsernameEqualTo(username); adminMapper.updateByExampleSelective(record, example); } @Override public UmsAdmin getItem(Long id) { return adminMapper.selectByPrimaryKey(id); } @Override public List<UmsAdmin> list(String keyword, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); UmsAdminExample example = new UmsAdminExample(); UmsAdminExample.Criteria criteria = example.createCriteria(); if (!StringUtils.isEmpty(keyword)) { criteria.andUsernameLike("%" + keyword + "%"); example.or(example.createCriteria().andNickNameLike("%" + keyword + "%")); } return adminMapper.selectByExample(example); } @Override public int update(Long id, UmsAdmin admin) { admin.setId(id); UmsAdmin rawAdmin = adminMapper.selectByPrimaryKey(id); if(rawAdmin.getPassword().equals(admin.getPassword())){ //与原加密密码相同的不需要修改 admin.setPassword(null); }else{ //与原加密密码不同的需要加密修改 if(StrUtil.isEmpty(admin.getPassword())){ admin.setPassword(null); }else{ admin.setPassword(BCrypt.hashpw(admin.getPassword())); } } int count = adminMapper.updateByPrimaryKeySelective(admin); adminCacheService.delAdmin(id); return count; } @Override public int delete(Long id) { int count = adminMapper.deleteByPrimaryKey(id); adminCacheService.delAdmin(id); return count; } @Override public int updateRole(Long adminId, List<Long> roleIds) { int count = roleIds == null ? 0 : roleIds.size(); //先删除原来的关系 UmsAdminRoleRelationExample adminRoleRelationExample = new UmsAdminRoleRelationExample(); adminRoleRelationExample.createCriteria().andAdminIdEqualTo(adminId); adminRoleRelationMapper.deleteByExample(adminRoleRelationExample); //建立新关系 if (!CollectionUtils.isEmpty(roleIds)) { List<UmsAdminRoleRelation> list = new ArrayList<>(); for (Long roleId : roleIds) { UmsAdminRoleRelation roleRelation = new UmsAdminRoleRelation(); roleRelation.setAdminId(adminId); roleRelation.setRoleId(roleId); list.add(roleRelation); } adminRoleRelationDao.insertList(list); } return count; } @Override public List<UmsRole> getRoleList(Long adminId) { return adminRoleRelationDao.getRoleList(adminId); } @Override public List<UmsResource> getResourceList(Long adminId) { return adminRoleRelationDao.getResourceList(adminId); } @Override public int updatePassword(UpdateAdminPasswordParam param) { if(StrUtil.isEmpty(param.getUsername()) ||StrUtil.isEmpty(param.getOldPassword()) ||StrUtil.isEmpty(param.getNewPassword())){ return -1; } UmsAdminExample example = new UmsAdminExample(); example.createCriteria().andUsernameEqualTo(param.getUsername()); List<UmsAdmin> adminList = adminMapper.selectByExample(example); if(CollUtil.isEmpty(adminList)){ return -2; } UmsAdmin umsAdmin = adminList.get(0); if(!BCrypt.checkpw(param.getOldPassword(),umsAdmin.getPassword())){ return -3; } umsAdmin.setPassword(BCrypt.hashpw(param.getNewPassword())); adminMapper.updateByPrimaryKey(umsAdmin); adminCacheService.delAdmin(umsAdmin.getId()); return 1; } @Override public UserDto loadUserByUsername(String username){ //获取用户信息 UmsAdmin admin = getAdminByUsername(username); if (admin != null) { List<UmsRole> roleList = getRoleList(admin.getId()); UserDto userDTO = new UserDto(); BeanUtils.copyProperties(admin,userDTO); if(CollUtil.isNotEmpty(roleList)){ List<String> roleStrList = roleList.stream().map(item -> item.getId() + "_" + item.getName()).collect(Collectors.toList()); userDTO.setRoles(roleStrList); } return userDTO; } return null; } @Override public UmsAdmin getCurrentAdmin() { String userStr = request.getHeader(AuthConstant.USER_TOKEN_HEADER); if(StrUtil.isEmpty(userStr)){ Asserts.fail(ResultCode.UNAUTHORIZED); } UserDto userDto = JSONUtil.toBean(userStr, UserDto.class); UmsAdmin admin = adminCacheService.getAdmin(userDto.getId()); if(admin!=null){ return admin; }else{ admin = adminMapper.selectByPrimaryKey(userDto.getId()); adminCacheService.setAdmin(admin); return admin; } } }
package com.macro.mall.portal.service.impl; import com.macro.mall.model.UmsMember; import com.macro.mall.portal.domain.MemberReadHistory; import com.macro.mall.portal.repository.MemberReadHistoryRepository; import com.macro.mall.portal.service.MemberReadHistoryService; import com.macro.mall.portal.service.UmsMemberService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * 会员浏览记录管理Service实现类 * Created by macro on 2018/8/3. */ @Service public class MemberReadHistoryServiceImpl implements MemberReadHistoryService { @Autowired private MemberReadHistoryRepository memberReadHistoryRepository; @Autowired private UmsMemberService memberService; @Override public int create(MemberReadHistory memberReadHistory) { UmsMember member = memberService.getCurrentMember(); memberReadHistory.setMemberId(member.getId()); memberReadHistory.setMemberNickname(member.getNickname()); memberReadHistory.setMemberIcon(member.getIcon()); memberReadHistory.setId(null); memberReadHistory.setCreateTime(new Date()); memberReadHistoryRepository.save(memberReadHistory); return 1; } @Override public int delete(List<String> ids) { List<MemberReadHistory> deleteList = new ArrayList<>(); for(String id:ids){ MemberReadHistory memberReadHistory = new MemberReadHistory(); memberReadHistory.setId(id); deleteList.add(memberReadHistory); } memberReadHistoryRepository.deleteAll(deleteList); return ids.size(); } @Override public Page<MemberReadHistory> list(Integer pageNum, Integer pageSize) { UmsMember member = memberService.getCurrentMember(); Pageable pageable = PageRequest.of(pageNum-1, pageSize); return memberReadHistoryRepository.findByMemberIdOrderByCreateTimeDesc(member.getId(),pageable); } @Override public void clear() { UmsMember member = memberService.getCurrentMember(); memberReadHistoryRepository.deleteAllByMemberId(member.getId()); } }
package com.macro.mall.portal.service.impl; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.crypto.digest.BCrypt; import cn.hutool.json.JSONUtil; import com.macro.mall.common.api.CommonResult; import com.macro.mall.common.api.ResultCode; import com.macro.mall.common.constant.AuthConstant; import com.macro.mall.common.domain.UserDto; import com.macro.mall.common.exception.Asserts; import com.macro.mall.mapper.UmsMemberLevelMapper; import com.macro.mall.mapper.UmsMemberMapper; import com.macro.mall.model.UmsMember; import com.macro.mall.model.UmsMemberExample; import com.macro.mall.model.UmsMemberLevel; import com.macro.mall.model.UmsMemberLevelExample; import com.macro.mall.portal.service.AuthService; import com.macro.mall.portal.service.UmsMemberCacheService; import com.macro.mall.portal.service.UmsMemberService; import org.apache.catalina.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletRequest; import java.util.*; /** * 会员管理Service实现类 * Created by macro on 2018/8/3. */ @Service public class UmsMemberServiceImpl implements UmsMemberService { private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class); @Autowired private UmsMemberMapper memberMapper; @Autowired private UmsMemberLevelMapper memberLevelMapper; @Autowired private UmsMemberCacheService memberCacheService; @Value("${redis.key.authCode}") private String REDIS_KEY_PREFIX_AUTH_CODE; @Value("${redis.expire.authCode}") private Long AUTH_CODE_EXPIRE_SECONDS; @Autowired private AuthService authService; @Autowired private HttpServletRequest request; @Override public UmsMember getByUsername(String username) { UmsMemberExample example = new UmsMemberExample(); example.createCriteria().andUsernameEqualTo(username); List<UmsMember> memberList = memberMapper.selectByExample(example); if (!CollectionUtils.isEmpty(memberList)) { return memberList.get(0); } return null; } @Override public UmsMember getById(Long id) { return memberMapper.selectByPrimaryKey(id); } @Override public void register(String username, String password, String telephone, String authCode) { //验证验证码 if(!verifyAuthCode(authCode,telephone)){ Asserts.fail("验证码错误"); } //查询是否已有该用户 UmsMemberExample example = new UmsMemberExample(); example.createCriteria().andUsernameEqualTo(username); example.or(example.createCriteria().andPhoneEqualTo(telephone)); List<UmsMember> umsMembers = memberMapper.selectByExample(example); if (!CollectionUtils.isEmpty(umsMembers)) { Asserts.fail("该用户已经存在"); } //没有该用户进行添加操作 UmsMember umsMember = new UmsMember(); umsMember.setUsername(username); umsMember.setPhone(telephone); umsMember.setPassword(BCrypt.hashpw(password)); umsMember.setCreateTime(new Date()); umsMember.setStatus(1); //获取默认会员等级并设置 UmsMemberLevelExample levelExample = new UmsMemberLevelExample(); levelExample.createCriteria().andDefaultStatusEqualTo(1); List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample); if (!CollectionUtils.isEmpty(memberLevelList)) { umsMember.setMemberLevelId(memberLevelList.get(0).getId()); } memberMapper.insert(umsMember); umsMember.setPassword(null); } @Override public String generateAuthCode(String telephone) { StringBuilder sb = new StringBuilder(); Random random = new Random(); for(int i=0;i<6;i++){ sb.append(random.nextInt(10)); } memberCacheService.setAuthCode(telephone,sb.toString()); return sb.toString(); } @Override public void updatePassword(String telephone, String password, String authCode) { UmsMemberExample example = new UmsMemberExample(); example.createCriteria().andPhoneEqualTo(telephone); List<UmsMember> memberList = memberMapper.selectByExample(example); if(CollectionUtils.isEmpty(memberList)){ Asserts.fail("该账号不存在"); } //验证验证码 if(!verifyAuthCode(authCode,telephone)){ Asserts.fail("验证码错误"); } UmsMember umsMember = memberList.get(0); umsMember.setPassword(BCrypt.hashpw(password)); memberMapper.updateByPrimaryKeySelective(umsMember); memberCacheService.delMember(umsMember.getId()); } @Override public UmsMember getCurrentMember() { String userStr = request.getHeader(AuthConstant.USER_TOKEN_HEADER); if(StrUtil.isEmpty(userStr)){ Asserts.fail(ResultCode.UNAUTHORIZED); } UserDto userDto = JSONUtil.toBean(userStr, UserDto.class); UmsMember member = memberCacheService.getMember(userDto.getId()); if(member!=null){ return member; }else{ member = getById(userDto.getId()); memberCacheService.setMember(member); return member; } } @Override public void updateIntegration(Long id, Integer integration) { UmsMember record=new UmsMember(); record.setId(id); record.setIntegration(integration); memberMapper.updateByPrimaryKeySelective(record); memberCacheService.delMember(id); } @Override public UserDto loadUserByUsername(String username) { UmsMember member = getByUsername(username); if(member!=null){ UserDto userDto = new UserDto(); BeanUtil.copyProperties(member,userDto); userDto.setRoles(CollUtil.toList("前台会员")); return userDto; } return null; } @Override public CommonResult login(String username, String password) { if(StrUtil.isEmpty(username)||StrUtil.isEmpty(password)){ Asserts.fail("用户名或密码不能为空!"); } Map<String, String> params = new HashMap<>(); params.put("client_id", AuthConstant.PORTAL_CLIENT_ID); params.put("client_secret","123456"); params.put("grant_type","password"); params.put("username",username); params.put("password",password); return authService.getAccessToken(params); } //对输入的验证码进行校验 private boolean verifyAuthCode(String authCode, String telephone){ if(StringUtils.isEmpty(authCode)){ return false; } String realAuthCode = memberCacheService.getAuthCode(telephone); return authCode.equals(realAuthCode); } }
package com.macro.mall.search.service.impl; import com.macro.mall.search.dao.EsProductDao; import com.macro.mall.search.domain.EsProduct; import com.macro.mall.search.domain.EsProductRelatedInfo; import com.macro.mall.search.repository.EsProductRepository; import com.macro.mall.search.service.EsProductService; import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder; import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.aggregations.Aggregation; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilter; import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested; import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms; import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.search.sort.SortOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import org.springframework.data.elasticsearch.core.SearchHit; import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * 商品搜索管理Service实现类 * Created by macro on 2018/6/19. */ @Service public class EsProductServiceImpl implements EsProductService { private static final Logger LOGGER = LoggerFactory.getLogger(EsProductServiceImpl.class); @Autowired private EsProductDao productDao; @Autowired private EsProductRepository productRepository; @Autowired private ElasticsearchRestTemplate elasticsearchRestTemplate; @Override public int importAll() { List<EsProduct> esProductList = productDao.getAllEsProductList(null); Iterable<EsProduct> esProductIterable = productRepository.saveAll(esProductList); Iterator<EsProduct> iterator = esProductIterable.iterator(); int result = 0; while (iterator.hasNext()) { result++; iterator.next(); } return result; } @Override public void delete(Long id) { productRepository.deleteById(id); } @Override public EsProduct create(Long id) { EsProduct result = null; List<EsProduct> esProductList = productDao.getAllEsProductList(id); if (esProductList.size() > 0) { EsProduct esProduct = esProductList.get(0); result = productRepository.save(esProduct); } return result; } @Override public void delete(List<Long> ids) { if (!CollectionUtils.isEmpty(ids)) { List<EsProduct> esProductList = new ArrayList<>(); for (Long id : ids) { EsProduct esProduct = new EsProduct(); esProduct.setId(id); esProductList.add(esProduct); } productRepository.deleteAll(esProductList); } } @Override public Page<EsProduct> search(String keyword, Integer pageNum, Integer pageSize) { Pageable pageable = PageRequest.of(pageNum, pageSize); return productRepository.findByNameOrSubTitleOrKeywords(keyword, keyword, keyword, pageable); } @Override public Page<EsProduct> search(String keyword, Long brandId, Long productCategoryId, Integer pageNum, Integer pageSize,Integer sort) { Pageable pageable = PageRequest.of(pageNum, pageSize); NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder(); //分页 nativeSearchQueryBuilder.withPageable(pageable); //过滤 if (brandId != null || productCategoryId != null) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); if (brandId != null) { boolQueryBuilder.must(QueryBuilders.termQuery("brandId", brandId)); } if (productCategoryId != null) { boolQueryBuilder.must(QueryBuilders.termQuery("productCategoryId", productCategoryId)); } nativeSearchQueryBuilder.withFilter(boolQueryBuilder); } //搜索 if (StringUtils.isEmpty(keyword)) { nativeSearchQueryBuilder.withQuery(QueryBuilders.matchAllQuery()); } else { List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>(); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("name", keyword), ScoreFunctionBuilders.weightFactorFunction(10))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("subTitle", keyword), ScoreFunctionBuilders.weightFactorFunction(5))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("keywords", keyword), ScoreFunctionBuilders.weightFactorFunction(2))); FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()]; filterFunctionBuilders.toArray(builders); FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders) .scoreMode(FunctionScoreQuery.ScoreMode.SUM) .setMinScore(2); nativeSearchQueryBuilder.withQuery(functionScoreQueryBuilder); } //排序 if(sort==1){ //按新品从新到旧 nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC)); }else if(sort==2){ //按销量从高到低 nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("sale").order(SortOrder.DESC)); }else if(sort==3){ //按价格从低到高 nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC)); }else if(sort==4){ //按价格从高到低 nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC)); }else{ //按相关度 nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC)); } nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC)); NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build(); LOGGER.info("DSL:{}", searchQuery.getQuery().toString()); SearchHits<EsProduct> searchHits = elasticsearchRestTemplate.search(searchQuery, EsProduct.class); if(searchHits.getTotalHits()<=0){ return new PageImpl<>(null,pageable,0); } List<EsProduct> searchProductList = searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList()); return new PageImpl<>(searchProductList,pageable,searchHits.getTotalHits()); } @Override public Page<EsProduct> recommend(Long id, Integer pageNum, Integer pageSize) { Pageable pageable = PageRequest.of(pageNum, pageSize); List<EsProduct> esProductList = productDao.getAllEsProductList(id); if (esProductList.size() > 0) { EsProduct esProduct = esProductList.get(0); String keyword = esProduct.getName(); Long brandId = esProduct.getBrandId(); Long productCategoryId = esProduct.getProductCategoryId(); //根据商品标题、品牌、分类进行搜索 List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>(); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("name", keyword), ScoreFunctionBuilders.weightFactorFunction(8))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("subTitle", keyword), ScoreFunctionBuilders.weightFactorFunction(2))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("keywords", keyword), ScoreFunctionBuilders.weightFactorFunction(2))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("brandId", brandId), ScoreFunctionBuilders.weightFactorFunction(5))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("productCategoryId", productCategoryId), ScoreFunctionBuilders.weightFactorFunction(3))); FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()]; filterFunctionBuilders.toArray(builders); FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders) .scoreMode(FunctionScoreQuery.ScoreMode.SUM) .setMinScore(2); //用于过滤掉相同的商品 BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); boolQueryBuilder.mustNot(QueryBuilders.termQuery("id",id)); //构建查询条件 NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder(); builder.withQuery(functionScoreQueryBuilder); builder.withFilter(boolQueryBuilder); builder.withPageable(pageable); NativeSearchQuery searchQuery = builder.build(); LOGGER.info("DSL:{}", searchQuery.getQuery().toString()); SearchHits<EsProduct> searchHits = elasticsearchRestTemplate.search(searchQuery, EsProduct.class); if(searchHits.getTotalHits()<=0){ return new PageImpl<>(null,pageable,0); } List<EsProduct> searchProductList = searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList()); return new PageImpl<>(searchProductList,pageable,searchHits.getTotalHits()); } return new PageImpl<>(null); } @Override public EsProductRelatedInfo searchRelatedInfo(String keyword) { NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder(); //搜索条件 if(StringUtils.isEmpty(keyword)){ builder.withQuery(QueryBuilders.matchAllQuery()); }else{ builder.withQuery(QueryBuilders.multiMatchQuery(keyword,"name","subTitle","keywords")); } //聚合搜索品牌名称 builder.addAggregation(AggregationBuilders.terms("brandNames").field("brandName")); //集合搜索分类名称 builder.addAggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName")); //聚合搜索商品属性,去除type=1的属性 AbstractAggregationBuilder aggregationBuilder = AggregationBuilders.nested("allAttrValues","attrValueList") .subAggregation(AggregationBuilders.filter("productAttrs",QueryBuilders.termQuery("attrValueList.type",1)) .subAggregation(AggregationBuilders.terms("attrIds") .field("attrValueList.productAttributeId") .subAggregation(AggregationBuilders.terms("attrValues") .field("attrValueList.value")) .subAggregation(AggregationBuilders.terms("attrNames") .field("attrValueList.name")))); builder.addAggregation(aggregationBuilder); NativeSearchQuery searchQuery = builder.build(); SearchHits<EsProduct> searchHits = elasticsearchRestTemplate.search(searchQuery, EsProduct.class); return convertProductRelatedInfo(searchHits); } /** * 将返回结果转换为对象 */ private EsProductRelatedInfo convertProductRelatedInfo(SearchHits<EsProduct> response) { EsProductRelatedInfo productRelatedInfo = new EsProductRelatedInfo(); Map<String, Aggregation> aggregationMap = response.getAggregations().getAsMap(); //设置品牌 Aggregation brandNames = aggregationMap.get("brandNames"); List<String> brandNameList = new ArrayList<>(); for(int i = 0; i<((Terms) brandNames).getBuckets().size(); i++){ brandNameList.add(((Terms) brandNames).getBuckets().get(i).getKeyAsString()); } productRelatedInfo.setBrandNames(brandNameList); //设置分类 Aggregation productCategoryNames = aggregationMap.get("productCategoryNames"); List<String> productCategoryNameList = new ArrayList<>(); for(int i=0;i<((Terms) productCategoryNames).getBuckets().size();i++){ productCategoryNameList.add(((Terms) productCategoryNames).getBuckets().get(i).getKeyAsString()); } productRelatedInfo.setProductCategoryNames(productCategoryNameList); //设置参数 Aggregation productAttrs = aggregationMap.get("allAttrValues"); List<? extends Terms.Bucket> attrIds = ((ParsedLongTerms) ((ParsedFilter) ((ParsedNested) productAttrs).getAggregations().get("productAttrs")).getAggregations().get("attrIds")).getBuckets(); List<EsProductRelatedInfo.ProductAttr> attrList = new ArrayList<>(); for (Terms.Bucket attrId : attrIds) { EsProductRelatedInfo.ProductAttr attr = new EsProductRelatedInfo.ProductAttr(); attr.setAttrId((Long) attrId.getKey()); List<String> attrValueList = new ArrayList<>(); List<? extends Terms.Bucket> attrValues = ((ParsedStringTerms) attrId.getAggregations().get("attrValues")).getBuckets(); List<? extends Terms.Bucket> attrNames = ((ParsedStringTerms) attrId.getAggregations().get("attrNames")).getBuckets(); for (Terms.Bucket attrValue : attrValues) { attrValueList.add(attrValue.getKeyAsString()); } attr.setAttrValues(attrValueList); if(!CollectionUtils.isEmpty(attrNames)){ String attrName = attrNames.get(0).getKeyAsString(); attr.setAttrName(attrName); } attrList.add(attr); } productRelatedInfo.setProductAttrs(attrList); return productRelatedInfo; } }
package com.zrkworld.sns.article.service; import com.zrkworld.sns.article.dao.ArticleDao; import com.zrkworld.sns.article.pojo.Article; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.DirectExchange; import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import utils.IdWorker; import javax.annotation.Resource; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 文章 * * @author zrk * */ @Service public class ArticleService { @Autowired private ArticleDao articleDao; @Autowired private IdWorker idWorker; @Resource private RedisTemplate redisTemplate; @Autowired private RabbitTemplate rabbitTemplate; public void updateState(String id) { articleDao.updateState(id); } public void addThumbup(String id) { articleDao.addThumbup(id); } public Article findById(String id) { // 先从缓存中查询当前对象 Article article = (Article) redisTemplate.opsForValue().get("article_" + id); // 如果没有取到 if (null == article) { // 从数据库中查询 article = articleDao.findById(id).orElse(null); // 存入缓存 redisTemplate.opsForValue().set("article_" + id, article); } return article; } /** * 查询全部列表 * @return */ public List<Article> findAll() { return articleDao.findAll(); } /** * 条件查询+分页 * @param whereMap * @param page * @param size * @return */ public Page<Article> findSearch(Map whereMap, int page, int size) { Specification<Article> specification = createSpecification(whereMap); PageRequest pageRequest = PageRequest.of(page-1, size); return articleDao.findAll(specification, pageRequest); } /** * 条件查询 * @param whereMap * @return */ public List<Article> findSearch(Map whereMap) { Specification<Article> specification = createSpecification(whereMap); return articleDao.findAll(specification); } /** * 增加 * @param article */ public void add(Article article) { article.setId( idWorker.nextId()+"" ); articleDao.save(article); //入库成功后,发送mq消息,内容是消息通知id rabbitTemplate.convertAndSend("article_subscribe", article.getUserid(), article.getId()); } /** * 修改 * @param article */ public void update(Article article) { articleDao.save(article); } /** * 删除 * @param id */ public void deleteById(String id) { articleDao.deleteById(id); } /** * 动态条件构建 * @param searchMap * @return */ private Specification<Article> createSpecification(Map searchMap) { return new Specification<Article>() { @Override public Predicate toPredicate(Root<Article> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicateList = new ArrayList<Predicate>(); // ID if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) { predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%")); } // 专栏ID if (searchMap.get("columnid")!=null && !"".equals(searchMap.get("columnid"))) { predicateList.add(cb.like(root.get("columnid").as(String.class), "%"+(String)searchMap.get("columnid")+"%")); } // 用户ID if (searchMap.get("userid")!=null && !"".equals(searchMap.get("userid"))) { predicateList.add(cb.like(root.get("userid").as(String.class), "%"+(String)searchMap.get("userid")+"%")); } // 标题 if (searchMap.get("title")!=null && !"".equals(searchMap.get("title"))) { predicateList.add(cb.like(root.get("title").as(String.class), "%"+(String)searchMap.get("title")+"%")); } // 文章正文 if (searchMap.get("content")!=null && !"".equals(searchMap.get("content"))) { predicateList.add(cb.like(root.get("content").as(String.class), "%"+(String)searchMap.get("content")+"%")); } // 文章封面 if (searchMap.get("image")!=null && !"".equals(searchMap.get("image"))) { predicateList.add(cb.like(root.get("image").as(String.class), "%"+(String)searchMap.get("image")+"%")); } // 是否公开 if (searchMap.get("ispublic")!=null && !"".equals(searchMap.get("ispublic"))) { predicateList.add(cb.like(root.get("ispublic").as(String.class), "%"+(String)searchMap.get("ispublic")+"%")); } // 是否置顶 if (searchMap.get("istop")!=null && !"".equals(searchMap.get("istop"))) { predicateList.add(cb.like(root.get("istop").as(String.class), "%"+(String)searchMap.get("istop")+"%")); } // 审核状态 if (searchMap.get("state")!=null && !"".equals(searchMap.get("state"))) { predicateList.add(cb.like(root.get("state").as(String.class), "%"+(String)searchMap.get("state")+"%")); } // 所属频道 if (searchMap.get("channelid")!=null && !"".equals(searchMap.get("channelid"))) { predicateList.add(cb.like(root.get("channelid").as(String.class), "%"+(String)searchMap.get("channelid")+"%")); } // URL if (searchMap.get("url")!=null && !"".equals(searchMap.get("url"))) { predicateList.add(cb.like(root.get("url").as(String.class), "%"+(String)searchMap.get("url")+"%")); } // 类型 if (searchMap.get("type")!=null && !"".equals(searchMap.get("type"))) { predicateList.add(cb.like(root.get("type").as(String.class), "%"+(String)searchMap.get("type")+"%")); } return cb.and( predicateList.toArray(new Predicate[predicateList.size()])); } }; } /** * 将订阅文章的关系放置到redis中,当有作者发布文章时,可以通过websocket和mq通知用户 * @param userId * @param articleId * @return */ public Boolean subscribe(String userId, String articleId) { //根据文章id查询文章作者id String authorId = articleDao.findById(articleId).orElse(null).getUserid();; //创建Rabbit管理器 RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate.getConnectionFactory()); //声明exchange DirectExchange exchange = new DirectExchange("article_subscribe"); rabbitAdmin.declareExchange(exchange); //创建queue Queue queue = new Queue("article_subscribe_" + userId, true); //声明exchange和queue的绑定关系,设置路由键为作者id Binding binding = BindingBuilder.bind(queue).to(exchange).with(authorId); //用户=>作者 String userKey = "article_subscribe_" + userId; //作者=>用户 String authorKey = "article_author_" + authorId; //查询该用户是否已经订阅作者 Boolean flag = redisTemplate.boundSetOps(userKey).isMember(authorId); if (flag) { //如果为flag为true,已经订阅,则取消订阅 redisTemplate.boundSetOps(userKey).remove(authorId); redisTemplate.boundSetOps(authorKey).remove(userId); //删除绑定的队列 rabbitAdmin.removeBinding(binding); return false; } else { // 如果为flag为false,没有订阅,则进行订阅 redisTemplate.boundSetOps(userKey).add(authorId); redisTemplate.boundSetOps(authorKey).add(userId); //声明队列和绑定队列 rabbitAdmin.declareQueue(queue); rabbitAdmin.declareBinding(binding); return true; } } }
package com.zrkworld.sns.article.service; import com.zrkworld.sns.article.dao.ChannelDao; import com.zrkworld.sns.article.pojo.Channel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import utils.IdWorker; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 频道 * * @author zrk * */ @Service public class ChannelService { @Autowired private ChannelDao channelDao; @Autowired private IdWorker idWorker; /** * 查询全部列表 * @return */ public List<Channel> findAll() { return channelDao.findAll(); } /** * 条件查询+分页 * @param whereMap * @param page * @param size * @return */ public Page<Channel> findSearch(Map whereMap, int page, int size) { Specification<Channel> specification = createSpecification(whereMap); PageRequest pageRequest = PageRequest.of(page-1, size); return channelDao.findAll(specification, pageRequest); } /** * 条件查询 * @param whereMap * @return */ public List<Channel> findSearch(Map whereMap) { Specification<Channel> specification = createSpecification(whereMap); return channelDao.findAll(specification); } /** * 根据ID查询实体 * @param id * @return */ public Channel findById(String id) { return channelDao.findById(id).get(); } /** * 增加 * @param channel */ public void add(Channel channel) { channel.setId( idWorker.nextId()+"" ); channelDao.save(channel); } /** * 修改 * @param channel */ public void update(Channel channel) { channelDao.save(channel); } /** * 删除 * @param id */ public void deleteById(String id) { channelDao.deleteById(id); } /** * 动态条件构建 * @param searchMap * @return */ private Specification<Channel> createSpecification(Map searchMap) { return new Specification<Channel>() { @Override public Predicate toPredicate(Root<Channel> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicateList = new ArrayList<Predicate>(); // ID if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) { predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%")); } // 频道名称 if (searchMap.get("name")!=null && !"".equals(searchMap.get("name"))) { predicateList.add(cb.like(root.get("name").as(String.class), "%"+(String)searchMap.get("name")+"%")); } // 状态 if (searchMap.get("state")!=null && !"".equals(searchMap.get("state"))) { predicateList.add(cb.like(root.get("state").as(String.class), "%"+(String)searchMap.get("state")+"%")); } return cb.and( predicateList.toArray(new Predicate[predicateList.size()])); } }; } }
package com.zrkworld.sns.article.service; import com.zrkworld.sns.article.dao.ColumnDao; import com.zrkworld.sns.article.pojo.Column; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import utils.IdWorker; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 专栏 * * @author zrk * */ @Service public class ColumnService { @Autowired private ColumnDao columnDao; @Autowired private IdWorker idWorker; /** * 查询全部列表 * @return */ public List<Column> findAll() { return columnDao.findAll(); } /** * 条件查询+分页 * @param whereMap * @param page * @param size * @return */ public Page<Column> findSearch(Map whereMap, int page, int size) { Specification<Column> specification = createSpecification(whereMap); PageRequest pageRequest = PageRequest.of(page-1, size); return columnDao.findAll(specification, pageRequest); } /** * 条件查询 * @param whereMap * @return */ public List<Column> findSearch(Map whereMap) { Specification<Column> specification = createSpecification(whereMap); return columnDao.findAll(specification); } /** * 根据ID查询实体 * @param id * @return */ public Column findById(String id) { return columnDao.findById(id).get(); } /** * 增加 * @param column */ public void add(Column column) { column.setId( idWorker.nextId()+"" ); columnDao.save(column); } /** * 修改 * @param column */ public void update(Column column) { columnDao.save(column); } /** * 删除 * @param id */ public void deleteById(String id) { columnDao.deleteById(id); } /** * 动态条件构建 * @param searchMap * @return */ private Specification<Column> createSpecification(Map searchMap) { return new Specification<Column>() { @Override public Predicate toPredicate(Root<Column> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicateList = new ArrayList<Predicate>(); // ID if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) { predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%")); } // 专栏名称 if (searchMap.get("name")!=null && !"".equals(searchMap.get("name"))) { predicateList.add(cb.like(root.get("name").as(String.class), "%"+(String)searchMap.get("name")+"%")); } // 专栏简介 if (searchMap.get("summary")!=null && !"".equals(searchMap.get("summary"))) { predicateList.add(cb.like(root.get("summary").as(String.class), "%"+(String)searchMap.get("summary")+"%")); } // 用户ID if (searchMap.get("userid")!=null && !"".equals(searchMap.get("userid"))) { predicateList.add(cb.like(root.get("userid").as(String.class), "%"+(String)searchMap.get("userid")+"%")); } // 状态 if (searchMap.get("state")!=null && !"".equals(searchMap.get("state"))) { predicateList.add(cb.like(root.get("state").as(String.class), "%"+(String)searchMap.get("state")+"%")); } return cb.and( predicateList.toArray(new Predicate[predicateList.size()])); } }; } }
package com.zrkworld.sns.notice.service; import com.zrkworld.sns.notice.client.ArticleClient; import com.zrkworld.sns.notice.client.UserClient; import com.zrkworld.sns.notice.dao.NoticeDao; import com.zrkworld.sns.notice.dao.NoticeFreshDao; import com.zrkworld.sns.notice.pojo.Notice; import com.zrkworld.sns.notice.pojo.NoticeFresh; import entity.PageResult; import entity.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import utils.IdWorker; import javax.annotation.Resource; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.*; @Service public class NoticeService { @Resource private NoticeDao noticeDao; @Resource private NoticeFreshDao noticeFreshDao; @Autowired private ArticleClient articleClient; @Autowired private UserClient userClient; @Autowired private IdWorker idWorker; //完善消息内容 private Notice getInfo(Notice notice) { //查询用户昵称 Result userResult = userClient.selectById(notice.getOperatorId()); HashMap userMap = (HashMap) userResult.getData(); //设置操作者用户昵称到消息通知中 notice.setOperatorName(userMap.get("nickname").toString()); //查询对象名称 Result articleResult = articleClient.findById(notice.getTargetId()); HashMap articleMap = (HashMap) articleResult.getData(); //设置对象名称到消息通知中 notice.setTargetName(articleMap.get("title").toString()); return notice; } public Notice selectById(String id) { Notice notice = noticeDao.findById(id).get(); //完善消息 getInfo(notice); return notice; } public List<Notice> selectByPage(Map whereMap, int page, int size) { Specification<Notice> specification = createSpecification(whereMap); PageRequest pageRequest = PageRequest.of(page-1,size); Page temp = noticeDao.findAll(specification,pageRequest); List<Notice> notices = new ArrayList<Notice>(); for (Object n : temp.getContent()) { notices.add(getInfo((Notice)n)); } //试图使用匿名lambda作为方法对象传入给map,遍历Page对象中的content //temp.map(n->getInfo((Notice)n)); return notices; } public void save(Notice notice) { //设置初始值 //设置状态 0表示未读 1表示已读 notice.setState("0"); notice.setCreatetime(new Date()); //使用分布式Id生成器,生成id String id = idWorker.nextId() + ""; notice.setId(id); noticeDao.save(notice); //待推送消息入库,新消息提醒,这里交给rabbitMQ来处理了 // NoticeFresh noticeFresh = new NoticeFresh(); // noticeFresh.setNoticeId(id);//消息id // noticeFresh.setUserId(notice.getReceiverId());//待通知用户的id // noticeFreshMapper.insert(noticeFresh); } public void updateById(Notice notice) { noticeDao.save(notice); } public Page<NoticeFresh> freshPage(Map whereMap, Integer page, Integer size) { Specification<NoticeFresh> specification = createSpecificationWithFresh(whereMap); PageRequest pageRequest = PageRequest.of(page-1,size); return noticeFreshDao.findAll(specification,pageRequest); } private Specification<NoticeFresh> createSpecificationWithFresh(Map searchMap) { return new Specification<NoticeFresh>() { //此处省略了关于创建时间的条件 @Override public Predicate toPredicate(Root<NoticeFresh> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicateList = new ArrayList<Predicate>(); // ID if (searchMap.get("userid") != null && !"".equals(searchMap.get("userid"))) { predicateList.add(cb.like(root.get("userid").as(String.class), "%" + (String) searchMap.get("userid") + "%")); } if (searchMap.get("noticeid") != null && !"".equals(searchMap.get("noticeid"))) { predicateList.add(cb.like(root.get("noticeid").as(String.class), "%" + (String) searchMap.get("noticeid") + "%")); } return cb.and(predicateList.toArray(new Predicate[predicateList.size()])); } }; } public void freshDelete(NoticeFresh noticeFresh) { noticeFreshDao.deleteByUserIdAndNoticeId(noticeFresh.getUserId(),noticeFresh.getNoticeId()); } /** * 动态条件构建 * @param searchMap * @return */ private Specification<Notice> createSpecification(Map searchMap) { return new Specification<Notice>() { //此处省略了关于创建时间的条件 @Override public Predicate toPredicate(Root<Notice> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicateList = new ArrayList<Predicate>(); // ID if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) { predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%")); } if (searchMap.get("receiverId")!=null && !"".equals(searchMap.get("receiverId"))) { predicateList.add(cb.like(root.get("receiverId").as(String.class), "%"+(String)searchMap.get("receiverId")+"%")); } if (searchMap.get("operatorId")!=null && !"".equals(searchMap.get("operatorId"))) { predicateList.add(cb.like(root.get("operatorId").as(String.class), "%"+(String)searchMap.get("operatorId")+"%")); } if (searchMap.get("action")!=null && !"".equals(searchMap.get("action"))) { predicateList.add(cb.like(root.get("action").as(String.class), "%"+(String)searchMap.get("action")+"%")); } if (searchMap.get("targetType")!=null && !"".equals(searchMap.get("targetType"))) { predicateList.add(cb.like(root.get("targetType").as(String.class), "%"+(String)searchMap.get("targetType")+"%")); } if (searchMap.get("targetId")!=null && !"".equals(searchMap.get("targetId"))) { predicateList.add(cb.like(root.get("targetId").as(String.class), "%"+(String)searchMap.get("targetId")+"%")); } if (searchMap.get("type")!=null && !"".equals(searchMap.get("type"))) { predicateList.add(cb.like(root.get("type").as(String.class), "%"+(String)searchMap.get("type")+"%")); } if (searchMap.get("state")!=null && !"".equals(searchMap.get("state"))) { predicateList.add(cb.like(root.get("state").as(String.class), "%"+(String)searchMap.get("state")+"%")); } return cb.and( predicateList.toArray(new Predicate[predicateList.size()])); } }; } }
package com.zrkworld.sns.qa.service; import com.zrkworld.sns.qa.dao.ProblemDao; import com.zrkworld.sns.qa.pojo.Problem; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import utils.IdWorker; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 服务层 * * @author Administrator * */ @Service public class ProblemService { @Autowired private ProblemDao problemDao; @Autowired private IdWorker idWorker; /** * 最新回答 * @param labelId * @param currentPage * @param pageSize * @return */ public Page<Problem> newList(String labelId, int currentPage, int pageSize) { Pageable pageable = PageRequest.of(currentPage - 1, pageSize); return problemDao.newList(labelId, pageable); } /** * 热门回答 * @param labelId * @param currentPage * @param pageSize * @return */ public Page<Problem> hotList(String labelId, int currentPage, int pageSize) { Pageable pageable = PageRequest.of(currentPage - 1, pageSize); return problemDao.hotList(labelId, pageable); } /** * 等待回答 * @param labelId * @param currentPage * @param pageSize * @return */ public Page<Problem> waitList(String labelId, int currentPage, int pageSize) { Pageable pageable = PageRequest.of(currentPage - 1, pageSize); return problemDao.waitList(labelId, pageable); } /** * 查询全部列表 * @return */ public List<Problem> findAll() { return problemDao.findAll(); } /** * 条件查询+分页 * @param whereMap * @param page * @param size * @return */ public Page<Problem> findSearch(Map whereMap, int page, int size) { Specification<Problem> specification = createSpecification(whereMap); PageRequest pageRequest = PageRequest.of(page-1, size); return problemDao.findAll(specification, pageRequest); } /** * 条件查询 * @param whereMap * @return */ public List<Problem> findSearch(Map whereMap) { Specification<Problem> specification = createSpecification(whereMap); return problemDao.findAll(specification); } /** * 根据ID查询实体 * @param id * @return */ public Problem findById(String id) { return problemDao.findById(id).get(); } /** * 增加 * @param problem */ public void add(Problem problem) { problem.setId( idWorker.nextId()+"" ); problemDao.save(problem); } /** * 修改 * @param problem */ public void update(Problem problem) { problemDao.save(problem); } /** * 删除 * @param id */ public void deleteById(String id) { problemDao.deleteById(id); } /** * 动态条件构建 * @param searchMap * @return */ private Specification<Problem> createSpecification(Map searchMap) { return new Specification<Problem>() { @Override public Predicate toPredicate(Root<Problem> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicateList = new ArrayList<Predicate>(); // ID if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) { predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%")); } // 标题 if (searchMap.get("title")!=null && !"".equals(searchMap.get("title"))) { predicateList.add(cb.like(root.get("title").as(String.class), "%"+(String)searchMap.get("title")+"%")); } // 内容 if (searchMap.get("content")!=null && !"".equals(searchMap.get("content"))) { predicateList.add(cb.like(root.get("content").as(String.class), "%"+(String)searchMap.get("content")+"%")); } // 用户ID if (searchMap.get("userid")!=null && !"".equals(searchMap.get("userid"))) { predicateList.add(cb.like(root.get("userid").as(String.class), "%"+(String)searchMap.get("userid")+"%")); } // 昵称 if (searchMap.get("nickname")!=null && !"".equals(searchMap.get("nickname"))) { predicateList.add(cb.like(root.get("nickname").as(String.class), "%"+(String)searchMap.get("nickname")+"%")); } // 是否解决 if (searchMap.get("solve")!=null && !"".equals(searchMap.get("solve"))) { predicateList.add(cb.like(root.get("solve").as(String.class), "%"+(String)searchMap.get("solve")+"%")); } // 回复人昵称 if (searchMap.get("replyname")!=null && !"".equals(searchMap.get("replyname"))) { predicateList.add(cb.like(root.get("replyname").as(String.class), "%"+(String)searchMap.get("replyname")+"%")); } return cb.and( predicateList.toArray(new Predicate[predicateList.size()])); } }; } }
package com.zrkworld.sns.qa.service; import com.zrkworld.sns.qa.dao.ReplyDao; import com.zrkworld.sns.qa.pojo.Reply; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import utils.IdWorker; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 服务层 * * @author Administrator * */ @Service public class ReplyService { @Autowired private ReplyDao replyDao; @Autowired private IdWorker idWorker; /** * 查询全部列表 * @return */ public List<Reply> findAll() { return replyDao.findAll(); } /** * 条件查询+分页 * @param whereMap * @param page * @param size * @return */ public Page<Reply> findSearch(Map whereMap, int page, int size) { Specification<Reply> specification = createSpecification(whereMap); PageRequest pageRequest = PageRequest.of(page-1, size); return replyDao.findAll(specification, pageRequest); } /** * 条件查询 * @param whereMap * @return */ public List<Reply> findSearch(Map whereMap) { Specification<Reply> specification = createSpecification(whereMap); return replyDao.findAll(specification); } /** * 根据ID查询实体 * @param id * @return */ public Reply findById(String id) { return replyDao.findById(id).get(); } /** * 增加 * @param reply */ public void add(Reply reply) { reply.setId( idWorker.nextId()+"" ); replyDao.save(reply); } /** * 修改 * @param reply */ public void update(Reply reply) { replyDao.save(reply); } /** * 删除 * @param id */ public void deleteById(String id) { replyDao.deleteById(id); } /** * 动态条件构建 * @param searchMap * @return */ private Specification<Reply> createSpecification(Map searchMap) { return new Specification<Reply>() { @Override public Predicate toPredicate(Root<Reply> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicateList = new ArrayList<Predicate>(); // 编号 if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) { predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%")); } // 问题ID if (searchMap.get("problemid")!=null && !"".equals(searchMap.get("problemid"))) { predicateList.add(cb.like(root.get("problemid").as(String.class), "%"+(String)searchMap.get("problemid")+"%")); } // 回答内容 if (searchMap.get("content")!=null && !"".equals(searchMap.get("content"))) { predicateList.add(cb.like(root.get("content").as(String.class), "%"+(String)searchMap.get("content")+"%")); } // 回答人ID if (searchMap.get("userid")!=null && !"".equals(searchMap.get("userid"))) { predicateList.add(cb.like(root.get("userid").as(String.class), "%"+(String)searchMap.get("userid")+"%")); } // 回答人昵称 if (searchMap.get("nickname")!=null && !"".equals(searchMap.get("nickname"))) { predicateList.add(cb.like(root.get("nickname").as(String.class), "%"+(String)searchMap.get("nickname")+"%")); } return cb.and( predicateList.toArray(new Predicate[predicateList.size()])); } }; } }
package com.zrkworld.sns.recruit.service; import com.zrkworld.sns.recruit.dao.EnterpriseDao; import com.zrkworld.sns.recruit.pojo.Enterprise; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import utils.IdWorker; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 服务层 * * @author Administrator */ @Service @Transactional public class EnterpriseService { @Autowired private EnterpriseDao enterpriseDao; @Autowired private IdWorker idWorker; public List<Enterprise> hotList(String ishot) { return enterpriseDao.findByIshot(ishot); } /** * 查询全部列表 * * @return */ public List<Enterprise> findAll() { return enterpriseDao.findAll(); } /** * 条件查询+分页 * * @param whereMap * @param page * @param size * @return */ public Page<Enterprise> findSearch(Map whereMap, int page, int size) { Specification<Enterprise> specification = createSpecification(whereMap); PageRequest pageRequest = PageRequest.of(page - 1, size); return enterpriseDao.findAll(specification, pageRequest); } /** * 条件查询 * * @param whereMap * @return */ public List<Enterprise> findSearch(Map whereMap) { Specification<Enterprise> specification = createSpecification(whereMap); return enterpriseDao.findAll(specification); } /** * 根据ID查询实体 * * @param id * @return */ public Enterprise findById(String id) { return enterpriseDao.findById(id).get(); } /** * 增加 * * @param enterprise */ public void add(Enterprise enterprise) { enterprise.setId(idWorker.nextId() + ""); enterpriseDao.save(enterprise); } /** * 修改 * * @param enterprise */ public void update(Enterprise enterprise) { enterpriseDao.save(enterprise); } /** * 删除 * * @param id */ public void deleteById(String id) { enterpriseDao.deleteById(id); } /** * 动态条件构建 * * @param searchMap * @return */ private Specification<Enterprise> createSpecification(Map searchMap) { return new Specification<Enterprise>() { @Override public Predicate toPredicate(Root<Enterprise> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicateList = new ArrayList<Predicate>(); // ID if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) { predicateList.add(cb.like(root.get("id").as(String.class), "%" + (String) searchMap.get("id") + "%")); } // 企业名称 if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) { predicateList.add(cb.like(root.get("name").as(String.class), "%" + (String) searchMap.get("name") + "%")); } // 企业简介 if (searchMap.get("summary") != null && !"".equals(searchMap.get("summary"))) { predicateList.add(cb.like(root.get("summary").as(String.class), "%" + (String) searchMap.get("summary") + "%")); } // 企业地址 if (searchMap.get("address") != null && !"".equals(searchMap.get("address"))) { predicateList.add(cb.like(root.get("address").as(String.class), "%" + (String) searchMap.get("address") + "%")); } // 标签列表 if (searchMap.get("labels") != null && !"".equals(searchMap.get("labels"))) { predicateList.add(cb.like(root.get("labels").as(String.class), "%" + (String) searchMap.get("labels") + "%")); } // 坐标 if (searchMap.get("coordinate") != null && !"".equals(searchMap.get("coordinate"))) { predicateList.add(cb.like(root.get("coordinate").as(String.class), "%" + (String) searchMap.get("coordinate") + "%")); } // 是否热门 if (searchMap.get("ishot") != null && !"".equals(searchMap.get("ishot"))) { predicateList.add(cb.like(root.get("ishot").as(String.class), "%" + (String) searchMap.get("ishot") + "%")); } // LOGO if (searchMap.get("logo") != null && !"".equals(searchMap.get("logo"))) { predicateList.add(cb.like(root.get("logo").as(String.class), "%" + (String) searchMap.get("logo") + "%")); } // URL if (searchMap.get("url") != null && !"".equals(searchMap.get("url"))) { predicateList.add(cb.like(root.get("url").as(String.class), "%" + (String) searchMap.get("url") + "%")); } return cb.and(predicateList.toArray(new Predicate[predicateList.size()])); } }; } }
package com.zrkworld.sns.recruit.service; import com.zrkworld.sns.recruit.dao.RecruitDao; import com.zrkworld.sns.recruit.pojo.Recruit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import utils.IdWorker; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 服务层 * * @author Administrator * */ @Service public class RecruitService { @Autowired private RecruitDao recruitDao; @Autowired private IdWorker idWorker; public List<Recruit> recommend() { return recruitDao.findTop6ByStateOrderByCreatetimeDesc("2"); } public List<Recruit> newList() { return recruitDao.findTop6ByStateNotOrderByCreatetimeDesc("0"); } public void save(Recruit recruit) { // 根据雪花算法生成分布式id recruit.setId(String.valueOf(idWorker.nextId())); recruitDao.save(recruit); } /** * 查询全部列表 * @return */ public List<Recruit> findAll() { return recruitDao.findAll(); } /** * 条件查询+分页 * @param whereMap * @param page * @param size * @return */ public Page<Recruit> findSearch(Map whereMap, int page, int size) { Specification<Recruit> specification = createSpecification(whereMap); PageRequest pageRequest = PageRequest.of(page-1, size); return recruitDao.findAll(specification, pageRequest); } /** * 条件查询 * @param whereMap * @return */ public List<Recruit> findSearch(Map whereMap) { Specification<Recruit> specification = createSpecification(whereMap); return recruitDao.findAll(specification); } /** * 根据ID查询实体 * @param id * @return */ public Recruit findById(String id) { return recruitDao.findById(id).orElse(null); } /** * 修改 * @param recruit */ public void update(Recruit recruit) { recruitDao.save(recruit); } /** * 删除 * @param id */ public void deleteById(String id) { recruitDao.deleteById(id); } /** * 动态条件构建 * @param searchMap * @return */ private Specification<Recruit> createSpecification(Map searchMap) { return new Specification<Recruit>() { @Override public Predicate toPredicate(Root<Recruit> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicateList = new ArrayList<Predicate>(); // ID if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) { predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%")); } // 职位名称 if (searchMap.get("jobname")!=null && !"".equals(searchMap.get("jobname"))) { predicateList.add(cb.like(root.get("jobname").as(String.class), "%"+(String)searchMap.get("jobname")+"%")); } // 薪资范围 if (searchMap.get("salary")!=null && !"".equals(searchMap.get("salary"))) { predicateList.add(cb.like(root.get("salary").as(String.class), "%"+(String)searchMap.get("salary")+"%")); } // 经验要求 if (searchMap.get("condition")!=null && !"".equals(searchMap.get("condition"))) { predicateList.add(cb.like(root.get("condition").as(String.class), "%"+(String)searchMap.get("condition")+"%")); } // 学历要求 if (searchMap.get("education")!=null && !"".equals(searchMap.get("education"))) { predicateList.add(cb.like(root.get("education").as(String.class), "%"+(String)searchMap.get("education")+"%")); } // 任职方式 if (searchMap.get("type")!=null && !"".equals(searchMap.get("type"))) { predicateList.add(cb.like(root.get("type").as(String.class), "%"+(String)searchMap.get("type")+"%")); } // 办公地址 if (searchMap.get("address")!=null && !"".equals(searchMap.get("address"))) { predicateList.add(cb.like(root.get("address").as(String.class), "%"+(String)searchMap.get("address")+"%")); } // 企业ID if (searchMap.get("eid")!=null && !"".equals(searchMap.get("eid"))) { predicateList.add(cb.like(root.get("eid").as(String.class), "%"+(String)searchMap.get("eid")+"%")); } // 状态 if (searchMap.get("state")!=null && !"".equals(searchMap.get("state"))) { predicateList.add(cb.like(root.get("state").as(String.class), "%"+(String)searchMap.get("state")+"%")); } // 网址 if (searchMap.get("url")!=null && !"".equals(searchMap.get("url"))) { predicateList.add(cb.like(root.get("url").as(String.class), "%"+(String)searchMap.get("url")+"%")); } // 标签 if (searchMap.get("label")!=null && !"".equals(searchMap.get("label"))) { predicateList.add(cb.like(root.get("label").as(String.class), "%"+(String)searchMap.get("label")+"%")); } // 职位描述 if (searchMap.get("content1")!=null && !"".equals(searchMap.get("content1"))) { predicateList.add(cb.like(root.get("content1").as(String.class), "%"+(String)searchMap.get("content1")+"%")); } // 职位要求 if (searchMap.get("content2")!=null && !"".equals(searchMap.get("content2"))) { predicateList.add(cb.like(root.get("content2").as(String.class), "%"+(String)searchMap.get("content2")+"%")); } return cb.and( predicateList.toArray(new Predicate[predicateList.size()])); } }; } }
package com.zrkworld.sns.user.service; import com.zrkworld.sns.user.dao.AdminDao; import com.zrkworld.sns.user.pojo.Admin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.domain.Specification; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import utils.IdWorker; import javax.annotation.Resource; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 管理员服务层 * * @author zrk * */ @Service public class AdminService { @Autowired private AdminDao adminDao; @Resource private IdWorker idWorker; @Resource private BCryptPasswordEncoder bCryptPasswordEncoder; public Admin login(Admin admin) { // 先根据用户名查询对象 Admin loginName = adminDao.findByLoginname(admin.getLoginname()); // 然后用数据库中的密码跟用户输入密码进行比对 if (loginName != null && bCryptPasswordEncoder.matches(admin.getPassword(), loginName.getPassword())) { return loginName; } return null; } /** * 查询全部列表 * @return */ public List<Admin> findAll() { return adminDao.findAll(); } /** * 条件查询+分页 * @param whereMap * @param page * @param size * @return */ public Page<Admin> findSearch(Map whereMap, int page, int size) { Specification<Admin> specification = createSpecification(whereMap); PageRequest pageRequest = PageRequest.of(page-1, size); return adminDao.findAll(specification, pageRequest); } /** * 条件查询 * @param whereMap * @return */ public List<Admin> findSearch(Map whereMap) { Specification<Admin> specification = createSpecification(whereMap); return adminDao.findAll(specification); } /** * 根据ID查询实体 * @param id * @return */ public Admin findById(String id) { return adminDao.findById(id).get(); } /** * 增加 * @param admin */ public void add(Admin admin) { admin.setId( idWorker.nextId() + ""); // 密码加密 admin.setPassword(bCryptPasswordEncoder.encode(admin.getPassword())); adminDao.save(admin); } /** * 修改 * @param admin */ public void update(Admin admin) { adminDao.save(admin); } /** * 删除 * @param id */ public void deleteById(String id) { adminDao.deleteById(id); } /** * 动态条件构建 * @param searchMap * @return */ private Specification<Admin> createSpecification(Map searchMap) { return new Specification<Admin>() { @Override public Predicate toPredicate(Root<Admin> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicateList = new ArrayList<Predicate>(); // ID if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) { predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%")); } // 登陆名称 if (searchMap.get("loginname")!=null && !"".equals(searchMap.get("loginname"))) { predicateList.add(cb.like(root.get("loginname").as(String.class), "%"+(String)searchMap.get("loginname")+"%")); } // 密码 if (searchMap.get("password")!=null && !"".equals(searchMap.get("password"))) { predicateList.add(cb.like(root.get("password").as(String.class), "%"+(String)searchMap.get("password")+"%")); } // 状态 if (searchMap.get("state")!=null && !"".equals(searchMap.get("state"))) { predicateList.add(cb.like(root.get("state").as(String.class), "%"+(String)searchMap.get("state")+"%")); } return cb.and( predicateList.toArray(new Predicate[predicateList.size()])); } }; } }
package com.zrkworld.sns.user.service; import com.zrkworld.sns.user.dao.UserDao; import com.zrkworld.sns.user.pojo.User; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import utils.IdWorker; import javax.annotation.Resource; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.servlet.http.HttpServletRequest; import java.util.*; import java.util.concurrent.TimeUnit; /** * 服务层 * * @author Administrator */ @Service @Transactional public class UserService { @Resource private UserDao userDao; @Resource private IdWorker idWorker; @Resource private RedisTemplate redisTemplate; @Resource private RabbitTemplate rabbitTemplate; @Resource private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired private HttpServletRequest request; /** * 更新被关注好友粉丝数跟用户自己的关注数 * @param num * @param userId * @param friendId */ public void updateFansAndFollower(int num, String userId, String friendId) { userDao.updateFansNum(num, friendId); userDao.updateFollowNum(num, userId); } /** * 用户登录 * @param mobile * @param password * @return */ public User login(String mobile, String password) { User user = userDao.findByMobile(mobile); if (user != null && bCryptPasswordEncoder.matches(password, user.getPassword())) { return user; } return null; } /** * 发送短信 * * @param mobile */ public void sendSms(String mobile) { // 生成6位随机验证码 String checkCode = RandomStringUtils.randomNumeric(6); // 向缓存中放一份,设置过期时间为6小时 redisTemplate.opsForValue().set("check_code_" + mobile, checkCode, 6, TimeUnit.HOURS); // 给用户发一份 Map<String, String> map = new HashMap<>(); map.put("mobile", mobile); map.put("check_code", checkCode); rabbitTemplate.convertAndSend("sms", map); } /** * 查询全部列表 * * @return */ public List<User> findAll() { return userDao.findAll(); } /** * 条件查询+分页 * * @param whereMap * @param page * @param size * @return */ public Page<User> findSearch(Map whereMap, int page, int size) { Specification<User> specification = createSpecification(whereMap); PageRequest pageRequest = PageRequest.of(page - 1, size); return userDao.findAll(specification, pageRequest); } /** * 条件查询 * * @param whereMap * @return */ public List<User> findSearch(Map whereMap) { Specification<User> specification = createSpecification(whereMap); return userDao.findAll(specification); } /** * 根据ID查询实体 * * @param id * @return */ public User findById(String id) { return userDao.findById(id).get(); } /** * 增加 * * @param user */ public void add(User user) { user.setId(idWorker.nextId() + ""); // 密码加密 user.setPassword(bCryptPasswordEncoder.encode(user.getPassword())); user.setFollowcount(0); // 关注数 user.setFanscount(0); // 粉丝数 user.setOnline(0L); // 在线时长 user.setRegdate(new Date()); // 注册日期 user.setUpdatedate(new Date()); // 更新日期 user.setLastdate(new Date()); // 最后登录日期 userDao.save(user); } /** * 修改 * * @param user */ public void update(User user) { userDao.save(user); } /** * 删除, 必须有admin角色才能删除 * * @param id */ public void deleteById(String id) { String token = (String) request.getAttribute("claims_admin"); if (StringUtils.isEmpty(token)) { throw new RuntimeException("权限不足!"); } userDao.deleteById(id); } /** * 动态条件构建 * * @param searchMap * @return */ private Specification<User> createSpecification(Map searchMap) { return new Specification<User>() { @Override public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicateList = new ArrayList<Predicate>(); // ID if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) { predicateList.add(cb.like(root.get("id").as(String.class), "%" + (String) searchMap.get("id") + "%")); } // 手机号码 if (searchMap.get("mobile") != null && !"".equals(searchMap.get("mobile"))) { predicateList.add(cb.like(root.get("mobile").as(String.class), "%" + (String) searchMap.get("mobile") + "%")); } // 密码 if (searchMap.get("password") != null && !"".equals(searchMap.get("password"))) { predicateList.add(cb.like(root.get("password").as(String.class), "%" + (String) searchMap.get("password") + "%")); } // 昵称 if (searchMap.get("nickname") != null && !"".equals(searchMap.get("nickname"))) { predicateList.add(cb.like(root.get("nickname").as(String.class), "%" + (String) searchMap.get("nickname") + "%")); } // 性别 if (searchMap.get("sex") != null && !"".equals(searchMap.get("sex"))) { predicateList.add(cb.like(root.get("sex").as(String.class), "%" + (String) searchMap.get("sex") + "%")); } // 头像 if (searchMap.get("avatar") != null && !"".equals(searchMap.get("avatar"))) { predicateList.add(cb.like(root.get("avatar").as(String.class), "%" + (String) searchMap.get("avatar") + "%")); } // E-Mail if (searchMap.get("email") != null && !"".equals(searchMap.get("email"))) { predicateList.add(cb.like(root.get("email").as(String.class), "%" + (String) searchMap.get("email") + "%")); } // 兴趣 if (searchMap.get("interest") != null && !"".equals(searchMap.get("interest"))) { predicateList.add(cb.like(root.get("interest").as(String.class), "%" + (String) searchMap.get("interest") + "%")); } // 个性 if (searchMap.get("personality") != null && !"".equals(searchMap.get("personality"))) { predicateList.add(cb.like(root.get("personality").as(String.class), "%" + (String) searchMap.get("personality") + "%")); } return cb.and(predicateList.toArray(new Predicate[predicateList.size()])); } }; } }
package com.jerusalem.order.listener; import com.jerusalem.order.entity.OrdersEntity; import com.jerusalem.order.service.OrdersService; import com.rabbitmq.client.Channel; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; /**** * @Author: jerusalem * @Description: OrderCloseListener * 定时关闭订单监听器 * @Date 2020/11/15 13:44 *****/ @Service @RabbitListener(queues = "order.release.queue") public class OrderCloseListener { @Autowired OrdersService ordersService; @RabbitHandler public void handleCloseOrder(OrdersEntity ordersEntity, Channel channel, Message message) throws IOException { System.out.println("收到过期的订单信息,准备关闭订单"+ordersEntity.getOrderSn()); try { ordersService.closeOrder(ordersEntity); //TODO 手动调用支付宝收单(防止时延造成订单已解锁,支付仍在进行) //执行成功,回复mq消息消费成功 channel.basicAck(message.getMessageProperties().getDeliveryTag(),false); }catch (Exception e){ System.out.println("错误:"+e.getMessage()); //只要出现异常,消息重新入队 channel.basicReject(message.getMessageProperties().getDeliveryTag(),true); } } }
package com.jerusalem.order.listener; import com.jerusalem.common.to.SeckillOrderTo; import com.jerusalem.order.entity.OrdersEntity; import com.jerusalem.order.service.OrdersService; import com.rabbitmq.client.Channel; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import java.io.IOException; /**** * @Author: jerusalem * @Description: OrderCloseListener * 秒杀订单监听器 * @Date 2020/11/15 13:44 *****/ @Component @RabbitListener(queues = "order.seckill.queue") public class OrderSeckillListener { @Autowired OrdersService ordersService; @RabbitHandler public void handleCloseOrder(SeckillOrderTo seckillOrderTo, Channel channel, Message message) throws IOException { System.out.println("准备创建秒杀订单"+seckillOrderTo.getOrderSn()+"的详细信息"); try { ordersService.createSeckillOrder(seckillOrderTo); //执行成功,回复mq消息消费成功 channel.basicAck(message.getMessageProperties().getDeliveryTag(),false); }catch (Exception e){ System.out.println("错误:"+e.getMessage()); //只要出现异常,消息重新入队 channel.basicReject(message.getMessageProperties().getDeliveryTag(),true); } } }
package com.jerusalem.ware.listener; import com.jerusalem.common.to.OrderTo; import com.jerusalem.common.to.StockLockedTo; import com.jerusalem.ware.service.WareSkuService; import com.rabbitmq.client.Channel; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; /**** * @Author: jerusalem * @Description: StockReleaseListener * 库存解锁监听器 * @Date 2020/11/14 17:59 *****/ @Service @RabbitListener(queues = "stock.release.queue") public class StockReleaseListener { @Autowired WareSkuService wareSkuService; /*** * 监听队列、处理库存解锁业务 * 库存解锁的场景: * 1.库存锁定成功,下单成功,但是订单过期未支付或被取消 -》 库存解锁 * 2.库存锁定成功,订单后续业务逻辑失败,下单失败,订单回滚 -》 库存解锁 * 3.库存锁定失败,库存回滚(此情况无库存工作单详情)-》无需解锁 * 逻辑分析: * 1.查询关于该订单的库存工作单信息是否存在 * 1.1 有 -》 证明库存锁定成功,查询该订单是否存在 * 1.1.1 无 -》 证明下单失败,必须解锁 * 1.1.2 有 -》 证明下单成功,查询订单状态 * 1.1.2.1 已取消 -》 解锁库存 * 1.1.2.2 未取消(其他任何状态) -》 无需解锁 * 1.2 无 -》 证明库存锁定失败,所有都回滚,无需解锁 * * @param stockLockedTo * @param message * @param channel */ @RabbitHandler public void handleStockRelease(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException { System.out.println("收到解锁库存的消息"); try { wareSkuService.unLockStock(stockLockedTo); //执行成功,回复mq消息消费成功 channel.basicAck(message.getMessageProperties().getDeliveryTag(),false); }catch (Exception e){ System.out.println("错误:"+e.getMessage()); //只要出现异常,消息重新入队 channel.basicReject(message.getMessageProperties().getDeliveryTag(),true); } } /*** * 监听关闭订单的消息 * 接受订单关闭消息,解锁库存(防止网络原因导致的库存无法解锁) * @param orderTo * @param message * @param channel * @throws IOException */ @RabbitHandler public void handleCloseOrderRelease(OrderTo orderTo, Message message, Channel channel) throws IOException { System.out.println("收到订单关闭的消息,准备解锁库存"); try { wareSkuService.unLockStock(orderTo); //执行成功,回复mq消息消费成功 channel.basicAck(message.getMessageProperties().getDeliveryTag(),false); }catch (Exception e){ System.out.println("错误:"+e.getMessage()); //只要出现异常,消息重新入队 channel.basicReject(message.getMessageProperties().getDeliveryTag(),true); } } }
package assurance.service; import assurance.entity.*; import assurance.repository.AssuranceRepository; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * @author fdse */ @Service public class AssuranceServiceImpl implements AssuranceService { @Autowired private AssuranceRepository assuranceRepository; private static final Logger LOGGER = LoggerFactory.getLogger(AssuranceServiceImpl.class); @Override public Response findAssuranceById(UUID id, HttpHeaders headers) { Assurance assurance = assuranceRepository.findById(id); if (assurance == null) { AssuranceServiceImpl.LOGGER.warn("No content, id: {}", id); return new Response<>(0, "No Content by this id", null); } else { AssuranceServiceImpl.LOGGER.info("Find Assurance, id: {}", id); return new Response<>(1, "Find Assurance Success", assurance); } } @Override public Response findAssuranceByOrderId(UUID orderId, HttpHeaders headers) { Assurance assurance = assuranceRepository.findByOrderId(orderId); if (assurance == null) { AssuranceServiceImpl.LOGGER.warn("No content, orderId: {}", orderId); return new Response<>(0, "No Content by this orderId", null); } else { AssuranceServiceImpl.LOGGER.info("Find assurance, orderId: {}", orderId); return new Response<>(1, "Find Assurance Success", assurance); } } @Override public Response create(int typeIndex, String orderId, HttpHeaders headers) { Assurance a = assuranceRepository.findByOrderId(UUID.fromString(orderId)); AssuranceType at = AssuranceType.getTypeByIndex(typeIndex); if (a != null) { AssuranceServiceImpl.LOGGER.error("[AddAssurance] Fail.Assurance already exists, typeIndex: {}, orderId: {}", typeIndex, orderId); return new Response<>(0, "Fail.Assurance already exists", null); } else if (at == null) { AssuranceServiceImpl.LOGGER.warn("[AddAssurance] Fail.Assurance type doesn't exist, typeIndex: {}, orderId: {}", typeIndex, orderId); return new Response<>(0, "Fail.Assurance type doesn't exist", null); } else { Assurance assurance = new Assurance(UUID.randomUUID(), UUID.fromString(orderId), at); assuranceRepository.save(assurance); AssuranceServiceImpl.LOGGER.info("[AddAssurance] Success."); return new Response<>(1, "Success", assurance); } } @Override public Response deleteById(UUID assuranceId, HttpHeaders headers) { assuranceRepository.deleteById(assuranceId); Assurance a = assuranceRepository.findById(assuranceId); if (a == null) { AssuranceServiceImpl.LOGGER.info("[DeleteAssurance] Success, assuranceId: {}", assuranceId); return new Response<>(1, "Delete Success with Assurance id", null); } else { AssuranceServiceImpl.LOGGER.error("[DeleteAssurance] Fail.Assurance not clear, assuranceId: {}", assuranceId); return new Response<>(0, "Fail.Assurance not clear", assuranceId); } } @Override public Response deleteByOrderId(UUID orderId, HttpHeaders headers) { assuranceRepository.removeAssuranceByOrderId(orderId); Assurance isExistAssurace = assuranceRepository.findByOrderId(orderId); if (isExistAssurace == null) { AssuranceServiceImpl.LOGGER.info("[DeleteAssurance] Success, orderId: {}", orderId); return new Response<>(1, "Delete Success with Order Id", null); } else { AssuranceServiceImpl.LOGGER.error("[DeleteAssurance] Fail.Assurance not clear, orderId: {}", orderId); return new Response<>(0, "Fail.Assurance not clear", orderId); } } @Override public Response modify(String assuranceId, String orderId, int typeIndex, HttpHeaders headers) { Response oldAssuranceResponse = findAssuranceById(UUID.fromString(assuranceId), headers); Assurance oldAssurance = (Assurance) oldAssuranceResponse.getData(); if (oldAssurance == null) { AssuranceServiceImpl.LOGGER.error("[ModifyAssurance] Fail.Assurance not found, assuranceId: {}, orderId: {}, typeIndex: {}", assuranceId, orderId, typeIndex); return new Response<>(0, "Fail.Assurance not found.", null); } else { AssuranceType at = AssuranceType.getTypeByIndex(typeIndex); if (at != null) { oldAssurance.setType(at); assuranceRepository.save(oldAssurance); AssuranceServiceImpl.LOGGER.info("[ModifyAssurance] Success, assuranceId: {}, orderId: {}, typeIndex: {}", assuranceId, orderId, typeIndex); return new Response<>(1, "Modify Success", oldAssurance); } else { AssuranceServiceImpl.LOGGER.error("[ModifyAssurance] Fail.Assurance Type not exist, assuranceId: {}, orderId: {}, typeIndex: {}", assuranceId, orderId, typeIndex); return new Response<>(0, "Assurance Type not exist", null); } } } @Override public Response getAllAssurances(HttpHeaders headers) { List<Assurance> as = assuranceRepository.findAll(); if (as != null && !as.isEmpty()) { ArrayList<PlainAssurance> result = new ArrayList<>(); for (Assurance a : as) { PlainAssurance pa = new PlainAssurance(); pa.setId(a.getId()); pa.setOrderId(a.getOrderId()); pa.setTypeIndex(a.getType().getIndex()); pa.setTypeName(a.getType().getName()); pa.setTypePrice(a.getType().getPrice()); result.add(pa); } AssuranceServiceImpl.LOGGER.info("find all assurance success, list size: {}", as.size()); return new Response<>(1, "Success", result); } else { AssuranceServiceImpl.LOGGER.warn("find all assurance: No content"); return new Response<>(0, "No Content, Assurance is empty", null); } } @Override public Response getAllAssuranceTypes(HttpHeaders headers) { List<AssuranceTypeBean> atlist = new ArrayList<>(); for (AssuranceType at : AssuranceType.values()) { AssuranceTypeBean atb = new AssuranceTypeBean(); atb.setIndex(at.getIndex()); atb.setName(at.getName()); atb.setPrice(at.getPrice()); atlist.add(atb); } if (!atlist.isEmpty()) { AssuranceServiceImpl.LOGGER.info("find all assurance type success, list size: {}", atlist.size()); return new Response<>(1, "Find All Assurance", atlist); } else { AssuranceServiceImpl.LOGGER.warn("find all assurance type: No content"); return new Response<>(0, "Assurance is Empty", null); } } }
package config.service; import config.entity.Config; import config.repository.ConfigRepository; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import java.util.List; /** * @author fdse */ @Service public class ConfigServiceImpl implements ConfigService { @Autowired ConfigRepository repository; private static final Logger logger = LoggerFactory.getLogger(ConfigServiceImpl.class); String config0 = "Config "; @Override public Response create(Config info, HttpHeaders headers) { if (repository.findByName(info.getName()) != null) { String result = config0 + info.getName() + " already exists."; logger.warn(result); return new Response<>(0, result, null); } else { Config config = new Config(info.getName(), info.getValue(), info.getDescription()); repository.save(config); logger.info("Config: ({}) create success", info); return new Response<>(1, "Create success", config); } } @Override public Response update(Config info, HttpHeaders headers) { if (repository.findByName(info.getName()) == null) { String result = config0 + info.getName() + " doesn't exist."; logger.warn(result); return new Response<>(0, result, null); } else { Config config = new Config(info.getName(), info.getValue(), info.getDescription()); repository.save(config); logger.info("Config: ({}) update success", config); return new Response<>(1, "Update success", config); } } @Override public Response query(String name, HttpHeaders headers) { Config config = repository.findByName(name); if (config == null) { logger.warn("Config does not exist, name: {}, message: {}", name, "No content"); return new Response<>(0, "No content", null); } else { logger.info("Query config {} success", name); return new Response<>(1, "Success", config); } } @Override public Response delete(String name, HttpHeaders headers) { Config config = repository.findByName(name); if (config == null) { String result = config0 + name + " doesn't exist."; logger.warn(result); return new Response<>(0, result, null); } else { repository.deleteByName(name); logger.info("Config {} delete success", name); return new Response<>(1, "Delete success", config); } } @Override public Response queryAll(HttpHeaders headers) { List<Config> configList = repository.findAll(); if (configList != null && !configList.isEmpty()) { logger.info("Query all config success"); return new Response<>(1, "Find all config success", configList); } else { logger.warn("Query config: {}", "No content"); return new Response<>(0, "No content", null); } } }
package consign.service; import consign.entity.ConsignRecord; import consign.entity.Consign; import consign.repository.ConsignRepository; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.List; import java.util.UUID; /** * @author fdse */ @Service public class ConsignServiceImpl implements ConsignService { @Autowired ConsignRepository repository; @Autowired RestTemplate restTemplate; private static final Logger LOGGER = LoggerFactory.getLogger(ConsignServiceImpl.class); @Override public Response insertConsignRecord(Consign consignRequest, HttpHeaders headers) { ConsignServiceImpl.LOGGER.info("[ Insert new consign record] {}", consignRequest.getOrderId()); ConsignRecord consignRecord = new ConsignRecord(); //Set the record attribute consignRecord.setId(UUID.randomUUID()); LOGGER.info("Order ID is :" + consignRequest.getOrderId()); consignRecord.setOrderId(consignRequest.getOrderId()); consignRecord.setAccountId(consignRequest.getAccountId()); ConsignServiceImpl.LOGGER.info("The handle date is {}", consignRequest.getHandleDate()); ConsignServiceImpl.LOGGER.info("The target date is {}", consignRequest.getTargetDate()); consignRecord.setHandleDate(consignRequest.getHandleDate()); consignRecord.setTargetDate(consignRequest.getTargetDate()); consignRecord.setFrom(consignRequest.getFrom()); consignRecord.setTo(consignRequest.getTo()); consignRecord.setConsignee(consignRequest.getConsignee()); consignRecord.setPhone(consignRequest.getPhone()); consignRecord.setWeight(consignRequest.getWeight()); //get the price HttpEntity requestEntity = new HttpEntity(null, headers); ResponseEntity<Response<Double>> re = restTemplate.exchange( "http://ts-consign-price-service:16110/api/v1/consignpriceservice/consignprice/" + consignRequest.getWeight() + "/" + consignRequest.isWithin(), HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Double>>() { }); consignRecord.setPrice(re.getBody().getData()); LOGGER.info("SAVE consign info : " + consignRecord.toString()); ConsignRecord result = repository.save(consignRecord); LOGGER.info("SAVE consign result : " + result.toString()); return new Response<>(1, "You have consigned successfully! The price is " + result.getPrice(), result); } @Override public Response updateConsignRecord(Consign consignRequest, HttpHeaders headers) { ConsignServiceImpl.LOGGER.info("[ Update consign record]"); ConsignRecord originalRecord = repository.findById(consignRequest.getId()); if (originalRecord == null) { return insertConsignRecord(consignRequest, headers); } originalRecord.setAccountId(consignRequest.getAccountId()); originalRecord.setHandleDate(consignRequest.getHandleDate()); originalRecord.setTargetDate(consignRequest.getTargetDate()); originalRecord.setFrom(consignRequest.getFrom()); originalRecord.setTo(consignRequest.getTo()); originalRecord.setConsignee(consignRequest.getConsignee()); originalRecord.setPhone(consignRequest.getPhone()); //Recalculate price if (originalRecord.getWeight() != consignRequest.getWeight()) { HttpEntity requestEntity = new HttpEntity<>(null, headers); ResponseEntity<Response<Double>> re = restTemplate.exchange( "http://ts-consign-price-service:16110/api/v1/consignpriceservice/consignprice/" + consignRequest.getWeight() + "/" + consignRequest.isWithin(), HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Double>>() { }); originalRecord.setPrice(re.getBody().getData()); } else { originalRecord.setPrice(originalRecord.getPrice()); } originalRecord.setConsignee(consignRequest.getConsignee()); originalRecord.setPhone(consignRequest.getPhone()); originalRecord.setWeight(consignRequest.getWeight()); repository.save(originalRecord); return new Response<>(1, "Update consign success", originalRecord); } @Override public Response queryByAccountId(UUID accountId, HttpHeaders headers) { List<ConsignRecord> consignRecords = repository.findByAccountId(accountId); if (consignRecords != null && !consignRecords.isEmpty()) { return new Response<>(1, "Find consign by account id success", consignRecords); }else { LOGGER.warn("No Content according to accountId: {}", accountId); return new Response<>(0, "No Content according to accountId", null); } } @Override public Response queryByOrderId(UUID orderId, HttpHeaders headers) { ConsignRecord consignRecords = repository.findByOrderId(orderId); if (consignRecords != null ) { return new Response<>(1, "Find consign by order id success", consignRecords); }else { LOGGER.warn("No Content according to orderId: {}", orderId); return new Response<>(0, "No Content according to order id", null); } } @Override public Response queryByConsignee(String consignee, HttpHeaders headers) { List<ConsignRecord> consignRecords = repository.findByConsignee(consignee); if (consignRecords != null && !consignRecords.isEmpty()) { return new Response<>(1, "Find consign by consignee success", consignRecords); }else { LOGGER.warn("No Content according to consignee: {}", consignee); return new Response<>(0, "No Content according to consignee", null); } } }
package contacts.service; import contacts.entity.*; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import contacts.repository.ContactsRepository; import java.util.ArrayList; import java.util.UUID; /** * @author fdse */ @Service public class ContactsServiceImpl implements ContactsService { @Autowired private ContactsRepository contactsRepository; String success = "Success"; private static final Logger LOGGER = LoggerFactory.getLogger(ContactsServiceImpl.class); @Override public Response findContactsById(UUID id, HttpHeaders headers) { LOGGER.info("FIND CONTACTS BY ID: " + id); Contacts contacts = contactsRepository.findById(id); if (contacts != null) { return new Response<>(1, success, contacts); } else { LOGGER.error("No contacts according to contactsId: {}", id); return new Response<>(0, "No contacts according to contacts id", null); } } @Override public Response findContactsByAccountId(UUID accountId, HttpHeaders headers) { ArrayList<Contacts> arr = contactsRepository.findByAccountId(accountId); ContactsServiceImpl.LOGGER.info("[Contacts-Query-Service][Query-Contacts] Result Size: {}", arr.size()); return new Response<>(1, success, arr); } @Override public Response createContacts(Contacts contacts, HttpHeaders headers) { Contacts contactsTemp = contactsRepository.findById(contacts.getId()); if (contactsTemp != null) { ContactsServiceImpl.LOGGER.warn("[Contacts Service][Init Contacts] Already Exists Id: {}", contacts.getId()); return new Response<>(0, "Already Exists", contactsTemp); } else { contactsRepository.save(contacts); return new Response<>(1, "Create Success", null); } } @Override public Response create(Contacts addContacts, HttpHeaders headers) { Contacts contacts = new Contacts(); contacts.setId(UUID.randomUUID()); contacts.setName(addContacts.getName()); contacts.setPhoneNumber(addContacts.getPhoneNumber()); contacts.setDocumentNumber(addContacts.getDocumentNumber()); contacts.setAccountId(addContacts.getAccountId()); contacts.setDocumentType(addContacts.getDocumentType()); ArrayList<Contacts> accountContacts = contactsRepository.findByAccountId(addContacts.getAccountId()); if (accountContacts.contains(contacts)) { ContactsServiceImpl.LOGGER.warn("[Contacts-Add&Delete-Service][AddContacts] Fail.Contacts already exists, contactId: {}", addContacts.getId()); return new Response<>(0, "Contacts already exists", null); } else { contactsRepository.save(contacts); ContactsServiceImpl.LOGGER.info("[Contacts-Add&Delete-Service][AddContacts] Success."); return new Response<>(1, "Create contacts success", contacts); } } @Override public Response delete(UUID contactsId, HttpHeaders headers) { contactsRepository.deleteById(contactsId); Contacts contacts = contactsRepository.findById(contactsId); if (contacts == null) { ContactsServiceImpl.LOGGER.info("[Contacts-Add&Delete-Service][DeleteContacts] Success."); return new Response<>(1, "Delete success", contactsId); } else { ContactsServiceImpl.LOGGER.error("[Contacts-Add&Delete-Service][DeleteContacts] Fail.Reason not clear, contactsId: {}", contactsId); return new Response<>(0, "Delete failed", contactsId); } } @Override public Response modify(Contacts contacts, HttpHeaders headers) { headers = null; Response oldContactResponse = findContactsById(contacts.getId(), headers); LOGGER.info(oldContactResponse.toString()); Contacts oldContacts = (Contacts) oldContactResponse.getData(); if (oldContacts == null) { ContactsServiceImpl.LOGGER.error("[Contacts-Modify-Service][ModifyContacts] Fail.Contacts not found, contactId: {}", contacts.getId()); return new Response<>(0, "Contacts not found", null); } else { oldContacts.setName(contacts.getName()); oldContacts.setDocumentType(contacts.getDocumentType()); oldContacts.setDocumentNumber(contacts.getDocumentNumber()); oldContacts.setPhoneNumber(contacts.getPhoneNumber()); contactsRepository.save(oldContacts); ContactsServiceImpl.LOGGER.info("[Contacts-Modify-Service][ModifyContacts] Success."); return new Response<>(1, "Modify success", oldContacts); } } @Override public Response getAllContacts(HttpHeaders headers) { ArrayList<Contacts> contacts = contactsRepository.findAll(); if (contacts != null && !contacts.isEmpty()) { return new Response<>(1, success, contacts); } else { LOGGER.error("Get all contacts error, message: {}", "No content"); return new Response<>(0, "No content", null); } } }
package food.service; import edu.fudan.common.util.Response; import food.entity.FoodStore; import food.entity.TrainFood; import food.repository.FoodStoreRepository; import food.repository.TrainFoodRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import java.util.List; @Service public class FoodMapServiceImpl implements FoodMapService { @Autowired FoodStoreRepository foodStoreRepository; @Autowired TrainFoodRepository trainFoodRepository; private static final Logger LOGGER = LoggerFactory.getLogger(FoodMapServiceImpl.class); String success = "Success"; String noContent = "No content"; @Override public Response createFoodStore(FoodStore fs, HttpHeaders headers) { FoodStore fsTemp = foodStoreRepository.findById(fs.getId()); if (fsTemp != null) { FoodMapServiceImpl.LOGGER.error("[Init FoodStore] Already Exists Id: {}", fs.getId()); return new Response<>(0, "Already Exists Id", null); } else { foodStoreRepository.save(fs); return new Response<>(1, "Save Success", fs); } } @Override public TrainFood createTrainFood(TrainFood tf, HttpHeaders headers) { TrainFood tfTemp = trainFoodRepository.findById(tf.getId()); if (tfTemp != null) { FoodMapServiceImpl.LOGGER.error("[Init TrainFood] Already Exists Id: {}", tf.getId()); } else { trainFoodRepository.save(tf); } return tf; } @Override public Response listFoodStores(HttpHeaders headers) { List<FoodStore> foodStores = foodStoreRepository.findAll(); if (foodStores != null && !foodStores.isEmpty()) { return new Response<>(1, success, foodStores); } else { FoodMapServiceImpl.LOGGER.error("List food stores error: {}", "Food store is empty"); return new Response<>(0, "Food store is empty", null); } } @Override public Response listTrainFood(HttpHeaders headers) { List<TrainFood> trainFoodList = trainFoodRepository.findAll(); if (trainFoodList != null && !trainFoodList.isEmpty()) { return new Response<>(1, success, trainFoodList); } else { FoodMapServiceImpl.LOGGER.error("List train food error: {}", noContent); return new Response<>(0, noContent, null); } } @Override public Response listFoodStoresByStationId(String stationId, HttpHeaders headers) { List<FoodStore> foodStoreList = foodStoreRepository.findByStationId(stationId); if (foodStoreList != null && !foodStoreList.isEmpty()) { return new Response<>(1, success, foodStoreList); } else { FoodMapServiceImpl.LOGGER.error("List food stores by station id error: {}, stationId: {}", "Food store is empty", stationId); return new Response<>(0, "Food store is empty", null); } } @Override public Response listTrainFoodByTripId(String tripId, HttpHeaders headers) { List<TrainFood> trainFoodList = trainFoodRepository.findByTripId(tripId); if (trainFoodList != null) { return new Response<>(1, success, trainFoodList); } else { FoodMapServiceImpl.LOGGER.error("List train food by trip id error: {}, tripId: {}", noContent, tripId); return new Response<>(0, noContent, null); } } @Override public Response getFoodStoresByStationIds(List<String> stationIds) { List<FoodStore> foodStoreList = foodStoreRepository.findByStationIdIn(stationIds); if (foodStoreList != null) { return new Response<>(1, success, foodStoreList); } else { FoodMapServiceImpl.LOGGER.error("List food stores by station ids error: {}, stationId list: {}", "Food store is empty", stationIds); return new Response<>(0, noContent, null); } } }
package foodsearch.service; import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; import foodsearch.entity.*; import foodsearch.mq.RabbitSend; import foodsearch.repository.FoodOrderRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; @Service public class FoodServiceImpl implements FoodService { @Autowired private RestTemplate restTemplate; @Autowired private FoodOrderRepository foodOrderRepository; @Autowired private RabbitSend sender; private static final Logger LOGGER = LoggerFactory.getLogger(FoodServiceImpl.class); String success = "Success."; String orderIdNotExist = "Order Id Is Non-Existent."; @Override public Response createFoodOrder(FoodOrder addFoodOrder, HttpHeaders headers) { FoodOrder fo = foodOrderRepository.findByOrderId(addFoodOrder.getOrderId()); if (fo != null) { FoodServiceImpl.LOGGER.error("[AddFoodOrder] Order Id Has Existed, OrderId: {}", addFoodOrder.getOrderId()); return new Response<>(0, "Order Id Has Existed.", null); } else { fo = new FoodOrder(); fo.setId(UUID.randomUUID()); fo.setOrderId(addFoodOrder.getOrderId()); fo.setFoodType(addFoodOrder.getFoodType()); if (addFoodOrder.getFoodType() == 2) { fo.setStationName(addFoodOrder.getStationName()); fo.setStoreName(addFoodOrder.getStoreName()); } fo.setFoodName(addFoodOrder.getFoodName()); fo.setPrice(addFoodOrder.getPrice()); foodOrderRepository.save(fo); FoodServiceImpl.LOGGER.info("[AddFoodOrder] Success."); Delivery delivery = new Delivery(); delivery.setFoodName(addFoodOrder.getFoodName()); delivery.setOrderId(addFoodOrder.getOrderId()); delivery.setStationName(addFoodOrder.getStationName()); delivery.setStoreName(addFoodOrder.getStoreName()); String deliveryJson = JsonUtils.object2Json(delivery); LOGGER.info("[AddFoodOrder] delivery info [{}] send to mq", deliveryJson); try { sender.send(deliveryJson); } catch (Exception e) { LOGGER.error("[AddFoodOrder] send delivery info to mq error, exception is [{}]", e.toString()); } return new Response<>(1, success, fo); } } @Override public Response deleteFoodOrder(String orderId, HttpHeaders headers) { FoodOrder foodOrder = foodOrderRepository.findByOrderId(UUID.fromString(orderId)); if (foodOrder == null) { FoodServiceImpl.LOGGER.error("[Cancel FoodOrder] Order Id Is Non-Existent, orderId: {}", orderId); return new Response<>(0, orderIdNotExist, null); } else { foodOrderRepository.deleteFoodOrderByOrderId(UUID.fromString(orderId)); FoodServiceImpl.LOGGER.info("[Cancel FoodOrder] Success."); return new Response<>(1, success, null); } } @Override public Response findAllFoodOrder(HttpHeaders headers) { List<FoodOrder> foodOrders = foodOrderRepository.findAll(); if (foodOrders != null && !foodOrders.isEmpty()) { return new Response<>(1, success, foodOrders); } else { FoodServiceImpl.LOGGER.error("Find all food order error: {}", "No Content"); return new Response<>(0, "No Content", null); } } @Override public Response updateFoodOrder(FoodOrder updateFoodOrder, HttpHeaders headers) { FoodOrder fo = foodOrderRepository.findById(updateFoodOrder.getId()); if (fo == null) { FoodServiceImpl.LOGGER.info("[Update FoodOrder] Order Id Is Non-Existent, orderId: {}", updateFoodOrder.getOrderId()); return new Response<>(0, orderIdNotExist, null); } else { fo.setFoodType(updateFoodOrder.getFoodType()); if (updateFoodOrder.getFoodType() == 1) { fo.setStationName(updateFoodOrder.getStationName()); fo.setStoreName(updateFoodOrder.getStoreName()); } fo.setFoodName(updateFoodOrder.getFoodName()); fo.setPrice(updateFoodOrder.getPrice()); foodOrderRepository.save(fo); FoodServiceImpl.LOGGER.info("[Update FoodOrder] Success."); return new Response<>(1, "Success", fo); } } @Override public Response findByOrderId(String orderId, HttpHeaders headers) { FoodOrder fo = foodOrderRepository.findByOrderId(UUID.fromString(orderId)); if (fo != null) { FoodServiceImpl.LOGGER.info("[Find Order by id] Success."); return new Response<>(1, success, fo); } else { FoodServiceImpl.LOGGER.info("[Find Order by id] Order Id Is Non-Existent, orderId: {}", orderId); return new Response<>(0, orderIdNotExist, null); } } @Override public Response getAllFood(String date, String startStation, String endStation, String tripId, HttpHeaders headers) { FoodServiceImpl.LOGGER.info("data={} start={} end={} tripid={}", date, startStation, endStation, tripId); AllTripFood allTripFood = new AllTripFood(); if (null == tripId || tripId.length() <= 2) { FoodServiceImpl.LOGGER.error("Get the Get Food Request Failed! Trip id is not suitable, date: {}, tripId: {}", date, tripId); return new Response<>(0, "Trip id is not suitable", null); } // need return this tow element List<TrainFood> trainFoodList = null; Map<String, List<FoodStore>> foodStoreListMap = new HashMap<>(); /**--------------------------------------------------------------------------------------*/ HttpEntity requestEntityGetTrainFoodListResult = new HttpEntity(null); ResponseEntity<Response<List<TrainFood>>> reGetTrainFoodListResult = restTemplate.exchange( "http://ts-food-map-service:18855/api/v1/foodmapservice/trainfoods/" + tripId, HttpMethod.GET, requestEntityGetTrainFoodListResult, new ParameterizedTypeReference<Response<List<TrainFood>>>() { }); List<TrainFood> trainFoodListResult = reGetTrainFoodListResult.getBody().getData(); if (trainFoodListResult != null) { trainFoodList = trainFoodListResult; FoodServiceImpl.LOGGER.info("Get Train Food List!"); } else { FoodServiceImpl.LOGGER.error("Get the Get Food Request Failed!, date: {}, tripId: {}", date, tripId); return new Response<>(0, "Get the Get Food Request Failed!", null); } //车次途经的车站 /**--------------------------------------------------------------------------------------*/ HttpEntity requestEntityGetRouteResult = new HttpEntity(null, null); ResponseEntity<Response<Route>> reGetRouteResult = restTemplate.exchange( "http://ts-travel-service:12346/api/v1/travelservice/routes/" + tripId, HttpMethod.GET, requestEntityGetRouteResult, new ParameterizedTypeReference<Response<Route>>() { }); Response<Route> stationResult = reGetRouteResult.getBody(); if (stationResult.getStatus() == 1) { Route route = stationResult.getData(); List<String> stations = route.getStations(); //去除不经过的站,如果起点终点有的话 if (null != startStation && !"".equals(startStation)) { /**--------------------------------------------------------------------------------------*/ HttpEntity requestEntityStartStationId = new HttpEntity(null); ResponseEntity<Response<String>> reStartStationId = restTemplate.exchange( "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + startStation, HttpMethod.GET, requestEntityStartStationId, new ParameterizedTypeReference<Response<String>>() { }); Response<String> startStationId = reStartStationId.getBody(); for (int i = 0; i < stations.size(); i++) { if (stations.get(i).equals(startStationId.getData())) { break; } else { stations.remove(i); } } } if (null != endStation && !"".equals(endStation)) { /**--------------------------------------------------------------------------------------*/ HttpEntity requestEntityEndStationId = new HttpEntity(null); ResponseEntity<Response<String>> reEndStationId = restTemplate.exchange( "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + endStation, HttpMethod.GET, requestEntityEndStationId, new ParameterizedTypeReference<Response<String>>() { }); Response endStationId = reEndStationId.getBody(); for (int i = stations.size() - 1; i >= 0; i--) { if (stations.get(i).equals(endStationId.getData())) { break; } else { stations.remove(i); } } } HttpEntity requestEntityFoodStoresListResult = new HttpEntity(stations, null); ResponseEntity<Response<List<FoodStore>>> reFoodStoresListResult = restTemplate.exchange( "http://ts-food-map-service:18855/api/v1/foodmapservice/foodstores", HttpMethod.POST, requestEntityFoodStoresListResult, new ParameterizedTypeReference<Response<List<FoodStore>>>() { }); List<FoodStore> foodStoresListResult = reFoodStoresListResult.getBody().getData(); if (foodStoresListResult != null && !foodStoresListResult.isEmpty()) { for (String stationId : stations) { List<FoodStore> res = foodStoresListResult.stream() .filter(foodStore -> (foodStore.getStationId().equals(stationId))) .collect(Collectors.toList()); foodStoreListMap.put(stationId, res); } } else { FoodServiceImpl.LOGGER.error("Get the Get Food Request Failed! foodStoresListResult is null, date: {}, tripId: {}", date, tripId); return new Response<>(0, "Get All Food Failed", allTripFood); } } else { FoodServiceImpl.LOGGER.error("Get the Get Food Request Failed! station status error, date: {}, tripId: {}", date, tripId); return new Response<>(0, "Get All Food Failed", allTripFood); } allTripFood.setTrainFoodList(trainFoodList); allTripFood.setFoodStoreListMap(foodStoreListMap); return new Response<>(1, "Get All Food Success", allTripFood); } }
package inside_payment.service; import edu.fudan.common.util.Response; import inside_payment.entity.*; import inside_payment.repository.AddMoneyRepository; import inside_payment.repository.PaymentRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.math.BigDecimal; import java.util.*; /** * @author fdse */ @Service public class InsidePaymentServiceImpl implements InsidePaymentService { @Autowired public AddMoneyRepository addMoneyRepository; @Autowired public PaymentRepository paymentRepository; @Autowired public RestTemplate restTemplate; private static final Logger LOGGER = LoggerFactory.getLogger(InsidePaymentServiceImpl.class); @Override public Response pay(PaymentInfo info, HttpHeaders headers) { String userId = info.getUserId(); String requestOrderURL = ""; if (info.getTripId().startsWith("G") || info.getTripId().startsWith("D")) { requestOrderURL = "http://ts-order-service:12031/api/v1/orderservice/order/" + info.getOrderId(); } else { requestOrderURL = "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + info.getOrderId(); } HttpEntity requestGetOrderResults = new HttpEntity(headers); ResponseEntity<Response<Order>> reGetOrderResults = restTemplate.exchange( requestOrderURL, HttpMethod.GET, requestGetOrderResults, new ParameterizedTypeReference<Response<Order>>() { }); Response<Order> result = reGetOrderResults.getBody(); if (result.getStatus() == 1) { Order order = result.getData(); if (order.getStatus() != OrderStatus.NOTPAID.getCode()) { InsidePaymentServiceImpl.LOGGER.info("[Inside Payment Service][Pay] Error. Order status Not allowed to Pay."); return new Response<>(0, "Error. Order status Not allowed to Pay.", null); } Payment payment = new Payment(); payment.setOrderId(info.getOrderId()); payment.setPrice(order.getPrice()); payment.setUserId(userId); //判断一下账户余额够不够,不够要去站外支付 List<Payment> payments = paymentRepository.findByUserId(userId); List<Money> addMonies = addMoneyRepository.findByUserId(userId); Iterator<Payment> paymentsIterator = payments.iterator(); Iterator<Money> addMoniesIterator = addMonies.iterator(); BigDecimal totalExpand = new BigDecimal("0"); while (paymentsIterator.hasNext()) { Payment p = paymentsIterator.next(); totalExpand = totalExpand.add(new BigDecimal(p.getPrice())); } totalExpand = totalExpand.add(new BigDecimal(order.getPrice())); BigDecimal money = new BigDecimal("0"); while (addMoniesIterator.hasNext()) { Money addMoney = addMoniesIterator.next(); money = money.add(new BigDecimal(addMoney.getMoney())); } if (totalExpand.compareTo(money) > 0) { //站外支付 Payment outsidePaymentInfo = new Payment(); outsidePaymentInfo.setOrderId(info.getOrderId()); outsidePaymentInfo.setUserId(userId); outsidePaymentInfo.setPrice(order.getPrice()); /****这里调用第三方支付***/ HttpEntity requestEntityOutsidePaySuccess = new HttpEntity(outsidePaymentInfo, headers); ResponseEntity<Response> reOutsidePaySuccess = restTemplate.exchange( "http://ts-payment-service:19001/api/v1/paymentservice/payment", HttpMethod.POST, requestEntityOutsidePaySuccess, Response.class); Response outsidePaySuccess = reOutsidePaySuccess.getBody(); InsidePaymentServiceImpl.LOGGER.info("Out pay result: {}", outsidePaySuccess.toString()); if (outsidePaySuccess.getStatus() == 1) { payment.setType(PaymentType.O); paymentRepository.save(payment); setOrderStatus(info.getTripId(), info.getOrderId(), headers); return new Response<>(1, "Payment Success " + outsidePaySuccess.getMsg(), null); } else { LOGGER.error("Payment failed: {}", outsidePaySuccess.getMsg()); return new Response<>(0, "Payment Failed: " + outsidePaySuccess.getMsg(), null); } } else { setOrderStatus(info.getTripId(), info.getOrderId(), headers); payment.setType(PaymentType.P); paymentRepository.save(payment); } LOGGER.info("Payment success, orderId: {}", info.getOrderId()); return new Response<>(1, "Payment Success", null); } else { LOGGER.error("Payment failed: Order not exists, orderId: {}", info.getOrderId()); return new Response<>(0, "Payment Failed, Order Not Exists", null); } } @Override public Response createAccount(AccountInfo info, HttpHeaders headers) { List<Money> list = addMoneyRepository.findByUserId(info.getUserId()); if (list.isEmpty()) { Money addMoney = new Money(); addMoney.setMoney(info.getMoney()); addMoney.setUserId(info.getUserId()); addMoney.setType(MoneyType.A); addMoneyRepository.save(addMoney); return new Response<>(1, "Create Account Success", null); } else { LOGGER.error("Create Account Failed, Account already Exists, userId: {}", info.getUserId()); return new Response<>(0, "Create Account Failed, Account already Exists", null); } } @Override public Response addMoney(String userId, String money, HttpHeaders headers) { if (addMoneyRepository.findByUserId(userId) != null) { Money addMoney = new Money(); addMoney.setUserId(userId); addMoney.setMoney(money); addMoney.setType(MoneyType.A); addMoneyRepository.save(addMoney); return new Response<>(1, "Add Money Success", null); } else { LOGGER.error("Add Money Failed, userId: {}", userId); return new Response<>(0, "Add Money Failed", null); } } @Override public Response queryAccount(HttpHeaders headers) { List<Balance> result = new ArrayList<>(); List<Money> list = addMoneyRepository.findAll(); Iterator<Money> ite = list.iterator(); HashMap<String, String> map = new HashMap<>(); while (ite.hasNext()) { Money addMoney = ite.next(); if (map.containsKey(addMoney.getUserId())) { BigDecimal money = new BigDecimal(map.get(addMoney.getUserId())); map.put(addMoney.getUserId(), money.add(new BigDecimal(addMoney.getMoney())).toString()); } else { map.put(addMoney.getUserId(), addMoney.getMoney()); } } Iterator ite1 = map.entrySet().iterator(); while (ite1.hasNext()) { Map.Entry entry = (Map.Entry) ite1.next(); String userId = (String) entry.getKey(); String money = (String) entry.getValue(); List<Payment> payments = paymentRepository.findByUserId(userId); Iterator<Payment> iterator = payments.iterator(); String totalExpand = "0"; while (iterator.hasNext()) { Payment p = iterator.next(); BigDecimal expand = new BigDecimal(totalExpand); totalExpand = expand.add(new BigDecimal(p.getPrice())).toString(); } String balanceMoney = new BigDecimal(money).subtract(new BigDecimal(totalExpand)).toString(); Balance balance = new Balance(); balance.setUserId(userId); balance.setBalance(balanceMoney); result.add(balance); } return new Response<>(1, "Success", result); } public String queryAccount(String userId, HttpHeaders headers) { List<Payment> payments = paymentRepository.findByUserId(userId); List<Money> addMonies = addMoneyRepository.findByUserId(userId); Iterator<Payment> paymentsIterator = payments.iterator(); Iterator<Money> addMoniesIterator = addMonies.iterator(); BigDecimal totalExpand = new BigDecimal("0"); while (paymentsIterator.hasNext()) { Payment p = paymentsIterator.next(); totalExpand.add(new BigDecimal(p.getPrice())); } BigDecimal money = new BigDecimal("0"); while (addMoniesIterator.hasNext()) { Money addMoney = addMoniesIterator.next(); money.add(new BigDecimal(addMoney.getMoney())); } return money.subtract(totalExpand).toString(); } @Override public Response queryPayment(HttpHeaders headers) { List<Payment> payments = paymentRepository.findAll(); if (payments != null && !payments.isEmpty()) { return new Response<>(1, "Query Payment Success", payments); }else { LOGGER.error("Query payment failed"); return new Response<>(0, "Query Payment Failed", null); } } @Override public Response drawBack(String userId, String money, HttpHeaders headers) { if (addMoneyRepository.findByUserId(userId) != null) { Money addMoney = new Money(); addMoney.setUserId(userId); addMoney.setMoney(money); addMoney.setType(MoneyType.D); addMoneyRepository.save(addMoney); return new Response<>(1, "Draw Back Money Success", null); } else { LOGGER.error("Draw Back Money Failed"); return new Response<>(0, "Draw Back Money Failed", null); } } @Override public Response payDifference(PaymentInfo info, HttpHeaders headers) { String userId = info.getUserId(); Payment payment = new Payment(); payment.setOrderId(info.getOrderId()); payment.setPrice(info.getPrice()); payment.setUserId(info.getUserId()); List<Payment> payments = paymentRepository.findByUserId(userId); List<Money> addMonies = addMoneyRepository.findByUserId(userId); Iterator<Payment> paymentsIterator = payments.iterator(); Iterator<Money> addMoniesIterator = addMonies.iterator(); BigDecimal totalExpand = new BigDecimal("0"); while (paymentsIterator.hasNext()) { Payment p = paymentsIterator.next(); totalExpand.add(new BigDecimal(p.getPrice())); } totalExpand.add(new BigDecimal(info.getPrice())); BigDecimal money = new BigDecimal("0"); while (addMoniesIterator.hasNext()) { Money addMoney = addMoniesIterator.next(); money.add(new BigDecimal(addMoney.getMoney())); } if (totalExpand.compareTo(money) > 0) { //站外支付 Payment outsidePaymentInfo = new Payment(); outsidePaymentInfo.setOrderId(info.getOrderId()); outsidePaymentInfo.setUserId(userId); outsidePaymentInfo.setPrice(info.getPrice()); HttpEntity requestEntityOutsidePaySuccess = new HttpEntity(outsidePaymentInfo, headers); ResponseEntity<Response> reOutsidePaySuccess = restTemplate.exchange( "http://ts-payment-service:19001/api/v1/paymentservice/payment", HttpMethod.POST, requestEntityOutsidePaySuccess, Response.class); Response outsidePaySuccess = reOutsidePaySuccess.getBody(); if (outsidePaySuccess.getStatus() == 1) { payment.setType(PaymentType.E); paymentRepository.save(payment); return new Response<>(1, "Pay Difference Success", null); } else { LOGGER.error("Pay Difference Failed, orderId: {}", info.getOrderId()); return new Response<>(0, "Pay Difference Failed", null); } } else { payment.setType(PaymentType.E); paymentRepository.save(payment); } return new Response<>(1, "Pay Difference Success", null); } @Override public Response queryAddMoney(HttpHeaders headers) { List<Money> monies = addMoneyRepository.findAll(); if (monies != null && !monies.isEmpty()) { return new Response<>(1, "Query Money Success", null); } else { LOGGER.error("Query money failed"); return new Response<>(0, "Query money failed", null); } } private Response setOrderStatus(String tripId, String orderId, HttpHeaders headers) { //order paid and not collected int orderStatus = 1; Response result; if (tripId.startsWith("G") || tripId.startsWith("D")) { HttpEntity requestEntityModifyOrderStatusResult = new HttpEntity(headers); ResponseEntity<Response> reModifyOrderStatusResult = restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/status/" + orderId + "/" + orderStatus, HttpMethod.GET, requestEntityModifyOrderStatusResult, Response.class); result = reModifyOrderStatusResult.getBody(); } else { HttpEntity requestEntityModifyOrderStatusResult = new HttpEntity(headers); ResponseEntity<Response> reModifyOrderStatusResult = restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/status/" + orderId + "/" + orderStatus, HttpMethod.GET, requestEntityModifyOrderStatusResult, Response.class); result = reModifyOrderStatusResult.getBody(); } return result; } @Override public void initPayment(Payment payment, HttpHeaders headers) { Payment paymentTemp = paymentRepository.findById(payment.getId()); if (paymentTemp == null) { paymentRepository.save(payment); } else { InsidePaymentServiceImpl.LOGGER.error("[Init Payment] Already Exists, paymentId: {}, orderId: {}", payment.getId(), payment.getOrderId()); } } }
package order.service; import edu.fudan.common.util.Response; import order.entity.*; import order.repository.OrderRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.*; /** * @author fdse */ @Service public class OrderServiceImpl implements OrderService { @Autowired private OrderRepository orderRepository; @Autowired private RestTemplate restTemplate; private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class); String success = "Success"; String orderNotFound = "Order Not Found"; @Override public Response getSoldTickets(Seat seatRequest, HttpHeaders headers) { ArrayList<Order> list = orderRepository.findByTravelDateAndTrainNumber(seatRequest.getTravelDate(), seatRequest.getTrainNumber()); if (list != null && !list.isEmpty()) { Set ticketSet = new HashSet(); for (Order tempOrder : list) { ticketSet.add(new Ticket(Integer.parseInt(tempOrder.getSeatNumber()), tempOrder.getFrom(), tempOrder.getTo())); } LeftTicketInfo leftTicketInfo = new LeftTicketInfo(); leftTicketInfo.setSoldTickets(ticketSet); OrderServiceImpl.LOGGER.info("Left ticket info is: {}", leftTicketInfo.toString()); return new Response<>(1, success, leftTicketInfo); } else { OrderServiceImpl.LOGGER.error("Left ticket info is empty, seat from date: {}, train number: {}",seatRequest.getTravelDate(),seatRequest.getTrainNumber()); return new Response<>(0, "Order is Null.", null); } } @Override public Response findOrderById(UUID id, HttpHeaders headers) { Order order = orderRepository.findById(id); if (order == null) { OrderServiceImpl.LOGGER.error("No content, id: {}",id); return new Response<>(0, "No Content by this id", null); } else { return new Response<>(1, success, order); } } @Override public Response create(Order order, HttpHeaders headers) { OrderServiceImpl.LOGGER.info("[Create Order] Ready Create Order."); ArrayList<Order> accountOrders = orderRepository.findByAccountId(order.getAccountId()); if (accountOrders.contains(order)) { OrderServiceImpl.LOGGER.error("[Order Create] Fail.Order already exists, OrderId: {}", order.getId()); return new Response<>(0, "Order already exist", null); } else { order.setId(UUID.randomUUID()); orderRepository.save(order); OrderServiceImpl.LOGGER.info("[Order Create] Success."); OrderServiceImpl.LOGGER.info("[Order Create] Price: {}", order.getPrice()); return new Response<>(1, success, order); } } @Override public Response alterOrder(OrderAlterInfo oai, HttpHeaders headers) { UUID oldOrderId = oai.getPreviousOrderId(); Order oldOrder = orderRepository.findById(oldOrderId); if (oldOrder == null) { OrderServiceImpl.LOGGER.error("[Alter Order] Fail.Order do not exist, OrderId: {}", oldOrderId); return new Response<>(0, "Old Order Does Not Exists", null); } oldOrder.setStatus(OrderStatus.CANCEL.getCode()); saveChanges(oldOrder, headers); Order newOrder = oai.getNewOrderInfo(); newOrder.setId(UUID.randomUUID()); Response cor = create(oai.getNewOrderInfo(), headers); if (cor.getStatus() == 1) { OrderServiceImpl.LOGGER.info("[Alter Order] Success."); return new Response<>(1, success, newOrder); } else { OrderServiceImpl.LOGGER.error("Alter Order Fail.Create new order fail, OrderId: {}", newOrder.getId()); return new Response<>(0, cor.getMsg(), null); } } @Override public Response<ArrayList<Order>> queryOrders(OrderInfo qi, String accountId, HttpHeaders headers) { //1.Get all orders of the user ArrayList<Order> list = orderRepository.findByAccountId(UUID.fromString(accountId)); OrderServiceImpl.LOGGER.info("[Query Order][Step 1] Get Orders Number of Account: {}", list.size()); //2.Check is these orders fit the requirement/ if (qi.isEnableStateQuery() || qi.isEnableBoughtDateQuery() || qi.isEnableTravelDateQuery()) { ArrayList<Order> finalList = new ArrayList<>(); for (Order tempOrder : list) { boolean statePassFlag = false; boolean boughtDatePassFlag = false; boolean travelDatePassFlag = false; //3.Check order state requirement. if (qi.isEnableStateQuery()) { if (tempOrder.getStatus() != qi.getState()) { statePassFlag = false; } else { statePassFlag = true; } } else { statePassFlag = true; } OrderServiceImpl.LOGGER.info("[Query Order][Step 2][Check Status Fits End]"); //4.Check order travel date requirement. if (qi.isEnableTravelDateQuery()) { if (tempOrder.getTravelDate().before(qi.getTravelDateEnd()) && tempOrder.getTravelDate().after(qi.getBoughtDateStart())) { travelDatePassFlag = true; } else { travelDatePassFlag = false; } } else { travelDatePassFlag = true; } OrderServiceImpl.LOGGER.info("[Query Order][Step 2][Check Travel Date End]"); //5.Check order bought date requirement. if (qi.isEnableBoughtDateQuery()) { if (tempOrder.getBoughtDate().before(qi.getBoughtDateEnd()) && tempOrder.getBoughtDate().after(qi.getBoughtDateStart())) { boughtDatePassFlag = true; } else { boughtDatePassFlag = false; } } else { boughtDatePassFlag = true; } OrderServiceImpl.LOGGER.info("[Query Order][Step 2][Check Bought Date End]"); //6.check if all requirement fits. if (statePassFlag && boughtDatePassFlag && travelDatePassFlag) { finalList.add(tempOrder); } OrderServiceImpl.LOGGER.info("[Query Order][Step 2][Check All Requirement End]"); } OrderServiceImpl.LOGGER.info("[Query Order] Get order num: {}", finalList.size()); return new Response<>(1, "Get order num", finalList); } else { OrderServiceImpl.LOGGER.warn("[Query Order] Orders don't fit the requirement, loginId: {}", qi.getLoginId()); return new Response<>(1, "Get order num", list); } } @Override public Response queryOrdersForRefresh(OrderInfo qi, String accountId, HttpHeaders headers) { ArrayList<Order> orders = queryOrders(qi, accountId, headers).getData(); ArrayList<String> stationIds = new ArrayList<>(); for (Order order : orders) { stationIds.add(order.getFrom()); stationIds.add(order.getTo()); } List<String> names = queryForStationId(stationIds, headers); for (int i = 0; i < orders.size(); i++) { orders.get(i).setFrom(names.get(i * 2)); orders.get(i).setTo(names.get(i * 2 + 1)); } return new Response<>(1, "Query Orders For Refresh Success", orders); } public List<String> queryForStationId(List<String> ids, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(ids, null); ResponseEntity<Response<List<String>>> re = restTemplate.exchange( "http://ts-station-service:12345/api/v1/stationservice/stations/namelist", HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Response<List<String>>>() { }); OrderServiceImpl.LOGGER.info("Name List is: {}", re.getBody().toString()); return re.getBody().getData(); } @Override public Response saveChanges(Order order, HttpHeaders headers) { Order oldOrder = orderRepository.findById(order.getId()); if (oldOrder == null) { OrderServiceImpl.LOGGER.error("[Modify Order] Fail.Order not found, OrderId: {}", order.getId()); return new Response<>(0, orderNotFound, null); } else { oldOrder.setAccountId(order.getAccountId()); oldOrder.setBoughtDate(order.getBoughtDate()); oldOrder.setTravelDate(order.getTravelDate()); oldOrder.setTravelTime(order.getTravelTime()); oldOrder.setCoachNumber(order.getCoachNumber()); oldOrder.setSeatClass(order.getSeatClass()); oldOrder.setSeatNumber(order.getSeatNumber()); oldOrder.setFrom(order.getFrom()); oldOrder.setTo(order.getTo()); oldOrder.setStatus(order.getStatus()); oldOrder.setTrainNumber(order.getTrainNumber()); oldOrder.setPrice(order.getPrice()); oldOrder.setContactsName(order.getContactsName()); oldOrder.setContactsDocumentNumber(order.getContactsDocumentNumber()); oldOrder.setDocumentType(order.getDocumentType()); orderRepository.save(oldOrder); OrderServiceImpl.LOGGER.info("Success."); return new Response<>(1, success, oldOrder); } } @Override public Response cancelOrder(UUID accountId, UUID orderId, HttpHeaders headers) { Order oldOrder = orderRepository.findById(orderId); if (oldOrder == null) { OrderServiceImpl.LOGGER.error("[Cancel Order] Fail.Order not found, OrderId: {}", orderId); return new Response<>(0, orderNotFound, null); } else { oldOrder.setStatus(OrderStatus.CANCEL.getCode()); orderRepository.save(oldOrder); OrderServiceImpl.LOGGER.info("[Cancel Order] Success."); return new Response<>(1, success, oldOrder); } } @Override public Response queryAlreadySoldOrders(Date travelDate, String trainNumber, HttpHeaders headers) { ArrayList<Order> orders = orderRepository.findByTravelDateAndTrainNumber(travelDate, trainNumber); SoldTicket cstr = new SoldTicket(); cstr.setTravelDate(travelDate); cstr.setTrainNumber(trainNumber); OrderServiceImpl.LOGGER.info("[Calculate Sold Ticket] Get Orders Number: {}", orders.size()); for (Order order : orders) { if (order.getStatus() >= OrderStatus.CHANGE.getCode()) { continue; } if (order.getSeatClass() == SeatClass.NONE.getCode()) { cstr.setNoSeat(cstr.getNoSeat() + 1); } else if (order.getSeatClass() == SeatClass.BUSINESS.getCode()) { cstr.setBusinessSeat(cstr.getBusinessSeat() + 1); } else if (order.getSeatClass() == SeatClass.FIRSTCLASS.getCode()) { cstr.setFirstClassSeat(cstr.getFirstClassSeat() + 1); } else if (order.getSeatClass() == SeatClass.SECONDCLASS.getCode()) { cstr.setSecondClassSeat(cstr.getSecondClassSeat() + 1); } else if (order.getSeatClass() == SeatClass.HARDSEAT.getCode()) { cstr.setHardSeat(cstr.getHardSeat() + 1); } else if (order.getSeatClass() == SeatClass.SOFTSEAT.getCode()) { cstr.setSoftSeat(cstr.getSoftSeat() + 1); } else if (order.getSeatClass() == SeatClass.HARDBED.getCode()) { cstr.setHardBed(cstr.getHardBed() + 1); } else if (order.getSeatClass() == SeatClass.SOFTBED.getCode()) { cstr.setSoftBed(cstr.getSoftBed() + 1); } else if (order.getSeatClass() == SeatClass.HIGHSOFTBED.getCode()) { cstr.setHighSoftBed(cstr.getHighSoftBed() + 1); } else { OrderServiceImpl.LOGGER.info("[Calculate Sold Tickets] Seat class not exists. Order ID: {}", order.getId()); } } return new Response<>(1, success, cstr); } @Override public Response getAllOrders(HttpHeaders headers) { ArrayList<Order> orders = orderRepository.findAll(); if (orders != null && !orders.isEmpty()) { return new Response<>(1, "Success.", orders); } else { OrderServiceImpl.LOGGER.warn("Find all orders warn: {}","No content"); return new Response<>(0, "No Content.", null); } } @Override public Response modifyOrder(String orderId, int status, HttpHeaders headers) { Order order = orderRepository.findById(UUID.fromString(orderId)); if (order == null) { OrderServiceImpl.LOGGER.error("Modify order error.Order not found, OrderId: {}",orderId); return new Response<>(0, orderNotFound, null); } else { order.setStatus(status); orderRepository.save(order); return new Response<>(1, "Modify Order Success", order); } } @Override public Response getOrderPrice(String orderId, HttpHeaders headers) { Order order = orderRepository.findById(UUID.fromString(orderId)); if (order == null) { OrderServiceImpl.LOGGER.error("Get order price error.Order not found, OrderId: {}",orderId); return new Response<>(0, orderNotFound, "-1.0"); } else { OrderServiceImpl.LOGGER.info("[Get Order Price] Price: {}", order.getPrice()); return new Response<>(1, success, order.getPrice()); } } @Override public Response payOrder(String orderId, HttpHeaders headers) { Order order = orderRepository.findById(UUID.fromString(orderId)); if (order == null) { OrderServiceImpl.LOGGER.error("Pay order error.Order not found, OrderId: {}",orderId); return new Response<>(0, orderNotFound, null); } else { order.setStatus(OrderStatus.PAID.getCode()); orderRepository.save(order); return new Response<>(1, "Pay Order Success.", order); } } @Override public Response getOrderById(String orderId, HttpHeaders headers) { Order order = orderRepository.findById(UUID.fromString(orderId)); if (order == null) { OrderServiceImpl.LOGGER.error("Order not found, OrderId: {}",orderId); return new Response<>(0, orderNotFound, null); } else { return new Response<>(1, "Success.", order); } } @Override public void initOrder(Order order, HttpHeaders headers) { Order orderTemp = orderRepository.findById(order.getId()); if (orderTemp == null) { orderRepository.save(order); } else { OrderServiceImpl.LOGGER.error("[Init Order] Order Already Exists, OrderId: {}", order.getId()); } } @Override public Response checkSecurityAboutOrder(Date dateFrom, String accountId, HttpHeaders headers) { OrderSecurity result = new OrderSecurity(); ArrayList<Order> orders = orderRepository.findByAccountId(UUID.fromString(accountId)); int countOrderInOneHour = 0; int countTotalValidOrder = 0; Calendar ca = Calendar.getInstance(); ca.setTime(dateFrom); ca.add(Calendar.HOUR_OF_DAY, -1); dateFrom = ca.getTime(); for (Order order : orders) { if (order.getStatus() == OrderStatus.NOTPAID.getCode() || order.getStatus() == OrderStatus.PAID.getCode() || order.getStatus() == OrderStatus.COLLECTED.getCode()) { countTotalValidOrder += 1; } if (order.getBoughtDate().after(dateFrom)) { countOrderInOneHour += 1; } } result.setOrderNumInLastOneHour(countOrderInOneHour); result.setOrderNumOfValidOrder(countTotalValidOrder); return new Response<>(1, "Check Security Success . ", result); } @Override public Response deleteOrder(String orderId, HttpHeaders headers) { UUID orderUuid = UUID.fromString(orderId); Order order = orderRepository.findById(orderUuid); if (order == null) { OrderServiceImpl.LOGGER.error("Delete order error.Order not found, OrderId: {}",orderId); return new Response<>(0, "Order Not Exist.", null); } else { orderRepository.deleteById(orderUuid); return new Response<>(1, "Delete Order Success", order); } } @Override public Response addNewOrder(Order order, HttpHeaders headers) { OrderServiceImpl.LOGGER.info("[Admin Add Order] Ready Add Order."); ArrayList<Order> accountOrders = orderRepository.findByAccountId(order.getAccountId()); if (accountOrders.contains(order)) { OrderServiceImpl.LOGGER.error("[Admin Add Order] Fail.Order already exists, OrderId: {}",order.getId()); return new Response<>(0, "Order already exist", null); } else { order.setId(UUID.randomUUID()); orderRepository.save(order); OrderServiceImpl.LOGGER.info("[Admin Add Order] Success."); OrderServiceImpl.LOGGER.info("[Admin Add Order] Price: {}", order.getPrice()); return new Response<>(1, "Add new Order Success", order); } } @Override public Response updateOrder(Order order, HttpHeaders headers) { LOGGER.info("UPDATE ORDER INFO: " + order.toString()); Order oldOrder = orderRepository.findById(order.getId()); if (oldOrder == null) { OrderServiceImpl.LOGGER.error("[Admin Update Order] Fail.Order not found, OrderId: {}",order.getId()); return new Response<>(0, "Order Not Found, Can't update", null); } else { OrderServiceImpl.LOGGER.info("{}", oldOrder.toString()); oldOrder.setAccountId(order.getAccountId()); oldOrder.setBoughtDate(order.getBoughtDate()); oldOrder.setTravelDate(order.getTravelDate()); oldOrder.setTravelTime(order.getTravelTime()); oldOrder.setCoachNumber(order.getCoachNumber()); oldOrder.setSeatClass(order.getSeatClass()); oldOrder.setSeatNumber(order.getSeatNumber()); oldOrder.setFrom(order.getFrom()); oldOrder.setTo(order.getTo()); oldOrder.setStatus(order.getStatus()); oldOrder.setTrainNumber(order.getTrainNumber()); oldOrder.setPrice(order.getPrice()); oldOrder.setContactsName(order.getContactsName()); oldOrder.setContactsDocumentNumber(order.getContactsDocumentNumber()); oldOrder.setDocumentType(order.getDocumentType()); orderRepository.save(oldOrder); OrderServiceImpl.LOGGER.info("[Admin Update Order] Success."); return new Response<>(1, "Admin Update Order Success", oldOrder); } } }
package com.trainticket.service; import com.trainticket.entity.Money; import com.trainticket.entity.Payment; import com.trainticket.repository.AddMoneyRepository; import com.trainticket.repository.PaymentRepository; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import java.util.List; /** * @author Administrator * @date 2017/6/23. */ @Service public class PaymentServiceImpl implements PaymentService{ @Autowired PaymentRepository paymentRepository; @Autowired AddMoneyRepository addMoneyRepository; private static final Logger LOGGER = LoggerFactory.getLogger(PaymentServiceImpl.class); @Override public Response pay(Payment info, HttpHeaders headers){ if(paymentRepository.findByOrderId(info.getOrderId()) == null){ Payment payment = new Payment(); payment.setOrderId(info.getOrderId()); payment.setPrice(info.getPrice()); payment.setUserId(info.getUserId()); paymentRepository.save(payment); return new Response<>(1, "Pay Success", null); }else{ PaymentServiceImpl.LOGGER.warn("Pay Failed.Order not found with order id, PaymentId: {}, OrderId: {}",info.getId(),info.getOrderId()); return new Response<>(0, "Pay Failed, order not found with order id" +info.getOrderId(), null); } } @Override public Response addMoney(Payment info, HttpHeaders headers){ Money addMoney = new Money(); addMoney.setUserId(info.getUserId()); addMoney.setMoney(info.getPrice()); addMoneyRepository.save(addMoney); return new Response<>(1,"Add Money Success", addMoney); } @Override public Response query(HttpHeaders headers){ List<Payment> payments = paymentRepository.findAll(); if(payments!= null && !payments.isEmpty()){ return new Response<>(1,"Query Success", payments); }else { PaymentServiceImpl.LOGGER.warn("Find all payment warn: {}","No content"); return new Response<>(0, "No Content", null); } } @Override public void initPayment(Payment payment, HttpHeaders headers){ Payment paymentTemp = paymentRepository.findById(payment.getId()); if(paymentTemp == null){ PaymentServiceImpl.LOGGER.error("Init payment error.Payment not found, PaymentId: {}",payment.getId()); paymentRepository.save(payment); }else{ PaymentServiceImpl.LOGGER.info("[Init Payment] Already Exists: {}", payment.getId()); } } }
package preserve.service; import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import preserve.entity.*; import preserve.mq.RabbitSend; import java.util.Date; import java.util.UUID; /** * @author fdse */ @Service public class PreserveServiceImpl implements PreserveService { @Autowired private RestTemplate restTemplate; @Autowired private RabbitSend sendService; private static final Logger LOGGER = LoggerFactory.getLogger(PreserveServiceImpl.class); @Override public Response preserve(OrderTicketsInfo oti, HttpHeaders headers) { //1.detect ticket scalper PreserveServiceImpl.LOGGER.info("[Step 1] Check Security"); Response result = checkSecurity(oti.getAccountId(), headers); if (result.getStatus() == 0) { PreserveServiceImpl.LOGGER.error("[Step 1] Check Security Fail, AccountId: {}",oti.getAccountId()); return new Response<>(0, result.getMsg(), null); } PreserveServiceImpl.LOGGER.info("[Step 1] Check Security Complete"); //2.Querying contact information -- modification, mediated by the underlying information micro service PreserveServiceImpl.LOGGER.info("[Step 2] Find contacts"); PreserveServiceImpl.LOGGER.info("[Step 2] Contacts Id: {}", oti.getContactsId()); Response<Contacts> gcr = getContactsById(oti.getContactsId(), headers); if (gcr.getStatus() == 0) { PreserveServiceImpl.LOGGER.error("[Get Contacts] Fail,ContactsId: {},message: {}",oti.getContactsId(),gcr.getMsg()); return new Response<>(0, gcr.getMsg(), null); } PreserveServiceImpl.LOGGER.info("[Step 2] Complete"); //3.Check the info of train and the number of remaining tickets PreserveServiceImpl.LOGGER.info("[Step 3] Check tickets num"); TripAllDetailInfo gtdi = new TripAllDetailInfo(); gtdi.setFrom(oti.getFrom()); gtdi.setTo(oti.getTo()); gtdi.setTravelDate(oti.getDate()); gtdi.setTripId(oti.getTripId()); PreserveServiceImpl.LOGGER.info("[Step 3] TripId: {}", oti.getTripId()); Response<TripAllDetail> response = getTripAllDetailInformation(gtdi, headers); TripAllDetail gtdr = response.getData(); LOGGER.info("TripAllDetail:" + gtdr.toString()); if (response.getStatus() == 0) { PreserveServiceImpl.LOGGER.error("[Search For Trip Detail Information] error, TripId: {}, message: {}", gtdi.getTripId(), response.getMsg()); return new Response<>(0, response.getMsg(), null); } else { TripResponse tripResponse = gtdr.getTripResponse(); LOGGER.info("TripResponse:" + tripResponse.toString()); if (oti.getSeatType() == SeatClass.FIRSTCLASS.getCode()) { if (tripResponse.getConfortClass() == 0) { PreserveServiceImpl.LOGGER.warn("[Check seat is enough], TripId: {}",oti.getTripId()); return new Response<>(0, "Seat Not Enough", null); } } else { if (tripResponse.getEconomyClass() == SeatClass.SECONDCLASS.getCode() && tripResponse.getConfortClass() == 0) { PreserveServiceImpl.LOGGER.warn("[Check seat is Not enough], TripId: {}",oti.getTripId()); return new Response<>(0, "Seat Not Enough", null); } } } Trip trip = gtdr.getTrip(); PreserveServiceImpl.LOGGER.info("[Step 3] Tickets Enough"); //4.send the order request and set the order information PreserveServiceImpl.LOGGER.info("[Step 4] Do Order"); Contacts contacts = gcr.getData(); Order order = new Order(); UUID orderId = UUID.randomUUID(); order.setId(orderId); order.setTrainNumber(oti.getTripId()); order.setAccountId(UUID.fromString(oti.getAccountId())); String fromStationId = queryForStationId(oti.getFrom(), headers); String toStationId = queryForStationId(oti.getTo(), headers); order.setFrom(fromStationId); order.setTo(toStationId); order.setBoughtDate(new Date()); order.setStatus(OrderStatus.NOTPAID.getCode()); order.setContactsDocumentNumber(contacts.getDocumentNumber()); order.setContactsName(contacts.getName()); order.setDocumentType(contacts.getDocumentType()); Travel query = new Travel(); query.setTrip(trip); query.setStartingPlace(oti.getFrom()); query.setEndPlace(oti.getTo()); query.setDepartureTime(new Date()); HttpEntity requestEntity = new HttpEntity(query, headers); ResponseEntity<Response<TravelResult>> re = restTemplate.exchange( "http://ts-ticketinfo-service:15681/api/v1/ticketinfoservice/ticketinfo", HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Response<TravelResult>>() { }); TravelResult resultForTravel = re.getBody().getData(); order.setSeatClass(oti.getSeatType()); PreserveServiceImpl.LOGGER.info("[Order] Order Travel Date: {}", oti.getDate().toString()); order.setTravelDate(oti.getDate()); order.setTravelTime(gtdr.getTripResponse().getStartingTime()); //Dispatch the seat if (oti.getSeatType() == SeatClass.FIRSTCLASS.getCode()) { Ticket ticket = dipatchSeat(oti.getDate(), order.getTrainNumber(), fromStationId, toStationId, SeatClass.FIRSTCLASS.getCode(), headers); order.setSeatNumber("" + ticket.getSeatNo()); order.setSeatClass(SeatClass.FIRSTCLASS.getCode()); order.setPrice(resultForTravel.getPrices().get("confortClass")); } else { Ticket ticket = dipatchSeat(oti.getDate(), order.getTrainNumber(), fromStationId, toStationId, SeatClass.SECONDCLASS.getCode(), headers); order.setSeatClass(SeatClass.SECONDCLASS.getCode()); order.setSeatNumber("" + ticket.getSeatNo()); order.setPrice(resultForTravel.getPrices().get("economyClass")); } PreserveServiceImpl.LOGGER.info("[Order Price] Price is: {}", order.getPrice()); Response<Order> cor = createOrder(order, headers); if (cor.getStatus() == 0) { PreserveServiceImpl.LOGGER.error("[Create Order Fail] Create Order Fail. OrderId: {}, Reason: {}", order.getId(), cor.getMsg()); return new Response<>(0, cor.getMsg(), null); } PreserveServiceImpl.LOGGER.info("[Step 4] Do Order Complete"); Response returnResponse = new Response<>(1, "Success.", cor.getMsg()); //5.Check insurance options if (oti.getAssurance() == 0) { PreserveServiceImpl.LOGGER.info("[Step 5] Do not need to buy assurance"); } else { Response addAssuranceResult = addAssuranceForOrder( oti.getAssurance(), cor.getData().getId().toString(), headers); if (addAssuranceResult.getStatus() == 1) { PreserveServiceImpl.LOGGER.info("[Step 5] Buy Assurance Success"); } else { PreserveServiceImpl.LOGGER.warn("[Step 5] Buy Assurance Fail, assurance: {}, OrderId: {}", oti.getAssurance(),cor.getData().getId()); returnResponse.setMsg("Success.But Buy Assurance Fail."); } } //6.Increase the food order if (oti.getFoodType() != 0) { FoodOrder foodOrder = new FoodOrder(); foodOrder.setOrderId(cor.getData().getId()); foodOrder.setFoodType(oti.getFoodType()); foodOrder.setFoodName(oti.getFoodName()); foodOrder.setPrice(oti.getFoodPrice()); if (oti.getFoodType() == 2) { foodOrder.setStationName(oti.getStationName()); foodOrder.setStoreName(oti.getStoreName()); PreserveServiceImpl.LOGGER.info("foodstore= {} {} {}", foodOrder.getFoodType(), foodOrder.getStationName(), foodOrder.getStoreName()); } Response afor = createFoodOrder(foodOrder, headers); if (afor.getStatus() == 1) { PreserveServiceImpl.LOGGER.info("[Step 6] Buy Food Success"); } else { PreserveServiceImpl.LOGGER.error("[Step 6] Buy Food Fail, OrderId: {}",cor.getData().getId()); returnResponse.setMsg("Success.But Buy Food Fail."); } } else { PreserveServiceImpl.LOGGER.info("[Step 6] Do not need to buy food"); } //7.add consign if (null != oti.getConsigneeName() && !"".equals(oti.getConsigneeName())) { Consign consignRequest = new Consign(); consignRequest.setOrderId(cor.getData().getId()); consignRequest.setAccountId(cor.getData().getAccountId()); consignRequest.setHandleDate(oti.getHandleDate()); consignRequest.setTargetDate(cor.getData().getTravelDate().toString()); consignRequest.setFrom(cor.getData().getFrom()); consignRequest.setTo(cor.getData().getTo()); consignRequest.setConsignee(oti.getConsigneeName()); consignRequest.setPhone(oti.getConsigneePhone()); consignRequest.setWeight(oti.getConsigneeWeight()); consignRequest.setWithin(oti.isWithin()); LOGGER.info("CONSIGN INFO : " +consignRequest.toString()); Response icresult = createConsign(consignRequest, headers); if (icresult.getStatus() == 1) { PreserveServiceImpl.LOGGER.info("[Step 7] Consign Success"); } else { PreserveServiceImpl.LOGGER.error("[Step 7] Preserve Consign Fail, OrderId: {}", cor.getData().getId()); returnResponse.setMsg("Consign Fail."); } } else { PreserveServiceImpl.LOGGER.info("[Step 7] Do not need to consign"); } //8.send notification User getUser = getAccount(order.getAccountId().toString(), headers); NotifyInfo notifyInfo = new NotifyInfo(); notifyInfo.setDate(new Date().toString()); notifyInfo.setEmail(getUser.getEmail()); notifyInfo.setStartingPlace(order.getFrom()); notifyInfo.setEndPlace(order.getTo()); notifyInfo.setUsername(getUser.getUserName()); notifyInfo.setSeatNumber(order.getSeatNumber()); notifyInfo.setOrderNumber(order.getId().toString()); notifyInfo.setPrice(order.getPrice()); notifyInfo.setSeatClass(SeatClass.getNameByCode(order.getSeatClass())); notifyInfo.setStartingTime(order.getTravelTime().toString()); // TODO: change to async message serivce // sendEmail(notifyInfo, headers); return returnResponse; } public Ticket dipatchSeat(Date date, String tripId, String startStationId, String endStataionId, int seatType, HttpHeaders httpHeaders) { Seat seatRequest = new Seat(); seatRequest.setTravelDate(date); seatRequest.setTrainNumber(tripId); seatRequest.setStartStation(startStationId); seatRequest.setDestStation(endStataionId); seatRequest.setSeatType(seatType); HttpEntity requestEntityTicket = new HttpEntity(seatRequest, httpHeaders); ResponseEntity<Response<Ticket>> reTicket = restTemplate.exchange( "http://ts-seat-service:18898/api/v1/seatservice/seats", HttpMethod.POST, requestEntityTicket, new ParameterizedTypeReference<Response<Ticket>>() { }); return reTicket.getBody().getData(); } public boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders httpHeaders) { PreserveServiceImpl.LOGGER.info("[Preserve Service][Send Email] send email to mq"); try { String infoJson = JsonUtils.object2Json(notifyInfo); sendService.send(infoJson); } catch (Exception e) { PreserveServiceImpl.LOGGER.error("[Preserve Service] send email to mq error, exception is:" + e); return false; } return true; } public User getAccount(String accountId, HttpHeaders httpHeaders) { PreserveServiceImpl.LOGGER.info("[Cancel Order Service][Get Order By Id]"); HttpEntity requestEntitySendEmail = new HttpEntity(httpHeaders); ResponseEntity<Response<User>> getAccount = restTemplate.exchange( "http://ts-user-service:12342/api/v1/userservice/users/id/" + accountId, HttpMethod.GET, requestEntitySendEmail, new ParameterizedTypeReference<Response<User>>() { }); Response<User> result = getAccount.getBody(); return result.getData(); } private Response addAssuranceForOrder(int assuranceType, String orderId, HttpHeaders httpHeaders) { PreserveServiceImpl.LOGGER.info("[Preserve Service][Add Assurance For Order]"); HttpEntity requestAddAssuranceResult = new HttpEntity(httpHeaders); ResponseEntity<Response> reAddAssuranceResult = restTemplate.exchange( "http://ts-assurance-service:18888/api/v1/assuranceservice/assurances/" + assuranceType + "/" + orderId, HttpMethod.GET, requestAddAssuranceResult, Response.class); return reAddAssuranceResult.getBody(); } private String queryForStationId(String stationName, HttpHeaders httpHeaders) { PreserveServiceImpl.LOGGER.info("[Preserve Other Service][Get Station Name]"); HttpEntity requestQueryForStationId = new HttpEntity(httpHeaders); ResponseEntity<Response<String>> reQueryForStationId = restTemplate.exchange( "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + stationName, HttpMethod.GET, requestQueryForStationId, new ParameterizedTypeReference<Response<String>>() { }); return reQueryForStationId.getBody().getData(); } private Response checkSecurity(String accountId, HttpHeaders httpHeaders) { PreserveServiceImpl.LOGGER.info("[Preserve Other Service][Check Security] Checking...."); HttpEntity requestCheckResult = new HttpEntity(httpHeaders); ResponseEntity<Response> reCheckResult = restTemplate.exchange( "http://ts-security-service:11188/api/v1/securityservice/securityConfigs/" + accountId, HttpMethod.GET, requestCheckResult, Response.class); return reCheckResult.getBody(); } private Response<TripAllDetail> getTripAllDetailInformation(TripAllDetailInfo gtdi, HttpHeaders httpHeaders) { PreserveServiceImpl.LOGGER.info("[Preserve Other Service][Get Trip All Detail Information] Getting...."); HttpEntity requestGetTripAllDetailResult = new HttpEntity(gtdi, httpHeaders); ResponseEntity<Response<TripAllDetail>> reGetTripAllDetailResult = restTemplate.exchange( "http://ts-travel-service:12346/api/v1/travelservice/trip_detail", HttpMethod.POST, requestGetTripAllDetailResult, new ParameterizedTypeReference<Response<TripAllDetail>>() { }); return reGetTripAllDetailResult.getBody(); } private Response<Contacts> getContactsById(String contactsId, HttpHeaders httpHeaders) { PreserveServiceImpl.LOGGER.info("[Preserve Other Service][Get Contacts By Id] Getting...."); HttpEntity requestGetContactsResult = new HttpEntity(httpHeaders); ResponseEntity<Response<Contacts>> reGetContactsResult = restTemplate.exchange( "http://ts-contacts-service:12347/api/v1/contactservice/contacts/" + contactsId, HttpMethod.GET, requestGetContactsResult, new ParameterizedTypeReference<Response<Contacts>>() { }); return reGetContactsResult.getBody(); } private Response createOrder(Order coi, HttpHeaders httpHeaders) { PreserveServiceImpl.LOGGER.info("[Preserve Other Service][Get Contacts By Id] Creating...."); HttpEntity requestEntityCreateOrderResult = new HttpEntity(coi, httpHeaders); ResponseEntity<Response<Order>> reCreateOrderResult = restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order", HttpMethod.POST, requestEntityCreateOrderResult, new ParameterizedTypeReference<Response<Order>>() { }); return reCreateOrderResult.getBody(); } private Response createFoodOrder(FoodOrder afi, HttpHeaders httpHeaders) { PreserveServiceImpl.LOGGER.info("[Preserve Service][Add food Order] Creating...."); HttpEntity requestEntityAddFoodOrderResult = new HttpEntity(afi, httpHeaders); ResponseEntity<Response> reAddFoodOrderResult = restTemplate.exchange( "http://ts-food-service:18856/api/v1/foodservice/orders", HttpMethod.POST, requestEntityAddFoodOrderResult, Response.class); return reAddFoodOrderResult.getBody(); } private Response createConsign(Consign cr, HttpHeaders httpHeaders) { PreserveServiceImpl.LOGGER.info("[Preserve Service][Add Condign] Creating...."); HttpEntity requestEntityResultForTravel = new HttpEntity(cr, httpHeaders); ResponseEntity<Response> reResultForTravel = restTemplate.exchange( "http://ts-consign-service:16111/api/v1/consignservice/consigns", HttpMethod.POST, requestEntityResultForTravel, Response.class); return reResultForTravel.getBody(); } }
package price.service; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import price.entity.PriceConfig; import price.repository.PriceConfigRepository; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * @author fdse */ @Service public class PriceServiceImpl implements PriceService { @Autowired private PriceConfigRepository priceConfigRepository; private static final Logger LOGGER = LoggerFactory.getLogger(PriceServiceImpl.class); String noThatConfig = "No that config"; @Override public Response createNewPriceConfig(PriceConfig createAndModifyPriceConfig, HttpHeaders headers) { PriceServiceImpl.LOGGER.info("[Create New Price Config]"); PriceConfig priceConfig = null; // create if (createAndModifyPriceConfig.getId() == null || createAndModifyPriceConfig.getId().toString().length() < 10) { priceConfig = new PriceConfig(); priceConfig.setId(UUID.randomUUID()); priceConfig.setBasicPriceRate(createAndModifyPriceConfig.getBasicPriceRate()); priceConfig.setFirstClassPriceRate(createAndModifyPriceConfig.getFirstClassPriceRate()); priceConfig.setRouteId(createAndModifyPriceConfig.getRouteId()); priceConfig.setTrainType(createAndModifyPriceConfig.getTrainType()); priceConfigRepository.save(priceConfig); } else { // modify priceConfig = priceConfigRepository.findById(createAndModifyPriceConfig.getId()); if (priceConfig == null) { priceConfig = new PriceConfig(); priceConfig.setId(createAndModifyPriceConfig.getId()); } priceConfig.setBasicPriceRate(createAndModifyPriceConfig.getBasicPriceRate()); priceConfig.setFirstClassPriceRate(createAndModifyPriceConfig.getFirstClassPriceRate()); priceConfig.setRouteId(createAndModifyPriceConfig.getRouteId()); priceConfig.setTrainType(createAndModifyPriceConfig.getTrainType()); priceConfigRepository.save(priceConfig); } return new Response<>(1, "Create success", priceConfig); } @Override public PriceConfig findById(String id, HttpHeaders headers) { PriceServiceImpl.LOGGER.info("[Find By Id] ID: {}", id); return priceConfigRepository.findById(UUID.fromString(id)); } @Override public Response findByRouteIdAndTrainType(String routeId, String trainType, HttpHeaders headers) { PriceServiceImpl.LOGGER.info("[Find By Route And Train Type] Rote: {} Train Type: {}", routeId, trainType); PriceConfig priceConfig = priceConfigRepository.findByRouteIdAndTrainType(routeId, trainType); PriceServiceImpl.LOGGER.info("[Find By Route Id And Train Type]"); if (priceConfig == null) { PriceServiceImpl.LOGGER.warn("Find by route and train type warn. PricrConfig not found, RouteId: {}, TrainType: {}",routeId,trainType); return new Response<>(0, noThatConfig, null); } else { return new Response<>(1, "Success", priceConfig); } } @Override public Response findAllPriceConfig(HttpHeaders headers) { List<PriceConfig> list = priceConfigRepository.findAll(); if (list == null) { list = new ArrayList<>(); } if (!list.isEmpty()) { PriceServiceImpl.LOGGER.warn("Find all price config warn,{}","No Content"); return new Response<>(1, "Success", list); } else { return new Response<>(0, "No price config", null); } } @Override public Response deletePriceConfig(PriceConfig c, HttpHeaders headers) { PriceConfig priceConfig = priceConfigRepository.findById(c.getId()); if (priceConfig == null) { PriceServiceImpl.LOGGER.error("Delete price config error. Price config not found, PriceConfigId: {}",c.getId()); return new Response<>(0, noThatConfig, null); } else { PriceConfig pc = new PriceConfig(); pc.setId(c.getId()); pc.setRouteId(c.getRouteId()); pc.setTrainType(c.getTrainType()); pc.setBasicPriceRate(c.getBasicPriceRate()); pc.setFirstClassPriceRate(c.getFirstClassPriceRate()); priceConfigRepository.delete(pc); return new Response<>(1, "Delete success", pc); } } @Override public Response updatePriceConfig(PriceConfig c, HttpHeaders headers) { PriceConfig priceConfig = priceConfigRepository.findById(c.getId()); if (priceConfig == null) { PriceServiceImpl.LOGGER.error("Update price config error. Price config not found, PriceConfigId: {}",c.getId()); return new Response<>(0, noThatConfig, null); } else { priceConfig.setId(c.getId()); priceConfig.setBasicPriceRate(c.getBasicPriceRate()); priceConfig.setFirstClassPriceRate(c.getFirstClassPriceRate()); priceConfig.setRouteId(c.getRouteId()); priceConfig.setTrainType(c.getTrainType()); priceConfigRepository.save(priceConfig); return new Response<>(1, "Update success", priceConfig); } } }
package rebook.service; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import rebook.entity.*; import rebook.entity.RebookInfo; import java.math.BigDecimal; import java.util.Calendar; import java.util.Date; /** * @author fdse */ @Service public class RebookServiceImpl implements RebookService { @Autowired private RestTemplate restTemplate; private static final Logger LOGGER = LoggerFactory.getLogger(RebookServiceImpl.class); @Override public Response rebook(RebookInfo info, HttpHeaders httpHeaders) { Response<Order> queryOrderResult = getOrderByRebookInfo(info, httpHeaders); if (queryOrderResult.getStatus() == 1) { if (queryOrderResult.getData().getStatus() != 1) { RebookServiceImpl.LOGGER.warn("Rebook warn.Order not suitable to rebook,OrderId: {}",info.getOrderId()); return new Response<>(0, "you order not suitable to rebook!", null); } } else { RebookServiceImpl.LOGGER.warn("Rebook warn.Order not found,OrderId: {}",info.getOrderId()); return new Response(0, "order not found", null); } Order order = queryOrderResult.getData(); int status = order.getStatus(); if (status == OrderStatus.NOTPAID.getCode()) { RebookServiceImpl.LOGGER.warn("Rebook warn.Order not paid, OrderId: {}",info.getOrderId()); return new Response<>(0, "You haven't paid the original ticket!", null); } else if (status == OrderStatus.PAID.getCode()) { // do nothing } else if (status == OrderStatus.CHANGE.getCode()) { RebookServiceImpl.LOGGER.warn("Rebook warn.Order can't change twice,OrderId: {}",info.getOrderId()); return new Response<>(0, "You have already changed your ticket and you can only change one time.", null); } else if (status == OrderStatus.COLLECTED.getCode()) { RebookServiceImpl.LOGGER.warn("Rebook warn.Order already collected,OrderId: {}",info.getOrderId()); return new Response<>(0, "You have already collected your ticket and you can change it now.", null); } else { RebookServiceImpl.LOGGER.warn("Rebook warn.Order can't change,OrderId: {}",info.getOrderId()); return new Response<>(0, "You can't change your ticket.", null); } //Check the current time and the bus time of the old order, and judge whether the ticket can be changed according to the time. The ticket cannot be changed after two hours. if (!checkTime(order.getTravelDate(), order.getTravelTime())) { RebookServiceImpl.LOGGER.warn("Rebook warn.Order beyond change time,OrderId: {}",info.getOrderId()); return new Response<>(0, "You can only change the ticket before the train start or within 2 hours after the train start.", null); } //The departure and destination cannot be changed, only the train number, seat and time can be changed //Check the info of seat availability and trains TripAllDetailInfo gtdi = new TripAllDetailInfo(); gtdi.setFrom(queryForStationName(order.getFrom(), httpHeaders)); gtdi.setTo(queryForStationName(order.getTo(), httpHeaders)); gtdi.setTravelDate(info.getDate()); gtdi.setTripId(info.getTripId()); Response<TripAllDetail> gtdr = getTripAllDetailInformation(gtdi, info.getTripId(), httpHeaders); if (gtdr.getStatus() == 0) { RebookServiceImpl.LOGGER.warn("Rebook warn.Trip detail not found,OrderId: {}",info.getOrderId()); return new Response<>(0, gtdr.getMsg(), null); } else { TripResponse tripResponse = gtdr.getData().getTripResponse(); if (info.getSeatType() == SeatClass.FIRSTCLASS.getCode()) { if (tripResponse.getConfortClass() <= 0) { RebookServiceImpl.LOGGER.warn("Rebook warn.Seat Not Enough,OrderId: {},SeatType: {}",info.getOrderId(),info.getSeatType()); return new Response<>(0, "Seat Not Enough", null); } } else { if (tripResponse.getEconomyClass() == SeatClass.SECONDCLASS.getCode() && tripResponse.getConfortClass() <= 0) { RebookServiceImpl.LOGGER.warn("Rebook warn.Seat Not Enough,OrderId: {},SeatType: {}",info.getOrderId(),info.getSeatType()); return new Response<>(0, "Seat Not Enough", null); } } } //Deal with the difference, more refund less compensation //Return the original ticket so that someone else can book the corresponding seat String ticketPrice = "0"; if (info.getSeatType() == SeatClass.FIRSTCLASS.getCode()) { ticketPrice = ((TripAllDetail) gtdr.getData()).getTripResponse().getPriceForConfortClass(); } else if (info.getSeatType() == SeatClass.SECONDCLASS.getCode()) { ticketPrice = ((TripAllDetail) gtdr.getData()).getTripResponse().getPriceForEconomyClass(); } String oldPrice = order.getPrice(); BigDecimal priceOld = new BigDecimal(oldPrice); BigDecimal priceNew = new BigDecimal(ticketPrice); if (priceOld.compareTo(priceNew) > 0) { //Refund the difference String difference = priceOld.subtract(priceNew).toString(); if (!drawBackMoney(info.getLoginId(), difference, httpHeaders)) { RebookServiceImpl.LOGGER.warn("Rebook warn.Can't draw back the difference money,OrderId: {},LoginId: {},difference: {}",info.getOrderId(),info.getLoginId(),difference); return new Response<>(0, "Can't draw back the difference money, please try again!", null); } return updateOrder(order, info, (TripAllDetail) gtdr.getData(), ticketPrice, httpHeaders); } else if (priceOld.compareTo(priceNew) == 0) { //do nothing return updateOrder(order, info, (TripAllDetail) gtdr.getData(), ticketPrice, httpHeaders); } else { //make up the difference String difference = priceNew.subtract(priceOld).toString(); Order orderMoneyDifference = new Order(); orderMoneyDifference.setDifferenceMoney(difference); return new Response<>(2, "Please pay the different money!", orderMoneyDifference); } } @Override public Response payDifference(RebookInfo info, HttpHeaders httpHeaders) { httpHeaders = null; Response queryOrderResult = getOrderByRebookInfo(info, httpHeaders); if (queryOrderResult.getStatus() == 0) { return new Response<>(0, queryOrderResult.getMsg(), null); } Order order = (Order) queryOrderResult.getData(); TripAllDetailInfo gtdi = new TripAllDetailInfo(); gtdi.setFrom(queryForStationName(order.getFrom(), httpHeaders)); gtdi.setTo(queryForStationName(order.getTo(), httpHeaders)); gtdi.setTravelDate(info.getDate()); gtdi.setTripId(info.getTripId()); // TripAllDetail Response gtdrResposne = getTripAllDetailInformation(gtdi, info.getTripId(), httpHeaders); TripAllDetail gtdr = (TripAllDetail) gtdrResposne.getData(); String ticketPrice = "0"; if (info.getSeatType() == SeatClass.FIRSTCLASS.getCode()) { ticketPrice = gtdr.getTripResponse().getPriceForConfortClass(); } else if (info.getSeatType() == SeatClass.SECONDCLASS.getCode()) { ticketPrice = gtdr.getTripResponse().getPriceForEconomyClass(); } String oldPrice = order.getPrice(); BigDecimal priceOld = new BigDecimal(oldPrice); BigDecimal priceNew = new BigDecimal(ticketPrice); if (payDifferentMoney(info.getOrderId(), info.getTripId(), info.getLoginId(), priceNew.subtract(priceOld).toString(), httpHeaders)) { return updateOrder(order, info, gtdr, ticketPrice, httpHeaders); } else { RebookServiceImpl.LOGGER.warn("Pay difference warn.Can't pay the difference money,OrderId: {},LoginId: {},TripId: {}",info.getOrderId(),info.getLoginId(),info.getTripId()); return new Response<>(0, "Can't pay the difference,please try again", null); } } private Response updateOrder(Order order, RebookInfo info, TripAllDetail gtdr, String ticketPrice, HttpHeaders httpHeaders) { //4.Modify the original order and set the information of the order Trip trip = gtdr.getTrip(); String oldTripId = order.getTrainNumber(); order.setTrainNumber(info.getTripId()); order.setBoughtDate(new Date()); order.setStatus(OrderStatus.CHANGE.getCode()); order.setPrice(ticketPrice);//Set ticket price order.setSeatClass(info.getSeatType()); order.setTravelDate(info.getDate()); order.setTravelTime(trip.getStartingTime()); if (info.getSeatType() == SeatClass.FIRSTCLASS.getCode()) {//Dispatch the seat Ticket ticket = dipatchSeat(info.getDate(), order.getTrainNumber(), order.getFrom(), order.getTo(), SeatClass.FIRSTCLASS.getCode(), httpHeaders); order.setSeatClass(SeatClass.FIRSTCLASS.getCode()); order.setSeatNumber("" + ticket.getSeatNo()); } else { Ticket ticket = dipatchSeat(info.getDate(), order.getTrainNumber(), order.getFrom(), order.getTo(), SeatClass.SECONDCLASS.getCode(), httpHeaders); order.setSeatClass(SeatClass.SECONDCLASS.getCode()); order.setSeatNumber("" + ticket.getSeatNo()); } //Update order information //If the original order and the new order are located in the high-speed train and other orders respectively, the original order should be deleted and created on the other side with a new id. if ((tripGD(oldTripId) && tripGD(info.getTripId())) || (!tripGD(oldTripId) && !tripGD(info.getTripId()))) { Response changeOrderResult = updateOrder(order, info.getTripId(), httpHeaders); if (changeOrderResult.getStatus() == 1) { return new Response<>(1, "Success!", order); } else { RebookServiceImpl.LOGGER.error("Update order error,OrderId: {},TripId: {}",info.getOrderId(),info.getTripId()); return new Response<>(0, "Can't update Order!", null); } } else { //Delete the original order deleteOrder(order.getId().toString(), oldTripId, httpHeaders); //Create a new order on the other side createOrder(order, order.getTrainNumber(), httpHeaders); return new Response<>(1, "Success", order); } } public Ticket dipatchSeat(Date date, String tripId, String startStationId, String endStataionId, int seatType, HttpHeaders httpHeaders) { Seat seatRequest = new Seat(); seatRequest.setTravelDate(date); seatRequest.setTrainNumber(tripId); seatRequest.setSeatType(seatType); seatRequest.setStartStation(startStationId); seatRequest.setDestStation(endStataionId); HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestEntityTicket = new HttpEntity(seatRequest, newHeaders); ResponseEntity<Response<Ticket>> reTicket = restTemplate.exchange( "http://ts-seat-service:18898/api/v1/seatservice/seats", HttpMethod.POST, requestEntityTicket, new ParameterizedTypeReference<Response<Ticket>>() { }); return reTicket.getBody().getData(); } private boolean tripGD(String tripId) { return tripId.startsWith("G") || tripId.startsWith("D"); } private boolean checkTime(Date travelDate, Date travelTime) { boolean result = true; Calendar calDateA = Calendar.getInstance(); Date today = new Date(); calDateA.setTime(today); Calendar calDateB = Calendar.getInstance(); calDateB.setTime(travelDate); Calendar calDateC = Calendar.getInstance(); calDateC.setTime(travelTime); if (calDateA.get(Calendar.YEAR) > calDateB.get(Calendar.YEAR)) { result = false; } else if (calDateA.get(Calendar.YEAR) == calDateB.get(Calendar.YEAR)) { if (calDateA.get(Calendar.MONTH) > calDateB.get(Calendar.MONTH)) { result = false; } else if (calDateA.get(Calendar.MONTH) == calDateB.get(Calendar.MONTH)) { if (calDateA.get(Calendar.DAY_OF_MONTH) > calDateB.get(Calendar.DAY_OF_MONTH)) { result = false; } else if (calDateA.get(Calendar.DAY_OF_MONTH) == calDateB.get(Calendar.DAY_OF_MONTH)) { if (calDateA.get(Calendar.HOUR_OF_DAY) > calDateC.get(Calendar.HOUR_OF_DAY) + 2) { result = false; } else if (calDateA.get(Calendar.HOUR_OF_DAY) == (calDateC.get(Calendar.HOUR_OF_DAY) + 2) && calDateA.get(Calendar.MINUTE) > calDateC.get(Calendar.MINUTE)) { result = false; } } } } return result; } private Response<TripAllDetail> getTripAllDetailInformation(TripAllDetailInfo gtdi, String tripId, HttpHeaders httpHeaders) { Response<TripAllDetail> gtdr; String requestUrl = ""; if (tripId.startsWith("G") || tripId.startsWith("D")) { requestUrl = "http://ts-travel-service:12346/api/v1/travelservice/trip_detail"; // ts-travel-service:12346/travel/getTripAllDetailInfo } else { requestUrl = "http://ts-travel2-service:16346/api/v1/travel2service/trip_detail"; //ts-travel2-service:16346/travel2/getTripAllDetailInfo } HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestGetTripAllDetailResult = new HttpEntity(gtdi, newHeaders); ResponseEntity<Response<TripAllDetail>> reGetTripAllDetailResult = restTemplate.exchange( requestUrl, HttpMethod.POST, requestGetTripAllDetailResult, new ParameterizedTypeReference<Response<TripAllDetail>>() { }); gtdr = reGetTripAllDetailResult.getBody(); return gtdr; } private Response createOrder(Order order, String tripId, HttpHeaders httpHeaders) { String requestUrl = ""; if (tripId.startsWith("G") || tripId.startsWith("D")) { // ts-order-service:12031/order/create requestUrl = "http://ts-order-service:12031/api/v1/orderservice/order"; } else { //ts-order-other-service:12032/orderOther/create requestUrl = "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther"; } HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestCreateOrder = new HttpEntity(order, newHeaders); ResponseEntity<Response> reCreateOrder = restTemplate.exchange( requestUrl, HttpMethod.POST, requestCreateOrder, Response.class); return reCreateOrder.getBody(); } private Response updateOrder(Order info, String tripId, HttpHeaders httpHeaders) { String requestOrderUtl = ""; if (tripGD(tripId)) { requestOrderUtl = "http://ts-order-service:12031/api/v1/orderservice/order"; } else { requestOrderUtl = "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther"; } HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestUpdateOrder = new HttpEntity(info, newHeaders); ResponseEntity<Response> reUpdateOrder = restTemplate.exchange( requestOrderUtl, HttpMethod.PUT, requestUpdateOrder, Response.class); return reUpdateOrder.getBody(); } private Response deleteOrder(String orderId, String tripId, HttpHeaders httpHeaders) { String requestUrl = ""; if (tripGD(tripId)) { requestUrl = "http://ts-order-service:12031/api/v1/orderservice/order/" + orderId; } else { requestUrl = "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + orderId; } HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestDeleteOrder = new HttpEntity(newHeaders); ResponseEntity<Response> reDeleteOrder = restTemplate.exchange( requestUrl, HttpMethod.POST, requestDeleteOrder, Response.class); return reDeleteOrder.getBody(); } private Response<Order> getOrderByRebookInfo(RebookInfo info, HttpHeaders httpHeaders) { Response<Order> queryOrderResult; //Change can only be changed once, check the status of the order to determine whether it has been changed String requestUrl = ""; if (info.getOldTripId().startsWith("G") || info.getOldTripId().startsWith("D")) { requestUrl = "http://ts-order-service:12031/api/v1/orderservice/order/" + info.getOrderId(); } else { requestUrl = "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + info.getOrderId(); } HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestEntityGetOrderByRebookInfo = new HttpEntity(newHeaders); ResponseEntity<Response<Order>> reGetOrderByRebookInfo = restTemplate.exchange( requestUrl, HttpMethod.GET, requestEntityGetOrderByRebookInfo, new ParameterizedTypeReference<Response<Order>>() { }); queryOrderResult = reGetOrderByRebookInfo.getBody(); return queryOrderResult; } private String queryForStationName(String stationId, HttpHeaders httpHeaders) { HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestEntityQueryForStationName = new HttpEntity(newHeaders); ResponseEntity<Response> reQueryForStationName = restTemplate.exchange( "http://ts-station-service:12345/api/v1/stationservice/stations/name/" + stationId, HttpMethod.GET, requestEntityQueryForStationName, Response.class); Response station = reQueryForStationName.getBody(); return (String) station.getData(); } private boolean payDifferentMoney(String orderId, String tripId, String userId, String money, HttpHeaders httpHeaders) { PaymentDifferenceInfo info = new PaymentDifferenceInfo(); info.setOrderId(orderId); info.setTripId(tripId); info.setUserId(userId); info.setPrice(money); HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestEntityPayDifferentMoney = new HttpEntity(info, newHeaders); ResponseEntity<Response> rePayDifferentMoney = restTemplate.exchange( "http://ts-inside-payment-service:18673/api/v1/inside_pay_service/inside_payment/difference", HttpMethod.POST, requestEntityPayDifferentMoney, Response.class); Response result = rePayDifferentMoney.getBody(); return result.getStatus() == 1; } private boolean drawBackMoney(String userId, String money, HttpHeaders httpHeaders) { HttpHeaders newHeaders = getAuthorizationHeadersFrom(httpHeaders); HttpEntity requestEntityDrawBackMoney = new HttpEntity(newHeaders); ResponseEntity<Response> reDrawBackMoney = restTemplate.exchange( "http://ts-inside-payment-service:18673/api/v1/inside_pay_service/inside_payment/drawback/" + userId + "/" + money, HttpMethod.GET, requestEntityDrawBackMoney, Response.class); Response result = reDrawBackMoney.getBody(); return result.getStatus() == 1; } public static HttpHeaders getAuthorizationHeadersFrom(HttpHeaders oldHeaders) { HttpHeaders newHeaders = new HttpHeaders(); if (oldHeaders.containsKey(HttpHeaders.AUTHORIZATION)) { newHeaders.add(HttpHeaders.AUTHORIZATION, oldHeaders.getFirst(HttpHeaders.AUTHORIZATION)); } return newHeaders; } }
package route.service; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import route.entity.Route; import route.entity.RouteInfo; import route.repository.RouteRepository; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * @author fdse */ @Service public class RouteServiceImpl implements RouteService { @Autowired private RouteRepository routeRepository; private static final Logger LOGGER = LoggerFactory.getLogger(RouteServiceImpl.class); String success = "Success"; @Override public Response createAndModify(RouteInfo info, HttpHeaders headers) { RouteServiceImpl.LOGGER.info("Create And Modify Start: {} End: {}", info.getStartStation(), info.getEndStation()); String[] stations = info.getStationList().split(","); String[] distances = info.getDistanceList().split(","); List<String> stationList = new ArrayList<>(); List<Integer> distanceList = new ArrayList<>(); if (stations.length != distances.length) { RouteServiceImpl.LOGGER.error("Create and modify error.Station number not equal to distance number,RouteId: {}",info.getId()); return new Response<>(0, "Station Number Not Equal To Distance Number", null); } for (int i = 0; i < stations.length; i++) { stationList.add(stations[i]); distanceList.add(Integer.parseInt(distances[i])); } int maxIdArrayLen = 10; if (info.getId() == null || info.getId().length() < maxIdArrayLen) { Route route = new Route(); route.setId(UUID.randomUUID().toString()); route.setStartStationId(info.getStartStation()); route.setTerminalStationId(info.getEndStation()); route.setStations(stationList); route.setDistances(distanceList); routeRepository.save(route); RouteServiceImpl.LOGGER.info("Save success"); return new Response<>(1, "Save Success", route); } else { Route route = routeRepository.findById(info.getId()); if (route == null) { route = new Route(); route.setId(info.getId()); } route.setStartStationId(info.getStartStation()); route.setTerminalStationId(info.getEndStation()); route.setStations(stationList); route.setDistances(distanceList); routeRepository.save(route); RouteServiceImpl.LOGGER.info("Modify success"); return new Response<>(1, "Modify success", route); } } @Override public Response deleteRoute(String routeId, HttpHeaders headers) { routeRepository.removeRouteById(routeId); Route route = routeRepository.findById(routeId); if (route == null) { return new Response<>(1, "Delete Success", routeId); } else { RouteServiceImpl.LOGGER.error("Delete error.Route not found,RouteId: {}",routeId); return new Response<>(0, "Delete failed, Reason unKnown with this routeId", routeId); } } @Override public Response getRouteById(String routeId, HttpHeaders headers) { Route route = routeRepository.findById(routeId); if (route == null) { RouteServiceImpl.LOGGER.error("Find route error.Route not found,RouteId: {}",routeId); return new Response<>(0, "No content with the routeId", null); } else { return new Response<>(1, success, route); } } @Override public Response getRouteByStartAndTerminal(String startId, String terminalId, HttpHeaders headers) { ArrayList<Route> routes = routeRepository.findAll(); RouteServiceImpl.LOGGER.info("Find All: {}", routes.size()); List<Route> resultList = new ArrayList<>(); for (Route route : routes) { if (route.getStations().contains(startId) && route.getStations().contains(terminalId) && route.getStations().indexOf(startId) < route.getStations().indexOf(terminalId)) { resultList.add(route); } } if (!resultList.isEmpty()) { return new Response<>(1, success, resultList); } else { RouteServiceImpl.LOGGER.warn("Find by start and terminal warn.Routes not found,startId: {},terminalId: {}",startId,terminalId); return new Response<>(0, "No routes with the startId and terminalId", null); } } @Override public Response getAllRoutes(HttpHeaders headers) { ArrayList<Route> routes = routeRepository.findAll(); if (routes != null && !routes.isEmpty()) { return new Response<>(1, success, routes); } else { RouteServiceImpl.LOGGER.warn("Find all routes warn: {}","No Content"); return new Response<>(0, "No Content", null); } } }
package fdse.microservice.service; import edu.fudan.common.util.Response; import fdse.microservice.entity.*; import fdse.microservice.repository.StationRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class StationServiceImpl implements StationService { @Autowired private StationRepository repository; String success = "Success"; private static final Logger LOGGER = LoggerFactory.getLogger(StationServiceImpl.class); @Override public Response create(Station station, HttpHeaders headers) { if (repository.findById(station.getId()) == null) { station.setStayTime(station.getStayTime()); repository.save(station); return new Response<>(1, "Create success", station); } StationServiceImpl.LOGGER.error("Create station error.Already exists, StationId: {}",station.getId()); return new Response<>(0, "Already exists", station); } @Override public boolean exist(String stationName, HttpHeaders headers) { boolean result = false; if (repository.findByName(stationName) != null) { result = true; } return result; } @Override public Response update(Station info, HttpHeaders headers) { if (repository.findById(info.getId()) == null) { StationServiceImpl.LOGGER.error("Update station error.Station not found, StationId: {}",info.getId()); return new Response<>(0, "Station not exist", null); } else { Station station = new Station(info.getId(), info.getName()); station.setStayTime(info.getStayTime()); repository.save(station); return new Response<>(1, "Update success", station); } } @Override public Response delete(Station info, HttpHeaders headers) { if (repository.findById(info.getId()) != null) { Station station = new Station(info.getId(), info.getName()); repository.delete(station); return new Response<>(1, "Delete success", station); } StationServiceImpl.LOGGER.error("Delete station error.Station not found, StationId: {}",info.getId()); return new Response<>(0, "Station not exist", null); } @Override public Response query(HttpHeaders headers) { List<Station> stations = repository.findAll(); if (stations != null && !stations.isEmpty()) { return new Response<>(1, "Find all content", stations); } else { StationServiceImpl.LOGGER.warn("Query stations warn.Find all stations: {}","No content"); return new Response<>(0, "No content", null); } } @Override public Response queryForId(String stationName, HttpHeaders headers) { Station station = repository.findByName(stationName); if (station != null) { return new Response<>(1, success, station.getId()); } else { StationServiceImpl.LOGGER.warn("Find station id warn.Station not found, StationName: {}",stationName); return new Response<>(0, "Not exists", stationName); } } @Override public Response queryForIdBatch(List<String> nameList, HttpHeaders headers) { ArrayList<String> result = new ArrayList<>(); for (int i = 0; i < nameList.size(); i++) { Station station = repository.findByName(nameList.get(i)); if (station == null) { result.add("Not Exist"); } else { result.add(station.getId()); } } if (!result.isEmpty()) { return new Response<>(1, success, result); } else { StationServiceImpl.LOGGER.warn("Find station ids warn.Stations not found, StationNameNumber: {}",nameList.size()); return new Response<>(0, "No content according to name list", null); } } @Override public Response queryById(String stationId, HttpHeaders headers) { Station station = repository.findById(stationId); if (station != null) { return new Response<>(1, success, station.getName()); } else { StationServiceImpl.LOGGER.error("Find station name error.Station not found, StationId: {}",stationId); return new Response<>(0, "No that stationId", stationId); } } @Override public Response queryByIdBatch(List<String> idList, HttpHeaders headers) { ArrayList<String> result = new ArrayList<>(); for (int i = 0; i < idList.size(); i++) { Station station = repository.findById(idList.get(i)); if (station != null) { result.add(station.getName()); } } if (!result.isEmpty()) { return new Response<>(1, success, result); } else { StationServiceImpl.LOGGER.error("Find station names error.Stations not found, StationIdNumber: {}",idList.size()); return new Response<>(0, "No stationNamelist according to stationIdList", result); } } }
package travelplan.service; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import travelplan.entity.*; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author fdse */ @Service public class TravelPlanServiceImpl implements TravelPlanService { @Autowired private RestTemplate restTemplate; private static final Logger LOGGER = LoggerFactory.getLogger(TravelPlanServiceImpl.class); String success = "Success"; String cannotFind = "Cannot Find"; @Override public Response getTransferSearch(TransferTravelInfo info, HttpHeaders headers) { TripInfo queryInfoFirstSection = new TripInfo(); queryInfoFirstSection.setDepartureTime(info.getTravelDate()); queryInfoFirstSection.setStartingPlace(info.getFromStationName()); queryInfoFirstSection.setEndPlace(info.getViaStationName()); List<TripResponse> firstSectionFromHighSpeed; List<TripResponse> firstSectionFromNormal; firstSectionFromHighSpeed = tripsFromHighSpeed(queryInfoFirstSection, headers); firstSectionFromNormal = tripsFromNormal(queryInfoFirstSection, headers); TripInfo queryInfoSecondSectoin = new TripInfo(); queryInfoSecondSectoin.setDepartureTime(info.getTravelDate()); queryInfoSecondSectoin.setStartingPlace(info.getViaStationName()); queryInfoSecondSectoin.setEndPlace(info.getToStationName()); List<TripResponse> secondSectionFromHighSpeed; List<TripResponse> secondSectionFromNormal; secondSectionFromHighSpeed = tripsFromHighSpeed(queryInfoSecondSectoin, headers); secondSectionFromNormal = tripsFromNormal(queryInfoSecondSectoin, headers); List<TripResponse> firstSection = new ArrayList<>(); firstSection.addAll(firstSectionFromHighSpeed); firstSection.addAll(firstSectionFromNormal); List<TripResponse> secondSection = new ArrayList<>(); secondSection.addAll(secondSectionFromHighSpeed); secondSection.addAll(secondSectionFromNormal); TransferTravelResult result = new TransferTravelResult(); result.setFirstSectionResult(firstSection); result.setSecondSectionResult(secondSection); return new Response<>(1, "Success.", result); } @Override public Response getCheapest(TripInfo info, HttpHeaders headers) { RoutePlanInfo routePlanInfo = new RoutePlanInfo(); routePlanInfo.setNum(5); routePlanInfo.setFormStationName(info.getStartingPlace()); routePlanInfo.setToStationName(info.getEndPlace()); routePlanInfo.setTravelDate(info.getDepartureTime()); ArrayList<RoutePlanResultUnit> routePlanResultUnits = getRoutePlanResultCheapest(routePlanInfo, headers); if (!routePlanResultUnits.isEmpty()) { ArrayList<TravelAdvanceResultUnit> lists = new ArrayList<>(); for (int i = 0; i < routePlanResultUnits.size(); i++) { RoutePlanResultUnit tempUnit = routePlanResultUnits.get(i); TravelAdvanceResultUnit newUnit = new TravelAdvanceResultUnit(); newUnit.setTripId(tempUnit.getTripId()); newUnit.setToStationName(tempUnit.getToStationName()); newUnit.setTrainTypeId(tempUnit.getTrainTypeId()); newUnit.setFromStationName(tempUnit.getFromStationName()); List<String> stops = transferStationIdToStationName(tempUnit.getStopStations(), headers); newUnit.setStopStations(stops); newUnit.setPriceForFirstClassSeat(tempUnit.getPriceForFirstClassSeat()); newUnit.setPriceForSecondClassSeat(tempUnit.getPriceForSecondClassSeat()); newUnit.setStartingTime(tempUnit.getStartingTime()); newUnit.setEndTime(tempUnit.getEndTime()); int first = getRestTicketNumber(info.getDepartureTime(), tempUnit.getTripId(), tempUnit.getFromStationName(), tempUnit.getToStationName(), SeatClass.FIRSTCLASS.getCode(), headers); int second = getRestTicketNumber(info.getDepartureTime(), tempUnit.getTripId(), tempUnit.getFromStationName(), tempUnit.getToStationName(), SeatClass.SECONDCLASS.getCode(), headers); newUnit.setNumberOfRestTicketFirstClass(first); newUnit.setNumberOfRestTicketSecondClass(second); lists.add(newUnit); } return new Response<>(1, success, lists); } else { TravelPlanServiceImpl.LOGGER.warn("Get cheapest trip warn.Route Plan Result Units: {}","No Content"); return new Response<>(0, cannotFind, null); } } @Override public Response getQuickest(TripInfo info, HttpHeaders headers) { RoutePlanInfo routePlanInfo = new RoutePlanInfo(); routePlanInfo.setNum(5); routePlanInfo.setFormStationName(info.getStartingPlace()); routePlanInfo.setToStationName(info.getEndPlace()); routePlanInfo.setTravelDate(info.getDepartureTime()); ArrayList<RoutePlanResultUnit> routePlanResultUnits = getRoutePlanResultQuickest(routePlanInfo, headers); if (!routePlanResultUnits.isEmpty()) { ArrayList<TravelAdvanceResultUnit> lists = new ArrayList<>(); for (int i = 0; i < routePlanResultUnits.size(); i++) { RoutePlanResultUnit tempUnit = routePlanResultUnits.get(i); TravelAdvanceResultUnit newUnit = new TravelAdvanceResultUnit(); newUnit.setTripId(tempUnit.getTripId()); newUnit.setTrainTypeId(tempUnit.getTrainTypeId()); newUnit.setToStationName(tempUnit.getToStationName()); newUnit.setFromStationName(tempUnit.getFromStationName()); List<String> stops = transferStationIdToStationName(tempUnit.getStopStations(), headers); newUnit.setStopStations(stops); newUnit.setPriceForFirstClassSeat(tempUnit.getPriceForFirstClassSeat()); newUnit.setPriceForSecondClassSeat(tempUnit.getPriceForSecondClassSeat()); newUnit.setStartingTime(tempUnit.getStartingTime()); newUnit.setEndTime(tempUnit.getEndTime()); int first = getRestTicketNumber(info.getDepartureTime(), tempUnit.getTripId(), tempUnit.getFromStationName(), tempUnit.getToStationName(), SeatClass.FIRSTCLASS.getCode(), headers); int second = getRestTicketNumber(info.getDepartureTime(), tempUnit.getTripId(), tempUnit.getFromStationName(), tempUnit.getToStationName(), SeatClass.SECONDCLASS.getCode(), headers); newUnit.setNumberOfRestTicketFirstClass(first); newUnit.setNumberOfRestTicketSecondClass(second); lists.add(newUnit); } return new Response<>(1, success, lists); } else { TravelPlanServiceImpl.LOGGER.warn("Get quickest trip warn.Route Plan Result Units: {}","No Content"); return new Response<>(0, cannotFind, null); } } @Override public Response getMinStation(TripInfo info, HttpHeaders headers) { RoutePlanInfo routePlanInfo = new RoutePlanInfo(); routePlanInfo.setNum(5); routePlanInfo.setFormStationName(info.getStartingPlace()); routePlanInfo.setToStationName(info.getEndPlace()); routePlanInfo.setTravelDate(info.getDepartureTime()); ArrayList<RoutePlanResultUnit> routePlanResultUnits = getRoutePlanResultMinStation(routePlanInfo, headers); if (!routePlanResultUnits.isEmpty()) { ArrayList<TravelAdvanceResultUnit> lists = new ArrayList<>(); for (int i = 0; i < routePlanResultUnits.size(); i++) { RoutePlanResultUnit tempUnit = routePlanResultUnits.get(i); TravelAdvanceResultUnit newUnit = new TravelAdvanceResultUnit(); newUnit.setTripId(tempUnit.getTripId()); newUnit.setTrainTypeId(tempUnit.getTrainTypeId()); newUnit.setFromStationName(tempUnit.getFromStationName()); newUnit.setToStationName(tempUnit.getToStationName()); List<String> stops = transferStationIdToStationName(tempUnit.getStopStations(), headers); newUnit.setStopStations(stops); newUnit.setPriceForFirstClassSeat(tempUnit.getPriceForFirstClassSeat()); newUnit.setPriceForSecondClassSeat(tempUnit.getPriceForSecondClassSeat()); newUnit.setEndTime(tempUnit.getEndTime()); newUnit.setStartingTime(tempUnit.getStartingTime()); int first = getRestTicketNumber(info.getDepartureTime(), tempUnit.getTripId(), tempUnit.getFromStationName(), tempUnit.getToStationName(), SeatClass.FIRSTCLASS.getCode(), headers); int second = getRestTicketNumber(info.getDepartureTime(), tempUnit.getTripId(), tempUnit.getFromStationName(), tempUnit.getToStationName(), SeatClass.SECONDCLASS.getCode(), headers); newUnit.setNumberOfRestTicketFirstClass(first); newUnit.setNumberOfRestTicketSecondClass(second); lists.add(newUnit); } return new Response<>(1, success, lists); } else { TravelPlanServiceImpl.LOGGER.warn("Get min stations trip warn.Route Plan Result Units: {}","No Content"); return new Response<>(0, cannotFind, null); } } private int getRestTicketNumber(Date travelDate, String trainNumber, String startStationName, String endStationName, int seatType, HttpHeaders headers) { Seat seatRequest = new Seat(); String fromId = queryForStationId(startStationName, headers); String toId = queryForStationId(endStationName, headers); seatRequest.setDestStation(toId); seatRequest.setStartStation(fromId); seatRequest.setTrainNumber(trainNumber); seatRequest.setTravelDate(travelDate); seatRequest.setSeatType(seatType); TravelPlanServiceImpl.LOGGER.info("Seat Request is: {}", seatRequest.toString()); HttpEntity requestEntity = new HttpEntity(seatRequest, null); ResponseEntity<Response<Integer>> re = restTemplate.exchange( "http://ts-seat-service:18898/api/v1/seatservice/seats/left_tickets", HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Response<Integer>>() { }); return re.getBody().getData(); } private ArrayList<RoutePlanResultUnit> getRoutePlanResultCheapest(RoutePlanInfo info, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(info, null); ResponseEntity<Response<ArrayList<RoutePlanResultUnit>>> re = restTemplate.exchange( "http://ts-route-plan-service:14578/api/v1/routeplanservice/routePlan/cheapestRoute", HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Response<ArrayList<RoutePlanResultUnit>>>() { }); return re.getBody().getData(); } private ArrayList<RoutePlanResultUnit> getRoutePlanResultQuickest(RoutePlanInfo info, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(info, null); ResponseEntity<Response<ArrayList<RoutePlanResultUnit>>> re = restTemplate.exchange( "http://ts-route-plan-service:14578/api/v1/routeplanservice/routePlan/quickestRoute", HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Response<ArrayList<RoutePlanResultUnit>>>() { }); return re.getBody().getData(); } private ArrayList<RoutePlanResultUnit> getRoutePlanResultMinStation(RoutePlanInfo info, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(info, null); ResponseEntity<Response<ArrayList<RoutePlanResultUnit>>> re = restTemplate.exchange( "http://ts-route-plan-service:14578/api/v1/routeplanservice/routePlan/minStopStations", HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Response<ArrayList<RoutePlanResultUnit>>>() { }); return re.getBody().getData(); } private List<TripResponse> tripsFromHighSpeed(TripInfo info, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(info, null); ResponseEntity<Response<List<TripResponse>>> re = restTemplate.exchange( "http://ts-travel-service:12346/api/v1/travelservice/trips/left", HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Response<List<TripResponse>>>() { }); return re.getBody().getData(); } private ArrayList<TripResponse> tripsFromNormal(TripInfo info, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(info, null); ResponseEntity<Response<ArrayList<TripResponse>>> re = restTemplate.exchange( "http://ts-travel2-service:16346/api/v1/travel2service/trips/left", HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Response<ArrayList<TripResponse>>>() { }); return re.getBody().getData(); } private String queryForStationId(String stationName, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(null); ResponseEntity<Response<String>> re = restTemplate.exchange( "http://ts-ticketinfo-service:15681/api/v1/ticketinfoservice/ticketinfo/" + stationName, HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<String>>() { }); return re.getBody().getData(); } private List<String> transferStationIdToStationName(ArrayList<String> stations, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(stations, null); ResponseEntity<Response<List<String>>> re = restTemplate.exchange( "http://ts-station-service:12345/api/v1/stationservice/stations/namelist", HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Response<List<String>>>() { }); return re.getBody().getData(); } }
package travel.service; import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import travel.entity.*; import travel.repository.TripRepository; import java.util.*; /** * @author fdse */ @Service public class TravelServiceImpl implements TravelService { @Autowired private TripRepository repository; @Autowired private RestTemplate restTemplate; private static final Logger LOGGER = LoggerFactory.getLogger(TravelServiceImpl.class); String success = "Success"; String noContent = "No Content"; @Override public Response create(TravelInfo info, HttpHeaders headers) { TripId ti = new TripId(info.getTripId()); if (repository.findByTripId(ti) == null) { Trip trip = new Trip(ti, info.getTrainTypeId(), info.getStartingStationId(), info.getStationsId(), info.getTerminalStationId(), info.getStartingTime(), info.getEndTime()); trip.setRouteId(info.getRouteId()); repository.save(trip); return new Response<>(1, "Create trip:" + ti.toString() + ".", null); } else { TravelServiceImpl.LOGGER.error("Create trip error.Trip already exists,TripId: {}",info.getTripId()); return new Response<>(1, "Trip " + info.getTripId().toString() + " already exists", null); } } @Override public Response getRouteByTripId(String tripId, HttpHeaders headers) { Route route = null; if (null != tripId && tripId.length() >= 2) { TripId tripId1 = new TripId(tripId); Trip trip = repository.findByTripId(tripId1); if (trip != null) { route = getRouteByRouteId(trip.getRouteId(), headers); } else{ TravelServiceImpl.LOGGER.error("Get route by Trip id error.Trip not found, TripId: {}",tripId); } } if (route != null) { return new Response<>(1, success, route); } else { TravelServiceImpl.LOGGER.error("Get route by Trip id error.Route not found, TripId: {}",tripId); return new Response<>(0, noContent, null); } } @Override public Response getTrainTypeByTripId(String tripId, HttpHeaders headers) { TripId tripId1 = new TripId(tripId); TrainType trainType = null; Trip trip = repository.findByTripId(tripId1); if (trip != null) { trainType = getTrainType(trip.getTrainTypeId(), headers); } else{ TravelServiceImpl.LOGGER.error("Get Train Type by Trip id error.Trip not found, TripId: {}",tripId); } if (trainType != null) { return new Response<>(1, success, trainType); } else { TravelServiceImpl.LOGGER.error("Get Train Type by Trip id error.Train Type not found, TripId: {}",tripId); return new Response<>(0, noContent, null); } } @Override public Response getTripByRoute(ArrayList<String> routeIds, HttpHeaders headers) { ArrayList<ArrayList<Trip>> tripList = new ArrayList<>(); for (String routeId : routeIds) { ArrayList<Trip> tempTripList = repository.findByRouteId(routeId); if (tempTripList == null) { tempTripList = new ArrayList<>(); } tripList.add(tempTripList); } if (!tripList.isEmpty()) { return new Response<>(1, success, tripList); } else { TravelServiceImpl.LOGGER.warn("Get trips by routes warn.Trip list: {}","No content"); return new Response<>(0, noContent, null); } } @Override public Response retrieve(String tripId, HttpHeaders headers) { TripId ti = new TripId(tripId); Trip trip = repository.findByTripId(ti); if (trip != null) { return new Response<>(1, "Search Trip Success by Trip Id " + tripId, trip); } else { TravelServiceImpl.LOGGER.error("Retrieve trip error.Trip not found,TripId: {}",tripId); return new Response<>(0, "No Content according to tripId" + tripId, null); } } @Override public Response update(TravelInfo info, HttpHeaders headers) { TripId ti = new TripId(info.getTripId()); if (repository.findByTripId(ti) != null) { Trip trip = new Trip(ti, info.getTrainTypeId(), info.getStartingStationId(), info.getStationsId(), info.getTerminalStationId(), info.getStartingTime(), info.getEndTime()); trip.setRouteId(info.getRouteId()); repository.save(trip); return new Response<>(1, "Update trip:" + ti.toString(), trip); } else { TravelServiceImpl.LOGGER.error("Update trip error.Trip not found,TripId: {}",info.getTripId()); return new Response<>(1, "Trip" + info.getTripId().toString() + "doesn 't exists", null); } } @Override public Response delete(String tripId, HttpHeaders headers) { TripId ti = new TripId(tripId); if (repository.findByTripId(ti) != null) { repository.deleteByTripId(ti); return new Response<>(1, "Delete trip:" + tripId + ".", tripId); } else { TravelServiceImpl.LOGGER.error("Delete trip error.Trip not found,TripId: {}",tripId); return new Response<>(0, "Trip " + tripId + " doesn't exist.", null); } } @Override public Response query(TripInfo info, HttpHeaders headers) { //Gets the start and arrival stations of the train number to query. The originating and arriving stations received here are both station names, so two requests need to be sent to convert to station ids String startingPlaceName = info.getStartingPlace(); String endPlaceName = info.getEndPlace(); String startingPlaceId = queryForStationId(startingPlaceName, headers); String endPlaceId = queryForStationId(endPlaceName, headers); //This is the final result List<TripResponse> list = new ArrayList<>(); //Check all train info List<Trip> allTripList = repository.findAll(); for (Trip tempTrip : allTripList) { //Get the detailed route list of this train Route tempRoute = getRouteByRouteId(tempTrip.getRouteId(), headers); //Check the route list for this train. Check that the required start and arrival stations are in the list of stops that are not on the route, and check that the location of the start station is before the stop //Trains that meet the above criteria are added to the return list if (tempRoute.getStations().contains(startingPlaceId) && tempRoute.getStations().contains(endPlaceId) && tempRoute.getStations().indexOf(startingPlaceId) < tempRoute.getStations().indexOf(endPlaceId)) { TripResponse response = getTickets(tempTrip, tempRoute, startingPlaceId, endPlaceId, startingPlaceName, endPlaceName, info.getDepartureTime(), headers); if (response == null) { TravelServiceImpl.LOGGER.warn("Query trip error.Tickets not found,start: {},end: {},time: {}",startingPlaceName,endPlaceName,info.getDepartureTime()); return new Response<>(0, "No Trip info content", null); } list.add(response); } } return new Response<>(1, success, list); } @Override public Response getTripAllDetailInfo(TripAllDetailInfo gtdi, HttpHeaders headers) { TripAllDetail gtdr = new TripAllDetail(); TravelServiceImpl.LOGGER.info("[TripAllDetailInfo] TripId: {}", gtdi.getTripId()); Trip trip = repository.findByTripId(new TripId(gtdi.getTripId())); if (trip == null) { gtdr.setTripResponse(null); gtdr.setTrip(null); TravelServiceImpl.LOGGER.error("Get trip detail error.Trip not found,TripId: {}",gtdi.getTripId()); } else { String startingPlaceName = gtdi.getFrom(); String endPlaceName = gtdi.getTo(); String startingPlaceId = queryForStationId(startingPlaceName, headers); String endPlaceId = queryForStationId(endPlaceName, headers); Route tempRoute = getRouteByRouteId(trip.getRouteId(), headers); TripResponse tripResponse = getTickets(trip, tempRoute, startingPlaceId, endPlaceId, gtdi.getFrom(), gtdi.getTo(), gtdi.getTravelDate(), headers); if (tripResponse == null) { gtdr.setTripResponse(null); gtdr.setTrip(null); TravelServiceImpl.LOGGER.warn("Get trip detail error.Tickets not found,start: {},end: {},time: {}",startingPlaceName,endPlaceName,gtdi.getTravelDate()); } else { gtdr.setTripResponse(tripResponse); gtdr.setTrip(repository.findByTripId(new TripId(gtdi.getTripId()))); } } return new Response<>(1, success, gtdr); } private TripResponse getTickets(Trip trip, Route route, String startingPlaceId, String endPlaceId, String startingPlaceName, String endPlaceName, Date departureTime, HttpHeaders headers) { //Determine if the date checked is the same day and after if (!afterToday(departureTime)) { return null; } Travel query = new Travel(); query.setTrip(trip); query.setStartingPlace(startingPlaceName); query.setEndPlace(endPlaceName); query.setDepartureTime(departureTime); HttpEntity requestEntity = new HttpEntity(query, null); ResponseEntity<Response> re = restTemplate.exchange( "http://ts-ticketinfo-service:15681/api/v1/ticketinfoservice/ticketinfo", HttpMethod.POST, requestEntity, Response.class); TravelServiceImpl.LOGGER.info("Ts-basic-service ticket info is: {}", re.getBody().toString()); TravelResult resultForTravel = JsonUtils.conveterObject(re.getBody().getData(), TravelResult.class); //Ticket order _ high-speed train (number of tickets purchased) requestEntity = new HttpEntity(null); ResponseEntity<Response<SoldTicket>> re2 = restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + departureTime + "/" + trip.getTripId().toString(), HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<SoldTicket>>() { }); Response<SoldTicket> result = re2.getBody(); TravelServiceImpl.LOGGER.info("Order info is: {}", result.toString()); //Set the returned ticket information TripResponse response = new TripResponse(); response.setConfortClass(50); response.setEconomyClass(50); int first = getRestTicketNumber(departureTime, trip.getTripId().toString(), startingPlaceName, endPlaceName, SeatClass.FIRSTCLASS.getCode(), headers); int second = getRestTicketNumber(departureTime, trip.getTripId().toString(), startingPlaceName, endPlaceName, SeatClass.SECONDCLASS.getCode(), headers); response.setConfortClass(first); response.setEconomyClass(second); response.setStartingStation(startingPlaceName); response.setTerminalStation(endPlaceName); //Calculate the distance from the starting point int indexStart = route.getStations().indexOf(startingPlaceId); int indexEnd = route.getStations().indexOf(endPlaceId); int distanceStart = route.getDistances().get(indexStart) - route.getDistances().get(0); int distanceEnd = route.getDistances().get(indexEnd) - route.getDistances().get(0); TrainType trainType = getTrainType(trip.getTrainTypeId(), headers); //Train running time is calculated according to the average running speed of the train int minutesStart = 60 * distanceStart / trainType.getAverageSpeed(); int minutesEnd = 60 * distanceEnd / trainType.getAverageSpeed(); Calendar calendarStart = Calendar.getInstance(); calendarStart.setTime(trip.getStartingTime()); calendarStart.add(Calendar.MINUTE, minutesStart); response.setStartingTime(calendarStart.getTime()); TravelServiceImpl.LOGGER.info("calculate time:{} time: {}", minutesStart, calendarStart.getTime()); Calendar calendarEnd = Calendar.getInstance(); calendarEnd.setTime(trip.getStartingTime()); calendarEnd.add(Calendar.MINUTE, minutesEnd); response.setEndTime(calendarEnd.getTime()); TravelServiceImpl.LOGGER.info("calculate time:{} time: {}", minutesEnd, calendarEnd.getTime()); response.setTripId(new TripId(result.getData().getTrainNumber())); response.setTrainTypeId(trip.getTrainTypeId()); response.setPriceForConfortClass(resultForTravel.getPrices().get("confortClass")); response.setPriceForEconomyClass(resultForTravel.getPrices().get("economyClass")); return response; } @Override public Response queryAll(HttpHeaders headers) { List<Trip> tripList = repository.findAll(); if (tripList != null && !tripList.isEmpty()) { return new Response<>(1, success, tripList); } TravelServiceImpl.LOGGER.warn("Query all trips warn: {}","No Content"); return new Response<>(0, noContent, null); } private static boolean afterToday(Date date) { Calendar calDateA = Calendar.getInstance(); Date today = new Date(); calDateA.setTime(today); Calendar calDateB = Calendar.getInstance(); calDateB.setTime(date); if (calDateA.get(Calendar.YEAR) > calDateB.get(Calendar.YEAR)) { return false; } else if (calDateA.get(Calendar.YEAR) == calDateB.get(Calendar.YEAR)) { if (calDateA.get(Calendar.MONTH) > calDateB.get(Calendar.MONTH)) { return false; } else if (calDateA.get(Calendar.MONTH) == calDateB.get(Calendar.MONTH)) { return calDateA.get(Calendar.DAY_OF_MONTH) <= calDateB.get(Calendar.DAY_OF_MONTH) ; } else { return true; } } else { return true; } } private TrainType getTrainType(String trainTypeId, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(null); ResponseEntity<Response<TrainType>> re = restTemplate.exchange( "http://ts-train-service:14567/api/v1/trainservice/trains/" + trainTypeId, HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<TrainType>>() { }); return re.getBody().getData(); } private String queryForStationId(String stationName, HttpHeaders headers) { HttpEntity requestEntity = new HttpEntity(null); ResponseEntity<Response<String>> re = restTemplate.exchange( "http://ts-ticketinfo-service:15681/api/v1/ticketinfoservice/ticketinfo/" + stationName, HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<String>>() { }); TravelServiceImpl.LOGGER.info("Query for Station id is: {}", re.getBody().toString()); return re.getBody().getData(); } private Route getRouteByRouteId(String routeId, HttpHeaders headers) { TravelServiceImpl.LOGGER.info("[Travel Service][Get Route By Id] Route ID:{}", routeId); HttpEntity requestEntity = new HttpEntity(null); ResponseEntity<Response> re = restTemplate.exchange( "http://ts-route-service:11178/api/v1/routeservice/routes/" + routeId, HttpMethod.GET, requestEntity, Response.class); Response routeRes = re.getBody(); Route route1 = new Route(); TravelServiceImpl.LOGGER.info("Routes Response is : {}", routeRes.toString()); if (routeRes.getStatus() == 1) { route1 = JsonUtils.conveterObject(routeRes.getData(), Route.class); TravelServiceImpl.LOGGER.info("Route is: {}", route1.toString()); } return route1; } private int getRestTicketNumber(Date travelDate, String trainNumber, String startStationName, String endStationName, int seatType, HttpHeaders headers) { Seat seatRequest = new Seat(); String fromId = queryForStationId(startStationName, headers); String toId = queryForStationId(endStationName, headers); seatRequest.setDestStation(toId); seatRequest.setStartStation(fromId); seatRequest.setTrainNumber(trainNumber); seatRequest.setTravelDate(travelDate); seatRequest.setSeatType(seatType); TravelServiceImpl.LOGGER.info("Seat request To String: {}", seatRequest.toString()); HttpEntity requestEntity = new HttpEntity(seatRequest, null); ResponseEntity<Response<Integer>> re = restTemplate.exchange( "http://ts-seat-service:18898/api/v1/seatservice/seats/left_tickets", HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Response<Integer>>() { }); TravelServiceImpl.LOGGER.info("Get Rest tickets num is: {}", re.getBody().toString()); return re.getBody().getData(); } @Override public Response adminQueryAll(HttpHeaders headers) { List<Trip> trips = repository.findAll(); ArrayList<AdminTrip> adminTrips = new ArrayList<>(); for (Trip trip : trips) { AdminTrip adminTrip = new AdminTrip(); adminTrip.setTrip(trip); adminTrip.setRoute(getRouteByRouteId(trip.getRouteId(), headers)); adminTrip.setTrainType(getTrainType(trip.getTrainTypeId(), headers)); adminTrips.add(adminTrip); } if (!adminTrips.isEmpty()) { return new Response<>(1, success, adminTrips); } else { TravelServiceImpl.LOGGER.warn("Admin query all trips warn: {}","No Content"); return new Response<>(0, noContent, null); } } }
package com.wanxin.repayment.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.wanxin.api.depository.model.UserAutoPreTransactionRequest; import com.wanxin.api.repayment.model.EqualInterestRepayment; import com.wanxin.api.repayment.model.RepaymentDetailRequest; import com.wanxin.api.repayment.model.RepaymentPlanDTO; import com.wanxin.api.repayment.model.RepaymentRequest; import com.wanxin.api.transaction.model.ProjectDTO; import com.wanxin.api.transaction.model.ProjectWithTendersDTO; import com.wanxin.api.transaction.model.TenderDTO; import com.wanxin.common.domain.*; import com.wanxin.common.util.CodeNoUtil; import com.wanxin.common.util.DateUtil; import com.wanxin.repayment.agent.DepositoryAgentApiAgent; import com.wanxin.repayment.entity.ReceivableDetail; import com.wanxin.repayment.entity.ReceivablePlan; import com.wanxin.repayment.entity.RepaymentDetail; import com.wanxin.repayment.entity.RepaymentPlan; import com.wanxin.repayment.mapper.ReceivableDetailMapper; import com.wanxin.repayment.mapper.ReceivablePlanMapper; import com.wanxin.repayment.mapper.RepaymentDetailMapper; import com.wanxin.repayment.mapper.RepaymentPlanMapper; import com.wanxin.repayment.message.RepaymentProducer; import com.wanxin.repayment.utils.RepaymentUtil; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ @Service public class RepaymentServiceImpl implements RepaymentService { @Autowired private RepaymentPlanMapper planMapper; @Autowired private ReceivablePlanMapper receivablePlanMapper; @Autowired private RepaymentDetailMapper repaymentDetailMapper; @Autowired private ReceivableDetailMapper receivableDetailMapper; @Autowired private DepositoryAgentApiAgent depositoryAgentApiAgent; @Autowired private RepaymentProducer repaymentProducer; @Override public void invokeConfirmRepayment(RepaymentPlan repaymentPlan, RepaymentRequest repaymentRequest) { RestResponse<String> repaymentResponse = depositoryAgentApiAgent.confirmRepayment(repaymentRequest); if (!DepositoryReturnCode.RETURN_CODE_00000.getCode().equals(repaymentResponse.getResult())) { throw new RuntimeException("还款失败"); } } @Override public void executeRepayment(String date) { // 查询所有到期的还款计划 List<RepaymentPlanDTO> repaymentPlanList = selectDueRepayment(date); repaymentPlanList.forEach(repaymentPlanDTO -> { RepaymentPlan repaymentPlan = convertDto2Entity(repaymentPlanDTO); // 生成还款明细(未同步) RepaymentDetail repaymentDetail = saveRepaymentDetail(repaymentPlan); // 还款预处理 String preRequestNo = repaymentDetail.getRequestNo(); Boolean preRepaymentResult = preRepayment(repaymentPlan, preRequestNo); if (preRepaymentResult) { // 构造还款信息请求数据 RepaymentRequest repaymentRequest = generateRepaymentRequest(repaymentPlan, preRequestNo); // 发送确认还款事务消息 repaymentProducer.confirmRepayment(repaymentPlan, repaymentRequest); } }); } /** * 构造还款信息请求数据 * * @param repaymentPlan * @param preRequestNo * @return */ private RepaymentRequest generateRepaymentRequest(RepaymentPlan repaymentPlan, String preRequestNo) { // 根据还款计划id, 获取应收计划 final List<ReceivablePlan> receivablePlanList = receivablePlanMapper.selectList(Wrappers.<ReceivablePlan>lambdaQuery().eq(ReceivablePlan::getRepaymentId, repaymentPlan.getId())); // 封装请求数据 RepaymentRequest repaymentRequest = new RepaymentRequest(); // 还款总额 repaymentRequest.setAmount(repaymentPlan.getAmount()); // 业务实体id repaymentRequest.setId(repaymentPlan.getId()); // 向借款人收取的佣金 repaymentRequest.setCommission(repaymentPlan.getCommission()); // 标的编码 repaymentRequest.setProjectNo(repaymentPlan.getProjectNo()); // 请求流水号 repaymentRequest.setRequestNo(CodeNoUtil.getNo(CodePrefixCode.CODE_REQUEST_PREFIX)); // 预处理业务流水号 repaymentRequest.setPreRequestNo(preRequestNo); // 放款明细 List<RepaymentDetailRequest> detailRequests = new ArrayList<>(); receivablePlanList.forEach(receivablePlan -> { RepaymentDetailRequest detailRequest = new RepaymentDetailRequest(); // 投资人用户编码 detailRequest.setUserNo(receivablePlan.getUserNo()); // 向投资人收取的佣金 detailRequest.setCommission(receivablePlan.getCommission()); // 派息 - 无 // 投资人应得本金 detailRequest.setAmount(receivablePlan.getPrincipal()); // 投资人应得利息 detailRequest.setInterest(receivablePlan.getInterest()); // 添加到集合 detailRequests.add(detailRequest); }); // 还款明细请求信息 repaymentRequest.setDetails(detailRequests); return repaymentRequest; } private RepaymentPlan convertDto2Entity(RepaymentPlanDTO repaymentPlanDTO) { if (repaymentPlanDTO == null) { return null; } RepaymentPlan repaymentPlan = new RepaymentPlan(); BeanUtils.copyProperties(repaymentPlan, repaymentPlanDTO); return repaymentPlan; } @Override @Transactional(rollbackFor = Exception.class) public Boolean confirmRepayment(RepaymentPlan repaymentPlan, RepaymentRequest repaymentRequest) { // 更新还款明细: 已同步 String preRequestNo = repaymentRequest.getPreRequestNo(); repaymentDetailMapper.update(null, Wrappers.<RepaymentDetail>lambdaUpdate().set(RepaymentDetail::getStatus, StatusCode.STATUS_IN.getCode()).eq(RepaymentDetail::getRequestNo, preRequestNo)); // 更新receivable_plan表为: 已收 // 根据还款计划id, 查询应收计划 List<ReceivablePlan> rereceivablePlanList = receivablePlanMapper.selectList(Wrappers.<ReceivablePlan>lambdaQuery().eq(ReceivablePlan::getRepaymentId, repaymentPlan.getId())); rereceivablePlanList.forEach(receivablePlan -> { receivablePlan.setReceivableStatus(1); receivablePlanMapper.updateById(receivablePlan); // 保存数据到receivable_detail // 构造应收明细 ReceivableDetail receivableDetail = new ReceivableDetail(); // 应收项标识 receivableDetail.setReceivableId(receivablePlan.getId()); // 实收本息 receivableDetail.setAmount(receivablePlan.getAmount()); // 实收时间 receivableDetail.setReceivableDate(DateUtil.now()); // 保存投资人应收明细 receivableDetailMapper.insert(receivableDetail); }); // 更新还款计划:已还款 repaymentPlan.setRepaymentStatus("1"); int rows = planMapper.updateById(repaymentPlan); return rows > 0; } @Override public Boolean preRepayment(RepaymentPlan repaymentPlan, String preRequestNo) { // 构造请求数据 final UserAutoPreTransactionRequest userAutoPreTransactionRequest = generateUserAutoPreTransactionRequest(repaymentPlan, preRequestNo); // 请求存管代理服务 final RestResponse<String> restResponse = depositoryAgentApiAgent.userAutoPreTransaction(userAutoPreTransactionRequest); // 返回结果 return DepositoryReturnCode.RETURN_CODE_00000.getCode().equals(restResponse.getResult()); } /** * 构造存管代理服务预处理请求数据 * * @param repaymentPlan * @param preRequestNo * @return */ private UserAutoPreTransactionRequest generateUserAutoPreTransactionRequest(RepaymentPlan repaymentPlan, String preRequestNo) { // 构造请求数据 UserAutoPreTransactionRequest userAutoPreTransactionRequest = new UserAutoPreTransactionRequest(); // 冻结金额 userAutoPreTransactionRequest.setAmount(repaymentPlan.getAmount()); // 预处理业务类型 userAutoPreTransactionRequest.setBizType(PreprocessBusinessTypeCode.REPAYMENT.getCode()); // 标的号 userAutoPreTransactionRequest.setProjectNo(repaymentPlan.getProjectNo()); // 请求流水号 userAutoPreTransactionRequest.setRequestNo(preRequestNo); // 标的用户编码 userAutoPreTransactionRequest.setUserNo(repaymentPlan.getUserNo()); // 关联业务实体标识 userAutoPreTransactionRequest.setId(repaymentPlan.getId()); // 返回结果 return userAutoPreTransactionRequest; } @Override public RepaymentDetail saveRepaymentDetail(RepaymentPlan repaymentPlan) { RepaymentDetail repaymentDetail = repaymentDetailMapper.selectOne(new LambdaQueryWrapper<RepaymentDetail>().eq(RepaymentDetail::getRepaymentPlanId, repaymentPlan.getId())); if (repaymentDetail == null) { repaymentDetail = new RepaymentDetail(); // 还款计划项标识 repaymentDetail.setRepaymentPlanId(repaymentPlan.getId()); // 实还本息 repaymentDetail.setAmount(repaymentPlan.getAmount()); // 实际还款时间 repaymentDetail.setRepaymentDate(LocalDateTime.now()); // 请求流水号 repaymentDetail.setRequestNo(CodeNoUtil.getNo(CodePrefixCode.CODE_REQUEST_PREFIX)); // 未同步 repaymentDetail.setStatus(StatusCode.STATUS_OUT.getCode()); // 保存数据 repaymentDetailMapper.insert(repaymentDetail); } return repaymentDetail; } @Override public List<RepaymentPlanDTO> selectDueRepayment(String date) { return convertEntityList2DtoList(planMapper.selectDueRepayment(date)); } private List<RepaymentPlanDTO> convertEntityList2DtoList(List<RepaymentPlan> repaymentPlanList) { if (repaymentPlanList == null) { return null; } List<RepaymentPlanDTO> repaymentPlanDTOList = new ArrayList<>(); repaymentPlanList.forEach(repaymentPlan -> { RepaymentPlanDTO repaymentPlanDTO = new RepaymentPlanDTO(); BeanUtils.copyProperties(repaymentPlan, repaymentPlanDTO); repaymentPlanDTOList.add(repaymentPlanDTO); }); return repaymentPlanDTOList; } @Override public String startRepayment(ProjectWithTendersDTO projectWithTendersDTO) { // 生成借款人还款计划 // 获取标的信息 ProjectDTO projectDTO = projectWithTendersDTO.getProject(); // 获取投标信息 List<TenderDTO> tenders = projectWithTendersDTO.getTenders(); // 计算还款的月数 double ceil = Math.ceil(projectDTO.getPeriod() / 30.0); int month = (int) ceil; // 还款方式, 只针对等额本息 String repaymentWay = projectDTO.getRepaymentWay(); if (repaymentWay.equals(RepaymentWayCode.FIXED_REPAYMENT)) { // 生成还款计划 EqualInterestRepayment fixedRepayment = RepaymentUtil.fixedRepayment(projectDTO.getAmount(), projectDTO.getBorrowerAnnualRate(), month, projectDTO.getCommissionAnnualRate()); // 保存还款计划 List<RepaymentPlan> planList = saveRepaymentPlan(projectDTO, fixedRepayment); // 生成投资人应收明细 // 根据投标信息生成应收明细 tenders.forEach(tender -> { // 当前投标人的收款明细 final EqualInterestRepayment receipt = RepaymentUtil.fixedRepayment(tender.getAmount(), tender.getProjectAnnualRate(), month, projectWithTendersDTO.getCommissionInvestorAnnualRate()); // 由于投标人的收款明细需要还款信息,所有遍历还款计划, 把还款期数与投资人应收期数对应上 planList.forEach(plan -> { // 保存应收明细到数据库 saveReceivablePlan(plan, tender, receipt); }); }); } else { return "-1"; } return DepositoryReturnCode.RETURN_CODE_00000.getCode(); } /** * 保存还款计划到数据库 * * @param projectDTO * @param fixedRepayment * @return */ private List<RepaymentPlan> saveRepaymentPlan(ProjectDTO projectDTO, EqualInterestRepayment fixedRepayment) { List<RepaymentPlan> repaymentPlanList = new ArrayList<>(); // 获取每期利息 final Map<Integer, BigDecimal> interestMap = fixedRepayment.getInterestMap(); // 平台收取利息 final Map<Integer, BigDecimal> commissionMap = fixedRepayment.getCommissionMap(); // 获取每期本金 fixedRepayment.getPrincipalMap().forEach((k, v) -> { // 还款计划封装数据 final RepaymentPlan repaymentPlan = new RepaymentPlan(); // 标的id repaymentPlan.setProjectId(projectDTO.getId()); // 发标人用户标识 repaymentPlan.setConsumerId(projectDTO.getConsumerId()); // 发标人用户编码 repaymentPlan.setUserNo(projectDTO.getUserNo()); // 标的编码 repaymentPlan.setProjectNo(projectDTO.getProjectNo()); // 期数 repaymentPlan.setNumberOfPeriods(k); // 当期还款利息 repaymentPlan.setInterest(interestMap.get(k)); // 还款本金 repaymentPlan.setPrincipal(v); // 本息 = 本金 + 利息 repaymentPlan.setAmount(repaymentPlan.getPrincipal().add(repaymentPlan.getInterest())); // 应还时间 = 当前时间 + 期数( 单位月 ) repaymentPlan.setShouldRepaymentDate(DateUtil.localDateTimeAddMonth(DateUtil.now(), k)); // 应还状态, 当前业务为待还 repaymentPlan.setRepaymentStatus("0"); // 计划创建时间 repaymentPlan.setCreateDate(DateUtil.now()); // 设置平台佣金( 借款人让利 ) 注意这个地方是 具体佣金 repaymentPlan.setCommission(commissionMap.get(k)); // 保存到数据库 planMapper.insert(repaymentPlan); repaymentPlanList.add(repaymentPlan); }); return repaymentPlanList; } /** * 保存应收明细到数据库 * * @param repaymentPlan * @param tender * @param receipt */ private void saveReceivablePlan(RepaymentPlan repaymentPlan, TenderDTO tender, EqualInterestRepayment receipt) { // 应收本金 final Map<Integer, BigDecimal> principalMap = receipt.getPrincipalMap(); // 应收利息 final Map<Integer, BigDecimal> interestMap = receipt.getInterestMap(); // 平台收取利息 final Map<Integer, BigDecimal> commissionMap = receipt.getCommissionMap(); // 封装投资人应收明细 ReceivablePlan receivablePlan = new ReceivablePlan(); // 投标信息标识 receivablePlan.setTenderId(tender.getId()); // 设置期数 receivablePlan.setNumberOfPeriods(repaymentPlan.getNumberOfPeriods()); // 投标人用户标识 receivablePlan.setConsumerId(tender.getConsumerId()); // 投标人用户编码 receivablePlan.setUserNo(tender.getUserNo()); // 还款计划项标识 receivablePlan.setRepaymentId(repaymentPlan.getId()); // 应收利息 receivablePlan.setInterest(interestMap.get(repaymentPlan.getNumberOfPeriods())); // 应收本金 receivablePlan.setPrincipal(principalMap.get(repaymentPlan.getNumberOfPeriods())); // 应收本息 = 应收本金 + 应收利息 receivablePlan.setAmount(receivablePlan.getInterest().add(receivablePlan.getPrincipal())); // 应收时间 receivablePlan.setShouldReceivableDate(repaymentPlan.getShouldRepaymentDate()); // 应收状态, 当前业务为未收 receivablePlan.setReceivableStatus(0); // 创建时间 receivablePlan.setCreateDate(DateUtil.now()); // 设置投资人让利, 注意这个地方是具体: 佣金 receivablePlan.setCommission(commissionMap.get(repaymentPlan.getNumberOfPeriods())); // 保存 receivablePlanMapper.insert(receivablePlan); } }
package com.wanxin.transaction.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.wanxin.api.consumer.model.ConsumerDTO; import com.wanxin.api.depository.model.LoanDetailRequest; import com.wanxin.api.depository.model.LoanRequest; import com.wanxin.api.depository.model.UserAutoPreTransactionRequest; import com.wanxin.api.transaction.model.*; import com.wanxin.common.domain.*; import com.wanxin.common.util.CodeNoUtil; import com.wanxin.common.util.CommonUtil; import com.wanxin.transaction.agent.ConsumerApiAgent; import com.wanxin.transaction.agent.ContentSearchApiAgent; import com.wanxin.transaction.agent.DepositoryAgentApiAgent; import com.wanxin.transaction.common.constant.TradingCode; import com.wanxin.transaction.common.constant.TransactionErrorCode; import com.wanxin.transaction.common.utils.IncomeCalcUtil; import com.wanxin.transaction.entity.Project; import com.wanxin.transaction.entity.Tender; import com.wanxin.transaction.mapper.ProjectMapper; import com.wanxin.transaction.mapper.TenderMapper; import com.wanxin.transaction.message.TransactionProducer; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; /** * @author yuelimin * @version 1.0.0 * @since 1.8 */ @Slf4j @Service public class ProjectServiceImpl implements ProjectService { @Autowired private ConfigService configService; @Autowired private ConsumerApiAgent consumerApiAgent; @Autowired private ProjectMapper projectMapper; @Autowired private DepositoryAgentApiAgent depositoryAgentApiAgent; @Autowired private ContentSearchApiAgent contentSearchApiAgent; @Autowired private TenderMapper tenderMapper; @Autowired private TransactionProducer transactionProducer; @Override @Transactional(rollbackFor = BusinessException.class) public Boolean updateProjectStatusAndStartRepayment(Project project) { project.setProjectStatus(ProjectCode.REPAYING.getCode()); return projectMapper.updateById(project) == 1; } @Override @Transactional(rollbackFor = Exception.class) public String loansApprovalStatus(Long id, String approveStatus, String commission) { if ("3".equals(approveStatus)) { Project project = new Project(); project.setId(id); project.setProjectStatus(ProjectCode.MISCARRY.getCode()); projectMapper.updateById(project); } else if ("4".equals(approveStatus)) { // 第一阶段: 生成放款明细 // 获取标的信息 final Project project = projectMapper.selectById(id); // 构造查询参数, 获取所有投标信息 final List<Tender> tenderList = tenderMapper.selectList(new LambdaQueryWrapper<Tender>().eq(Tender::getProjectId, id)); // 生成还款明细 final LoanRequest loanRequest = generateLoanRequest(project, tenderList, commission); // 第二阶段: 放款 // 请求存管代理服务 final RestResponse<String> restResponse = depositoryAgentApiAgent.confirmLoan(loanRequest); if (DepositoryReturnCode.RETURN_CODE_00000.getCode().equals(restResponse.getResult())) { // 响应成功, 更新投标信息: 已放款 updateTenderStatusAlreadyLoan(tenderList); // 第三阶段: 修改标的业务状态 // 调用存管代理服务,修改状态为还款中 // 构造请求参数 ModifyProjectStatusDTO modifyProjectStatusDTO = new ModifyProjectStatusDTO(); // 业务实体id modifyProjectStatusDTO.setId(project.getId()); // 业务状态 modifyProjectStatusDTO.setProjectStatus(ProjectCode.REPAYING.getCode()); // 请求流水号 modifyProjectStatusDTO.setRequestNo(loanRequest.getRequestNo()); // 执行请求 final RestResponse<String> modifyProjectProjectStatus = depositoryAgentApiAgent.modifyProjectStatus(modifyProjectStatusDTO); if (DepositoryReturnCode.RETURN_CODE_00000.getCode().equals(modifyProjectProjectStatus.getResult())) { // 如果处理成功, 就修改标的状态为还款中 project.setProjectStatus(ProjectCode.REPAYING.getCode()); projectMapper.updateById(project); // 第四阶段: 启动还款 // 封装调用还款服务请求对象的数据 ProjectWithTendersDTO projectWithTendersDTO = new ProjectWithTendersDTO(); // 封装标的信息 projectWithTendersDTO.setProject(convertProjectEntityToDTO(project)); // 封装投标信息 projectWithTendersDTO.setTenders(convertTenderEntityListToDTOList(tenderList)); // 封装投资人让利 projectWithTendersDTO.setCommissionInvestorAnnualRate(configService.getCommissionInvestorAnnualRate()); // 封装借款人让利 projectWithTendersDTO.setCommissionBorrowerAnnualRate(configService.getCommissionBorrowerAnnualRate()); transactionProducer.updateProjectStatusAndStartRepayment(project, projectWithTendersDTO); // 调用还款服务, 启动还款(生成还款计划, 应收明细) return "审核成功"; } else { log.warn("审核满标放款失败-标的ID为: {}, 存管代理服务返回的状态为-{}", project.getId(), restResponse.getResult()); throw new BusinessException(TransactionErrorCode.E_150113); } } else { log.warn("审核满标放款失败-标的ID为: {}, 存管代理服务返回的状态为-{}", project.getId(), restResponse.getResult()); throw new BusinessException(TransactionErrorCode.E_150113); } } return "审核拒绝"; } /** * 根据标的及投标信息生成放款明细 * * @param project * @param tenderList * @param commission * @return */ public LoanRequest generateLoanRequest(Project project, List<Tender> tenderList, String commission) { LoanRequest loanRequest = new LoanRequest(); // 设置标的id loanRequest.setId(project.getId()); // 设置平台佣金 if (StringUtils.isNotBlank(commission)) { loanRequest.setCommission(new BigDecimal(commission)); } // 设置标的编码 loanRequest.setProjectNo(project.getProjectNo()); // 设置请求流水号(标的不没有需要生成新的) loanRequest.setRequestNo(CodeNoUtil.getNo(CodePrefixCode.CODE_REQUEST_PREFIX)); // 处理放款明细 List<LoanDetailRequest> details = new ArrayList<>(); tenderList.forEach(tender -> { final LoanDetailRequest loanDetailRequest = new LoanDetailRequest(); // 设置放款金额 loanDetailRequest.setAmount(tender.getAmount()); // 设置预处理业务流水号 loanDetailRequest.setPreRequestNo(tender.getRequestNo()); details.add(loanDetailRequest); }); // 设置放款明细 loanRequest.setDetails(details); // 返回封装好的数据 return loanRequest; } /** * 更新投标信息: 已放款 * * @param tenderList */ private void updateTenderStatusAlreadyLoan(List<Tender> tenderList) { tenderList.forEach(tender -> { // 设置状态为已放款 tender.setTenderStatus(TradingCode.LOAN.getCode()); // 更新数据库 tenderMapper.updateById(tender); }); } private List<TenderDTO> convertTenderEntityListToDTOList(List<Tender> records) { if (records == null) { return null; } List<TenderDTO> dtoList = new ArrayList<>(); records.forEach(tender -> { TenderDTO tenderDTO = new TenderDTO(); BeanUtils.copyProperties(tender, tenderDTO); dtoList.add(tenderDTO); }); return dtoList; } @Override public TenderDTO createTender(ProjectInvestDTO projectInvestDTO) { // 获得投标金额 BigDecimal amount = new BigDecimal(projectInvestDTO.getAmount()); // 获得最小投标金额 BigDecimal miniInvestmentAmount = configService.getMiniInvestmentAmount(); if (amount.compareTo(miniInvestmentAmount) < 0) { throw new BusinessException(TransactionErrorCode.E_150109); } // 通过手机号查询用户信息 RestResponse<ConsumerDTO> restResponse = consumerApiAgent.getCurrentLoginConsumer(); // 通过用户编号查询账户余额 BigDecimal myBalance = consumerApiAgent.getBalance(restResponse.getResult().getUserNo()).getResult().getBalance(); if (myBalance.compareTo(amount) < 0) { throw new BusinessException(TransactionErrorCode.E_150112); } Project project = projectMapper.selectById(projectInvestDTO.getId()); if ("FULLY".equalsIgnoreCase(project.getProjectStatus())) { throw new BusinessException(TransactionErrorCode.E_150114); } // 判断投标金额是否超过剩余未投金额 BigDecimal remainingAmount = getProjectRemainingAmount(project); if (amount.compareTo(remainingAmount) < 1) { // 判断此次投标后的剩余未投金额是否满足最小投标金额 // 例如:借款人需要借1万 现在已经投标了8千 还剩2千 本次投标1950元 // 公式:此次投标后的剩余未投金额 = 目前剩余未投金额 - 本次投标金额 BigDecimal subtract = remainingAmount.subtract(amount); int result = subtract.compareTo(configService.getMiniInvestmentAmount()); if (result < 0) { throw new BusinessException(TransactionErrorCode.E_150111); } // 保存投标信息并发送给存管代理服务 // 封装投标信息 Tender tender = new Tender(); // 投资人投标金额( 投标冻结金额 ) tender.setAmount(amount); // 投标人用户标识 tender.setConsumerId(restResponse.getResult().getId()); tender.setConsumerUsername(restResponse.getResult().getUsername()); // 投标人用户编码 tender.setUserNo(restResponse.getResult().getUserNo()); // 标的标识 tender.setProjectId(projectInvestDTO.getId()); // 标的编码 tender.setProjectNo(project.getProjectNo()); // 投标状态 tender.setTenderStatus(TradingCode.FROZEN.getCode()); // 创建时间 tender.setCreateDate(new Date()); // 请求流水号 tender.setRequestNo(CodeNoUtil.getNo(CodePrefixCode.CODE_REQUEST_PREFIX)); // 可用状态 tender.setStatus(0); tender.setProjectName(project.getName()); // 标的期限(单位:天) tender.setProjectPeriod(project.getPeriod()); // 年化利率(投资人视图) tender.setProjectAnnualRate(project.getAnnualRate()); // 保存到数据库 tenderMapper.insert(tender); // 发送数据给存管代理服务 // 构造请求数据 UserAutoPreTransactionRequest userAutoPreTransactionRequest = new UserAutoPreTransactionRequest(); // 冻结金额 userAutoPreTransactionRequest.setAmount(amount); // 预处理业务类型 userAutoPreTransactionRequest.setBizType(PreprocessBusinessTypeCode.TENDER.getCode()); // 标的号 userAutoPreTransactionRequest.setProjectNo(project.getProjectNo()); // 请求流水号 userAutoPreTransactionRequest.setRequestNo(tender.getRequestNo()); // 投资人用户编码 userAutoPreTransactionRequest.setUserNo(restResponse.getResult().getUserNo()); // 设置关联业务实体标识 userAutoPreTransactionRequest.setId(tender.getId()); // 远程调用存管代理服务 RestResponse<String> response = depositoryAgentApiAgent.userAutoPreTransaction(userAutoPreTransactionRequest); // 根据结果更新投标状态 if (DepositoryReturnCode.RETURN_CODE_00000.getCode().equals(response.getResult())) { // 修改状态为: 已发布 tender.setStatus(1); tenderMapper.updateById(tender); // 投标成功后判断标的是否已投满, 如果满标, 更新标的状态 BigDecimal remainAmount = getProjectRemainingAmount(project); if (remainAmount.compareTo(new BigDecimal(0)) == 0) { project.setProjectStatus(ProjectCode.FULLY.getCode()); projectMapper.updateById(project); } // 转换为dto对象并封装数据 TenderDTO tenderDTO = convertTenderEntityToDTO(tender); // 封装标的信息 project.setRepaymentWay(RepaymentWayCode.FIXED_REPAYMENT.getDesc()); tenderDTO.setProject(convertProjectEntityToDTO(project)); // 封装预期收益 // 根据标的期限计算还款月数 Double ceil = Math.ceil(project.getPeriod() / 30.0); Integer month = ceil.intValue(); // 计算预期收益 tenderDTO.setExpectedIncome(IncomeCalcUtil.getIncomeTotalInterest(new BigDecimal(projectInvestDTO.getAmount()), configService.getAnnualRate(), month)); return tenderDTO; } else { log.warn("投标失败-标的ID: {}-存管代理服务返回的状态为-{}", projectInvestDTO.getId(), restResponse.getResult()); throw new BusinessException(TransactionErrorCode.E_150113); } } else { throw new BusinessException(TransactionErrorCode.E_150110); } } private TenderDTO convertTenderEntityToDTO(Tender tender) { if (tender == null) { return null; } TenderDTO tenderDTO = new TenderDTO(); BeanUtils.copyProperties(tender, tenderDTO); return tenderDTO; } @Override public List<TenderOverviewDTO> queryTendersByProjectId(Long id) { List<Tender> tenderList = tenderMapper.selectList(new LambdaQueryWrapper<Tender>().eq(Tender::getProjectId, id)); List<TenderOverviewDTO> tenderOverviewDTOList = new ArrayList<>(); tenderList.forEach(tender -> { TenderOverviewDTO tenderOverviewDTO = new TenderOverviewDTO(); BeanUtils.copyProperties(tender, tenderOverviewDTO); tenderOverviewDTO.setConsumerUsername(CommonUtil.hiddenMobile(tenderOverviewDTO.getConsumerUsername())); tenderOverviewDTOList.add(tenderOverviewDTO); }); return tenderOverviewDTOList; } @Override public List<ProjectDTO> queryProjectsIds(String ids) { // 构件查询对象 LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>(); // 获取id列表集合 List<Long> list = new ArrayList<Long>(); Arrays.asList(ids.split(",")).forEach(id -> { list.add(Long.parseLong(id)); }); // 查询 List<Project> projects = projectMapper.selectList(queryWrapper.in(Project::getId, list)); List<ProjectDTO> projectDTOList = new ArrayList<>(); projects.forEach(project -> { ProjectDTO projectDTO = convertProjectEntityToDTO(project); projectDTO.setRemainingAmount(getProjectRemainingAmount(project)); projectDTO.setTenderCount(tenderMapper.selectCount(new LambdaQueryWrapper<Tender>().eq(Tender::getProjectId, project.getId()))); }); return projectDTOList; } private BigDecimal getProjectRemainingAmount(Project project) { // 根据标的id在投标表查询已投金额 List<BigDecimal> decimalList = tenderMapper.selectAmountInvestedByProjectId(project.getId()); // 求和结果集 BigDecimal amountInvested = new BigDecimal("0.0"); for (BigDecimal d : decimalList) { amountInvested = amountInvested.add(d); } // 得到剩余额度 return project.getAmount().subtract(amountInvested); } @Override public PageVO<ProjectDTO> queryProjects(ProjectQueryDTO projectQueryDTO, String order, Integer pageNo, Integer pageSize, String sortBy) { RestResponse<PageVO<ProjectDTO>> esResponse = contentSearchApiAgent.queryProjectIndex(projectQueryDTO, pageNo, pageSize, sortBy, order); if (!esResponse.isSuccessful()) { throw new BusinessException(CommonErrorCode.UNKOWN); } return esResponse.getResult(); } @Override public String projectsApprovalStatus(Long id, String approveStatus) { // 根据id查询标的信息并转换为DTO对象 Project project = projectMapper.selectById(id); ProjectDTO projectDTO = convertProjectEntityToDTO(project); // 生成流水号(不存在才生成) if (project.getRequestNo() == null) { projectDTO.setRequestNo(CodeNoUtil.getNo(CodePrefixCode.CODE_REQUEST_PREFIX)); // 根据结果修改状态 Project pro = new Project(); pro.setId(project.getId()); pro.setRequestNo(projectDTO.getRequestNo()); pro.setModifyDate(new Date()); projectMapper.updateById(pro); } // 通过feign远程访问存管代理服务, 把标的信息传输过去 RestResponse<String> restResponse = depositoryAgentApiAgent.createProject(projectDTO); if (DepositoryReturnCode.RETURN_CODE_00000.getCode().equals(restResponse.getResult())) { int status = Integer.parseInt(approveStatus); // 根据结果修改状态 Project pro = new Project(); if (status == 2) { pro.setProjectStatus(ProjectCode.FULLY.getCode()); } if (status == 4) { pro.setProjectStatus(ProjectCode.MISCARRY.getCode()); } pro.setId(project.getId()); pro.setStatus(1); pro.setModifyDate(new Date()); projectMapper.updateById(pro); return "success"; } throw new BusinessException(TransactionErrorCode.E_150113); } @Override public PageVO<ProjectDTO> queryProjectsByQueryDTO(ProjectQueryDTO projectQueryDTO, Integer pageNo, Integer pageSize) { LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>(); if (projectQueryDTO != null) { // 标的类型 if (projectQueryDTO.getType() != null) { queryWrapper.eq(Project::getType, projectQueryDTO.getType()); } // 起止年化利率(投资人) -- 区间 if (projectQueryDTO.getStartAnnualRate() != null) { queryWrapper.ge(Project::getAnnualRate, projectQueryDTO.getStartAnnualRate()); } if (projectQueryDTO.getEndAnnualRate() != null) { queryWrapper.le(Project::getAnnualRate, projectQueryDTO.getStartAnnualRate()); } // 借款期限 -- 区间 if (projectQueryDTO.getStartPeriod() != null) { queryWrapper.ge(Project::getPeriod, projectQueryDTO.getStartPeriod()); } if (projectQueryDTO.getEndPeriod() != null) { queryWrapper.le(Project::getPeriod, projectQueryDTO.getEndPeriod()); } // 标的状态 if (projectQueryDTO.getProjectStatus() != null) { queryWrapper.eq(Project::getProjectStatus, projectQueryDTO.getProjectStatus()); } // 标的可用状态 if (projectQueryDTO.getStatus() != null) { queryWrapper.eq(Project::getStatus, projectQueryDTO.getStatus()); } } // 排序 queryWrapper.orderByDesc(Project::getCreateDate); // 执行查询 IPage<Project> iPage = projectMapper.selectPage(new Page<Project>(pageNo, pageSize), queryWrapper); // 封装结果 List<ProjectDTO> projectDTOList = convertProjectEntityListToDTOList(iPage.getRecords()); return new PageVO<>(projectDTOList, iPage.getTotal(), pageNo, pageSize); } private List<ProjectDTO> convertProjectEntityListToDTOList(List<Project> projectList) { if (projectList == null) { return null; } List<ProjectDTO> dtoList = new ArrayList<>(); projectList.forEach(project -> { ProjectDTO projectDTO = new ProjectDTO(); BeanUtils.copyProperties(project, projectDTO); dtoList.add(projectDTO); }); return dtoList; } @Override @Transactional(rollbackFor = Exception.class) public ProjectDTO createProject(ProjectDTO projectDTO) { RestResponse<ConsumerDTO> consumer = consumerApiAgent.getCurrentLoginConsumer(); // 设置用户编码 projectDTO.setUserNo(consumer.getResult().getUserNo()); // 设置用户id projectDTO.setConsumerId(consumer.getResult().getId()); // 生成标的编码 projectDTO.setProjectNo(CodeNoUtil.getNo(CodePrefixCode.CODE_PROJECT_PREFIX)); // 标的状态修改 projectDTO.setProjectStatus(ProjectCode.COLLECTING.getCode()); // 标的可用状态修改, 未同步 projectDTO.setStatus(StatusCode.STATUS_OUT.getCode()); // 设置标的创建时间 projectDTO.setCreateDate(new Date()); // 设置还款方式 projectDTO.setRepaymentWay(RepaymentWayCode.FIXED_REPAYMENT.getCode()); // 设置标的类型 projectDTO.setType("NEW"); Project project = convertProjectDTOToEntity(projectDTO); project.setBorrowerAnnualRate(configService.getBorrowerAnnualRate()); project.setAnnualRate(configService.getAnnualRate()); // 年化利率(平台佣金, 利差) project.setCommissionAnnualRate(configService.getCommissionAnnualRate()); // 债权转让 project.setIsAssignment(0); // 判断男女 String sex = Integer.parseInt(consumer.getResult().getIdNumber().substring(16, 17)) % 2 == 0 ? "女士" : "先生"; // 构造借款次数查询条件 LambdaQueryWrapper<Project> eq = new LambdaQueryWrapper<Project>().eq(Project::getConsumerId, consumer.getResult().getId()); // 设置标的名字, 姓名 + 性别 + 第N次借款 project.setName(consumer.getResult().getFullname() + sex + "第" + (projectMapper.selectCount(eq) + 1) + "次借款"); projectMapper.insert(project); projectDTO.setId(project.getId()); projectDTO.setName(project.getName()); return projectDTO; } @Override public Integer queryQualifications() { // 判断是否绑定银行卡 ConsumerDTO result = consumerApiAgent.getCurrentLoginConsumer().getResult(); if (!result.getIsBindCard().equals(1)) { return 0; } // 判断是否以发标 Integer count = projectMapper.selectCount(new LambdaQueryWrapper<Project>().eq(Project::getConsumerId, result.getId()).eq(Project::getStatus, 0)); if (!count.equals(0)) { return 0; } return 1; } private Project convertProjectDTOToEntity(ProjectDTO projectDTO) { if (projectDTO == null) { return null; } Project project = new Project(); BeanUtils.copyProperties(projectDTO, project); return project; } private ProjectDTO convertProjectEntityToDTO(Project project) { if (project == null) { return null; } ProjectDTO projectDTO = new ProjectDTO(); BeanUtils.copyProperties(project, projectDTO); return projectDTO; } }
package com.youlai.mall.pms.service.impl; import cn.hutool.core.bean.BeanUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.youlai.common.constant.GlobalConstants; import com.youlai.mall.pms.pojo.entity.PmsCategory; import com.youlai.mall.pms.mapper.PmsCategoryMapper; import com.youlai.mall.pms.pojo.vo.CascadeVO; import com.youlai.mall.pms.service.IPmsCategoryService; import com.youlai.mall.pms.pojo.vo.CategoryVO; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * 商品分类 * * @author haoxr */ @Service public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryMapper, PmsCategory> implements IPmsCategoryService { /** * 分类列表(树形) * * @param parentId * @return * @Cacheable value:缓存名称(分区);key:缓存键 */ @Cacheable(value = "pms", key = "'categoryList'") @Override public List<CategoryVO> listCategory(Long parentId) { List<PmsCategory> categoryList = this.list(new LambdaQueryWrapper<PmsCategory>() .eq(PmsCategory::getVisible, GlobalConstants.STATUS_YES).orderByDesc(PmsCategory::getSort)); List<CategoryVO> list = recursionTree(parentId != null ? parentId : 0l, categoryList); return list; } private static List<CategoryVO> recursionTree(Long parentId, List<PmsCategory> categoryList) { List<CategoryVO> list = new ArrayList<>(); Optional.ofNullable(categoryList) .ifPresent(categories -> categories.stream().filter(category -> category.getParentId().equals(parentId)) .forEach(category -> { CategoryVO categoryVO = new CategoryVO(); BeanUtil.copyProperties(category, categoryVO); List<CategoryVO> children = recursionTree(category.getId(), categoryList); categoryVO.setChildren(children); list.add(categoryVO); })); return list; } /** * 分类列表(级联) * * @return */ @Override public List<CascadeVO> listCascadeCategory() { List<PmsCategory> categoryList = this.list( new LambdaQueryWrapper<PmsCategory>() .eq(PmsCategory::getVisible, GlobalConstants.STATUS_YES) .orderByAsc(PmsCategory::getSort) ); List<CascadeVO> list = recursionCascade(0l, categoryList); return list; } private List<CascadeVO> recursionCascade(Long parentId, List<PmsCategory> categoryList) { List<CascadeVO> list = new ArrayList<>(); Optional.ofNullable(categoryList) .ifPresent(categories -> categories.stream().filter(category -> category.getParentId().equals(parentId)) .forEach(category -> { CascadeVO categoryVO = new CascadeVO() .setLabel(category.getName()) .setValue(category.getId()); BeanUtil.copyProperties(category, categoryVO); List<CascadeVO> children = recursionCascade(category.getId(), categoryList); categoryVO.setChildren(children); list.add(categoryVO); }) ); return list; } /** * 新增/修改分类 * * @param category * @return 分类ID * @CacheEvict 缓存失效 */ @CacheEvict(value = "pms", key = "'categoryList'") @Override public Long saveCategory(PmsCategory category) { this.saveOrUpdate(category); return category.getId(); } }
package com.youlai.admin.service.impl; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.youlai.admin.common.constant.SystemConstants; import com.youlai.admin.mapper.SysDeptMapper; import com.youlai.admin.pojo.entity.SysDept; import com.youlai.admin.pojo.vo.DeptVO; import com.youlai.admin.pojo.vo.TreeSelectVO; import com.youlai.admin.service.ISysDeptService; import com.youlai.common.constant.GlobalConstants; import org.apache.logging.log4j.util.Strings; import org.springframework.stereotype.Service; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; /** * 部门业务类 * * @author <a href="mailto:xianrui0365@163.com">xianrui</a> * @date 2021-08-22 */ @Service public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService { /** * 部门表格(Table)层级列表 * * @param name 部门名称 * @return */ @Override public List<DeptVO> listTable(Integer status, String name) { List<SysDept> deptList = this.list( new LambdaQueryWrapper<SysDept>() .like(StrUtil.isNotBlank(name), SysDept::getName, name) .orderByAsc(SysDept::getSort) ); return recursion(deptList); } /** * 递归生成部门表格层级列表 * * @param deptList 部门列表 * @return 部门列表 */ private static List<DeptVO> recursion(List<SysDept> deptList) { List<DeptVO> deptTableList = new ArrayList<>(); // 保存所有节点的 id Set<Long> nodeIdSet = deptList.stream() .map(SysDept::getId) .collect(Collectors.toSet()); for (SysDept sysDept : deptList) { // 不在节点 id 集合中存在的 id 即为顶级节点 id, 递归生成列表 Long parentId = sysDept.getParentId(); if (!nodeIdSet.contains(parentId)) { deptTableList.addAll(recursionTableList(parentId, deptList)); nodeIdSet.add(parentId); } } // 如果结果列表为空说明所有的节点都是独立分散的, 直接转换后返回 if (deptTableList.isEmpty()) { return deptList.stream() .map(item -> { DeptVO deptVO = new DeptVO(); BeanUtil.copyProperties(item, deptVO); return deptVO; }) .collect(Collectors.toList()); } return deptTableList; } /** * 递归生成部门表格层级列表 * * @param parentId * @param deptList * @return */ public static List<DeptVO> recursionTableList(Long parentId, List<SysDept> deptList) { List<DeptVO> deptTableList = new ArrayList<>(); Optional.ofNullable(deptList).orElse(new ArrayList<>()) .stream() .filter(dept -> dept.getParentId().equals(parentId)) .forEach(dept -> { DeptVO deptVO = new DeptVO(); BeanUtil.copyProperties(dept, deptVO); List<DeptVO> children = recursionTableList(dept.getId(), deptList); deptVO.setChildren(children); deptTableList.add(deptVO); }); return deptTableList; } /** * 部门下拉(Select)层级列表 * * @return */ @Override public List<TreeSelectVO> listTreeSelect() { List<SysDept> deptList = this.list(new LambdaQueryWrapper<SysDept>() .eq(SysDept::getStatus, GlobalConstants.STATUS_YES) .orderByAsc(SysDept::getSort) ); List<TreeSelectVO> deptSelectList = recursionTreeSelectList(SystemConstants.ROOT_DEPT_ID, deptList); return deptSelectList; } /** * 递归生成部门表格层级列表 * * @param parentId * @param deptList * @return */ public static List<TreeSelectVO> recursionTreeSelectList(long parentId, List<SysDept> deptList) { List<TreeSelectVO> deptTreeSelectList = new ArrayList<>(); Optional.ofNullable(deptList).orElse(new ArrayList<>()) .stream() .filter(dept -> dept.getParentId().equals(parentId)) .forEach(dept -> { TreeSelectVO treeSelectVO = new TreeSelectVO(dept.getId(), dept.getName()); List<TreeSelectVO> children = recursionTreeSelectList(dept.getId(), deptList); if (CollectionUtil.isNotEmpty(children)) { treeSelectVO.setChildren(children); } deptTreeSelectList.add(treeSelectVO); }); return deptTreeSelectList; } /** * 保存(新增/修改)部门 * * @param dept * @return */ @Override public Long saveDept(SysDept dept) { String treePath = getDeptTreePath(dept); dept.setTreePath(treePath); this.saveOrUpdate(dept); return dept.getId(); } /** * 删除部门 * * @param ids 部门ID,多个以英文逗号,拼接字符串 * @return */ @Override public boolean deleteByIds(String ids) { AtomicBoolean result = new AtomicBoolean(true); List<String> idList = Arrays.asList(ids.split(",")); // 删除部门及子部门 Optional.ofNullable(idList).orElse(new ArrayList<>()).forEach(id -> result.set(this.remove(new LambdaQueryWrapper<SysDept>() .eq(SysDept::getId, id) .or() .apply("concat (',',tree_path,',') like concat('%,',{0},',%')", id))) ); return result.get(); } /** * 获取部门级联路径 * * @param dept * @return */ private String getDeptTreePath(SysDept dept) { Long parentId = dept.getParentId(); String treePath; if (parentId.equals(SystemConstants.ROOT_DEPT_ID)) { treePath = String.valueOf(SystemConstants.ROOT_DEPT_ID); } else { SysDept parentDept = this.getById(parentId); treePath = Optional.ofNullable(parentDept).map(item -> item.getTreePath() + "," + item.getId()).orElse(Strings.EMPTY); } return treePath; } }
package com.youlai.admin.service.impl; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.youlai.admin.common.constant.SystemConstants; import com.youlai.admin.pojo.entity.SysMenu; import com.youlai.admin.pojo.vo.*; import com.youlai.admin.mapper.SysMenuMapper; import com.youlai.admin.service.ISysMenuService; import com.youlai.admin.service.ISysPermissionService; import com.youlai.common.constant.GlobalConstants; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.*; import java.util.stream.Collectors; /** * 菜单业务类 * * @author <a href="mailto:xianrui0365@163.com">xianrui</a> * @date 2020-11-06 */ @Service @RequiredArgsConstructor public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService { private final ISysPermissionService permissionService; /** * 菜单表格(Table)层级列表 * * @param name 菜单名称 * @return */ @Override public List<MenuVO> listTable(String name) { List<SysMenu> menuList = this.list( new LambdaQueryWrapper<SysMenu>() .like(StrUtil.isNotBlank(name), SysMenu::getName, name) .orderByAsc(SysMenu::getSort) ); return recursion(menuList); } /** * 递归生成菜单表格层级列表 * * @param menuList 菜单列表 * @return 菜单列表 */ private static List<MenuVO> recursion(List<SysMenu> menuList) { List<MenuVO> menuTableList = new ArrayList<>(); // 保存所有节点的 id Set<Long> nodeIdSet = menuList.stream() .map(SysMenu::getId) .collect(Collectors.toSet()); for (SysMenu sysMenu : menuList) { // 不在节点 id 集合中存在的 id 即为顶级节点 id, 递归生成列表 Long parentId = sysMenu.getParentId(); if (!nodeIdSet.contains(parentId)) { menuTableList.addAll(recursionTableList(parentId, menuList)); nodeIdSet.add(parentId); } } // 如果结果列表为空说明所有的节点都是独立分散的, 直接转换后返回 if (menuTableList.isEmpty()) { return menuList.stream() .map(item -> { MenuVO menuVO = new MenuVO(); BeanUtil.copyProperties(item, menuVO); return menuVO; }) .collect(Collectors.toList()); } return menuTableList; } /** * 递归生成菜单表格层级列表 * * @param parentId 父级ID * @param menuList 菜单列表 * @return */ private static List<MenuVO> recursionTableList(Long parentId, List<SysMenu> menuList) { List<MenuVO> menuTableList = new ArrayList<>(); Optional.ofNullable(menuList).orElse(new ArrayList<>()) .stream() .filter(menu -> menu.getParentId().equals(parentId)) .forEach(menu -> { MenuVO menuVO = new MenuVO(); BeanUtil.copyProperties(menu, menuVO); List<MenuVO> children = recursionTableList(menu.getId(), menuList); if (CollectionUtil.isNotEmpty(children)) { menuVO.setChildren(children); } menuTableList.add(menuVO); }); return menuTableList; } /** * 菜单下拉(Select)层级列表 * * @return */ @Override public List<SelectVO> listSelect() { List<SysMenu> menuList = this.list(new LambdaQueryWrapper<SysMenu>().orderByAsc(SysMenu::getSort)); List<SelectVO> menuSelectList = recursionSelectList(SystemConstants.ROOT_MENU_ID, menuList); return menuSelectList; } /** * 递归生成菜单下拉层级列表 * * @param parentId 父级ID * @param menuList 菜单列表 * @return */ private static List<SelectVO> recursionSelectList(Long parentId, List<SysMenu> menuList) { List<SelectVO> menuSelectList = new ArrayList<>(); Optional.ofNullable(menuList).orElse(new ArrayList<>()) .stream() .filter(menu -> menu.getParentId().equals(parentId)) .forEach(menu -> { SelectVO selectVO = new SelectVO(menu.getId(), menu.getName()); List<SelectVO> children = recursionSelectList(menu.getId(), menuList); if (CollectionUtil.isNotEmpty(children)) { selectVO.setChildren(children); } menuSelectList.add(selectVO); }); return menuSelectList; } /** * 菜单路由(Route)层级列表 * <p> * 读多写少,缓存至Redis * * @return * @Cacheable cacheNames:缓存名称,不同缓存的数据是彼此隔离; key: 缓存Key。 */ @Override @Cacheable(cacheNames = "system", key = "'routeList'") public List<RouteVO> listRoute() { List<SysMenu> menuList = this.baseMapper.listRoute(); List<RouteVO> list = recursionRoute(SystemConstants.ROOT_MENU_ID, menuList); return list; } /** * 递归生成菜单路由层级列表 * * @param parentId 父级ID * @param menuList 菜单列表 * @return */ private List<RouteVO> recursionRoute(Long parentId, List<SysMenu> menuList) { List<RouteVO> list = new ArrayList<>(); Optional.ofNullable(menuList).ifPresent(menus -> menus.stream().filter(menu -> menu.getParentId().equals(parentId)) .forEach(menu -> { RouteVO routeVO = new RouteVO(); routeVO.setName(menu.getId() + ""); // 根据name路由跳转 this.$router.push({path:xxx}) routeVO.setPath(menu.getPath()); // 根据path路由跳转 this.$router.push({name:xxx}) routeVO.setRedirect(menu.getRedirect()); routeVO.setComponent(menu.getComponent()); routeVO.setRedirect(menu.getRedirect()); RouteVO.Meta meta = new RouteVO.Meta(menu.getName(), menu.getIcon(), menu.getRoles()); routeVO.setMeta(meta); // 菜单显示隐藏 routeVO.setHidden(!GlobalConstants.STATUS_YES.equals(menu.getVisible())); List<RouteVO> children = recursionRoute(menu.getId(), menuList); routeVO.setChildren(children); if (CollectionUtil.isNotEmpty(children)) { routeVO.setAlwaysShow(Boolean.TRUE); } list.add(routeVO); })); return list; } /** * 菜单下拉(TreeSelect)层级列表 * * @return */ @Override public List<TreeSelectVO> listTreeSelect() { List<SysMenu> menuList = this.list(new LambdaQueryWrapper<SysMenu>().orderByAsc(SysMenu::getSort)); List<TreeSelectVO> menuSelectList = recursionTreeSelectList(SystemConstants.ROOT_MENU_ID, menuList); return menuSelectList; } /** * 新增菜单 * * @param menu * @return */ @Override public boolean saveMenu(SysMenu menu) { String component = menu.getComponent(); if ("Layout".equals(component)) { menu.setPath("/" + IdUtil.simpleUUID()); } else { menu.setPath(component.replaceAll("/", "_")); } boolean result = this.save(menu); if (result == true) { permissionService.refreshPermRolesRules(); } return result; } /** * 修改菜单 * * @param menu * @return */ @Override public boolean updateMenu(SysMenu menu) { String component = menu.getComponent(); // 检测页面路径是否变化 SysMenu oldMenu = this.getById(menu.getId()); if (oldMenu.getComponent() != null && !oldMenu.getComponent().equals(component)) { if ("Layout".equals(component)) { menu.setPath("/" + IdUtil.simpleUUID()); } else { menu.setPath(component.replaceAll("/", "_")); } } boolean result = this.updateById(menu); if (result == true) { permissionService.refreshPermRolesRules(); } return result; } /** * 递归生成菜单下拉(TreeSelect)层级列表 * * @param parentId 父级ID * @param menuList 菜单列表 * @return */ private static List<TreeSelectVO> recursionTreeSelectList(Long parentId, List<SysMenu> menuList) { List<TreeSelectVO> menuSelectList = new ArrayList<>(); Optional.ofNullable(menuList).orElse(new ArrayList<>()) .stream() .filter(menu -> menu.getParentId().equals(parentId)) .forEach(menu -> { TreeSelectVO treeSelectVO = new TreeSelectVO(menu.getId(), menu.getName()); List<TreeSelectVO> children = recursionTreeSelectList(menu.getId(), menuList); if (CollectionUtil.isNotEmpty(children)) { treeSelectVO.setChildren(children); } menuSelectList.add(treeSelectVO); }); return menuSelectList; } /** * 清理路由缓存 */ @Override @CacheEvict(cacheNames = "system", key = "'routeList'") public void cleanCache() { } /** * 获取路由列表(适配Vue3的vue-next-router) * * @return */ @Override @Cacheable(cacheNames = "system", key = "'nextRouteList'") public List<NextRouteVO> listNextRoutes() { List<SysMenu> menuList = this.baseMapper.listRoute(); List<NextRouteVO> list = recursionNextRoute(SystemConstants.ROOT_MENU_ID, menuList); return list; } /** * 递归生成菜单路由层级列表 * * @param parentId 父级ID * @param menuList 菜单列表 * @return */ private List<NextRouteVO> recursionNextRoute(Long parentId, List<SysMenu> menuList) { List<NextRouteVO> list = new ArrayList<>(); Optional.ofNullable(menuList).ifPresent(menus -> menus.stream().filter(menu -> menu.getParentId().equals(parentId)) .forEach(menu -> { NextRouteVO nextRouteVO = new NextRouteVO(); nextRouteVO.setName(menu.getId() + ""); // 根据name路由跳转 this.$router.push({path:xxx}) nextRouteVO.setPath(menu.getPath()); // 根据path路由跳转 this.$router.push({name:xxx}) nextRouteVO.setRedirect(menu.getRedirect()); nextRouteVO.setComponent(menu.getComponent()); nextRouteVO.setRedirect(menu.getRedirect()); NextRouteVO.Meta meta = new NextRouteVO.Meta(); meta.setTitle(menu.getName()); meta.setIcon(menu.getIcon()); meta.setRoles(menu.getRoles()); meta.setHidden(!GlobalConstants.STATUS_YES.equals(menu.getVisible())); nextRouteVO.setMeta(meta); List<NextRouteVO> children = recursionNextRoute(menu.getId(), menuList); nextRouteVO.setChildren(children); if (CollectionUtil.isNotEmpty(children)) { meta.setAlwaysShow(Boolean.TRUE); } list.add(nextRouteVO); })); return list; } }
package com.gpmall.order.services;/** * Created by mic on 2019/7/30. */ import com.gpmall.order.OrderCoreService; import com.gpmall.order.biz.TransOutboundInvoker; import com.gpmall.order.biz.context.AbsTransHandlerContext; import com.gpmall.order.biz.factory.OrderProcessPipelineFactory; import com.gpmall.order.constant.OrderRetCode; import com.gpmall.order.constants.OrderConstants; import com.gpmall.order.dal.entitys.Order; import com.gpmall.order.dal.persistence.OrderItemMapper; import com.gpmall.order.dal.persistence.OrderMapper; import com.gpmall.order.dal.persistence.OrderShippingMapper; import com.gpmall.order.dto.*; import com.gpmall.order.utils.ExceptionProcessorUtils; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import tk.mybatis.mapper.entity.Example; import java.util.Date; /** * 腾讯课堂搜索【咕泡学院】 * 官网:www.gupaoedu.com * 风骚的Mic 老师 * create-date: 2019/7/30-上午10:05 */ @Slf4j @Service(cluster = "failfast") public class OrderCoreServiceImpl implements OrderCoreService { @Autowired OrderMapper orderMapper; @Autowired OrderItemMapper orderItemMapper; @Autowired OrderShippingMapper orderShippingMapper; @Autowired OrderProcessPipelineFactory orderProcessPipelineFactory; @Autowired OrderCoreService orderCoreService; /** * 创建订单的处理流程 * * @param request * @return */ @Override public CreateOrderResponse createOrder(CreateOrderRequest request) { CreateOrderResponse response = new CreateOrderResponse(); try { TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request); invoker.start(); //启动流程(pipeline来处理) AbsTransHandlerContext context = invoker.getContext(); response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context); } catch (Exception e) { log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e); ExceptionProcessorUtils.wrapperHandlerException(response, e); } return response; } /** * 取消订单 * * @param request * @return */ @Override public CancelOrderResponse cancelOrder(CancelOrderRequest request) { CancelOrderResponse response = new CancelOrderResponse(); try { Order order = new Order(); order.setOrderId(request.getOrderId()); order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL); order.setCloseTime(new Date()); int num = orderMapper.updateByPrimaryKey(order); log.info("cancelOrder,effect Row:" + num); response.setCode(OrderRetCode.SUCCESS.getCode()); response.setMsg(OrderRetCode.SUCCESS.getMessage()); } catch (Exception e) { log.error("OrderCoreServiceImpl.cancelOrder Occur Exception :" + e); ExceptionProcessorUtils.wrapperHandlerException(response, e); } return response; } /** * 删除订单 * * @param request * @return */ @Override public DeleteOrderResponse deleteOrder(DeleteOrderRequest request) { DeleteOrderResponse response = new DeleteOrderResponse(); try { request.requestCheck(); deleteOrderWithTransaction(request); response.setCode(OrderRetCode.SUCCESS.getCode()); response.setMsg(OrderRetCode.SUCCESS.getMessage()); } catch (Exception e) { log.error("OrderCoreServiceImpl.deleteOrder Occur Exception :" + e); ExceptionProcessorUtils.wrapperHandlerException(response, e); } return response; } @Override public void updateOrder(Integer status, String orderId) { Order order = new Order(); order.setOrderId(orderId); order.setStatus(status); orderMapper.updateByPrimaryKey(order); } @Transactional(rollbackFor = Exception.class) @Override public void deleteOrderWithTransaction(DeleteOrderRequest request){ orderMapper.deleteByPrimaryKey(request.getOrderId()); Example example = new Example(Order.class); example.createCriteria().andEqualTo("orderId",request.getOrderId()); orderItemMapper.deleteByExample(example); orderShippingMapper.deleteByPrimaryKey(request.getOrderId()); } }
package com.gpmall.order.services; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.gpmall.order.OrderQueryService; import com.gpmall.order.constant.OrderRetCode; import com.gpmall.order.converter.OrderConverter; import com.gpmall.order.dal.entitys.*; import com.gpmall.order.dal.persistence.OrderItemMapper; import com.gpmall.order.dal.persistence.OrderMapper; import com.gpmall.order.dal.persistence.OrderShippingMapper; import com.gpmall.order.dto.*; import com.gpmall.order.utils.ExceptionProcessorUtils; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.config.annotation.Service; import org.springframework.beans.factory.annotation.Autowired; import tk.mybatis.mapper.entity.Example; import java.util.ArrayList; import java.util.List; /** * 腾讯课堂搜索【咕泡学院】 * 官网:www.gupaoedu.com * 风骚的Mic 老师 * create-date: 2019/7/30-上午10:04 */ @Slf4j @Service public class OrderQueryServiceImpl implements OrderQueryService{ @Autowired OrderMapper orderMapper; @Autowired OrderItemMapper orderItemMapper; @Autowired OrderShippingMapper orderShippingMapper; @Autowired OrderConverter orderConverter; @Override public OrderCountResponse orderCount(OrderCountRequest request) { OrderCountResponse response=new OrderCountResponse(); try { Long count = orderMapper.countAll(); response.setCount(count.intValue()); response.setCode(OrderRetCode.SUCCESS.getCode()); response.setMsg(OrderRetCode.SUCCESS.getMessage()); }catch (Exception e){ log.error("OrderQueryServiceImpl.orderCount occur Exception :" +e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } /** * 查询历史订单列表 * @param request * @return * @author GP17513-成都-Rigel */ @Override public OrderListResponse orderList(OrderListRequest request) { OrderListResponse response = new OrderListResponse(); try{ request.requestCheck(); response.setCode(OrderRetCode.SUCCESS.getCode()); response.setMsg(OrderRetCode.SUCCESS.getMessage()); PageHelper.startPage(request.getPage(),request.getSize()); Example example = new Example(Order.class); example.createCriteria().andEqualTo("userId",request.getUserId()); List<Order> orderList = orderMapper.selectByExample(example); if(CollectionUtils.isEmpty(orderList)){ response.setTotal(0L); response.setDetailInfoList(new ArrayList<>()); return response; } List<OrderDetailInfo> infos = new ArrayList<>(); PageInfo<Order> pageInfo=new PageInfo<>(orderList); response.setTotal(pageInfo.getTotal()); orderList.forEach( order -> { OrderDetailInfo info = orderConverter.order2detail(order); List<OrderItem> list = orderItemMapper.queryByOrderId(order.getOrderId()); // OrderItemExample itemExample=new OrderItemExample(); // itemExample.createCriteria().andOrderIdEqualTo(order.getOrderId()); // List<OrderItem> list=orderItemMapper.selectByExample(itemExample); OrderShipping orderShipping=orderShippingMapper.selectByPrimaryKey(order.getOrderId()); info.setOrderItemDto(orderConverter.item2dto(list)); info.setOrderShippingDto(orderConverter.shipping2dto(orderShipping)); infos.add(info); }); response.setDetailInfoList(infos); }catch (Exception e){ log.info("OrderQueryServiceImpl.orderList occur Exception: {}" , e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } /** * 查询订单明细 * @param request * @return */ @Override public OrderDetailResponse orderDetail(OrderDetailRequest request) { OrderDetailResponse response=new OrderDetailResponse(); try{ request.requestCheck(); Order order=orderMapper.selectByPrimaryKey(request.getOrderId()); // OrderItemExample example=new OrderItemExample(); // OrderItemExample.Criteria criteria=example.createCriteria(); // criteria.andOrderIdEqualTo(order.getOrderId()); // List<OrderItem> list=orderItemMapper.selectByExample(example); List<OrderItem> list = orderItemMapper.queryByOrderId(order.getOrderId()); OrderShipping orderShipping=orderShippingMapper.selectByPrimaryKey(order.getOrderId()); response=orderConverter.order2res(order); response.setOrderItemDto(orderConverter.item2dto(list)); response.setOrderShippingDto(orderConverter.shipping2dto(orderShipping)); response.setCode(OrderRetCode.SUCCESS.getCode()); response.setMsg(OrderRetCode.SUCCESS.getMessage()); return response; }catch (Exception e){ log.error("OrderQueryServiceImpl.orderDetail occur Exception :" +e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } @Override public OrderItemResponse orderItem(OrderItemRequest request) { OrderItemResponse response = new OrderItemResponse(); try { request.requestCheck(); OrderItem orderItem = orderItemMapper.selectByPrimaryKey(request.getOrderItemId()); response = orderConverter.item2res(orderItem); Order order = orderMapper.selectByPrimaryKey(orderItem.getOrderId()); response.setOrderDto(orderConverter.order2dto(order)); response.setCode(OrderRetCode.SUCCESS.getCode()); response.setMsg(OrderRetCode.SUCCESS.getMessage()); } catch (Exception e){ log.error("OrderQueryServiceImpl.orderItem occur Exception :" +e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } }
package com.gpmall.shopping.services; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.gpmall.shopping.ICartService; import com.gpmall.shopping.constant.GlobalConstants; import com.gpmall.shopping.constants.ShoppingRetCode; import com.gpmall.shopping.converter.CartItemConverter; import com.gpmall.shopping.dal.entitys.Item; import com.gpmall.shopping.dal.persistence.ItemMapper; import com.gpmall.shopping.dto.*; import com.gpmall.shopping.utils.ExceptionProcessorUtils; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.Service; import org.redisson.api.RMap; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 腾讯课堂搜索【咕泡学院】 * 官网:www.gupaoedu.com * 风骚的Mic 老师 * create-date: 2019/7/23-19:02 * * 购物车的信息,统一采用缓存存储 */ @Slf4j @Service public class CartServiceImpl implements ICartService { @Autowired RedissonClient redissonClient; @Autowired ItemMapper itemMapper; /** * 根据用户id获得购物车中的商品列表 * @param request * @return */ @Override public CartListByIdResponse getCartListById(CartListByIdRequest request) { CartListByIdResponse response=new CartListByIdResponse(); List<CartProductDto> productDtos=new ArrayList<>(); response.setCode(ShoppingRetCode.SUCCESS.getCode()); response.setMsg(ShoppingRetCode.SUCCESS.getMessage()); try{ Map<Object,Object> items=redissonClient.getMap(generatorCartItemKey(request.getUserId())); items.values().forEach(obj ->{ CartProductDto cartProductDto= JSONObject.parseObject(obj.toString(),CartProductDto.class); productDtos.add(cartProductDto); }); response.setCartProductDtos(productDtos); }catch (Exception e){ log.error("CartServiceImpl.getCartListById Occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } @Override public AddCartResponse addToCart(AddCartRequest request) { AddCartResponse response=new AddCartResponse(); response.setCode(ShoppingRetCode.SUCCESS.getCode()); response.setMsg(ShoppingRetCode.SUCCESS.getMessage()); try{ request.requestCheck(); boolean exists=redissonClient.getMap(generatorCartItemKey(request.getUserId())).containsKey(request.getItemId()); if(exists){ String cartItemJson=redissonClient.getMap(generatorCartItemKey(request.getUserId())).get(request.getItemId()).toString(); CartProductDto cartProductDto=JSON.parseObject(cartItemJson,CartProductDto.class); cartProductDto.setProductNum(cartProductDto.getProductNum().longValue()+request.getNum().longValue()); redissonClient.getMap(generatorCartItemKey(request.getUserId())).put(request.getItemId(),JSON.toJSON(cartProductDto).toString()); return response; } Item item=itemMapper.selectByPrimaryKey(request.getItemId().longValue()); if(item!=null){ CartProductDto cartProductDto=CartItemConverter.item2Dto(item); cartProductDto.setChecked("true"); cartProductDto.setProductNum(request.getNum().longValue()); redissonClient.getMap(generatorCartItemKey(request.getUserId())).put(request.getItemId(),JSON.toJSON(cartProductDto).toString()); return response; } response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode()); response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage()); }catch (Exception e){ log.error("CartServiceImpl.addToCart Occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } @Override public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) { UpdateCartNumResponse response=new UpdateCartNumResponse(); response.setCode(ShoppingRetCode.SUCCESS.getCode()); response.setMsg(ShoppingRetCode.SUCCESS.getMessage()); try { RMap itemMap = redissonClient.getMap(generatorCartItemKey(request.getUserId())); Object item=itemMap.get(request.getItemId()); if (item!=null) { CartProductDto cartProductDto=JSON.parseObject(item.toString(),CartProductDto.class); cartProductDto.setChecked(request.getChecked()); cartProductDto.setProductNum(request.getNum().longValue()); itemMap.put(request.getItemId(),JSON.toJSON(cartProductDto)); } }catch (Exception e){ log.error("CartServiceImpl.updateCartNum Occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } @Override public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) { CheckAllItemResponse response=new CheckAllItemResponse(); try{ RMap items=redissonClient.getMap(generatorCartItemKey(request.getUserId())); items.values().forEach(obj ->{ CartProductDto cartProductDto=(CartProductDto)obj; cartProductDto.setChecked(request.getChecked());//true / false items.put(cartProductDto.getProductId(),cartProductDto); }); response.setCode(ShoppingRetCode.SUCCESS.getCode()); response.setMsg(ShoppingRetCode.SUCCESS.getMessage()); }catch (Exception e){ log.error("CartServiceImpl.checkAllCartItem Occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } @Override public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) { DeleteCartItemResponse response=new DeleteCartItemResponse(); try{ RMap rMap=redissonClient.getMap(generatorCartItemKey(request.getUserId())); rMap.remove(request.getItemId()); response.setCode(ShoppingRetCode.SUCCESS.getCode()); response.setMsg(ShoppingRetCode.SUCCESS.getMessage()); }catch (Exception e){ log.error("CartServiceImpl.deleteCartItem Occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } @Override public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) { DeleteCheckedItemResposne response=new DeleteCheckedItemResposne(); try { RMap itemMap = redissonClient.getMap(generatorCartItemKey(request.getUserId())); itemMap.values().forEach(obj -> { CartProductDto cartProductDto = JSON.parseObject(obj.toString(), CartProductDto.class); if ("true".equals(cartProductDto.getChecked())) { itemMap.remove(cartProductDto.getProductId()); } }); response.setCode(ShoppingRetCode.SUCCESS.getCode()); response.setMsg(ShoppingRetCode.SUCCESS.getMessage()); }catch (Exception e){ log.error("CartServiceImpl.deleteCheckedItem Occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } @Override public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) { ClearCartItemResponse response=new ClearCartItemResponse(); try{ RMap itemMap = redissonClient.getMap(generatorCartItemKey(request.getUserId())); itemMap.values().forEach(obj -> { CartProductDto cartProductDto = JSON.parseObject(obj.toString(), CartProductDto.class); if(request.getProductIds().contains(cartProductDto.getProductId())){ itemMap.remove(cartProductDto.getProductId()); } }); response.setCode(ShoppingRetCode.SUCCESS.getCode()); response.setMsg(ShoppingRetCode.SUCCESS.getMessage()); }catch (Exception e){ log.error("CartServiceImpl.clearCartItemByUserID Occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } private String generatorCartItemKey(long userId){ StringBuilder sb=new StringBuilder(GlobalConstants.CART_ITEM_CACHE_PREFIX); sb.append(":").append(userId); return sb.toString(); } }
package com.gpmall.shopping.services; import com.gpmall.shopping.IContentService; import com.gpmall.shopping.constant.GlobalConstants; import com.gpmall.shopping.constants.ShoppingRetCode; import com.gpmall.shopping.converter.ContentConverter; import com.gpmall.shopping.dal.entitys.PanelContent; import com.gpmall.shopping.dal.persistence.PanelContentMapper; import com.gpmall.shopping.dto.NavListResponse; import com.gpmall.shopping.utils.ExceptionProcessorUtils; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.Service; import org.springframework.beans.factory.annotation.Autowired; import tk.mybatis.mapper.entity.Example; import java.util.List; /** * 腾讯课堂搜索【咕泡学院】 * 官网:www.gupaoedu.com * 风骚的Mic 老师 * create-date: 2019/7/23-16:23 */ @Slf4j @Service public class ContentServiceImpl implements IContentService { @Autowired PanelContentMapper panelContentMapper; @Autowired ContentConverter contentConverter; @Override public NavListResponse queryNavList() { NavListResponse response=new NavListResponse(); try { Example exampleContent = new Example(PanelContent.class); exampleContent.setOrderByClause("sort_order"); Example.Criteria criteriaContent = exampleContent.createCriteria(); criteriaContent.andEqualTo("panelId", GlobalConstants.HEADER_PANEL_ID); List<PanelContent> pannelContents = panelContentMapper.selectByExample(exampleContent); //添加缓存操作 TODO response.setPannelContentDtos(contentConverter.panelContents2Dto(pannelContents)); response.setCode(ShoppingRetCode.SUCCESS.getCode()); response.setMsg(ShoppingRetCode.SUCCESS.getMessage()); }catch (Exception e){ log.error("ContentServiceImpl.queryNavList Occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } }
package com.gpmall.user.services; import com.gpmall.user.IAddressService; import com.gpmall.user.constants.SysRetCodeConstants; import com.gpmall.user.converter.AddressConverter; import com.gpmall.user.dal.entitys.Address; import com.gpmall.user.dal.persistence.AddressMapper; import com.gpmall.user.dto.*; import com.gpmall.user.utils.ExceptionProcessorUtils; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.Service; import org.springframework.beans.factory.annotation.Autowired; import tk.mybatis.mapper.entity.Example; import java.util.List; /** * 腾讯课堂搜索【咕泡学院】 * 官网:www.gupaoedu.com * 风骚的Mic 老师 * create-date: 2019/7/31-19:27 */ @Slf4j @Service public class AddressServiceImpl implements IAddressService { @Autowired AddressMapper addressMapper; @Autowired AddressConverter converter; @Override public AddressListResponse addressList(AddressListRequest request) { //TODO 地址信息要做缓存处理 AddressListResponse response=new AddressListResponse(); try{ request.requestCheck(); Example example=new Example(Address.class); example.createCriteria().andEqualTo("userId",request.getUserId()); List<Address> addresses=addressMapper.selectByExample(example); response.setAddressDtos(converter.address2List(addresses)); response.setCode(SysRetCodeConstants.SUCCESS.getCode()); response.setMsg(SysRetCodeConstants.SUCCESS.getMessage()); }catch (Exception e){ log.error("AddressServiceImpl.addressList occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } @Override public AddressDetailResponse addressDetail(AddressDetailRequest request) { AddressDetailResponse response=new AddressDetailResponse(); try{ request.requestCheck(); Address address=addressMapper.selectByPrimaryKey(request.getAddressId()); response.setAddressDto(converter.address2List(address)); response.setCode(SysRetCodeConstants.SUCCESS.getCode()); response.setMsg(SysRetCodeConstants.SUCCESS.getMessage()); }catch (Exception e){ log.error("AddressServiceImpl.addressDetail occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } @Override public AddAddressResponse createAddress(AddAddressRequest request) { log.error("AddressServiceImpl.createAddress request :"+request); AddAddressResponse response=new AddAddressResponse(); try{ request.requestCheck(); checkAddressDefaultUnique(request.getIsDefault() != null && request.getIsDefault()==1,request.getUserId()); Address address=converter.req2Address(request); int row=addressMapper.insert(address); response.setCode(SysRetCodeConstants.SUCCESS.getCode()); response.setMsg(SysRetCodeConstants.SUCCESS.getMessage()); log.info("AddressServiceImpl.createAddress effect row :"+row); }catch (Exception e){ log.error("AddressServiceImpl.createAddress occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } @Override public UpdateAddressResponse updateAddress(UpdateAddressRequest request) { log.error("begin - AddressServiceImpl.updateAddress request :"+request); UpdateAddressResponse response=new UpdateAddressResponse(); try{ request.requestCheck(); checkAddressDefaultUnique(request.getIsDefault()==1,request.getUserId()); Address address=converter.req2Address(request); int row=addressMapper.updateByPrimaryKey(address); response.setMsg(SysRetCodeConstants.SUCCESS.getMessage()); response.setCode(SysRetCodeConstants.SUCCESS.getCode()); log.info("AddressServiceImpl.createAddress effect row :"+row); }catch (Exception e){ log.error("AddressServiceImpl.updateAddress occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } @Override public DeleteAddressResponse deleteAddress(DeleteAddressRequest request) { log.error("begin - AddressServiceImpl.deleteAddress request :"+request); DeleteAddressResponse response=new DeleteAddressResponse(); try{ request.requestCheck(); int row=addressMapper.deleteByPrimaryKey(request.getAddressId()); if(row>0){ response.setCode(SysRetCodeConstants.SUCCESS.getCode()); response.setMsg(SysRetCodeConstants.SUCCESS.getMessage()); }else{ response.setCode(SysRetCodeConstants.DATA_NOT_EXIST.getCode()); response.setMsg(SysRetCodeConstants.DATA_NOT_EXIST.getMessage()); } log.info("AddressServiceImpl.deleteAddress effect row :"+row); }catch (Exception e){ log.error("AddressServiceImpl.deleteAddress occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } //地址只能有一个默认 private void checkAddressDefaultUnique(boolean isDefault,Long userId){ if(isDefault){ Example example=new Example(Address.class); example.createCriteria().andEqualTo("userId",userId); List<Address> addresses=addressMapper.selectByExample(example); addresses.parallelStream().forEach(address->{ if(address.getIsDefault()==1){ address.setIsDefault(1); addressMapper.updateByPrimaryKey(address); } }); } } }
package com.gpmall.user.services;/** * Created by mic on 2019/7/30. */ import com.gpmall.user.IMemberService; import com.gpmall.user.IUserLoginService; import com.gpmall.user.constants.SysRetCodeConstants; import com.gpmall.user.converter.MemberConverter; import com.gpmall.user.dal.entitys.Member; import com.gpmall.user.dal.persistence.MemberMapper; import com.gpmall.user.dto.*; import com.gpmall.user.utils.ExceptionProcessorUtils; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.Service; import org.springframework.beans.factory.annotation.Autowired; /** * 腾讯课堂搜索【咕泡学院】 * 官网:www.gupaoedu.com * 风骚的Mic 老师 * create-date: 2019/7/30-下午11:51 */ @Slf4j @Service public class MemberServiceImpl implements IMemberService{ @Autowired MemberMapper memberMapper; @Autowired IUserLoginService userLoginService; @Autowired MemberConverter memberConverter; /** * 根据用户id查询用户会员信息 * @param request * @return */ @Override public QueryMemberResponse queryMemberById(QueryMemberRequest request) { QueryMemberResponse queryMemberResponse=new QueryMemberResponse(); try{ request.requestCheck(); Member member=memberMapper.selectByPrimaryKey(request.getUserId()); if(member==null){ queryMemberResponse.setCode(SysRetCodeConstants.DATA_NOT_EXIST.getCode()); queryMemberResponse.setMsg(SysRetCodeConstants.DATA_NOT_EXIST.getMessage()); } queryMemberResponse=memberConverter.member2Res(member); queryMemberResponse.setCode(SysRetCodeConstants.SUCCESS.getCode()); queryMemberResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage()); }catch (Exception e){ log.error("MemberServiceImpl.queryMemberById Occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(queryMemberResponse,e); } return queryMemberResponse; } @Override public HeadImageResponse updateHeadImage(HeadImageRequest request) { HeadImageResponse response=new HeadImageResponse(); //TODO return response; } @Override public UpdateMemberResponse updateMember(UpdateMemberRequest request) { UpdateMemberResponse response = new UpdateMemberResponse(); try{ request.requestCheck(); CheckAuthRequest checkAuthRequest = new CheckAuthRequest(); checkAuthRequest.setToken(request.getToken()); CheckAuthResponse authResponse = userLoginService.validToken(checkAuthRequest); if (!authResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) { response.setCode(authResponse.getCode()); response.setMsg(authResponse.getMsg()); return response; } Member member = memberConverter.updateReq2Member(request); int row = memberMapper.updateByPrimaryKeySelective(member); response.setMsg(SysRetCodeConstants.SUCCESS.getMessage()); response.setCode(SysRetCodeConstants.SUCCESS.getCode()); log.info("MemberServiceImpl.updateMember effect row :"+row); }catch (Exception e){ log.error("MemberServiceImpl.updateMember Occur Exception :"+e); ExceptionProcessorUtils.wrapperHandlerException(response,e); } return response; } }
package com.mall4j.cloud.multishop.service.impl; import com.mall4j.cloud.api.auth.dto.AuthAccountDTO; import com.mall4j.cloud.api.auth.bo.UserInfoInTokenBO; import com.mall4j.cloud.api.auth.feign.AccountFeignClient; import com.mall4j.cloud.api.auth.vo.AuthAccountVO; import com.mall4j.cloud.common.response.ServerResponseEntity; import com.mall4j.cloud.common.security.AuthUserContext; import com.mall4j.cloud.common.util.IpHelper; import com.mall4j.cloud.multishop.dto.ChangeAccountDTO; import com.mall4j.cloud.multishop.mapper.ShopUserMapper; import com.mall4j.cloud.multishop.model.ShopUser; import com.mall4j.cloud.multishop.service.ShopUserAccountService; import io.seata.spring.annotation.GlobalTransactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; /** * @author FrozenWatermelon * @date 2020/09/03 */ @Service public class ShopUserAccountServiceImpl implements ShopUserAccountService { @Resource private ShopUserMapper shopUserMapper; @Autowired private AccountFeignClient accountFeignClient; @Override @GlobalTransactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class) public ServerResponseEntity<Void> save(ChangeAccountDTO changeAccountDTO) { AuthAccountDTO authAccountDTO = getAuthAccountDTO(changeAccountDTO); authAccountDTO.setCreateIp(IpHelper.getIpAddr()); authAccountDTO.setIsAdmin(0); // 保存 ServerResponseEntity<Long> serverResponseEntity = accountFeignClient.save(authAccountDTO); if (!serverResponseEntity.isSuccess()) { return ServerResponseEntity.transform(serverResponseEntity); } ShopUser shopUser = new ShopUser(); shopUser.setShopUserId(changeAccountDTO.getUserId()); shopUser.setHasAccount(1); shopUser.setShopId(AuthUserContext.get().getTenantId()); shopUserMapper.update(shopUser); return ServerResponseEntity.success(); } @Override public ServerResponseEntity<Void> update(ChangeAccountDTO changeAccountDTO) { AuthAccountDTO authAccountDTO = getAuthAccountDTO(changeAccountDTO); // 更新,不涉及分布式事务 ServerResponseEntity<Void> serverResponseEntity = accountFeignClient.update(authAccountDTO); if (!serverResponseEntity.isSuccess()) { return serverResponseEntity; } return ServerResponseEntity.success(); } @Override public ServerResponseEntity<AuthAccountVO> getByUserIdAndSysType(Long userId, Integer sysType) { return accountFeignClient.getByUserIdAndSysType(userId,sysType); } private AuthAccountDTO getAuthAccountDTO(ChangeAccountDTO changeAccountDTO) { AuthAccountDTO authAccountDTO = new AuthAccountDTO(); UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get(); authAccountDTO.setPassword(changeAccountDTO.getPassword()); authAccountDTO.setUsername(changeAccountDTO.getUsername()); authAccountDTO.setStatus(changeAccountDTO.getStatus()); authAccountDTO.setSysType(userInfoInTokenBO.getSysType()); authAccountDTO.setTenantId(userInfoInTokenBO.getTenantId()); authAccountDTO.setUserId(changeAccountDTO.getUserId()); return authAccountDTO; } }
package com.mall4j.cloud.platform.service.impl; import com.mall4j.cloud.api.auth.dto.AuthAccountDTO; import com.mall4j.cloud.api.auth.bo.UserInfoInTokenBO; import com.mall4j.cloud.api.auth.feign.AccountFeignClient; import com.mall4j.cloud.api.auth.vo.AuthAccountVO; import com.mall4j.cloud.common.response.ServerResponseEntity; import com.mall4j.cloud.common.security.AuthUserContext; import com.mall4j.cloud.common.util.IpHelper; import com.mall4j.cloud.platform.dto.ChangeAccountDTO; import com.mall4j.cloud.platform.mapper.SysUserMapper; import com.mall4j.cloud.platform.model.SysUser; import com.mall4j.cloud.platform.service.SysUserAccountService; import io.seata.spring.annotation.GlobalTransactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; /** * @author lhd * @date 2020/12/22 */ @Service public class SysUserAccountServiceImpl implements SysUserAccountService { @Resource private SysUserMapper sysUserMapper; @Autowired private AccountFeignClient accountFeignClient; @Override @GlobalTransactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class) public ServerResponseEntity<Void> save(ChangeAccountDTO changeAccountDTO) { AuthAccountDTO authAccountDTO = getAuthAccountDTO(changeAccountDTO); authAccountDTO.setCreateIp(IpHelper.getIpAddr()); authAccountDTO.setIsAdmin(0); // 保存 ServerResponseEntity<Long> serverResponseEntity = accountFeignClient.save(authAccountDTO); if (!serverResponseEntity.isSuccess()) { return ServerResponseEntity.transform(serverResponseEntity); } SysUser sysUser = new SysUser(); sysUser.setSysUserId(changeAccountDTO.getUserId()); sysUser.setHasAccount(1); sysUserMapper.update(sysUser); return ServerResponseEntity.success(); } @Override public ServerResponseEntity<Void> update(ChangeAccountDTO changeAccountDTO) { AuthAccountDTO authAccountDTO = getAuthAccountDTO(changeAccountDTO); // 更新,不涉及分布式事务 ServerResponseEntity<Void> serverResponseEntity = accountFeignClient.update(authAccountDTO); if (!serverResponseEntity.isSuccess()) { return serverResponseEntity; } return ServerResponseEntity.success(); } @Override public ServerResponseEntity<AuthAccountVO> getByUserIdAndSysType(Long userId, Integer sysType) { return accountFeignClient.getByUserIdAndSysType(userId,sysType); } private AuthAccountDTO getAuthAccountDTO(ChangeAccountDTO changeAccountDTO) { AuthAccountDTO authAccountDTO = new AuthAccountDTO(); UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get(); authAccountDTO.setPassword(changeAccountDTO.getPassword()); authAccountDTO.setUsername(changeAccountDTO.getUsername()); authAccountDTO.setStatus(changeAccountDTO.getStatus()); authAccountDTO.setSysType(userInfoInTokenBO.getSysType()); authAccountDTO.setTenantId(userInfoInTokenBO.getTenantId()); authAccountDTO.setUserId(changeAccountDTO.getUserId()); return authAccountDTO; } }
package com.metamagic.ms.repository.read; import javax.jdo.PersistenceManager; import javax.jdo.Query; import org.springframework.stereotype.Repository; import com.metamagic.ms.entity.User; import com.metamagic.ms.exception.RepositoryException; import com.metamagic.ms.repository.GenericRepository; /** * @author sagar * * THIS REPOSITORY IMPLMENTATION IS FOR USER READ OPERAIONS */ @Repository public class UserReadRepositoryImpl extends GenericRepository<User> implements UserReadRepository { @Override public User findByUserId(String userId) throws RepositoryException { PersistenceManager pm = pm(); try { Query query = pm.newQuery(User.class); query.setFilter("userId == :userId"); query.setUnique(true); User user = (User) query.execute(userId); return user; } catch (Exception e) { throw new RepositoryException(e.getMessage()); } finally { pm.close(); } } }
package com.metamagic.ms.repository.read; import java.util.List; import javax.jdo.PersistenceManager; import javax.jdo.Query; import org.springframework.stereotype.Repository; import com.metamagic.ms.entity.Order; import com.metamagic.ms.entity.Order.Status; import com.metamagic.ms.exception.RepositoryException; import com.metamagic.ms.repository.GenericRepository; /** * @author sagar * * THIS REPOSITORY USED FOR READ ORDER OPERATION */ @Repository public class OrderReadRepositoryImpl extends GenericRepository<Order> implements OrderReadRepository { @Override public List<Order> findAll(String userId) throws RepositoryException { PersistenceManager pm = pm(); try { Query query = pm.newQuery(Order.class); query.setFilter("this.userId == :userId"); List<Order> orDocuments = (List<Order>) query.execute(userId); return orDocuments; } catch (Exception e) { throw new RepositoryException(e.getMessage()); } finally { pm.close(); } } @Override public Order findByUserIdAndStatus(String userId, Status status) throws RepositoryException { PersistenceManager pm = pm(); try { Query query = pm.newQuery(Order.class); query.setFilter("this.userId == :userId && this.status== :status"); query.setUnique(true); Order document = (Order) query.execute(userId, status); return pm.detachCopy(document); } catch (Exception e) { throw new RepositoryException(e.getMessage()); } finally { pm.close(); } } @Override public Order findByOrderId(String orderId) throws RepositoryException { PersistenceManager pm = pm(); try { Query query = pm.newQuery(Order.class); query.setFilter("this.orderId == :orderId"); query.setUnique(true); Order orderDocument = (Order) query.execute(orderId); return pm.detachCopy(orderDocument); } catch (Exception e) { throw new RepositoryException(e.getMessage()); } finally { pm.close(); } } }
package com.metamagic.ms.repo.read; import java.util.List; import javax.jdo.PersistenceManager; import javax.jdo.Query; import org.springframework.stereotype.Repository; import com.metamagic.ms.entity.Product; import com.metamagic.ms.exception.RepositoryException; import com.metamagic.ms.repo.GenericRepository; /** * @author sagar * * THIS REPOSITORY USED FOR READING PRODUCT */ @Repository public class ProductReadRepositoryImpl extends GenericRepository<Product> implements ProductReadRepository { /** * THIS METHOD IS USED FOR RETIEVD ALL PRODUCT * * @throws RepositoryException */ @SuppressWarnings("unchecked") public List<Product> findAll() throws RepositoryException { PersistenceManager pm = pm(); try { Query query = pm.newQuery(Product.class); List<Product> list = (List<Product>) query.execute(); List<Product> products = (List<Product>) pm.detachCopyAll(list); return products; } catch (Exception e) { throw new RepositoryException(e.getMessage()); } finally { pm.close(); } } }
package com.metamagic.ms.repository.read; import javax.jdo.PersistenceManager; import javax.jdo.Query; import org.springframework.stereotype.Repository; import com.metamagic.ms.entity.UserCart; import com.metamagic.ms.exception.RepositoryException; import com.metamagic.ms.repository.GenericRepository; /** * @author sagar * * THIS REPOSITORY CLASS IS USED FOR USER CART READ */ @Repository public class UserCartReadRepositoryImpl extends GenericRepository<UserCart> implements UserCartReadRepository { @Override public UserCart findByUserIdAndActive(String userId, String completed) throws RepositoryException { PersistenceManager pm = pm(); try { Query<UserCart> query = pm.newQuery(UserCart.class); query.setFilter("userId == :userId && status == :completed"); query.setUnique(true); UserCart userCart = (UserCart) pm.detachCopy(query.execute(userId, completed)); return userCart; } catch (Exception e) { throw new RepositoryException(e.getMessage()); } finally { pm.close(); } } }
package com.own.send.server.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; @Repository public class RdbBaseDao { @Autowired @PersistenceContext protected EntityManager em; public <T> T save(T obj) { em.persist(obj); return obj; } public Object find(Object obj, Object key) { Class<? extends Object> clazz = obj.getClass(); return em.find(clazz, key); } public void remove(Object obj) { em.remove(obj); } public Page<?> findPage(String jsql, String countJsql, Map<String, ?> paramsMap, Pageable pageable) { Integer count = 0; if (countJsql != null && !"".equals(countJsql)) { Query countQuery = em.createQuery(countJsql); if (paramsMap != null) { for (Entry<String, ?> entry : paramsMap.entrySet()) { countQuery.setParameter(entry.getKey(), entry.getValue()); } } count = Integer.valueOf(countQuery.getSingleResult().toString()); } Query query = em.createQuery(jsql); if (paramsMap != null) { for (Entry<String, ?> entry : paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } query.setFirstResult(pageable.getOffset()); query.setMaxResults(pageable.getPageSize()); List<?> list = query.getResultList(); Page<?> page = new PageImpl(list, pageable, count); return page; } public Page<?> findAll2Page(String jsql, Map<String, ?> paramsMap) { Query query = em.createQuery(jsql); if (paramsMap != null) { for (Entry<String, ?> entry : paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } List<?> list = query.getResultList(); Page<?> page = new PageImpl(list); return page; } public List<?> findList(String jsql, Map<String, ?> paramsMap) { Query query = em.createQuery(jsql); if (paramsMap != null) { for (Entry<String, ?> entry : paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } List<?> list = query.getResultList(); return list; } public Object findObject(String jsql, Map<String, ?> paramsMap) { Query query = em.createQuery(jsql); if (paramsMap != null) { for (Entry<String, ?> entry : paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } return query.getSingleResult(); } public Page<?> findAllByConditions(String jsql, String countJsql, Pageable pageable) { return findPage(jsql, countJsql, null, pageable); } public int exeNativeUpdate(String sql, Map<String, ?> paramsMap) { Query query = em.createNativeQuery(sql); if (paramsMap != null) { for (Entry<String, ?> entry : paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } int rec = 0; try { rec = query.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { return rec; } } public Page<?> findAllByNativeSql(String sql, String countSql, Map<String, ?> paramsMap, Pageable pageable) { Integer count = 0; if (countSql != null && !"".equals(countSql)) { Query countQuery = em.createNativeQuery(countSql); if (paramsMap != null) { for (Entry<String, ?> entry : paramsMap.entrySet()) { countQuery.setParameter(entry.getKey(), entry.getValue()); } } count = Integer.valueOf(countQuery.getSingleResult().toString()); } Query query = em.createNativeQuery(sql); if (paramsMap != null) { for (Entry<String, ?> entry : paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } query.setFirstResult(pageable.getOffset()); query.setMaxResults(pageable.getPageSize()); List<Object[]> list = query.getResultList(); if (list == null || list.size() == 0) return null; List<Map<String, Object>> resList = genarateResultList(sql, list); Page<?> page = new PageImpl(resList, pageable, count); return page; } private List<Map<String, Object>> genarateResultList(String sql, List<Object[]> list) { String sqlUpper = sql.toUpperCase(); String[] keys = sqlUpper.substring(sqlUpper.indexOf("SELECT") + 1, sqlUpper.indexOf("WHERE")).split(","); for (int i = 0; i < keys.length; i++) { keys[i] = keys[i].indexOf(" AS ") > -1 ? keys[i].substring(keys[i].indexOf(" AS ") + 3).trim() : keys[i].trim();//如果没有as,则是原字符串 } List<Map<String, Object>> resList = new ArrayList<Map<String, Object>>(); for (Object[] obj : list) { Map<String, Object> rowMap = new HashMap<String, Object>(); for (int i = 0; i < obj.length; i++) { rowMap.put(keys[i], obj[i]); } resList.add(rowMap); } return resList; } public int exeSql(String sql, Map<String, ?> paramsMap) { Query query = em.createNamedQuery(sql); if (paramsMap != null) { for (Entry<String, ?> entry : paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } return query.executeUpdate(); } }
package com.own.send.server.service; import java.util.List; import java.util.Map; import com.own.send.server.dao.RdbBaseDao; import com.own.send.server.domain.IDomainBase; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class RdbSvc{ @Autowired private RdbBaseDao baseDao = null; public RdbBaseDao getBaseDao() { return baseDao; } public void setBaseDao(RdbBaseDao baseDao) { this.baseDao = baseDao; } /** * 通用的保存实体方法 * */ @Transactional public Object save(Object obj){ IDomainBase objPo = (IDomainBase)obj ; if(objPo.getObjectId()!=null){ objPo = (IDomainBase)baseDao.find(obj,objPo.getObjectId()); if(objPo==null) //throw new IFException("要更新的实体记录不存在!"); System.out.println("要更新的实体记录不存在!"); BeanUtils.copyProperties(obj,objPo); baseDao.save(objPo); return objPo; }else{ baseDao.save(obj); return obj; } } /** * 通用的保存实体方法 * @param obj * @return */ @Transactional public Object update(Object obj){ Object objPo = baseDao.find(obj, ((IDomainBase)obj).getObjectId()); if(objPo==null) //throw new IFException("要更新的实体记录不存在!"); System.out.println("要更新的实体记录不存在!"); BeanUtils.copyProperties(obj,objPo); baseDao.save(objPo); return objPo; } /** * 通用删除方法 * @param <T> * @param obj */ public <T> void delete(Object obj){ if(!(obj instanceof IDomainBase)) //throw new IFException("该实体没有继承IDomainBase!!!"); System.out.println("该实体没有继承IDomainBase!!!"); Object key = ((IDomainBase)obj).getObjectId(); Object object = baseDao.find(obj, key); if(obj==null) //throw new IFException("要删除的实体不存在或已被删除!"); System.out.println("要删除的实体不存在或已被删除!"); baseDao.remove(object); } /** * 通用的查询指定实体方法 * @param clazz 实体类型 * @param primaryKey 实体主键 * @return */ public Object find(Object obj){ if(!(obj instanceof IDomainBase)) //throw new IFException("该实体没有继承IDomainBase!!!"); System.out.println("该实体没有继承IDomainBase!!!"); Object key = ((IDomainBase)obj).getObjectId(); Object returnO = baseDao.find(obj, key); // if(returnO==null) // throw new IFException("找不到该实体的实例!!!"); return returnO; } //根据实体和key进行查找 public Object find(Object obj,Object key){ if(!(obj instanceof IDomainBase)) //throw new IFException("该实体没有继承IDomainBase!!!"); System.out.println("该实体没有继承IDomainBase!!!"); Object returnO = baseDao.find(obj, key); return returnO; } /** * 通用查询列表的方法 * @param jsql * @param countJsql * @param paramsMap * @param pageRequest * @return */ /*public Object search(HSqlBean searchBean){ String jsql=searchBean.getJsql(); String countJsql=searchBean.getCountJsql(); Map paramMap = searchBean.getParamsMap(); Object result =null; if(countJsql==null||countJsql.trim().length()==0){ result = findAll2Page(jsql,paramMap); }else{ PageRequest pageRequest = searchBean.getPageRequest(); result = findAllByConditions(jsql,countJsql,paramMap,pageRequest); } return result; }*/ /* * 返回所有的查询数据不分页 * * * */ public Object findAll2Page(String jsql, Map paramMap) { Object result = baseDao.findAll2Page(jsql,paramMap); return result; } public Object findAllByConditions(String jsql, String countJsql,Map<String, ?> paramsMap, PageRequest pageRequest) { return baseDao.findPage(jsql, countJsql, paramsMap, pageRequest); } public int exeSql(String sql,Map params){ int count = baseDao.exeNativeUpdate(sql, params); return count; } public Object findObject(String jsql,Map paramMap){ return baseDao.findObject(jsql, paramMap); } public List<?> findList(String jsql,Map paramMap){ return baseDao.findList(jsql, paramMap); } }
package com.own.workflow.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; /** * @author BluceZhang */ @Slf4j @Repository public class RdbBaseDao{ @Autowired @PersistenceContext protected EntityManager em; public <T> T save(T obj){ log.info("RdbBaseDao methed save{}",obj); em.persist(obj); return obj; } public Object find(Object obj,Object key){ log.info("RdbBaseDao methed find{}{}",key,obj); Class<? extends Object> clazz = obj.getClass(); return em.find(clazz, key); } public void remove(Object obj){ em.remove(obj); } public Page<?> findPage(String jsql, String countJsql, Map<String, ?> paramsMap, Pageable pageable){ Integer count = 0; if(countJsql!=null&&!"".equals(countJsql)){ Query countQuery = em.createQuery(countJsql); if(paramsMap!=null){ for (Entry<String, ?> entry: paramsMap.entrySet()) { countQuery.setParameter(entry.getKey(), entry.getValue()); } } count = Integer.valueOf(countQuery.getSingleResult().toString()); } Query query = em.createQuery(jsql); if(paramsMap!=null){ for (Entry<String, ?> entry: paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } query.setFirstResult(pageable.getOffset()); query.setMaxResults(pageable.getPageSize()); List<?> list = query.getResultList(); Page<?> page = new PageImpl(list,pageable,count); return page; } public Page<?> findAll2Page(String jsql,Map<String, ?> paramsMap){ Query query = em.createQuery(jsql); if(paramsMap!=null){ for (Entry<String, ?> entry: paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } List<?> list = query.getResultList(); Page<?> page = new PageImpl(list); return page; } public List<?> findList(String jsql,Map<String, ?> paramsMap){ Query query = em.createQuery(jsql); if(paramsMap!=null){ for (Entry<String, ?> entry: paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } List<?> list = query.getResultList(); return list; } public Object findObject(String jsql,Map<String, ?> paramsMap){ Query query = em.createQuery(jsql); if(paramsMap!=null){ for (Entry<String, ?> entry: paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } return query.getSingleResult(); } public Page<?> findAllByConditions(String jsql, String countJsql,Pageable pageable) { return findPage(jsql, countJsql, null, pageable); } public int exeNativeUpdate(String sql, Map<String, ?> paramsMap) { Query query = em.createNativeQuery(sql); if(paramsMap!=null) { for (Entry<String, ?> entry : paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } int rec = 0; try{ rec = query.executeUpdate(); }catch(Exception e){ e.printStackTrace(); }finally{ return rec; } } public Page<?> findAllByNativeSql(String sql,String countSql, Map<String, ?> paramsMap, Pageable pageable){ Integer count = 0; if(countSql!=null&&!"".equals(countSql)){ Query countQuery = em.createNativeQuery(countSql); if(paramsMap!=null){ for (Entry<String, ?> entry: paramsMap.entrySet()) { countQuery.setParameter(entry.getKey(), entry.getValue()); } } count = Integer.valueOf(countQuery.getSingleResult().toString()); } Query query = em.createNativeQuery(sql); if(paramsMap!=null){ for (Entry<String, ?> entry: paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } query.setFirstResult(pageable.getOffset()); query.setMaxResults(pageable.getPageSize()); List<Object[]> list = query.getResultList(); if(list==null||list.size()==0) return null; List<Map<String,Object>> resList = genarateResultList(sql,list); Page<?> page = new PageImpl(resList,pageable,count); return page; } /** * 处理结果集(由于原生sql返回的是数组,这里将结果集转换成map) */ private List<Map<String,Object>> genarateResultList(String sql,List<Object[]> list){ String sqlUpper = sql.toUpperCase(); String[] keys = sqlUpper.substring(sqlUpper.indexOf("SELECT")+1,sqlUpper.indexOf("WHERE")).split(","); for (int i=0;i<keys.length;i++) { keys[i] = keys[i].indexOf(" AS ")>-1?keys[i].substring(keys[i].indexOf(" AS ")+3).trim():keys[i].trim();//如果没有as,则是原字符串 } List<Map<String,Object>> resList = new ArrayList<Map<String,Object>>(); for (Object[] obj : list) { Map<String,Object> rowMap = new HashMap<String,Object>(); for(int i=0;i<obj.length;i++){ rowMap.put(keys[i], obj[i]); } resList.add(rowMap); } return resList; } public int exeSql(String sql, Map<String,?> paramsMap) { Query query = em.createNamedQuery(sql); if(paramsMap!=null){ for (Entry<String, ?> entry: paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } return query.executeUpdate(); } }
package com.own.workflow.service; import java.util.List; import java.util.Map; import com.own.workflow.dao.RdbBaseDao; import com.own.workflow.domain.IDomainBase; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Slf4j @Service public class RdbSvc{ @Autowired private RdbBaseDao baseDao;//这里借用IPartyOrgDao来调用通用方法,其实任何一个dao都可以 public RdbBaseDao getBaseDao() { return baseDao; } public void setBaseDao(RdbBaseDao baseDao) { this.baseDao = baseDao; } /** * 通用的保存实体方法 * */ @Transactional public Object save(Object obj){ IDomainBase objPo = (IDomainBase)obj ; if(objPo.getObjectId()!=null){ objPo = (IDomainBase)baseDao.find(obj,objPo.getObjectId()); if(objPo==null) //throw new IFException("要更新的实体记录不存在!"); log.info("要更新的实体记录不存在!"); BeanUtils.copyProperties(obj,objPo); baseDao.save(objPo); return objPo; }else{ baseDao.save(obj); return obj; } } /** * 通用的保存实体方法 * @param obj * @return */ @Transactional public Object update(Object obj){ Object objPo = baseDao.find(obj, ((IDomainBase)obj).getObjectId()); if(objPo==null) //throw new IFException("要更新的实体记录不存在!"); log.info("要更新的实体记录不存在!"); BeanUtils.copyProperties(obj,objPo); baseDao.save(objPo); return objPo; } /** * 通用删除方法 * @param <T> * @param obj */ public <T> void delete(Object obj){ if(!(obj instanceof IDomainBase)) log.info("该实体没有继承IDomainBase!!!"); Object key = ((IDomainBase)obj).getObjectId(); Object object = baseDao.find(obj, key); if(obj==null) log.info("要删除的实体不存在或已被删除!"); baseDao.remove(object); } /** * 通用的查询指定实体方法 * @param obj 实体类型 * @param primaryKey 实体主键 * @return */ public Object find(Object obj){ if(!(obj instanceof IDomainBase)) log.info("该实体没有继承IDomainBase!!!"); Object key = ((IDomainBase)obj).getObjectId(); Object returnO = baseDao.find(obj, key); return returnO; } //根据实体和key进行查找 public Object find(Object obj,Object key){ if(!(obj instanceof IDomainBase)) log.info("该实体没有继承IDomainBase!!!"); Object returnO = baseDao.find(obj, key); return returnO; } /** * 通用查询列表的方法 * @param jsql * @param countJsql * @param paramsMap * @param pageRequest * @return */ /*public Object search(HSqlBean searchBean){ String jsql=searchBean.getJsql(); String countJsql=searchBean.getCountJsql(); Map paramMap = searchBean.getParamsMap(); Object result =null; if(countJsql==null||countJsql.trim().length()==0){ result = findAll2Page(jsql,paramMap); }else{ PageRequest pageRequest = searchBean.getPageRequest(); result = findAllByConditions(jsql,countJsql,paramMap,pageRequest); } return result; }*/ /* * 返回所有的查询数据不分页 * * * */ public Object findAll2Page(String jsql, Map paramMap) { Object result = baseDao.findAll2Page(jsql,paramMap); return result; } public Object findAllByConditions(String jsql, String countJsql,Map<String, ?> paramsMap, PageRequest pageRequest) { return baseDao.findPage(jsql, countJsql, paramsMap, pageRequest); } @Transactional public int exeSql(String sql,Map params){ int count = baseDao.exeNativeUpdate(sql, params); return count; } public Object findObject(String jsql,Map paramMap){ return baseDao.findObject(jsql, paramMap); } public List<?> findList(String jsql,Map paramMap){ return baseDao.findList(jsql, paramMap); } }
package com.moxi.mogublog.xo.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.google.gson.internal.LinkedTreeMap; import com.moxi.mogublog.commons.entity.*; import com.moxi.mogublog.commons.feign.PictureFeignClient; import com.moxi.mogublog.utils.*; import com.moxi.mogublog.xo.global.MessageConf; import com.moxi.mogublog.xo.global.RedisConf; import com.moxi.mogublog.xo.global.SQLConf; import com.moxi.mogublog.xo.global.SysConf; import com.moxi.mogublog.xo.mapper.BlogMapper; import com.moxi.mogublog.xo.mapper.BlogSortMapper; import com.moxi.mogublog.xo.mapper.TagMapper; import com.moxi.mogublog.xo.service.*; import com.moxi.mogublog.xo.utils.WebUtil; import com.moxi.mogublog.xo.vo.BlogVO; import com.moxi.mougblog.base.enums.*; import com.moxi.mougblog.base.global.BaseSQLConf; import com.moxi.mougblog.base.global.BaseSysConf; import com.moxi.mougblog.base.global.Constants; import com.moxi.mougblog.base.holder.RequestHolder; import com.moxi.mougblog.base.serviceImpl.SuperServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.Reader; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.TimeUnit; /** * 博客表 服务实现类 * * @author 陌溪 * @date 2018-09-08 */ @Service @Slf4j public class BlogServiceImpl extends SuperServiceImpl<BlogMapper, Blog> implements BlogService { @Autowired private WebUtil webUtil; @Autowired private CommentService commentService; @Autowired private WebVisitService webVisitService; @Autowired private TagService tagService; @Autowired private PictureService pictureService; @Autowired private BlogSortService blogSortService; @Autowired private RedisUtil redisUtil; @Resource private TagMapper tagMapper; @Resource private BlogSortMapper blogSortMapper; @Resource private BlogMapper blogMapper; @Autowired private AdminService adminService; @Autowired private SystemConfigService systemConfigService; @Autowired private SysParamsService sysParamsService; @Autowired private BlogService blogService; @Autowired private SubjectItemService subjectItemService; @Resource private PictureFeignClient pictureFeignClient; @Autowired private RabbitTemplate rabbitTemplate; @Override public List<Blog> setTagByBlogList(List<Blog> list) { for (Blog item : list) { if (item != null) { setTagByBlog(item); } } return list; } @Override public List<Blog> setTagAndSortByBlogList(List<Blog> list) { List<String> sortUids = new ArrayList<>(); List<String> tagUids = new ArrayList<>(); list.forEach(item -> { if (StringUtils.isNotEmpty(item.getBlogSortUid())) { sortUids.add(item.getBlogSortUid()); } if (StringUtils.isNotEmpty(item.getTagUid())) { List<String> tagUidsTemp = StringUtils.changeStringToString(item.getTagUid(), BaseSysConf.FILE_SEGMENTATION); for (String itemTagUid : tagUidsTemp) { tagUids.add(itemTagUid); } } }); Collection<BlogSort> sortList = new ArrayList<>(); Collection<Tag> tagList = new ArrayList<>(); if (sortUids.size() > 0) { sortList = blogSortMapper.selectBatchIds(sortUids); } if (tagUids.size() > 0) { tagList = tagMapper.selectBatchIds(tagUids); } Map<String, BlogSort> sortMap = new HashMap<>(); Map<String, Tag> tagMap = new HashMap<>(); sortList.forEach(item -> { sortMap.put(item.getUid(), item); }); tagList.forEach(item -> { tagMap.put(item.getUid(), item); }); for (Blog item : list) { //设置分类 if (StringUtils.isNotEmpty(item.getBlogSortUid())) { item.setBlogSort(sortMap.get(item.getBlogSortUid())); } //获取标签 if (StringUtils.isNotEmpty(item.getTagUid())) { List<String> tagUidsTemp = StringUtils.changeStringToString(item.getTagUid(), BaseSysConf.FILE_SEGMENTATION); List<Tag> tagListTemp = new ArrayList<Tag>(); tagUidsTemp.forEach(tag -> { tagListTemp.add(tagMap.get(tag)); }); item.setTagList(tagListTemp); } } return list; } @Override public List<Blog> setTagAndSortAndPictureByBlogList(List<Blog> list) { List<String> sortUids = new ArrayList<>(); List<String> tagUids = new ArrayList<>(); Set<String> fileUidSet = new HashSet<>(); list.forEach(item -> { if (StringUtils.isNotEmpty(item.getFileUid())) { fileUidSet.add(item.getFileUid()); } if (StringUtils.isNotEmpty(item.getBlogSortUid())) { sortUids.add(item.getBlogSortUid()); } if (StringUtils.isNotEmpty(item.getTagUid())) { // tagUid有多个,还需要切分 if (StringUtils.isNotEmpty(item.getTagUid())) { List<String> tagUidsTemp = StringUtils.changeStringToString(item.getTagUid(), BaseSysConf.FILE_SEGMENTATION); for (String itemTagUid : tagUidsTemp) { tagUids.add(itemTagUid); } } } }); String pictureList = null; StringBuffer fileUids = new StringBuffer(); List<Map<String, Object>> picList = new ArrayList<>(); // feign分页查询图片数据 if(fileUidSet.size() > 0) { int count = 1; for(String fileUid: fileUidSet) { fileUids.append(fileUid + ","); System.out.println(count%10); if(count%10 == 0) { pictureList = this.pictureFeignClient.getPicture(fileUids.toString(), ","); List<Map<String, Object>> tempPicList = webUtil.getPictureMap(pictureList); picList.addAll(tempPicList); fileUids = new StringBuffer(); } count ++; } // 判断是否存在图片需要获取 if(fileUids.length() >= Constants.NUM_32) { pictureList = this.pictureFeignClient.getPicture(fileUids.toString(), Constants.SYMBOL_COMMA); List<Map<String, Object>> tempPicList = webUtil.getPictureMap(pictureList); picList.addAll(tempPicList); } } Collection<BlogSort> sortList = new ArrayList<>(); Collection<Tag> tagList = new ArrayList<>(); if (sortUids.size() > 0) { sortList = blogSortService.listByIds(sortUids); } if (tagUids.size() > 0) { tagList = tagService.listByIds(tagUids); } Map<String, BlogSort> sortMap = new HashMap<>(); Map<String, Tag> tagMap = new HashMap<>(); Map<String, String> pictureMap = new HashMap<>(); sortList.forEach(item -> { sortMap.put(item.getUid(), item); }); tagList.forEach(item -> { tagMap.put(item.getUid(), item); }); picList.forEach(item -> { pictureMap.put(item.get(SysConf.UID).toString(), item.get(SysConf.URL).toString()); }); for (Blog item : list) { //设置分类 if (StringUtils.isNotEmpty(item.getBlogSortUid())) { item.setBlogSort(sortMap.get(item.getBlogSortUid())); if (sortMap.get(item.getBlogSortUid()) != null) { item.setBlogSortName(sortMap.get(item.getBlogSortUid()).getSortName()); } } //获取标签 if (StringUtils.isNotEmpty(item.getTagUid())) { List<String> tagUidsTemp = StringUtils.changeStringToString(item.getTagUid(), ","); List<Tag> tagListTemp = new ArrayList<Tag>(); tagUidsTemp.forEach(tag -> { tagListTemp.add(tagMap.get(tag)); }); item.setTagList(tagListTemp); } //获取图片 if (StringUtils.isNotEmpty(item.getFileUid())) { List<String> pictureUidsTemp = StringUtils.changeStringToString(item.getFileUid(), Constants.SYMBOL_COMMA); List<String> pictureListTemp = new ArrayList<String>(); pictureUidsTemp.forEach(picture -> { pictureListTemp.add(pictureMap.get(picture)); }); item.setPhotoList(pictureListTemp); // 只设置一张标题图 if (pictureListTemp.size() > 0) { item.setPhotoUrl(pictureListTemp.get(0)); } else { item.setPhotoUrl(""); } } } return list; } @Override public Blog setTagByBlog(Blog blog) { String tagUid = blog.getTagUid(); if (!StringUtils.isEmpty(tagUid)) { String[] uids = tagUid.split(SysConf.FILE_SEGMENTATION); List<Tag> tagList = new ArrayList<>(); for (String uid : uids) { Tag tag = tagMapper.selectById(uid); if (tag != null && tag.getStatus() != EStatus.DISABLED) { tagList.add(tag); } } blog.setTagList(tagList); } return blog; } @Override public Blog setSortByBlog(Blog blog) { if (blog != null && !StringUtils.isEmpty(blog.getBlogSortUid())) { BlogSort blogSort = blogSortMapper.selectById(blog.getBlogSortUid()); blog.setBlogSort(blogSort); } return blog; } @Override public List<Blog> getBlogListByLevel(Integer level) { QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(BaseSQLConf.LEVEL, level); queryWrapper.eq(BaseSQLConf.IS_PUBLISH, EPublish.PUBLISH); List<Blog> list = blogMapper.selectList(queryWrapper); return list; } @Override public IPage<Blog> getBlogPageByLevel(Page<Blog> page, Integer level, Integer useSort) { QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(BaseSQLConf.LEVEL, level); queryWrapper.eq(BaseSQLConf.STATUS, EStatus.ENABLE); queryWrapper.eq(BaseSQLConf.IS_PUBLISH, EPublish.PUBLISH); if (useSort == 0) { queryWrapper.orderByDesc(BaseSQLConf.CREATE_TIME); } else { queryWrapper.orderByDesc(BaseSQLConf.SORT); } //因为首页并不需要显示内容,所以需要排除掉内容字段 queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SysConf.CONTENT)); return blogMapper.selectPage(page, queryWrapper); } @Override public Integer getBlogCount(Integer status) { QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(BaseSQLConf.STATUS, EStatus.ENABLE); queryWrapper.eq(BaseSQLConf.IS_PUBLISH, EPublish.PUBLISH); return blogMapper.selectCount(queryWrapper); } @Override public List<Map<String, Object>> getBlogCountByTag() { // 从Redis中获取标签下包含的博客数量 String jsonArrayList = redisUtil.get(RedisConf.DASHBOARD + Constants.SYMBOL_COLON + RedisConf.BLOG_COUNT_BY_TAG); if (StringUtils.isNotEmpty(jsonArrayList)) { ArrayList jsonList = JsonUtils.jsonArrayToArrayList(jsonArrayList); return jsonList; } List<Map<String, Object>> blogCoutByTagMap = blogMapper.getBlogCountByTag(); Map<String, Integer> tagMap = new HashMap<>(); for (Map<String, Object> item : blogCoutByTagMap) { String tagUid = String.valueOf(item.get(SQLConf.TAG_UID)); // java.lang.Number是Integer,Long的父类 Number num = (Number) item.get(SysConf.COUNT); Integer count = num.intValue(); //如果只有一个UID的情况 if (tagUid.length() == 32) { //如果没有这个内容的话,就设置 if (tagMap.get(tagUid) == null) { tagMap.put(tagUid, count); } else { Integer tempCount = tagMap.get(tagUid) + count; tagMap.put(tagUid, tempCount); } } else { //如果长度大于32,说明含有多个UID if (StringUtils.isNotEmpty(tagUid)) { List<String> strList = StringUtils.changeStringToString(tagUid, ","); for (String strItem : strList) { if (tagMap.get(strItem) == null) { tagMap.put(strItem, count); } else { Integer tempCount = tagMap.get(strItem) + count; tagMap.put(strItem, tempCount); } } } } } //把查询到的Tag放到Map中 Set<String> tagUids = tagMap.keySet(); Collection<Tag> tagCollection = new ArrayList<>(); if (tagUids.size() > 0) { tagCollection = tagMapper.selectBatchIds(tagUids); } Map<String, String> tagEntityMap = new HashMap<>(); for (Tag tag : tagCollection) { if (StringUtils.isNotEmpty(tag.getContent())) { tagEntityMap.put(tag.getUid(), tag.getContent()); } } List<Map<String, Object>> resultList = new ArrayList<>(); for (Map.Entry<String, Integer> entry : tagMap.entrySet()) { String tagUid = entry.getKey(); if (tagEntityMap.get(tagUid) != null) { String tagName = tagEntityMap.get(tagUid); Integer count = entry.getValue(); Map<String, Object> itemResultMap = new HashMap<>(); itemResultMap.put(SysConf.TAG_UID, tagUid); itemResultMap.put(SysConf.NAME, tagName); itemResultMap.put(SysConf.VALUE, count); resultList.add(itemResultMap); } } // 将 每个标签下文章数目 存入到Redis【过期时间2小时】 if (resultList.size() > 0) { redisUtil.setEx(RedisConf.DASHBOARD + Constants.SYMBOL_COLON + RedisConf.BLOG_COUNT_BY_TAG, JsonUtils.objectToJson(resultList), 2, TimeUnit.HOURS); } return resultList; } @Override public List<Map<String, Object>> getBlogCountByBlogSort() { // 从Redis中获取博客分类下包含的博客数量 String jsonArrayList = redisUtil.get(RedisConf.DASHBOARD + Constants.SYMBOL_COLON + RedisConf.BLOG_COUNT_BY_SORT); if (StringUtils.isNotEmpty(jsonArrayList)) { ArrayList jsonList = JsonUtils.jsonArrayToArrayList(jsonArrayList); return jsonList; } List<Map<String, Object>> blogCoutByBlogSortMap = blogMapper.getBlogCountByBlogSort(); Map<String, Integer> blogSortMap = new HashMap<>(); for (Map<String, Object> item : blogCoutByBlogSortMap) { String blogSortUid = String.valueOf(item.get(SQLConf.BLOG_SORT_UID)); // java.lang.Number是Integer,Long的父类 Number num = (Number) item.get(SysConf.COUNT); Integer count = 0; if (num != null) { count = num.intValue(); } blogSortMap.put(blogSortUid, count); } //把查询到的BlogSort放到Map中 Set<String> blogSortUids = blogSortMap.keySet(); Collection<BlogSort> blogSortCollection = new ArrayList<>(); if (blogSortUids.size() > 0) { blogSortCollection = blogSortMapper.selectBatchIds(blogSortUids); } Map<String, String> blogSortEntityMap = new HashMap<>(); for (BlogSort blogSort : blogSortCollection) { if (StringUtils.isNotEmpty(blogSort.getSortName())) { blogSortEntityMap.put(blogSort.getUid(), blogSort.getSortName()); } } List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>(); for (Map.Entry<String, Integer> entry : blogSortMap.entrySet()) { String blogSortUid = entry.getKey(); if (blogSortEntityMap.get(blogSortUid) != null) { String blogSortName = blogSortEntityMap.get(blogSortUid); Integer count = entry.getValue(); Map<String, Object> itemResultMap = new HashMap<>(); itemResultMap.put(SysConf.BLOG_SORT_UID, blogSortUid); itemResultMap.put(SysConf.NAME, blogSortName); itemResultMap.put(SysConf.VALUE, count); resultList.add(itemResultMap); } } // 将 每个分类下文章数目 存入到Redis【过期时间2小时】 if (resultList.size() > 0) { redisUtil.setEx(RedisConf.DASHBOARD + Constants.SYMBOL_COLON + RedisConf.BLOG_COUNT_BY_SORT, JsonUtils.objectToJson(resultList), 2, TimeUnit.HOURS); } return resultList; } @Override public Map<String, Object> getBlogContributeCount() { // 从Redis中获取博客分类下包含的博客数量 String jsonMap = redisUtil.get(RedisConf.DASHBOARD + Constants.SYMBOL_COLON + RedisConf.BLOG_CONTRIBUTE_COUNT); if (StringUtils.isNotEmpty(jsonMap)) { Map<String, Object> resultMap = JsonUtils.jsonToMap(jsonMap); return resultMap; } // 获取今天结束时间 String endTime = DateUtils.getNowTime(); // 获取365天前的日期 Date temp = DateUtils.getDate(endTime, -365); String startTime = DateUtils.dateTimeToStr(temp); List<Map<String, Object>> blogContributeMap = blogMapper.getBlogContributeCount(startTime, endTime); List<String> dateList = DateUtils.getDayBetweenDates(startTime, endTime); Map<String, Object> dateMap = new HashMap<>(); for (Map<String, Object> itemMap : blogContributeMap) { dateMap.put(itemMap.get("DATE").toString(), itemMap.get("COUNT")); } List<List<Object>> resultList = new ArrayList<>(); for (String item : dateList) { Integer count = 0; if (dateMap.get(item) != null) { count = Integer.valueOf(dateMap.get(item).toString()); } List<Object> objectList = new ArrayList<>(); objectList.add(item); objectList.add(count); resultList.add(objectList); } Map<String, Object> resultMap = new HashMap<>(Constants.NUM_TWO); List<String> contributeDateList = new ArrayList<>(); contributeDateList.add(startTime); contributeDateList.add(endTime); resultMap.put(SysConf.CONTRIBUTE_DATE, contributeDateList); resultMap.put(SysConf.BLOG_CONTRIBUTE_COUNT, resultList); // 将 全年博客贡献度 存入到Redis【过期时间2小时】 redisUtil.setEx(RedisConf.DASHBOARD + Constants.SYMBOL_COLON + RedisConf.BLOG_CONTRIBUTE_COUNT, JsonUtils.objectToJson(resultMap), 2, TimeUnit.HOURS); return resultMap; } @Override public Blog getBlogByUid(String uid) { Blog blog = blogMapper.selectById(uid); if (blog != null && blog.getStatus() != EStatus.DISABLED) { blog = setTagByBlog(blog); blog = setSortByBlog(blog); return blog; } return null; } @Override public List<Blog> getSameBlogByBlogUid(String blogUid) { Blog blog = blogService.getById(blogUid); QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); Page<Blog> page = new Page<>(); page.setCurrent(1); page.setSize(10); // 通过分类来获取相关博客 String blogSortUid = blog.getBlogSortUid(); queryWrapper.eq(SQLConf.BLOG_SORT_UID, blogSortUid); queryWrapper.eq(SQLConf.IS_PUBLISH, EPublish.PUBLISH); queryWrapper.orderByDesc(SQLConf.CREATE_TIME); IPage<Blog> pageList = blogService.page(page, queryWrapper); List<Blog> list = pageList.getRecords(); list = blogService.setTagAndSortByBlogList(list); //过滤掉当前的博客 List<Blog> newList = new ArrayList<>(); for (Blog item : list) { if (item.getUid().equals(blogUid)) { continue; } newList.add(item); } return newList; } @Override public List<Blog> getBlogListByTop(Integer top) { QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); Page<Blog> page = new Page<>(); page.setCurrent(1); page.setSize(top); queryWrapper.eq(SQLConf.IS_PUBLISH, EPublish.PUBLISH); queryWrapper.orderByDesc(SQLConf.SORT); IPage<Blog> pageList = blogService.page(page, queryWrapper); List<Blog> list = pageList.getRecords(); list = blogService.setTagAndSortAndPictureByBlogList(list); return list; } @Override public IPage<Blog> getPageList(BlogVO blogVO) { QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); // 构建搜索条件 if (StringUtils.isNotEmpty(blogVO.getKeyword()) && !StringUtils.isEmpty(blogVO.getKeyword().trim())) { queryWrapper.like(SQLConf.TITLE, blogVO.getKeyword().trim()); } if (!StringUtils.isEmpty(blogVO.getTagUid())) { queryWrapper.like(SQLConf.TAG_UID, blogVO.getTagUid()); } if (!StringUtils.isEmpty(blogVO.getBlogSortUid())) { queryWrapper.like(SQLConf.BLOG_SORT_UID, blogVO.getBlogSortUid()); } if (!StringUtils.isEmpty(blogVO.getLevelKeyword())) { queryWrapper.eq(SQLConf.LEVEL, blogVO.getLevelKeyword()); } if (!StringUtils.isEmpty(blogVO.getIsPublish())) { queryWrapper.eq(SQLConf.IS_PUBLISH, blogVO.getIsPublish()); } if (!StringUtils.isEmpty(blogVO.getIsOriginal())) { queryWrapper.eq(SQLConf.IS_ORIGINAL, blogVO.getIsOriginal()); } if(!StringUtils.isEmpty(blogVO.getType())) { queryWrapper.eq(SQLConf.TYPE, blogVO.getType()); } //分页 Page<Blog> page = new Page<>(); page.setCurrent(blogVO.getCurrentPage()); page.setSize(blogVO.getPageSize()); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); if(StringUtils.isNotEmpty(blogVO.getOrderByAscColumn())) { // 将驼峰转换成下划线 String column = StringUtils.underLine(new StringBuffer(blogVO.getOrderByAscColumn())).toString(); queryWrapper.orderByAsc(column); }else if(StringUtils.isNotEmpty(blogVO.getOrderByDescColumn())) { // 将驼峰转换成下划线 String column = StringUtils.underLine(new StringBuffer(blogVO.getOrderByDescColumn())).toString(); queryWrapper.orderByDesc(column); } else { // 是否启动排序字段 if (blogVO.getUseSort() == 0) { // 未使用,默认按时间倒序 queryWrapper.orderByDesc(SQLConf.CREATE_TIME); } else { // 使用,默认按sort值大小倒序 queryWrapper.orderByDesc(SQLConf.SORT); } } IPage<Blog> pageList = blogService.page(page, queryWrapper); List<Blog> list = pageList.getRecords(); if (list.size() == 0) { return pageList; } final StringBuffer fileUids = new StringBuffer(); List<String> sortUids = new ArrayList<>(); List<String> tagUids = new ArrayList<>(); list.forEach(item -> { if (StringUtils.isNotEmpty(item.getFileUid())) { fileUids.append(item.getFileUid() + SysConf.FILE_SEGMENTATION); } if (StringUtils.isNotEmpty(item.getBlogSortUid())) { sortUids.add(item.getBlogSortUid()); } if (StringUtils.isNotEmpty(item.getTagUid())) { List<String> tagUidsTemp = StringUtils.changeStringToString(item.getTagUid(), SysConf.FILE_SEGMENTATION); for (String itemTagUid : tagUidsTemp) { tagUids.add(itemTagUid); } } }); String pictureList = null; if (fileUids != null) { pictureList = this.pictureFeignClient.getPicture(fileUids.toString(), SysConf.FILE_SEGMENTATION); } List<Map<String, Object>> picList = webUtil.getPictureMap(pictureList); Collection<BlogSort> sortList = new ArrayList<>(); Collection<Tag> tagList = new ArrayList<>(); if (sortUids.size() > 0) { sortList = blogSortService.listByIds(sortUids); } if (tagUids.size() > 0) { tagList = tagService.listByIds(tagUids); } Map<String, BlogSort> sortMap = new HashMap<>(); Map<String, Tag> tagMap = new HashMap<>(); Map<String, String> pictureMap = new HashMap<>(); sortList.forEach(item -> { sortMap.put(item.getUid(), item); }); tagList.forEach(item -> { tagMap.put(item.getUid(), item); }); picList.forEach(item -> { pictureMap.put(item.get(SQLConf.UID).toString(), item.get(SQLConf.URL).toString()); }); for (Blog item : list) { //设置分类 if (StringUtils.isNotEmpty(item.getBlogSortUid())) { item.setBlogSort(sortMap.get(item.getBlogSortUid())); } //获取标签 if (StringUtils.isNotEmpty(item.getTagUid())) { List<String> tagUidsTemp = StringUtils.changeStringToString(item.getTagUid(), SysConf.FILE_SEGMENTATION); List<Tag> tagListTemp = new ArrayList<Tag>(); tagUidsTemp.forEach(tag -> { tagListTemp.add(tagMap.get(tag)); }); item.setTagList(tagListTemp); } //获取图片 if (StringUtils.isNotEmpty(item.getFileUid())) { List<String> pictureUidsTemp = StringUtils.changeStringToString(item.getFileUid(), SysConf.FILE_SEGMENTATION); List<String> pictureListTemp = new ArrayList<>(); pictureUidsTemp.forEach(picture -> { pictureListTemp.add(pictureMap.get(picture)); }); item.setPhotoList(pictureListTemp); } } pageList.setRecords(list); return pageList; } @Override public String addBlog(BlogVO blogVO) { HttpServletRequest request = RequestHolder.getRequest(); QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(SQLConf.LEVEL, blogVO.getLevel()); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); Integer count = blogService.count(queryWrapper); // 判断插入博客的时候,会不会超过预期设置 String addVerdictResult = addVerdict(count + 1, blogVO.getLevel()); // 判断是否能够添加推荐 if (StringUtils.isNotBlank(addVerdictResult)) { return addVerdictResult; } Blog blog = new Blog(); //如果是原创,作者为用户的昵称 String projectName = sysParamsService.getSysParamsValueByKey(SysConf.PROJECT_NAME_); if (EOriginal.ORIGINAL.equals(blogVO.getIsOriginal())) { Admin admin = adminService.getById(request.getAttribute(SysConf.ADMIN_UID).toString()); if (admin != null) { if(StringUtils.isNotEmpty(admin.getNickName())) { blog.setAuthor(admin.getNickName()); } else { blog.setAuthor(admin.getUserName()); } blog.setAdminUid(admin.getUid()); } blog.setArticlesPart(projectName); } else { blog.setAuthor(blogVO.getAuthor()); blog.setArticlesPart(blogVO.getArticlesPart()); } blog.setTitle(blogVO.getTitle()); blog.setSummary(blogVO.getSummary()); blog.setContent(blogVO.getContent()); blog.setTagUid(blogVO.getTagUid()); blog.setBlogSortUid(blogVO.getBlogSortUid()); blog.setFileUid(blogVO.getFileUid()); blog.setLevel(blogVO.getLevel()); blog.setIsOriginal(blogVO.getIsOriginal()); blog.setIsPublish(blogVO.getIsPublish()); blog.setType(blogVO.getType()); blog.setOutsideLink(blogVO.getOutsideLink()); blog.setStatus(EStatus.ENABLE); blog.setOpenComment(blogVO.getOpenComment()); Boolean isSave = blogService.save(blog); //保存成功后,需要发送消息到solr 和 redis updateSolrAndRedis(isSave, blog); return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS); } @Override public String editBlog(BlogVO blogVO) { HttpServletRequest request = RequestHolder.getRequest(); Blog blog = blogService.getById(blogVO.getUid()); QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(SQLConf.LEVEL, blogVO.getLevel()); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); Integer count = blogService.count(queryWrapper); if (blog != null) { //传递过来的和数据库中的不同,代表用户已经修改过等级了,那么需要将count数加1 if (!blog.getLevel().equals(blogVO.getLevel())) { count += 1; } } String addVerdictResult = addVerdict(count, blogVO.getLevel()); //添加的时候进行判断 if (StringUtils.isNotBlank(addVerdictResult)) { return addVerdictResult; } //如果是原创,作者为用户的昵称 Admin admin = adminService.getById(request.getAttribute(SysConf.ADMIN_UID).toString()); blog.setAdminUid(admin.getUid()); if (EOriginal.ORIGINAL.equals(blogVO.getIsOriginal())) { if(StringUtils.isNotEmpty(admin.getNickName())) { blog.setAuthor(admin.getNickName()); } else { blog.setAuthor(admin.getUserName()); } String projectName = sysParamsService.getSysParamsValueByKey(SysConf.PROJECT_NAME_); blog.setArticlesPart(projectName); } else { blog.setAuthor(blogVO.getAuthor()); blog.setArticlesPart(blogVO.getArticlesPart()); } blog.setTitle(blogVO.getTitle()); blog.setSummary(blogVO.getSummary()); blog.setContent(blogVO.getContent()); blog.setTagUid(blogVO.getTagUid()); blog.setBlogSortUid(blogVO.getBlogSortUid()); blog.setFileUid(blogVO.getFileUid()); blog.setLevel(blogVO.getLevel()); blog.setIsOriginal(blogVO.getIsOriginal()); blog.setIsPublish(blogVO.getIsPublish()); blog.setOpenComment(blogVO.getOpenComment()); blog.setUpdateTime(new Date()); blog.setType(blogVO.getType()); blog.setOutsideLink(blogVO.getOutsideLink()); blog.setStatus(EStatus.ENABLE); Boolean isSave = blog.updateById(); //保存成功后,需要发送消息到solr 和 redis updateSolrAndRedis(isSave, blog); return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS); } @Override public String editBatch(List<BlogVO> blogVOList) { if (blogVOList.size() <= 0) { return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT); } List<String> blogUidList = new ArrayList<>(); Map<String, BlogVO> blogVOMap = new HashMap<>(); blogVOList.forEach(item -> { blogUidList.add(item.getUid()); blogVOMap.put(item.getUid(), item); }); Collection<Blog> blogList = blogService.listByIds(blogUidList); blogList.forEach(blog -> { BlogVO blogVO = blogVOMap.get(blog.getUid()); if (blogVO != null) { blog.setAuthor(blogVO.getAuthor()); blog.setArticlesPart(blogVO.getArticlesPart()); blog.setTitle(blogVO.getTitle()); blog.setSummary(blogVO.getSummary()); blog.setContent(blogVO.getContent()); blog.setTagUid(blogVO.getTagUid()); blog.setBlogSortUid(blogVO.getBlogSortUid()); blog.setFileUid(blogVO.getFileUid()); blog.setLevel(blogVO.getLevel()); blog.setIsOriginal(blogVO.getIsOriginal()); blog.setIsPublish(blogVO.getIsPublish()); blog.setSort(blogVO.getSort()); blog.setType(blogVO.getType()); blog.setOutsideLink(blogVO.getOutsideLink()); blog.setStatus(EStatus.ENABLE); } }); Boolean save = blogService.updateBatchById(blogList); //保存成功后,需要发送消息到solr 和 redis if (save) { Map<String, Object> map = new HashMap<>(); map.put(SysConf.COMMAND, SysConf.EDIT_BATCH); //发送到RabbitMq rabbitTemplate.convertAndSend(SysConf.EXCHANGE_DIRECT, SysConf.MOGU_BLOG, map); } return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS); } @Override public String deleteBlog(BlogVO blogVO) { Blog blog = blogService.getById(blogVO.getUid()); blog.setStatus(EStatus.DISABLED); Boolean save = blog.updateById(); //保存成功后,需要发送消息到solr 和 redis, 同时从专题管理Item中移除该博客 if (save) { Map<String, Object> map = new HashMap<>(); map.put(SysConf.COMMAND, SysConf.DELETE); map.put(SysConf.BLOG_UID, blog.getUid()); map.put(SysConf.LEVEL, blog.getLevel()); map.put(SysConf.CREATE_TIME, blog.getCreateTime()); //发送到RabbitMq rabbitTemplate.convertAndSend(SysConf.EXCHANGE_DIRECT, SysConf.MOGU_BLOG, map); // 移除所有包含该博客的专题Item List<String> blogUidList = new ArrayList<>(Constants.NUM_ONE); blogUidList.add(blogVO.getUid()); subjectItemService.deleteBatchSubjectItemByBlogUid(blogUidList); // 移除该文章下所有评论 commentService.batchDeleteCommentByBlogUid(blogUidList); } return ResultUtil.successWithMessage(MessageConf.DELETE_SUCCESS); } @Override public String deleteBatchBlog(List<BlogVO> blogVoList) { if (blogVoList.size() <= 0) { return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT); } List<String> uidList = new ArrayList<>(); StringBuffer uidSbf = new StringBuffer(); blogVoList.forEach(item -> { uidList.add(item.getUid()); uidSbf.append(item.getUid() + SysConf.FILE_SEGMENTATION); }); Collection<Blog> blogList = blogService.listByIds(uidList); blogList.forEach(item -> { item.setStatus(EStatus.DISABLED); }); Boolean save = blogService.updateBatchById(blogList); //保存成功后,需要发送消息到solr 和 redis if (save) { Map<String, Object> map = new HashMap<>(); map.put(SysConf.COMMAND, SysConf.DELETE_BATCH); map.put(SysConf.UID, uidSbf); //发送到RabbitMq rabbitTemplate.convertAndSend(SysConf.EXCHANGE_DIRECT, SysConf.MOGU_BLOG, map); // 移除所有包含该博客的专题Item subjectItemService.deleteBatchSubjectItemByBlogUid(uidList); // 移除该文章下所有评论 commentService.batchDeleteCommentByBlogUid(uidList); } return ResultUtil.successWithMessage(MessageConf.DELETE_SUCCESS); } @Override public String uploadLocalBlog(List<MultipartFile> filedatas) { SystemConfig systemConfig = systemConfigService.getConfig(); if (systemConfig == null) { return ResultUtil.errorWithMessage(MessageConf.SYSTEM_CONFIG_NOT_EXIST); } else { if (EOpenStatus.OPEN.equals(systemConfig.getUploadQiNiu()) && (StringUtils.isEmpty(systemConfig.getQiNiuPictureBaseUrl()) || StringUtils.isEmpty(systemConfig.getQiNiuAccessKey()) || StringUtils.isEmpty(systemConfig.getQiNiuSecretKey()) || StringUtils.isEmpty(systemConfig.getQiNiuBucket()) || StringUtils.isEmpty(systemConfig.getQiNiuArea()))) { return ResultUtil.errorWithMessage(MessageConf.PLEASE_SET_QI_NIU); } if (EOpenStatus.OPEN.equals(systemConfig.getUploadLocal()) && StringUtils.isEmpty(systemConfig.getLocalPictureBaseUrl())) { return ResultUtil.errorWithMessage(MessageConf.PLEASE_SET_LOCAL); } } List<MultipartFile> fileList = new ArrayList<>(); List<String> fileNameList = new ArrayList<>(); for (MultipartFile file : filedatas) { String fileOriginalName = file.getOriginalFilename(); if (FileUtils.isMarkdown(fileOriginalName)) { fileList.add(file); // 获取文件名 fileNameList.add(FileUtils.getFileName(fileOriginalName)); } else { return ResultUtil.errorWithMessage("目前仅支持Markdown文件"); } } if (fileList.size() == 0) { return ResultUtil.errorWithMessage("请选中需要上传的文件"); } // 文档解析 List<String> fileContentList = new ArrayList<>(); for (MultipartFile multipartFile : fileList) { try { Reader reader = new InputStreamReader(multipartFile.getInputStream(), "utf-8"); BufferedReader br = new BufferedReader(reader); String line; String content = ""; while ((line = br.readLine()) != null) { content += line + "\n"; } // 将Markdown转换成html String blogContent = FileUtils.markdownToHtml(content); fileContentList.add(blogContent); } catch (Exception e) { log.error("文件解析出错"); log.error(e.getMessage()); } } HttpServletRequest request = RequestHolder.getRequest(); String pictureList = request.getParameter(SysConf.PICTURE_LIST); List<LinkedTreeMap<String, String>> list = (List<LinkedTreeMap<String, String>>) JsonUtils.jsonArrayToArrayList(pictureList); Map<String, String> pictureMap = new HashMap<>(); for (LinkedTreeMap<String, String> item : list) { if (EFilePriority.QI_NIU.equals(systemConfig.getContentPicturePriority())) { // 获取七牛云上的图片 pictureMap.put(item.get(SysConf.FILE_OLD_NAME), item.get(SysConf.QI_NIU_URL)); } else if(EFilePriority.LOCAL.equals(systemConfig.getContentPicturePriority())) { // 获取本地的图片 pictureMap.put(item.get(SysConf.FILE_OLD_NAME), item.get(SysConf.PIC_URL)); } else if(EFilePriority.MINIO.equals(systemConfig.getContentPicturePriority())) { // 获取MINIO的图片 pictureMap.put(item.get(SysConf.FILE_OLD_NAME), item.get(SysConf.MINIO_URL)); } } // 需要替换的图片Map Map<String, String> matchUrlMap = new HashMap<>(); for (String blogContent : fileContentList) { List<String> matchList = RegexUtils.match(blogContent, "<img\\s+(?:[^>]*)src\\s*=\\s*([^>]+)>"); for (String matchStr : matchList) { String[] splitList = matchStr.split("\""); // 取出中间的图片 if (splitList.length >= 5) { // alt 和 src的先后顺序 // 得到具体的图片路径 String pictureUrl = ""; if (matchStr.indexOf("alt") > matchStr.indexOf("src")) { pictureUrl = splitList[1]; } else { pictureUrl = splitList[3]; } // 判断是网络图片还是本地图片 if (!pictureUrl.startsWith(SysConf.HTTP)) { // 那么就需要遍历全部的map和他匹配 for (Map.Entry<String, String> map : pictureMap.entrySet()) { // 查看Map中的图片是否在需要替换的key中 if (pictureUrl.indexOf(map.getKey()) > -1) { if (EFilePriority.QI_NIU.equals(systemConfig.getContentPicturePriority())) { // 获取七牛云上的图片 matchUrlMap.put(pictureUrl, systemConfig.getQiNiuPictureBaseUrl() + map.getValue()); } else if(EFilePriority.LOCAL.equals(systemConfig.getContentPicturePriority())) { // 获取本地的图片 matchUrlMap.put(pictureUrl, systemConfig.getLocalPictureBaseUrl() + map.getValue()); } else if(EFilePriority.MINIO.equals(systemConfig.getContentPicturePriority())) { // 获取MINIO的图片 matchUrlMap.put(pictureUrl, systemConfig.getMinioPictureBaseUrl() + map.getValue()); } break; } } } } } } // 获取一个排序最高的博客分类和标签 BlogSort blogSort = blogSortService.getTopOne(); Tag tag = tagService.getTopTag(); // 获取任意博客封面 Picture picture = pictureService.getTopOne(); if (blogSort == null || tag == null || picture == null) { return ResultUtil.errorWithMessage("使用本地上传,请先确保博客分类,博客标签,博客图片中含有数据"); } // 获取当前管理员 Admin admin = adminService.getMe(); // 存储需要上传的博客 List<Blog> blogList = new ArrayList<>(); // 开始进行图片替换操作 Integer count = 0; String projectName = sysParamsService.getSysParamsValueByKey(SysConf.PROJECT_NAME_); for (String content : fileContentList) { // 循环替换里面的图片 for (Map.Entry<String, String> map : matchUrlMap.entrySet()) { content = content.replace(map.getKey(), map.getValue()); } Blog blog = new Blog(); blog.setBlogSortUid(blogSort.getUid()); blog.setTagUid(tag.getUid()); blog.setAdminUid(admin.getUid()); blog.setAuthor(admin.getNickName()); blog.setArticlesPart(projectName); blog.setLevel(ELevel.NORMAL); blog.setTitle(fileNameList.get(count)); blog.setSummary(fileNameList.get(count)); blog.setContent(content); blog.setFileUid(picture.getFileUid()); blog.setIsOriginal(EOriginal.ORIGINAL); blog.setIsPublish(EPublish.NO_PUBLISH); blog.setOpenComment(EOpenStatus.OPEN); blog.setType(Constants.STR_ZERO); blogList.add(blog); count++; } // 批量添加博客 blogService.saveBatch(blogList); return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS); } @Override public void deleteRedisByBlogSort() { // 删除Redis中博客分类下的博客数量 redisUtil.delete(RedisConf.DASHBOARD + Constants.SYMBOL_COLON + RedisConf.BLOG_COUNT_BY_SORT); // 删除博客相关缓存 deleteRedisByBlog(); } @Override public void deleteRedisByBlogTag() { // 删除Redis中博客分类下的博客数量 redisUtil.delete(RedisConf.DASHBOARD + Constants.SYMBOL_COLON + RedisConf.BLOG_COUNT_BY_TAG); // 删除博客相关缓存 deleteRedisByBlog(); } @Override public void deleteRedisByBlog() { // 删除博客相关缓存 redisUtil.delete(RedisConf.NEW_BLOG); redisUtil.delete(RedisConf.HOT_BLOG); redisUtil.delete(RedisConf.BLOG_LEVEL + Constants.SYMBOL_COLON + ELevel.FIRST); redisUtil.delete(RedisConf.BLOG_LEVEL + Constants.SYMBOL_COLON + ELevel.SECOND); redisUtil.delete(RedisConf.BLOG_LEVEL + Constants.SYMBOL_COLON + ELevel.THIRD); redisUtil.delete(RedisConf.BLOG_LEVEL + Constants.SYMBOL_COLON + ELevel.FOURTH); } @Override public IPage<Blog> getBlogPageByLevel(Integer level, Long currentPage, Integer useSort) { //从Redis中获取内容 String jsonResult = redisUtil.get(RedisConf.BLOG_LEVEL + RedisConf.SEGMENTATION + level); //判断redis中是否有文章 if (StringUtils.isNotEmpty(jsonResult)) { List jsonResult2List = JsonUtils.jsonArrayToArrayList(jsonResult); IPage pageList = new Page(); pageList.setRecords(jsonResult2List); return pageList; } Page<Blog> page = new Page<>(); page.setCurrent(currentPage); String blogCount = null; switch (level) { case ELevel.NORMAL: { blogCount = sysParamsService.getSysParamsValueByKey(SysConf.BLOG_NEW_COUNT); } break; case ELevel.FIRST: { blogCount = sysParamsService.getSysParamsValueByKey(SysConf.BLOG_FIRST_COUNT); } break; case ELevel.SECOND: { blogCount = sysParamsService.getSysParamsValueByKey(SysConf.BLOG_SECOND_COUNT); } break; case ELevel.THIRD: { blogCount = sysParamsService.getSysParamsValueByKey(SysConf.BLOG_THIRD_COUNT); } break; case ELevel.FOURTH: { blogCount = sysParamsService.getSysParamsValueByKey(SysConf.BLOG_FOURTH_COUNT); } break; } if (StringUtils.isEmpty(blogCount)) { log.error(MessageConf.PLEASE_CONFIGURE_SYSTEM_PARAMS); } else { page.setSize(Long.valueOf(blogCount)); } IPage<Blog> pageList = blogService.getBlogPageByLevel(page, level, useSort); List<Blog> list = pageList.getRecords(); // 一级推荐或者二级推荐没有内容时,自动把top5填充至一级推荐和二级推荐中 if ((level == SysConf.ONE || level == SysConf.TWO) && list.size() == 0) { QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); Page<Blog> hotPage = new Page<>(); hotPage.setCurrent(1); String blogHotCount = sysParamsService.getSysParamsValueByKey(SysConf.BLOG_HOT_COUNT); String blogSecondCount = sysParamsService.getSysParamsValueByKey(SysConf.BLOG_SECOND_COUNT); if (StringUtils.isEmpty(blogHotCount) || StringUtils.isEmpty(blogSecondCount)) { log.error(MessageConf.PLEASE_CONFIGURE_SYSTEM_PARAMS); } else { hotPage.setSize(Long.valueOf(blogHotCount)); } queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); queryWrapper.eq(SQLConf.IS_PUBLISH, EPublish.PUBLISH); queryWrapper.orderByDesc(SQLConf.CLICK_COUNT); queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SQLConf.CONTENT)); IPage<Blog> hotPageList = blogService.page(hotPage, queryWrapper); List<Blog> hotBlogList = hotPageList.getRecords(); List<Blog> secondBlogList = new ArrayList<>(); List<Blog> firstBlogList = new ArrayList<>(); for (int a = 0; a < hotBlogList.size(); a++) { // 当推荐大于两个的时候 if ((hotBlogList.size() - firstBlogList.size()) > Long.valueOf(blogSecondCount)) { firstBlogList.add(hotBlogList.get(a)); } else { secondBlogList.add(hotBlogList.get(a)); } } firstBlogList = setBlog(firstBlogList); secondBlogList = setBlog(secondBlogList); // 将从数据库查询的数据缓存到redis中,设置1小时后过期 [避免 list 中没有数据而保存至 redis 的情况] if (firstBlogList.size() > 0) { redisUtil.setEx(RedisConf.BLOG_LEVEL + Constants.SYMBOL_COLON + Constants.NUM_ONE, JsonUtils.objectToJson(firstBlogList), 1, TimeUnit.HOURS); } if (secondBlogList.size() > 0) { redisUtil.setEx(RedisConf.BLOG_LEVEL + Constants.SYMBOL_COLON + Constants.NUM_TWO, JsonUtils.objectToJson(secondBlogList), 1, TimeUnit.HOURS); } switch (level) { case SysConf.ONE: { pageList.setRecords(firstBlogList); } break; case SysConf.TWO: { pageList.setRecords(secondBlogList); } break; } return pageList; } list = setBlog(list); pageList.setRecords(list); // 将从数据库查询的数据缓存到redis中 [避免 list 中没有数据而保存至 redis 的情况] if (list.size() > 0) { redisUtil.setEx(SysConf.BLOG_LEVEL + SysConf.REDIS_SEGMENTATION + level, JsonUtils.objectToJson(list).toString(), 1, TimeUnit.HOURS); } return pageList; } @Override public IPage<Blog> getHotBlog() { //从Redis中获取内容 String jsonResult = redisUtil.get(RedisConf.HOT_BLOG); //判断redis中是否有文章 if (StringUtils.isNotEmpty(jsonResult)) { List jsonResult2List = JsonUtils.jsonArrayToArrayList(jsonResult); IPage pageList = new Page(); pageList.setRecords(jsonResult2List); return pageList; } QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); Page<Blog> page = new Page<>(); page.setCurrent(0); String blogHotCount = sysParamsService.getSysParamsValueByKey(SysConf.BLOG_HOT_COUNT); if (StringUtils.isEmpty(blogHotCount)) { log.error(MessageConf.PLEASE_CONFIGURE_SYSTEM_PARAMS); } else { page.setSize(Long.valueOf(blogHotCount)); } queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); queryWrapper.eq(SQLConf.IS_PUBLISH, EPublish.PUBLISH); queryWrapper.orderByDesc(SQLConf.CLICK_COUNT); //因为首页并不需要显示内容,所以需要排除掉内容字段 queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SQLConf.CONTENT)); IPage<Blog> pageList = blogService.page(page, queryWrapper); List<Blog> list = pageList.getRecords(); list = setBlog(list); pageList.setRecords(list); // 将从数据库查询的数据缓存到redis中[避免list中没有数据而保存至redis的情况] if (list.size() > 0) { redisUtil.setEx(RedisConf.HOT_BLOG, JsonUtils.objectToJson(list), 1, TimeUnit.HOURS); } return pageList; } @Override public IPage<Blog> getNewBlog(Long currentPage, Long pageSize) { String blogNewCount = sysParamsService.getSysParamsValueByKey(SysConf.BLOG_NEW_COUNT); if (StringUtils.isEmpty(blogNewCount)) { log.error(MessageConf.PLEASE_CONFIGURE_SYSTEM_PARAMS); } // // 判断Redis中是否缓存了第一页的内容 // if (currentPage == 1L) { // //从Redis中获取内容 // String jsonResult = redisUtil.get(RedisConf.NEW_BLOG); // //判断redis中是否有文章 // if (StringUtils.isNotEmpty(jsonResult)) { // IPage pageList = JsonUtils.jsonToPojo(jsonResult, Page.class); // return pageList; // } // } QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); Page<Blog> page = new Page<>(); page.setCurrent(currentPage); page.setSize(Long.valueOf(blogNewCount)); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); queryWrapper.eq(BaseSQLConf.IS_PUBLISH, EPublish.PUBLISH); queryWrapper.orderByDesc(SQLConf.CREATE_TIME); //因为首页并不需要显示内容,所以需要排除掉内容字段 queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SQLConf.CONTENT)); IPage<Blog> pageList = blogService.page(page, queryWrapper); List<Blog> list = pageList.getRecords(); if (list.size() <= 0) { return pageList; } list = setBlog(list); pageList.setRecords(list); //将从最新博客缓存到redis中 // if (currentPage == 1L) { // redisUtil.setEx(RedisConf.NEW_BLOG, JsonUtils.objectToJson(pageList), 1, TimeUnit.HOURS); // } return pageList; } @Override public IPage<Blog> getBlogBySearch(Long currentPage, Long pageSize) { QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); Page<Blog> page = new Page<>(); page.setCurrent(currentPage); String blogNewCount = sysParamsService.getSysParamsValueByKey(SysConf.BLOG_NEW_COUNT); if (StringUtils.isEmpty(blogNewCount)) { log.error(MessageConf.PLEASE_CONFIGURE_SYSTEM_PARAMS); } else { page.setSize(Long.valueOf(blogNewCount)); } queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); queryWrapper.eq(BaseSQLConf.IS_PUBLISH, EPublish.PUBLISH); queryWrapper.orderByDesc(SQLConf.CREATE_TIME); IPage<Blog> pageList = blogService.page(page, queryWrapper); List<Blog> list = pageList.getRecords(); if (list.size() <= 0) { return pageList; } list = setBlog(list); pageList.setRecords(list); return pageList; } @Override public IPage<Blog> getBlogByTime(Long currentPage, Long pageSize) { QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); Page<Blog> page = new Page<>(); page.setCurrent(currentPage); page.setSize(pageSize); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); queryWrapper.eq(BaseSQLConf.IS_PUBLISH, EPublish.PUBLISH); queryWrapper.orderByDesc(SQLConf.CREATE_TIME); //因为首页并不需要显示内容,所以需要排除掉内容字段 queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SQLConf.CONTENT)); IPage<Blog> pageList = blogService.page(page, queryWrapper); List<Blog> list = pageList.getRecords(); list = setBlog(list); pageList.setRecords(list); return pageList; } @Override public Integer getBlogPraiseCountByUid(String uid) { Integer pariseCount = 0; if (StringUtils.isEmpty(uid)) { log.error("传入的UID为空"); return pariseCount; } //从Redis取出用户点赞数据 String pariseJsonResult = redisUtil.get(RedisConf.BLOG_PRAISE + RedisConf.SEGMENTATION + uid); if (!StringUtils.isEmpty(pariseJsonResult)) { pariseCount = Integer.parseInt(pariseJsonResult); } return pariseCount; } @Override public String praiseBlogByUid(String uid) { if (StringUtils.isEmpty(uid)) { return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT); } HttpServletRequest request = RequestHolder.getRequest(); // 如果用户登录了 if (request.getAttribute(SysConf.USER_UID) != null) { String userUid = request.getAttribute(SysConf.USER_UID).toString(); QueryWrapper<Comment> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(SQLConf.USER_UID, userUid); queryWrapper.eq(SQLConf.BLOG_UID, uid); queryWrapper.eq(SQLConf.TYPE, ECommentType.PRAISE); queryWrapper.last(SysConf.LIMIT_ONE); Comment praise = commentService.getOne(queryWrapper); if (praise != null) { return ResultUtil.errorWithMessage(MessageConf.YOU_HAVE_BEEN_PRISE); } } else { return ResultUtil.errorWithMessage(MessageConf.PLEASE_LOGIN_TO_PRISE); } Blog blog = blogService.getById(uid); String pariseJsonResult = redisUtil.get(RedisConf.BLOG_PRAISE + RedisConf.SEGMENTATION + uid); if (StringUtils.isEmpty(pariseJsonResult)) { //给该博客点赞数 redisUtil.set(RedisConf.BLOG_PRAISE + RedisConf.SEGMENTATION + uid, "1"); blog.setCollectCount(1); blog.updateById(); } else { Integer count = blog.getCollectCount() + 1; //给该博客点赞 +1 redisUtil.set(RedisConf.BLOG_PRAISE + RedisConf.SEGMENTATION + uid, count.toString()); blog.setCollectCount(count); blog.updateById(); } // 已登录用户,向评论表添加点赞数据 if (request.getAttribute(SysConf.USER_UID) != null) { String userUid = request.getAttribute(SysConf.USER_UID).toString(); Comment comment = new Comment(); comment.setUserUid(userUid); comment.setBlogUid(uid); comment.setSource(ECommentSource.BLOG_INFO.getCode()); comment.setType(ECommentType.PRAISE); comment.insert(); } return ResultUtil.successWithData(blog.getCollectCount()); } @Override public IPage<Blog> getSameBlogByTagUid(String tagUid) { QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); Page<Blog> page = new Page<>(); page.setCurrent(1); page.setSize(10); queryWrapper.like(SQLConf.TAG_UID, tagUid); queryWrapper.orderByDesc(SQLConf.CREATE_TIME); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); queryWrapper.eq(SQLConf.IS_PUBLISH, EPublish.PUBLISH); IPage<Blog> pageList = blogService.page(page, queryWrapper); List<Blog> list = pageList.getRecords(); list = blogService.setTagAndSortByBlogList(list); pageList.setRecords(list); return pageList; } @Override public IPage<Blog> getListByBlogSortUid(String blogSortUid, Long currentPage, Long pageSize) { //分页 Page<Blog> page = new Page<>(); page.setCurrent(currentPage); page.setSize(pageSize); QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); queryWrapper.orderByDesc(SQLConf.CREATE_TIME); queryWrapper.eq(BaseSQLConf.IS_PUBLISH, EPublish.PUBLISH); queryWrapper.eq(SQLConf.BLOG_SORT_UID, blogSortUid); //因为首页并不需要显示内容,所以需要排除掉内容字段 queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SQLConf.CONTENT)); IPage<Blog> pageList = blogService.page(page, queryWrapper); //给博客增加标签和分类 List<Blog> list = blogService.setTagAndSortAndPictureByBlogList(pageList.getRecords()); pageList.setRecords(list); return pageList; } @Override public Map<String, Object> getBlogByKeyword(String keywords, Long currentPage, Long pageSize) { final String keyword = keywords.trim(); QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); queryWrapper.and(wrapper -> wrapper.like(SQLConf.TITLE, keyword).or().like(SQLConf.SUMMARY, keyword)); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); queryWrapper.eq(SQLConf.IS_PUBLISH, EPublish.PUBLISH); queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SQLConf.CONTENT)); queryWrapper.orderByDesc(SQLConf.CLICK_COUNT); Page<Blog> page = new Page<>(); page.setCurrent(currentPage); page.setSize(pageSize); IPage<Blog> iPage = blogService.page(page, queryWrapper); List<Blog> blogList = iPage.getRecords(); List<String> blogSortUidList = new ArrayList<>(); Map<String, String> pictureMap = new HashMap<>(); final StringBuffer fileUids = new StringBuffer(); blogList.forEach(item -> { // 获取图片uid blogSortUidList.add(item.getBlogSortUid()); if (StringUtils.isNotEmpty(item.getFileUid())) { fileUids.append(item.getFileUid() + SysConf.FILE_SEGMENTATION); } // 给标题和简介设置高亮 item.setTitle(getHitCode(item.getTitle(), keyword)); item.setSummary(getHitCode(item.getSummary(), keyword)); }); // 调用图片接口,获取图片 String pictureList = null; if (fileUids != null) { pictureList = this.pictureFeignClient.getPicture(fileUids.toString(), SysConf.FILE_SEGMENTATION); } List<Map<String, Object>> picList = webUtil.getPictureMap(pictureList); picList.forEach(item -> { pictureMap.put(item.get(SQLConf.UID).toString(), item.get(SQLConf.URL).toString()); }); Collection<BlogSort> blogSortList = new ArrayList<>(); if (blogSortUidList.size() > 0) { blogSortList = blogSortService.listByIds(blogSortUidList); } Map<String, String> blogSortMap = new HashMap<>(); blogSortList.forEach(item -> { blogSortMap.put(item.getUid(), item.getSortName()); }); // 设置分类名 和 图片 blogList.forEach(item -> { if (blogSortMap.get(item.getBlogSortUid()) != null) { item.setBlogSortName(blogSortMap.get(item.getBlogSortUid())); } //获取图片 if (StringUtils.isNotEmpty(item.getFileUid())) { List<String> pictureUidsTemp = StringUtils.changeStringToString(item.getFileUid(), SysConf.FILE_SEGMENTATION); List<String> pictureListTemp = new ArrayList<>(); pictureUidsTemp.forEach(picture -> { pictureListTemp.add(pictureMap.get(picture)); }); // 只设置一张标题图 if (pictureListTemp.size() > 0) { item.setPhotoUrl(pictureListTemp.get(0)); } else { item.setPhotoUrl(""); } } }); Map<String, Object> map = new HashMap<>(); // 返回总记录数 map.put(SysConf.TOTAL, iPage.getTotal()); // 返回总页数 map.put(SysConf.TOTAL_PAGE, iPage.getPages()); // 返回当前页大小 map.put(SysConf.PAGE_SIZE, pageSize); // 返回当前页 map.put(SysConf.CURRENT_PAGE, iPage.getCurrent()); // 返回数据 map.put(SysConf.BLOG_LIST, blogList); return map; } @Override public IPage<Blog> searchBlogByTag(String tagUid, Long currentPage, Long pageSize) { Tag tag = tagService.getById(tagUid); if (tag != null) { HttpServletRequest request = RequestHolder.getRequest(); String ip = IpUtils.getIpAddr(request); //从Redis取出数据,判断该用户24小时内,是否点击过该标签 String jsonResult = redisUtil.get(RedisConf.TAG_CLICK + RedisConf.SEGMENTATION + ip + "#" + tagUid); if (StringUtils.isEmpty(jsonResult)) { //给标签点击数增加 int clickCount = tag.getClickCount() + 1; tag.setClickCount(clickCount); tag.updateById(); //将该用户点击记录存储到redis中, 24小时后过期 redisUtil.setEx(RedisConf.TAG_CLICK + RedisConf.SEGMENTATION + ip + RedisConf.WELL_NUMBER + tagUid, clickCount + "", 24, TimeUnit.HOURS); } } QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); Page<Blog> page = new Page<>(); page.setCurrent(currentPage); page.setSize(pageSize); queryWrapper.like(SQLConf.TAG_UID, tagUid); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); queryWrapper.eq(BaseSQLConf.IS_PUBLISH, EPublish.PUBLISH); queryWrapper.orderByDesc(SQLConf.CREATE_TIME); queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SysConf.CONTENT)); IPage<Blog> pageList = blogService.page(page, queryWrapper); List<Blog> list = pageList.getRecords(); list = blogService.setTagAndSortAndPictureByBlogList(list); pageList.setRecords(list); return pageList; } @Override public IPage<Blog> searchBlogByBlogSort(String blogSortUid, Long currentPage, Long pageSize) { BlogSort blogSort = blogSortService.getById(blogSortUid); if (blogSort != null) { HttpServletRequest request = RequestHolder.getRequest(); String ip = IpUtils.getIpAddr(request); //从Redis取出数据,判断该用户24小时内,是否点击过该分类 String jsonResult = redisUtil.get(RedisConf.TAG_CLICK + RedisConf.SEGMENTATION + ip + RedisConf.WELL_NUMBER + blogSortUid); if (StringUtils.isEmpty(jsonResult)) { //给标签点击数增加 int clickCount = blogSort.getClickCount() + 1; blogSort.setClickCount(clickCount); blogSort.updateById(); //将该用户点击记录存储到redis中, 24小时后过期 redisUtil.setEx(RedisConf.TAG_CLICK + RedisConf.SEGMENTATION + ip + RedisConf.WELL_NUMBER + blogSortUid, clickCount + "", 24, TimeUnit.HOURS); } } QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); Page<Blog> page = new Page<>(); page.setCurrent(currentPage); page.setSize(pageSize); queryWrapper.eq(SQLConf.BLOG_SORT_UID, blogSortUid); queryWrapper.orderByDesc(SQLConf.CREATE_TIME); queryWrapper.eq(BaseSQLConf.IS_PUBLISH, EPublish.PUBLISH); queryWrapper.eq(BaseSQLConf.STATUS, EStatus.ENABLE); // 排除博客详情 queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SysConf.CONTENT)); IPage<Blog> pageList = blogService.page(page, queryWrapper); List<Blog> list = pageList.getRecords(); list = blogService.setTagAndSortAndPictureByBlogList(list); pageList.setRecords(list); return pageList; } @Override public IPage<Blog> searchBlogByAuthor(String author, Long currentPage, Long pageSize) { QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); Page<Blog> page = new Page<>(); page.setCurrent(currentPage); page.setSize(pageSize); queryWrapper.eq(SQLConf.AUTHOR, author); queryWrapper.eq(BaseSQLConf.IS_PUBLISH, EPublish.PUBLISH); queryWrapper.eq(BaseSQLConf.STATUS, EStatus.ENABLE); queryWrapper.orderByDesc(SQLConf.CREATE_TIME); queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SysConf.CONTENT)); IPage<Blog> pageList = blogService.page(page, queryWrapper); List<Blog> list = pageList.getRecords(); list = blogService.setTagAndSortAndPictureByBlogList(list); pageList.setRecords(list); return pageList; } @Override public String getBlogTimeSortList() { //从Redis中获取内容 String monthResult = redisUtil.get(SysConf.MONTH_SET); //判断redis中时候包含归档的内容 if (StringUtils.isNotEmpty(monthResult)) { List list = JsonUtils.jsonArrayToArrayList(monthResult); return ResultUtil.successWithData(list); } // 第一次启动的时候归档 QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); queryWrapper.orderByDesc(SQLConf.CREATE_TIME); queryWrapper.eq(SQLConf.IS_PUBLISH, EPublish.PUBLISH); //因为首页并不需要显示内容,所以需要排除掉内容字段 queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SQLConf.CONTENT)); List<Blog> list = blogService.list(queryWrapper); //给博客增加标签、分类、图片 list = blogService.setTagAndSortAndPictureByBlogList(list); Map<String, List<Blog>> map = new HashMap<>(); Iterator iterable = list.iterator(); Set<String> monthSet = new TreeSet<>(); while (iterable.hasNext()) { Blog blog = (Blog) iterable.next(); Date createTime = blog.getCreateTime(); String month = new SimpleDateFormat("yyyy年MM月").format(createTime).toString(); monthSet.add(month); if (map.get(month) == null) { List<Blog> blogList = new ArrayList<>(); blogList.add(blog); map.put(month, blogList); } else { List<Blog> blogList = map.get(month); blogList.add(blog); map.put(month, blogList); } } // 缓存该月份下的所有文章 key: 月份 value:月份下的所有文章 map.forEach((key, value) -> { redisUtil.set(SysConf.BLOG_SORT_BY_MONTH + SysConf.REDIS_SEGMENTATION + key, JsonUtils.objectToJson(value).toString()); }); //将从数据库查询的数据缓存到redis中 redisUtil.set(SysConf.MONTH_SET, JsonUtils.objectToJson(monthSet).toString()); return ResultUtil.successWithData(monthSet); } @Override public String getArticleByMonth(String monthDate) { if (StringUtils.isEmpty(monthDate)) { return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT); } //从Redis中获取内容 String contentResult = redisUtil.get(SysConf.BLOG_SORT_BY_MONTH + SysConf.REDIS_SEGMENTATION + monthDate); //判断redis中时候包含该日期下的文章 if (StringUtils.isNotEmpty(contentResult)) { List list = JsonUtils.jsonArrayToArrayList(contentResult); return ResultUtil.successWithData(list); } // 第一次启动的时候归档 QueryWrapper<Blog> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE); queryWrapper.orderByDesc(SQLConf.CREATE_TIME); queryWrapper.eq(BaseSQLConf.IS_PUBLISH, EPublish.PUBLISH); //因为首页并不需要显示内容,所以需要排除掉内容字段 queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SQLConf.CONTENT)); List<Blog> list = blogService.list(queryWrapper); //给博客增加标签、分类、图片 list = blogService.setTagAndSortAndPictureByBlogList(list); Map<String, List<Blog>> map = new HashMap<>(); Iterator iterable = list.iterator(); Set<String> monthSet = new TreeSet<>(); while (iterable.hasNext()) { Blog blog = (Blog) iterable.next(); Date createTime = blog.getCreateTime(); String month = new SimpleDateFormat("yyyy年MM月").format(createTime).toString(); monthSet.add(month); if (map.get(month) == null) { List<Blog> blogList = new ArrayList<>(); blogList.add(blog); map.put(month, blogList); } else { List<Blog> blogList = map.get(month); blogList.add(blog); map.put(month, blogList); } } // 缓存该月份下的所有文章 key: 月份 value:月份下的所有文章 map.forEach((key, value) -> { redisUtil.set(SysConf.BLOG_SORT_BY_MONTH + SysConf.REDIS_SEGMENTATION + key, JsonUtils.objectToJson(value).toString()); }); //将从数据库查询的数据缓存到redis中 redisUtil.set(SysConf.MONTH_SET, JsonUtils.objectToJson(monthSet)); return ResultUtil.successWithData(map.get(monthDate)); } /** * 添加时校验 * * @param count * @param level * @return */ private String addVerdict(Integer count, Integer level) { //添加的时候进行判断 switch (level) { case ELevel.FIRST: { Long blogFirstCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.BLOG_FIRST_COUNT)); if (count > blogFirstCount) { return ResultUtil.errorWithMessage("一级推荐不能超过" + blogFirstCount + "个"); } } break; case ELevel.SECOND: { Long blogSecondCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.BLOG_SECOND_COUNT)); if (count > blogSecondCount) { return ResultUtil.errorWithMessage("二级推荐不能超过" + blogSecondCount + "个"); } } break; case ELevel.THIRD: { Long blogThirdCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.BLOG_THIRD_COUNT)); if (count > blogThirdCount) { return ResultUtil.errorWithMessage("三级推荐不能超过" + blogThirdCount + "个"); } } break; case ELevel.FOURTH: { Long blogFourthCount = Long.valueOf(sysParamsService.getSysParamsValueByKey(SysConf.BLOG_FOURTH_COUNT)); if (count > blogFourthCount) { return ResultUtil.errorWithMessage("四级推荐不能超过" + blogFourthCount + "个"); } } break; default: { } } return null; } /** * 保存成功后,需要发送消息到solr 和 redis * * @param isSave * @param blog */ private void updateSolrAndRedis(Boolean isSave, Blog blog) { // 保存操作,并且文章已设置发布 if (isSave && EPublish.PUBLISH.equals(blog.getIsPublish())) { Map<String, Object> map = new HashMap<>(); map.put(SysConf.COMMAND, SysConf.ADD); map.put(SysConf.BLOG_UID, blog.getUid()); map.put(SysConf.LEVEL, blog.getLevel()); map.put(SysConf.CREATE_TIME, blog.getCreateTime()); //发送到RabbitMq rabbitTemplate.convertAndSend(SysConf.EXCHANGE_DIRECT, SysConf.MOGU_BLOG, map); } else if (EPublish.NO_PUBLISH.equals(blog.getIsPublish())) { //这是需要做的是,是删除redis中的该条博客数据 Map<String, Object> map = new HashMap<>(); map.put(SysConf.COMMAND, SysConf.EDIT); map.put(SysConf.BLOG_UID, blog.getUid()); map.put(SysConf.LEVEL, blog.getLevel()); map.put(SysConf.CREATE_TIME, blog.getCreateTime()); //发送到RabbitMq rabbitTemplate.convertAndSend(SysConf.EXCHANGE_DIRECT, SysConf.MOGU_BLOG, map); } } /** * 设置博客的分类标签和内容 * * @param list * @return */ private List<Blog> setBlog(List<Blog> list) { final StringBuffer fileUids = new StringBuffer(); List<String> sortUids = new ArrayList<>(); List<String> tagUids = new ArrayList<>(); list.forEach(item -> { if (StringUtils.isNotEmpty(item.getFileUid())) { fileUids.append(item.getFileUid() + SysConf.FILE_SEGMENTATION); } if (StringUtils.isNotEmpty(item.getBlogSortUid())) { sortUids.add(item.getBlogSortUid()); } if (StringUtils.isNotEmpty(item.getTagUid())) { tagUids.add(item.getTagUid()); } }); String pictureList = null; if (fileUids != null) { pictureList = this.pictureFeignClient.getPicture(fileUids.toString(), SysConf.FILE_SEGMENTATION); } List<Map<String, Object>> picList = webUtil.getPictureMap(pictureList); Collection<BlogSort> sortList = new ArrayList<>(); Collection<Tag> tagList = new ArrayList<>(); if (sortUids.size() > 0) { sortList = blogSortService.listByIds(sortUids); } if (tagUids.size() > 0) { tagList = tagService.listByIds(tagUids); } Map<String, BlogSort> sortMap = new HashMap<>(); Map<String, Tag> tagMap = new HashMap<>(); Map<String, String> pictureMap = new HashMap<>(); sortList.forEach(item -> { sortMap.put(item.getUid(), item); }); tagList.forEach(item -> { tagMap.put(item.getUid(), item); }); picList.forEach(item -> { pictureMap.put(item.get(SQLConf.UID).toString(), item.get(SQLConf.URL).toString()); }); for (Blog item : list) { //设置分类 if (StringUtils.isNotEmpty(item.getBlogSortUid())) { item.setBlogSort(sortMap.get(item.getBlogSortUid())); } //获取标签 if (StringUtils.isNotEmpty(item.getTagUid())) { List<String> tagUidsTemp = StringUtils.changeStringToString(item.getTagUid(), SysConf.FILE_SEGMENTATION); List<Tag> tagListTemp = new ArrayList<Tag>(); tagUidsTemp.forEach(tag -> { if (tagMap.get(tag) != null) { tagListTemp.add(tagMap.get(tag)); } }); item.setTagList(tagListTemp); } //获取图片 if (StringUtils.isNotEmpty(item.getFileUid())) { List<String> pictureUidsTemp = StringUtils.changeStringToString(item.getFileUid(), SysConf.FILE_SEGMENTATION); List<String> pictureListTemp = new ArrayList<>(); pictureUidsTemp.forEach(picture -> { pictureListTemp.add(pictureMap.get(picture)); }); item.setPhotoList(pictureListTemp); } } return list; } /** * 添加高亮 * * @param str * @param keyword * @return */ private String getHitCode(String str, String keyword) { if (StringUtils.isEmpty(keyword) || StringUtils.isEmpty(str)) { return str; } String startStr = "<span style = 'color:red'>"; String endStr = "</span>"; // 判断关键字是否直接是搜索的内容,否者直接返回 if (str.equals(keyword)) { return startStr + str + endStr; } String lowerCaseStr = str.toLowerCase(); String lowerKeyword = keyword.toLowerCase(); String[] lowerCaseArray = lowerCaseStr.split(lowerKeyword); Boolean isEndWith = lowerCaseStr.endsWith(lowerKeyword); // 计算分割后的字符串位置 Integer count = 0; List<Map<String, Integer>> list = new ArrayList<>(); List<Map<String, Integer>> keyList = new ArrayList<>(); for (int a = 0; a < lowerCaseArray.length; a++) { // 将切割出来的存储map Map<String, Integer> map = new HashMap<>(); Map<String, Integer> keyMap = new HashMap<>(); map.put("startIndex", count); Integer len = lowerCaseArray[a].length(); count += len; map.put("endIndex", count); list.add(map); if (a < lowerCaseArray.length - 1 || isEndWith) { // 将keyword存储map keyMap.put("startIndex", count); count += keyword.length(); keyMap.put("endIndex", count); keyList.add(keyMap); } } // 截取切割对象 List<String> arrayList = new ArrayList<>(); for (Map<String, Integer> item : list) { Integer start = item.get("startIndex"); Integer end = item.get("endIndex"); String itemStr = str.substring(start, end); arrayList.add(itemStr); } // 截取关键字 List<String> keyArrayList = new ArrayList<>(); for (Map<String, Integer> item : keyList) { Integer start = item.get("startIndex"); Integer end = item.get("endIndex"); String itemStr = str.substring(start, end); keyArrayList.add(itemStr); } StringBuffer sb = new StringBuffer(); for (int a = 0; a < arrayList.size(); a++) { sb.append(arrayList.get(a)); if (a < arrayList.size() - 1 || isEndWith) { sb.append(startStr); sb.append(keyArrayList.get(a)); sb.append(endStr); } } return sb.toString(); } }
package com.java2nb.novel.book.service.impl; import com.github.pagehelper.PageHelper; import com.java2nb.novel.book.entity.*; import com.java2nb.novel.book.feign.UserFeignClient; import com.java2nb.novel.book.mapper.*; import com.java2nb.novel.book.service.BookService; import com.java2nb.novel.book.vo.BookCommentVO; import com.java2nb.novel.common.bean.PageBean; import com.java2nb.novel.common.enums.ResponseStatus; import com.java2nb.novel.common.exception.BusinessException; import com.java2nb.novel.common.utils.BeanUtil; import com.java2nb.novel.user.entity.User; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.mybatis.dynamic.sql.SortSpecification; import org.mybatis.dynamic.sql.render.RenderingStrategies; import org.mybatis.dynamic.sql.select.render.SelectStatementProvider; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import tk.mybatis.orderbyhelper.OrderByHelper; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import static com.java2nb.novel.book.mapper.BookDynamicSqlSupport.book; import static org.mybatis.dynamic.sql.SqlBuilder.*; import static org.mybatis.dynamic.sql.select.SelectDSL.select; /** * 小说服务接口实现 * * @author xiongxiaoyang * @version 1.0 * @since 2020/5/28 */ @Service @RequiredArgsConstructor public class BookServiceImpl implements BookService { private final BookMapper bookMapper; private final BookCategoryMapper bookCategoryMapper; private final BookIndexMapper bookIndexMapper; private final BookContentMapper bookContentMapper; private final BookCommentMapper bookCommentMapper; private final UserFeignClient userFeignClient; @Override public List<Book> queryBookByMinUpdateTime(Date minDate, int limit) { return bookMapper.selectMany(select(book.allColumns()) .from(book) .where(BookDynamicSqlSupport.updateTime, isGreaterThan(minDate)) .orderBy(BookDynamicSqlSupport.updateTime) .limit(limit) .build() .render(RenderingStrategies.MYBATIS3)); } @Override public List<Book> queryBookByIds(List<Long> ids) { return bookMapper.selectMany(select(BookDynamicSqlSupport.id, BookDynamicSqlSupport.catId, BookDynamicSqlSupport.catName, BookDynamicSqlSupport.bookName, BookDynamicSqlSupport.authorName, BookDynamicSqlSupport.lastIndexId, BookDynamicSqlSupport.lastIndexName, BookDynamicSqlSupport.lastIndexUpdateTime, BookDynamicSqlSupport.picUrl, BookDynamicSqlSupport.bookDesc, BookDynamicSqlSupport.score) .from(book) .where(BookDynamicSqlSupport.id, isIn(ids)) .build() .render(RenderingStrategies.MYBATIS3) ); } @Override public List<Book> listRank(Byte type, Integer limit) { SortSpecification sortSpecification = BookDynamicSqlSupport.visitCount.descending(); switch (type) { case 1: { //最新入库排序 sortSpecification = BookDynamicSqlSupport.createTime.descending(); break; } case 2: { //最新更新时间排序 sortSpecification = BookDynamicSqlSupport.lastIndexUpdateTime.descending(); break; } case 3: { //评论数量排序 sortSpecification = BookDynamicSqlSupport.commentCount.descending(); break; } default: { break; } } SelectStatementProvider selectStatement = select(BookDynamicSqlSupport.id, BookDynamicSqlSupport.catId, BookDynamicSqlSupport.catName, BookDynamicSqlSupport.bookName, BookDynamicSqlSupport.lastIndexId, BookDynamicSqlSupport.lastIndexName, BookDynamicSqlSupport.authorId, BookDynamicSqlSupport.authorName, BookDynamicSqlSupport.picUrl, BookDynamicSqlSupport.bookDesc, BookDynamicSqlSupport.wordCount, BookDynamicSqlSupport.lastIndexUpdateTime) .from(book) .where(BookDynamicSqlSupport.wordCount, isGreaterThan(0)) .orderBy(sortSpecification) .limit(limit) .build() .render(RenderingStrategies.MYBATIS3); return bookMapper.selectMany(selectStatement); } @Override public List<BookCategory> listBookCategory() { SelectStatementProvider selectStatementProvider = select(BookCategoryDynamicSqlSupport.id, BookCategoryDynamicSqlSupport.name, BookCategoryDynamicSqlSupport.workDirection) .from(BookCategoryDynamicSqlSupport.bookCategory) .orderBy(BookCategoryDynamicSqlSupport.sort) .build() .render(RenderingStrategies.MYBATIS3); return bookCategoryMapper.selectMany(selectStatementProvider); } @Override public Book queryBookDetail(Long id) { SelectStatementProvider selectStatement = select(BookDynamicSqlSupport.book.allColumns()) .from(BookDynamicSqlSupport.book) .where(BookDynamicSqlSupport.id, isEqualTo(id)) .limit(1) .build() .render(RenderingStrategies.MYBATIS3); List<Book> books = bookMapper.selectMany(selectStatement); return books.size() > 0 ? books.get(0) : null; } @Override public void addVisitCount(Long bookId, int addCount) { bookMapper.addVisitCount(bookId, addCount); } @Override public long queryIndexCount(Long bookId) { SelectStatementProvider selectStatement = select(count(BookIndexDynamicSqlSupport.id)) .from(BookIndexDynamicSqlSupport.bookIndex) .where(BookIndexDynamicSqlSupport.bookId, isEqualTo(bookId)) .build() .render(RenderingStrategies.MYBATIS3); return bookIndexMapper.count(selectStatement); } @Override public BookContent queryBookContent(Long bookIndexId) { SelectStatementProvider selectStatement = select(BookContentDynamicSqlSupport.id, BookContentDynamicSqlSupport.content) .from(BookContentDynamicSqlSupport.bookContent) .where(BookContentDynamicSqlSupport.indexId, isEqualTo(bookIndexId)) .limit(1) .build() .render(RenderingStrategies.MYBATIS3); return bookContentMapper.selectMany(selectStatement).get(0); } @Override public List<Book> listRecBookByCatId(Integer catId) { return bookMapper.listRecBookByCatId(catId); } @Override public PageBean<BookComment> listBookCommentByPage(Long bookId, int page, int pageSize) { //分页查询小说评论数据 PageHelper.startPage(page, pageSize); List<BookComment> bookCommentList = bookCommentMapper.selectMany( select(BookCommentDynamicSqlSupport.id, BookCommentDynamicSqlSupport.bookId, BookCommentDynamicSqlSupport.createUserId, BookCommentDynamicSqlSupport.commentContent, BookCommentDynamicSqlSupport.replyCount, BookCommentDynamicSqlSupport.createTime) .from(BookCommentDynamicSqlSupport.bookComment) .where(BookCommentDynamicSqlSupport.bookId, isEqualTo(bookId)) .orderBy(BookCommentDynamicSqlSupport.createTime.descending()) .build() .render(RenderingStrategies.MYBATIS3)); //根据评论人ID集合查询出评论人集合数据 List<User> users = userFeignClient.queryById(bookCommentList.stream().map(BookComment::getCreateUserId).collect(Collectors.toList())); Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2)); //将评论数据和评论人数据关联起来 TODO 评论表增加用户相关的冗余字段,用户信息更新后用户服务通过mq发送message,其他服务消费message更新所有的冗余字段 List<BookCommentVO> resultList = new ArrayList<>(bookCommentList.size()); bookCommentList.forEach(bookComment->{ BookCommentVO bookCommentVO = new BookCommentVO(); BeanUtils.copyProperties(bookComment, bookCommentVO); User user = userMap.get(bookComment.getCreateUserId()); if (user != null) { bookCommentVO.setCreateUserName(user.getUsername()); bookCommentVO.setCreateUserPhoto(user.getUserPhoto()); } resultList.add(bookCommentVO); }); PageBean<BookComment> pageBean = new PageBean<>(bookCommentList); pageBean.setList(resultList); return pageBean; } @Override public List<BookIndex> listNewIndex(Long bookId, String orderBy, Integer limit) { if (StringUtils.isNotBlank(orderBy)) { OrderByHelper.orderBy(orderBy); } if (limit != null) { PageHelper.startPage(1, limit); } SelectStatementProvider selectStatement = select(BookIndexDynamicSqlSupport.id, BookIndexDynamicSqlSupport.bookId, BookIndexDynamicSqlSupport.indexNum, BookIndexDynamicSqlSupport.indexName, BookIndexDynamicSqlSupport.updateTime, BookIndexDynamicSqlSupport.isVip) .from(BookIndexDynamicSqlSupport.bookIndex) .where(BookIndexDynamicSqlSupport.bookId, isEqualTo(bookId)) .build() .render(RenderingStrategies.MYBATIS3); return bookIndexMapper.selectMany(selectStatement); } @Override public Long queryFirstBookIndexId(Long bookId) { SelectStatementProvider selectStatement = select(BookIndexDynamicSqlSupport.id) .from(BookIndexDynamicSqlSupport.bookIndex) .where(BookIndexDynamicSqlSupport.bookId, isEqualTo(bookId)) .orderBy(BookIndexDynamicSqlSupport.indexNum) .limit(1) .build() .render(RenderingStrategies.MYBATIS3); return bookIndexMapper.selectMany(selectStatement).get(0).getId(); } @Override public BookIndex queryBookIndex(Long bookIndexId) { SelectStatementProvider selectStatement = select(BookIndexDynamicSqlSupport.id, BookIndexDynamicSqlSupport.bookId, BookIndexDynamicSqlSupport.indexNum, BookIndexDynamicSqlSupport.indexName, BookIndexDynamicSqlSupport.wordCount, BookIndexDynamicSqlSupport.updateTime, BookIndexDynamicSqlSupport.isVip) .from(BookIndexDynamicSqlSupport.bookIndex) .where(BookIndexDynamicSqlSupport.id, isEqualTo(bookIndexId)) .limit(1) .build() .render(RenderingStrategies.MYBATIS3); return bookIndexMapper.selectMany(selectStatement).get(0); } @Override public Map<String, Long> queryPreAndNextBookIndexId(Long bookId, Integer indexNum) { Map<String, Long> result = new HashMap<>(2); SelectStatementProvider selectStatement = select(BookIndexDynamicSqlSupport.id) .from(BookIndexDynamicSqlSupport.bookIndex) .where(BookIndexDynamicSqlSupport.bookId, isEqualTo(bookId)) .and(BookIndexDynamicSqlSupport.indexNum, isLessThan(indexNum)) .orderBy(BookIndexDynamicSqlSupport.indexNum.descending()) .limit(1) .build() .render(RenderingStrategies.MYBATIS3); List<BookIndex> list = bookIndexMapper.selectMany(selectStatement); if (list.size() == 0) { result.put("preBookIndexId", 0L); } else { result.put("preBookIndexId", list.get(0).getId()); } selectStatement = select(BookIndexDynamicSqlSupport.id) .from(BookIndexDynamicSqlSupport.bookIndex) .where(BookIndexDynamicSqlSupport.bookId, isEqualTo(bookId)) .and(BookIndexDynamicSqlSupport.indexNum, isGreaterThan(indexNum)) .orderBy(BookIndexDynamicSqlSupport.indexNum) .limit(1) .build() .render(RenderingStrategies.MYBATIS3); list = bookIndexMapper.selectMany(selectStatement); if (list.size() == 0) { result.put("nextBookIndexId", 0L); } else { result.put("nextBookIndexId", list.get(0).getId()); } return result; } @Transactional(rollbackFor = Exception.class) @Override public void addBookComment(Long userId, BookComment comment) { //判断该用户是否已评论过该书籍 SelectStatementProvider selectStatement = select(count(BookCommentDynamicSqlSupport.id)) .from(BookCommentDynamicSqlSupport.bookComment) .where(BookCommentDynamicSqlSupport.createUserId, isEqualTo(userId)) .and(BookCommentDynamicSqlSupport.bookId, isEqualTo(comment.getBookId())) .build() .render(RenderingStrategies.MYBATIS3); if (bookCommentMapper.count(selectStatement) > 0) { throw new BusinessException(ResponseStatus.HAS_COMMENTS); } //增加评论 comment.setCreateUserId(userId); comment.setCreateTime(new Date()); bookCommentMapper.insertSelective(comment); //增加书籍评论数 bookMapper.addCommentCount(comment.getBookId()); } @Override public PageBean<BookComment> listUserCommentByPage(Long userId, int page, int pageSize) { PageHelper.startPage(page, pageSize); return new PageBean<>(bookCommentMapper.selectMany( select(BookCommentDynamicSqlSupport.id, BookCommentDynamicSqlSupport.bookId, BookCommentDynamicSqlSupport.createUserId, BookCommentDynamicSqlSupport.commentContent, BookCommentDynamicSqlSupport.replyCount, BookCommentDynamicSqlSupport.createTime) .from(BookCommentDynamicSqlSupport.bookComment) .where(BookCommentDynamicSqlSupport.createUserId, isEqualTo(userId)) .orderBy(BookCommentDynamicSqlSupport.createTime.descending()) .build() .render(RenderingStrategies.MYBATIS3))); } @Override public List<Book> queryNetworkPicBooks(String localPicPrefix, Integer limit) { return bookMapper.selectMany( select(BookDynamicSqlSupport.id, BookDynamicSqlSupport.picUrl) .from(book) .where(BookDynamicSqlSupport.picUrl, isLike("http%")) .and(BookDynamicSqlSupport.picUrl, isNotLike(localPicPrefix)) .limit(limit) .build() .render(RenderingStrategies.MYBATIS3)); } @Override public void updateBookPic(String picUrl, Long bookId) { bookMapper.update(update(book) .set(BookDynamicSqlSupport.picUrl) .equalTo(picUrl) .set(BookDynamicSqlSupport.updateTime) .equalTo(new Date()) .where(BookDynamicSqlSupport.id, isEqualTo(bookId)) .build() .render(RenderingStrategies.MYBATIS3)); } }
package com.java2nb.novel.user.service.impl; import com.github.pagehelper.PageHelper; import com.java2nb.novel.book.entity.Book; import com.java2nb.novel.common.bean.PageBean; import com.java2nb.novel.common.bean.UserDetails; import com.java2nb.novel.common.enums.ResponseStatus; import com.java2nb.novel.common.exception.BusinessException; import com.java2nb.novel.common.utils.IdWorker; import com.java2nb.novel.common.utils.MD5Util; import com.java2nb.novel.user.entity.User; import com.java2nb.novel.user.entity.UserBookshelf; import com.java2nb.novel.user.entity.UserFeedback; import com.java2nb.novel.user.entity.UserReadHistory; import com.java2nb.novel.user.feign.BookFeignClient; import com.java2nb.novel.user.mapper.*; import com.java2nb.novel.user.service.UserService; import com.java2nb.novel.user.vo.BookReadHistoryVO; import com.java2nb.novel.user.vo.BookShelfVO; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.Charsets; import org.mybatis.dynamic.sql.delete.render.DeleteStatementProvider; import org.mybatis.dynamic.sql.render.RenderingStrategies; import org.mybatis.dynamic.sql.select.render.SelectStatementProvider; import org.mybatis.dynamic.sql.update.render.UpdateStatementProvider; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import static com.java2nb.novel.user.mapper.UserBookshelfDynamicSqlSupport.userBookshelf; import static com.java2nb.novel.user.mapper.UserReadHistoryDynamicSqlSupport.userReadHistory; import static org.mybatis.dynamic.sql.SqlBuilder.*; import static org.mybatis.dynamic.sql.select.SelectDSL.select; /** * 小说服务接口实现 * * @author xiongxiaoyang * @version 1.0 * @since 2020/5/28 */ @Service @Slf4j @RequiredArgsConstructor public class UserServiceImpl implements UserService { private final UserMapper userMapper; private final UserBookshelfMapper userBookshelfMapper; private final UserReadHistoryMapper userReadHistoryMapper; private final UserFeedbackMapper userFeedbackMapper; private final BookFeignClient bookFeignClient; @Override public User queryByUsernameAndPassword(String username, String password) { List<User> users = userMapper.selectMany( select(UserDynamicSqlSupport.id, UserDynamicSqlSupport.username, UserDynamicSqlSupport.nickName) .from(UserDynamicSqlSupport.user) .where(UserDynamicSqlSupport.username, isEqualTo(username)) .and(UserDynamicSqlSupport.password, isEqualTo(MD5Util.MD5Encode(password, Charsets.UTF_8.name()))) .limit(1) .build() .render(RenderingStrategies.MYBATIS3)); return users.size() > 0 ? users.get(0) : null; } @Override public UserDetails login(User user) { //根据用户名密码查询记录 user = queryByUsernameAndPassword(user.getUsername(), user.getPassword()); if (user == null) { throw new BusinessException(ResponseStatus.USERNAME_PASS_ERROR); } //生成UserDetail对象并返回 UserDetails userDetails = new UserDetails(); userDetails.setId(user.getId()); userDetails.setNickName(user.getNickName()); userDetails.setUsername(user.getUsername()); return userDetails; } @Override public List<User> queryById(List<Long> ids) { return userMapper.selectMany( select(UserDynamicSqlSupport.id, UserDynamicSqlSupport.username, UserDynamicSqlSupport.userPhoto) .from(UserDynamicSqlSupport.user) .where(UserDynamicSqlSupport.id, isIn(ids)).build() .render(RenderingStrategies.MYBATIS3)); } @Override public UserDetails register(User user) { //查询用户名是否已注册 SelectStatementProvider selectStatement = select(count(UserDynamicSqlSupport.id)) .from(UserDynamicSqlSupport.user) .where(UserDynamicSqlSupport.username, isEqualTo(user.getUsername())) .build() .render(RenderingStrategies.MYBATIS3); long count = userMapper.count(selectStatement); if (count > 0) { //用户名已注册 throw new BusinessException(ResponseStatus.USERNAME_EXIST); } User entity = new User(); BeanUtils.copyProperties(user, entity); //数据库生成注册记录 Long id = new IdWorker().nextId(); entity.setId(id); entity.setNickName(entity.getUsername()); Date currentDate = new Date(); entity.setCreateTime(currentDate); entity.setUpdateTime(currentDate); entity.setPassword(MD5Util.MD5Encode(entity.getPassword(), Charsets.UTF_8.name())); userMapper.insertSelective(entity); //生成UserDetail对象并返回 UserDetails userDetails = new UserDetails(); userDetails.setId(id); userDetails.setUsername(entity.getUsername()); userDetails.setNickName(entity.getNickName()); return userDetails; } @Override public Boolean queryIsInShelf(Long userId, Long bookId) { SelectStatementProvider selectStatement = select(count(UserBookshelfDynamicSqlSupport.id)) .from(userBookshelf) .where(UserBookshelfDynamicSqlSupport.userId, isEqualTo(userId)) .and(UserBookshelfDynamicSqlSupport.bookId, isEqualTo(bookId)) .build() .render(RenderingStrategies.MYBATIS3); return userBookshelfMapper.count(selectStatement) > 0; } @Override public void addToBookShelf(Long userId, Long bookId, Long preContentId) { if (!queryIsInShelf(userId, bookId)) { UserBookshelf shelf = new UserBookshelf(); shelf.setUserId(userId); shelf.setBookId(bookId); shelf.setPreContentId(preContentId); shelf.setCreateTime(new Date()); userBookshelfMapper.insert(shelf); } } @Override public void removeFromBookShelf(Long userId, Long bookId) { DeleteStatementProvider deleteStatement = deleteFrom(userBookshelf) .where(UserBookshelfDynamicSqlSupport.userId, isEqualTo(userId)) .and(UserBookshelfDynamicSqlSupport.bookId, isEqualTo(bookId)) .build() .render(RenderingStrategies.MYBATIS3); userBookshelfMapper.delete(deleteStatement); } @Override public PageBean<UserBookshelf> listBookShelfByPage(Long userId, int page, int pageSize) { PageHelper.startPage(page, pageSize); List<UserBookshelf> userBookshelves = userBookshelfMapper.selectMany( select(UserBookshelfDynamicSqlSupport.bookId, UserBookshelfDynamicSqlSupport.preContentId) .from(userBookshelf) .where(UserBookshelfDynamicSqlSupport.userId, isEqualTo(userId)) .orderBy(UserBookshelfDynamicSqlSupport.createTime.descending()) .build() .render(RenderingStrategies.MYBATIS3)); List<Book> books = bookFeignClient.queryBookByIds(userBookshelves.stream().map(UserBookshelf::getBookId).collect(Collectors.toList())); Map<Long, Book> booksById = books.stream().collect(Collectors.toMap(Book::getId, Function.identity(), (key1, key2) -> key2)); //TODO 书架表增加书籍相关的冗余字段,书籍信息更新后小说服务通过mq发送message,其他服务消费message更新所有的冗余字段 List<BookShelfVO> resultList = new ArrayList<>(booksById.size()); userBookshelves.forEach(bookshelf->{ BookShelfVO bookShelfVO = new BookShelfVO(); BeanUtils.copyProperties(bookshelf, bookShelfVO); Book book = booksById.get(bookshelf.getBookId()); if (book != null) { BeanUtils.copyProperties(book, bookShelfVO); resultList.add(bookShelfVO); } }); PageBean<UserBookshelf> pageBean = new PageBean<>(userBookshelves); pageBean.setList(resultList); return pageBean; } @Override public PageBean<UserReadHistory> listReadHistoryByPage(Long userId, int page, int pageSize) { PageHelper.startPage(page, pageSize); List<UserReadHistory> userReadHistories = userReadHistoryMapper.selectMany( select(UserReadHistoryDynamicSqlSupport.bookId, UserReadHistoryDynamicSqlSupport.preContentId) .from(userReadHistory) .where(UserReadHistoryDynamicSqlSupport.userId, isEqualTo(userId)) .orderBy(UserReadHistoryDynamicSqlSupport.createTime.descending()) .build() .render(RenderingStrategies.MYBATIS3)); List<Book> books = bookFeignClient.queryBookByIds(userReadHistories.stream().map(UserReadHistory::getBookId).collect(Collectors.toList())); Map<Long, Book> booksById = books.stream().collect(Collectors.toMap(Book::getId, Function.identity(), (key1, key2) -> key2)); List<BookReadHistoryVO> resultList = new ArrayList<>(booksById.size()); userReadHistories.forEach(readHistory->{ BookReadHistoryVO readHistoryVO = new BookReadHistoryVO(); BeanUtils.copyProperties(readHistory, readHistoryVO); Book book = booksById.get(readHistory.getBookId()); if (book != null) { BeanUtils.copyProperties(book, readHistoryVO); resultList.add(readHistoryVO); } }); PageBean<UserReadHistory> pageBean = new PageBean<>(userReadHistories); pageBean.setList(resultList); return pageBean; } @Transactional(rollbackFor = Exception.class) @Override public void addReadHistory(Long userId, Long bookId, Long preContentId) { Date currentDate = new Date(); //删除该书以前的历史记录 DeleteStatementProvider deleteStatement = deleteFrom(userReadHistory) .where(UserReadHistoryDynamicSqlSupport.bookId, isEqualTo(bookId)) .and(UserReadHistoryDynamicSqlSupport.userId, isEqualTo(userId)) .build() .render(RenderingStrategies.MYBATIS3); userReadHistoryMapper.delete(deleteStatement); //插入该书新的历史记录 UserReadHistory userReadHistory = new UserReadHistory(); userReadHistory.setBookId(bookId); userReadHistory.setUserId(userId); userReadHistory.setPreContentId(preContentId); userReadHistory.setCreateTime(currentDate); userReadHistory.setUpdateTime(currentDate); userReadHistoryMapper.insertSelective(userReadHistory); //更新书架的阅读历史 UpdateStatementProvider updateStatement = update(userBookshelf) .set(UserBookshelfDynamicSqlSupport.preContentId) .equalTo(preContentId) .set(UserBookshelfDynamicSqlSupport.updateTime) .equalTo(currentDate) .where(UserBookshelfDynamicSqlSupport.userId, isEqualTo(userId)) .and(UserBookshelfDynamicSqlSupport.bookId, isEqualTo(bookId)) .build() .render(RenderingStrategies.MYBATIS3); userBookshelfMapper.update(updateStatement); } @Override public void addFeedBack(Long userId, String content) { UserFeedback feedback = new UserFeedback(); feedback.setUserId(userId); feedback.setContent(content); feedback.setCreateTime(new Date()); userFeedbackMapper.insertSelective(feedback); } @Override public PageBean<UserFeedback> listUserFeedBackByPage(Long userId, int page, int pageSize) { PageHelper.startPage(page, pageSize); return new PageBean<>(userFeedbackMapper.selectMany(select(UserFeedbackDynamicSqlSupport.content, UserFeedbackDynamicSqlSupport.createTime) .from(UserFeedbackDynamicSqlSupport.userFeedback) .where(UserFeedbackDynamicSqlSupport.userId, isEqualTo(userId)) .orderBy(UserFeedbackDynamicSqlSupport.id.descending()) .build() .render(RenderingStrategies.MYBATIS3))); } @Override public User userInfo(Long userId) { SelectStatementProvider selectStatement = select(UserDynamicSqlSupport.username, UserDynamicSqlSupport.nickName, UserDynamicSqlSupport.userPhoto, UserDynamicSqlSupport.userSex, UserDynamicSqlSupport.accountBalance) .from(UserDynamicSqlSupport.user) .where(UserDynamicSqlSupport.id, isEqualTo(userId)) .limit(1) .build() .render(RenderingStrategies.MYBATIS3); return userMapper.selectMany(selectStatement).get(0); } @Override public void updateUserInfo(Long userId, User user) { user.setId(userId); user.setUpdateTime(new Date()); userMapper.updateByPrimaryKeySelective(user); } @Override public void updatePassword(Long userId, String oldPassword, String newPassword) { SelectStatementProvider selectStatement = select(UserDynamicSqlSupport.password) .from(UserDynamicSqlSupport.user) .where(UserDynamicSqlSupport.id, isEqualTo(userId)) .build() .render(RenderingStrategies.MYBATIS3); if (!userMapper.selectMany(selectStatement).get(0).getPassword().equals(MD5Util.MD5Encode(oldPassword, Charsets.UTF_8.name()))) { throw new BusinessException(ResponseStatus.OLD_PASSWORD_ERROR); } UpdateStatementProvider updateStatement = update(UserDynamicSqlSupport.user) .set(UserDynamicSqlSupport.password) .equalTo(MD5Util.MD5Encode(newPassword, Charsets.UTF_8.name())) .where(UserDynamicSqlSupport.id, isEqualTo(userId)) .build() .render(RenderingStrategies.MYBATIS3); userMapper.update(updateStatement); } }
package xyz.staffjoy.account.service.helper; import com.github.structlog4j.ILogger; import com.github.structlog4j.SLoggerFactory; import com.google.common.collect.Maps; import io.intercom.api.Avatar; import io.intercom.api.CustomAttribute; import io.intercom.api.Event; import io.intercom.api.User; import io.sentry.SentryClient; import lombok.RequiredArgsConstructor; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import xyz.staffjoy.account.config.AppConfig; import xyz.staffjoy.account.model.Account; import xyz.staffjoy.account.repo.AccountRepo; import xyz.staffjoy.bot.client.BotClient; import xyz.staffjoy.bot.dto.GreetingRequest; import xyz.staffjoy.common.api.BaseResponse; import xyz.staffjoy.common.api.ResultCode; import xyz.staffjoy.common.auth.AuthConstant; import xyz.staffjoy.common.env.EnvConfig; import xyz.staffjoy.common.error.ServiceException; import xyz.staffjoy.company.client.CompanyClient; import xyz.staffjoy.company.dto.*; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; @RequiredArgsConstructor @Component public class ServiceHelper { static final ILogger logger = SLoggerFactory.getLogger(ServiceHelper.class); private final CompanyClient companyClient; private final AccountRepo accountRepo; private final SentryClient sentryClient; private final BotClient botClient; private final EnvConfig envConfig; @Async(AppConfig.ASYNC_EXECUTOR_NAME) public void syncUserAsync(String userId) { if (envConfig.isDebug()) { logger.debug("intercom disabled in dev & test environment"); return; } Account account = accountRepo.findAccountById(userId); if (account == null) { throw new ServiceException(ResultCode.NOT_FOUND, String.format("User with id %s not found", userId)); } if (StringUtils.isEmpty(account.getPhoneNumber()) && StringUtils.isEmpty(account.getEmail())) { logger.info(String.format("skipping sync for user %s because no email or phonenumber", account.getId())); return; } // use a map to de-dupe Map<String, CompanyDto> memberships = new HashMap<>(); GetWorkerOfResponse workerOfResponse = null; try { workerOfResponse = companyClient.getWorkerOf(AuthConstant.AUTHORIZATION_ACCOUNT_SERVICE, userId); } catch(Exception ex) { String errMsg = "could not fetch workOfList"; handleException(logger, ex, errMsg); throw new ServiceException(errMsg, ex); } if (!workerOfResponse.isSuccess()) { handleError(logger, workerOfResponse.getMessage()); throw new ServiceException(workerOfResponse.getMessage()); } WorkerOfList workerOfList = workerOfResponse.getWorkerOfList(); boolean isWorker = workerOfList.getTeams().size() > 0; for(TeamDto teamDto : workerOfList.getTeams()) { GenericCompanyResponse genericCompanyResponse = null; try { genericCompanyResponse = companyClient.getCompany(AuthConstant.AUTHORIZATION_ACCOUNT_SERVICE, teamDto.getCompanyId()); } catch (Exception ex) { String errMsg = "could not fetch companyDto from teamDto"; handleException(logger, ex, errMsg); throw new ServiceException(errMsg, ex); } if (!genericCompanyResponse.isSuccess()) { handleError(logger, genericCompanyResponse.getMessage()); throw new ServiceException(genericCompanyResponse.getMessage()); } CompanyDto companyDto = genericCompanyResponse.getCompany(); memberships.put(companyDto.getId(), companyDto); } GetAdminOfResponse getAdminOfResponse = null; try { getAdminOfResponse = companyClient.getAdminOf(AuthConstant.AUTHORIZATION_ACCOUNT_SERVICE, userId); } catch (Exception ex) { String errMsg = "could not fetch adminOfList"; handleException(logger, ex, errMsg); throw new ServiceException(errMsg, ex); } if (!getAdminOfResponse.isSuccess()) { handleError(logger, getAdminOfResponse.getMessage()); throw new ServiceException(getAdminOfResponse.getMessage()); } AdminOfList adminOfList = getAdminOfResponse.getAdminOfList(); boolean isAdmin = adminOfList.getCompanies().size() > 0; for(CompanyDto companyDto : adminOfList.getCompanies()) { memberships.put(companyDto.getId(), companyDto); } User user = new User(); user.setUserId(account.getId()); user.setEmail(account.getEmail()); user.setName(account.getName()); user.setSignedUpAt(account.getMemberSince().toEpochMilli()); user.setAvatar(new Avatar().setImageURL(account.getPhotoUrl())); user.setLastRequestAt(Instant.now().toEpochMilli()); user.addCustomAttribute(CustomAttribute.newBooleanAttribute("v2", true)); user.addCustomAttribute(CustomAttribute.newStringAttribute("phonenumber", account.getPhoneNumber())); user.addCustomAttribute(CustomAttribute.newBooleanAttribute("confirmed_and_active", account.isConfirmedAndActive())); user.addCustomAttribute(CustomAttribute.newBooleanAttribute("is_worker", isWorker)); user.addCustomAttribute(CustomAttribute.newBooleanAttribute("is_admin", isAdmin)); user.addCustomAttribute(CustomAttribute.newBooleanAttribute("is_staffjoy_support", account.isSupport())); for(CompanyDto companyDto : memberships.values()) { user.addCompany(new io.intercom.api.Company().setCompanyID(companyDto.getId()).setName(companyDto.getName())); } this.syncUserWithIntercom(user, account.getId()); } void syncUserWithIntercom(User user, String userId) { try { Map<String, String> params = Maps.newHashMap(); params.put("user_id", userId); User existing = User.find(params); if (existing != null) { User.update(user); } else { User.create(user); } logger.debug("updated intercom"); } catch (Exception ex) { String errMsg = "fail to create/update user on Intercom"; handleException(logger, ex, errMsg); throw new ServiceException(errMsg, ex); } } @Async(AppConfig.ASYNC_EXECUTOR_NAME) public void trackEventAsync(String userId, String eventName) { if (envConfig.isDebug()) { logger.debug("intercom disabled in dev & test environment"); return; } Event event = new Event() .setUserID(userId) .setEventName("v2_" + eventName) .setCreatedAt(Instant.now().toEpochMilli()); try { Event.create(event); } catch (Exception ex) { String errMsg = "fail to create event on Intercom"; handleException(logger, ex, errMsg); throw new ServiceException(errMsg, ex); } logger.debug("updated intercom"); } public void sendSmsGreeting(String userId) { BaseResponse baseResponse = null; try { GreetingRequest greetingRequest = GreetingRequest.builder().userId(userId).build(); baseResponse = botClient.sendSmsGreeting(greetingRequest); } catch (Exception ex) { String errMsg = "could not send welcome sms"; handleException(logger, ex, errMsg); throw new ServiceException(errMsg, ex); } if (!baseResponse.isSuccess()) { handleError(logger, baseResponse.getMessage()); throw new ServiceException(baseResponse.getMessage()); } } // for time diff < 2s, treat them as almost same public boolean isAlmostSameInstant(Instant dt1, Instant dt2) { long diff = dt1.toEpochMilli() - dt2.toEpochMilli(); diff = Math.abs(diff); if (diff < TimeUnit.SECONDS.toMillis(1)) { return true; } return false; } public void handleError(ILogger log, String errMsg) { log.error(errMsg); if (!envConfig.isDebug()) { sentryClient.sendMessage(errMsg); } } public void handleException(ILogger log, Exception ex, String errMsg) { log.error(errMsg, ex); if (!envConfig.isDebug()) { sentryClient.sendException(ex); } } }
package xyz.staffjoy.company.service.helper; import com.github.structlog4j.ILogger; import com.github.structlog4j.SLoggerFactory; import io.sentry.SentryClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import xyz.staffjoy.account.client.AccountClient; import xyz.staffjoy.account.dto.TrackEventRequest; import xyz.staffjoy.bot.client.BotClient; import xyz.staffjoy.bot.dto.*; import xyz.staffjoy.common.api.BaseResponse; import xyz.staffjoy.common.auth.AuthContext; import xyz.staffjoy.common.env.EnvConfig; import xyz.staffjoy.common.error.ServiceException; import xyz.staffjoy.company.config.AppConfig; import xyz.staffjoy.company.dto.ShiftDto; import java.time.Instant; import java.util.List; import java.util.Map; @SuppressWarnings("Duplicates") @Component public class ServiceHelper { static final ILogger logger = SLoggerFactory.getLogger(ServiceHelper.class); @Autowired private AccountClient accountClient; @Autowired private BotClient botClient; @Autowired private SentryClient sentryClient; @Autowired private EnvConfig envConfig; @Async(AppConfig.ASYNC_EXECUTOR_NAME) public void trackEventAsync(String event) { String userId = AuthContext.getUserId(); if (StringUtils.isEmpty(userId)) { // Not an action performed by a normal user // (noop - not an view) return; } TrackEventRequest trackEventRequest = TrackEventRequest.builder() .userId(userId).event(event).build(); BaseResponse resp = null; try { resp = accountClient.trackEvent(trackEventRequest); } catch (Exception ex) { String errMsg = "fail to trackEvent through accountClient"; handleErrorAndThrowException(logger, ex, errMsg); } if (!resp.isSuccess()) { handleErrorAndThrowException(logger, resp.getMessage()); } } @Async(AppConfig.ASYNC_EXECUTOR_NAME) public void onboardWorkerAsync(OnboardWorkerRequest onboardWorkerRequest) { BaseResponse baseResponse = null; try { baseResponse = botClient.onboardWorker(onboardWorkerRequest); } catch (Exception ex) { String errMsg = "fail to call onboardWorker through botClient"; handleErrorAndThrowException(logger, ex, errMsg); } if (!baseResponse.isSuccess()) { handleErrorAndThrowException(logger, baseResponse.getMessage()); } } @Async(AppConfig.ASYNC_EXECUTOR_NAME) public void alertNewShiftAsync(AlertNewShiftRequest alertNewShiftRequest) { BaseResponse baseResponse = null; try { baseResponse = botClient.alertNewShift(alertNewShiftRequest); } catch (Exception ex) { String errMsg = "failed to alert worker about new shift"; handleErrorAndThrowException(logger, ex, errMsg); } if (!baseResponse.isSuccess()) { handleErrorAndThrowException(logger, baseResponse.getMessage()); } } @Async(AppConfig.ASYNC_EXECUTOR_NAME) public void alertRemovedShiftAsync(AlertRemovedShiftRequest alertRemovedShiftRequest) { BaseResponse baseResponse = null; try { baseResponse = botClient.alertRemovedShift(alertRemovedShiftRequest); } catch (Exception ex) { String errMsg = "failed to alert worker about removed shift"; handleErrorAndThrowException(logger, ex, errMsg); } if (!baseResponse.isSuccess()) { handleErrorAndThrowException(logger, baseResponse.getMessage()); } } @Async(AppConfig.ASYNC_EXECUTOR_NAME) public void buildShiftNotificationAsync(Map<String, List<ShiftDto>> notifs, boolean published) { for(Map.Entry<String, List<ShiftDto>> entry : notifs.entrySet()) { String userId = entry.getKey(); List<ShiftDto> shiftDtos = entry.getValue(); if (published) { // alert published AlertNewShiftsRequest alertNewShiftsRequest = AlertNewShiftsRequest.builder() .userId(userId) .newShifts(shiftDtos) .build(); BaseResponse baseResponse = null; try { baseResponse = botClient.alertNewShifts(alertNewShiftsRequest); } catch (Exception ex) { String errMsg = "failed to alert worker about new shifts"; handleErrorAndThrowException(logger, ex, errMsg); } if (!baseResponse.isSuccess()) { handleErrorAndThrowException(logger, baseResponse.getMessage()); } } else { // alert removed AlertRemovedShiftsRequest alertRemovedShiftsRequest = AlertRemovedShiftsRequest.builder() .userId(userId) .oldShifts(shiftDtos) .build(); BaseResponse baseResponse = null; try { baseResponse = botClient.alertRemovedShifts(alertRemovedShiftsRequest); } catch (Exception ex) { String errMsg = "failed to alert worker about removed shifts"; handleErrorAndThrowException(logger, ex, errMsg); } if (!baseResponse.isSuccess()) { handleErrorAndThrowException(logger, baseResponse.getMessage()); } } } } // send bot notifications @Async(AppConfig.ASYNC_EXECUTOR_NAME) public void updateShiftNotificationAsync(ShiftDto origShiftDto, ShiftDto shiftDtoToUpdte) { if (!origShiftDto.isPublished() && shiftDtoToUpdte.isPublished()) { if (shiftDtoToUpdte.getStart().isAfter(Instant.now()) && !StringUtils.isEmpty(shiftDtoToUpdte.getUserId())) { // looks like a new shift AlertNewShiftRequest alertNewShiftRequest = AlertNewShiftRequest.builder() .userId(shiftDtoToUpdte.getUserId()) .newShift(shiftDtoToUpdte) .build(); BaseResponse baseResponse = null; try { baseResponse = botClient.alertNewShift(alertNewShiftRequest); } catch (Exception ex) { String errMsg = "failed to alert worker about new shift"; handleErrorAndThrowException(logger, ex, errMsg); } if (!baseResponse.isSuccess()) { handleErrorAndThrowException(logger, baseResponse.getMessage()); } } return; } if (origShiftDto.isPublished() && !shiftDtoToUpdte.isPublished()) { if (shiftDtoToUpdte.getStart().isAfter(Instant.now()) && !StringUtils.isEmpty(origShiftDto.getUserId())) { // removed a shift AlertRemovedShiftRequest alertRemovedShiftRequest = AlertRemovedShiftRequest.builder() .userId(origShiftDto.getUserId()) .oldShift(origShiftDto) .build(); BaseResponse baseResponse = null; try { baseResponse = botClient.alertRemovedShift(alertRemovedShiftRequest); } catch (Exception ex) { String errMsg = "failed to alert worker about removed shift"; handleErrorAndThrowException(logger, ex, errMsg); } if (!baseResponse.isSuccess()) { handleErrorAndThrowException(logger, baseResponse.getMessage()); } } return; } if (!origShiftDto.isPublished() && !shiftDtoToUpdte.isPublished()) { // NOOP - basically return return; } if ((!StringUtils.isEmpty(origShiftDto.getUserId())) && origShiftDto.getUserId().equals(shiftDtoToUpdte.getUserId())) { if (shiftDtoToUpdte.getStart().isAfter(Instant.now())) { AlertChangedShiftRequest alertChangedShiftRequest = AlertChangedShiftRequest.builder() .userId(origShiftDto.getUserId()) .oldShift(origShiftDto) .newShift(shiftDtoToUpdte) .build(); BaseResponse baseResponse = null; try { baseResponse = botClient.alertChangedShift(alertChangedShiftRequest); } catch (Exception ex) { String errMsg = "failed to alert worker about changed shift"; handleErrorAndThrowException(logger, ex, errMsg); } if (!baseResponse.isSuccess()) { handleErrorAndThrowException(logger, baseResponse.getMessage()); } } return; } if (!origShiftDto.getUserId().equals(shiftDtoToUpdte.getUserId())) { if (!StringUtils.isEmpty(origShiftDto.getUserId()) && origShiftDto.getStart().isAfter(Instant.now())) { AlertRemovedShiftRequest alertRemovedShiftRequest = AlertRemovedShiftRequest.builder() .userId(origShiftDto.getUserId()) .oldShift(origShiftDto) .build(); BaseResponse baseResponse = null; try { baseResponse = botClient.alertRemovedShift(alertRemovedShiftRequest); } catch (Exception ex) { String errMsg = "failed to alert worker about removed shift"; handleErrorAndThrowException(logger, ex, errMsg); } if (!baseResponse.isSuccess()) { handleErrorAndThrowException(logger, baseResponse.getMessage()); } } if (!StringUtils.isEmpty(shiftDtoToUpdte.getUserId()) && shiftDtoToUpdte.getStart().isAfter(Instant.now())) { AlertNewShiftRequest alertNewShiftRequest = AlertNewShiftRequest.builder() .userId(shiftDtoToUpdte.getUserId()) .newShift(shiftDtoToUpdte) .build(); BaseResponse baseResponse = null; try { baseResponse = botClient.alertNewShift(alertNewShiftRequest); } catch (Exception ex) { String errMsg = "failed to alert worker about new shift"; handleErrorAndThrowException(logger, ex, errMsg); } if (!baseResponse.isSuccess()) { handleErrorAndThrowException(logger, baseResponse.getMessage()); } } return; } logger.error(String.format("unable to determine updated shift messaging - orig %s new %s", origShiftDto, shiftDtoToUpdte)); } public void handleErrorAndThrowException(ILogger log, String errMsg) { log.error(errMsg); if (!envConfig.isDebug()) { sentryClient.sendMessage(errMsg); } throw new ServiceException(errMsg); } public void handleErrorAndThrowException(ILogger log, Exception ex, String errMsg) { log.error(errMsg, ex); if (!envConfig.isDebug()) { sentryClient.sendException(ex); } throw new ServiceException(errMsg, ex); } }
package com.rainbowforest.productcatalogservice.controller; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.rainbowforest.productcatalogservice.entity.Product; import com.rainbowforest.productcatalogservice.service.ProductService; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class AdminProductControllerTest { private static final String PRODUCT_NAME= "test"; private static final String PRODUCT_CATEGORY = "testCategory"; @Autowired private MockMvc mockMvc; @MockBean private ProductService productService; @Test public void add_product_controller_should_return201_when_product_isSaved() throws Exception { //given Product product = new Product(); product.setProductName(PRODUCT_NAME); product.setCategory(PRODUCT_CATEGORY); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); ObjectWriter objectWriter = mapper.writer().withDefaultPrettyPrinter(); String requestJson = objectWriter.writeValueAsString(product); //when when(productService.addProduct(new Product())).thenReturn(product); //then mockMvc.perform(post("/admin/products").content(requestJson).contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isCreated()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.productName").value(PRODUCT_NAME)) .andExpect(jsonPath("$.category").value(PRODUCT_CATEGORY)); verify(productService, times(1)).addProduct(any(Product.class)); verifyNoMoreInteractions(productService); } @Test public void add_product_controller_should_return400_when_product_isNull() throws Exception { //given Product product = null; ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); ObjectWriter objectWriter = mapper.writer().withDefaultPrettyPrinter(); String requestJson = objectWriter.writeValueAsString(product); //then mockMvc.perform(post("/admin/products").content(requestJson).contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isBadRequest()); } }
package com.rainbowforest.userservice.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.rainbowforest.userservice.entity.User; import com.rainbowforest.userservice.service.UserService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class UserControllerTests { private final Long USER_ID = 2L; private final String USER_NAME = "test"; private User user; private List<User> users; @Autowired private MockMvc mockMvc; @MockBean UserService userService; @Test public void get_all_users_controller_should_return200_when_validRequest() throws Exception{ //given user = new User(); user.setId(USER_ID); user.setUserName(USER_NAME); users = new ArrayList<>(); users.add(user); //when when(userService.getAllUsers()).thenReturn(users); //then mockMvc.perform(get("/users")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$[0].id").value(USER_ID)) .andExpect(jsonPath("$[0].userName").value(USER_NAME)); verify(userService, times(1)).getAllUsers(); verifyNoMoreInteractions(userService); } @Test public void get_all_users_controller_should_return404_when_userList_isEmpty() throws Exception{ //given List<User> users = new ArrayList<User>(); //when when(userService.getAllUsers()).thenReturn(users); //then mockMvc.perform(get("/users")) .andExpect(status().isNotFound()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON_UTF8_VALUE)); verify(userService, times(1)).getAllUsers(); verifyNoMoreInteractions(userService); } @Test public void get_user_by_name_controller_should_return200_when_users_isExist() throws Exception{ //given User user = new User(); user.setId(USER_ID); user.setUserName(USER_NAME); //when when(userService.getUserByName(USER_NAME)).thenReturn(user); //then mockMvc.perform(get("/users").param("name", USER_NAME)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.id").value(USER_ID)) .andExpect(jsonPath("$.userName").value(USER_NAME)); verify(userService, times(1)).getUserByName(anyString()); verifyNoMoreInteractions(userService); } @Test public void get_user_by_name_controller_should_return404_when_users_is_notExist() throws Exception{ //when when(userService.getUserByName(USER_NAME)).thenReturn(null); //then mockMvc.perform(get("/users").param("name", USER_NAME)) .andExpect(status().isNotFound()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON_UTF8_VALUE)); verify(userService, times(1)).getUserByName(anyString()); verifyNoMoreInteractions(userService); } @Test public void get_user_by_id_controller_should_return200_when_users_isExist() throws Exception{ //given User user = new User(); user.setId(USER_ID); user.setUserName(USER_NAME); //when when(userService.getUserById(USER_ID)).thenReturn(user); //then mockMvc.perform(get("/users/{id}", USER_ID)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.id").value(USER_ID)) .andExpect(jsonPath("$.userName").value(USER_NAME)); verify(userService, times(1)).getUserById(anyLong()); verifyNoMoreInteractions(userService); } @Test public void get_user_by_id_controller_should_return404_when_users_is_notExist() throws Exception{ //when when(userService.getUserById(USER_ID)).thenReturn(user); //then mockMvc.perform(get("/users/{id}", USER_ID)) .andExpect(status().isNotFound()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON_UTF8_VALUE)); verify(userService, times(1)).getUserById(anyLong()); verifyNoMoreInteractions(userService); } @Test public void add_user_controller_should_return201_when_user_is_saved() throws Exception{ //given User user = new User(); user.setUserName(USER_NAME); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); ObjectWriter objectWriter = mapper.writer().withDefaultPrettyPrinter(); String requestJson = objectWriter.writeValueAsString(user); //when when(userService.saveUser(new User())).thenReturn(user); //then mockMvc.perform(post("/users").content(requestJson).contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isCreated()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.userName").value(USER_NAME)); verify(userService, times(1)).saveUser(any(User.class)); verifyNoMoreInteractions(userService); } @Test public void add_user_controller_should_return400_when_user_isNull() throws Exception{ //given User user = null; ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); ObjectWriter objectWriter = mapper.writer().withDefaultPrettyPrinter(); String requestJson = objectWriter.writeValueAsString(user); //then mockMvc.perform(post("/users").content(requestJson).contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isBadRequest()); } }
package adminorder.service; import adminorder.entity.Order; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; @RunWith(JUnit4.class) public class AdminOrderServiceImplTest { @InjectMocks private AdminOrderServiceImpl adminOrderService; @Mock private RestTemplate restTemplate; private HttpHeaders headers = new HttpHeaders(); private HttpEntity requestEntity = new HttpEntity(headers); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testGetAllOrders1() { Response<ArrayList<Order>> response = new Response<>(0, null, null); ResponseEntity<Response<ArrayList<Order>>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<Order>>>() { })).thenReturn(re); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<Order>>>() { })).thenReturn(re); Response result = adminOrderService.getAllOrders(headers); Assert.assertEquals(new Response<>(1, "Get the orders successfully!", new ArrayList<>()), result); } @Test public void testGetAllOrders2() { ArrayList<Order> orders = new ArrayList<>(); orders.add(new Order()); Response<ArrayList<Order>> response = new Response<>(1, null, orders); ResponseEntity<Response<ArrayList<Order>>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<Order>>>() { })).thenReturn(re); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<Order>>>() { })).thenReturn(re); Response result = adminOrderService.getAllOrders(headers); Assert.assertNotNull(result); } @Test public void testDeleteOrder1() { Response response = new Response(); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "orderId", HttpMethod.DELETE, requestEntity, Response.class)).thenReturn(re); Response result = adminOrderService.deleteOrder("orderId", "G", headers); Assert.assertEquals(new Response<>(null, null, null), result); } @Test public void testDeleteOrder2() { Response response = new Response(); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "orderId", HttpMethod.DELETE, requestEntity, Response.class)).thenReturn(re); Response result = adminOrderService.deleteOrder("orderId", "K", headers); Assert.assertEquals(new Response<>(null, null, null), result); } @Test public void testUpdateOrder1() { Order order = new Order(null, null, null, null, null, null, 0, null, "G", 0, 0, null, null, null, 0, null); HttpEntity<Order> requestEntity2 = new HttpEntity<>(order, headers); Response response = new Response(); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/admin", HttpMethod.PUT, requestEntity2, Response.class)).thenReturn(re); Response result = adminOrderService.updateOrder(order, headers); Assert.assertNotNull(result); } @Test public void testUpdateOrder2() { Order order = new Order(null, null, null, null, null, null, 0, null, "K", 0, 0, null, null, null, 0, null); HttpEntity<Order> requestEntity2 = new HttpEntity<>(order, headers); Response response = new Response(); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/admin", HttpMethod.PUT, requestEntity2, Response.class)).thenReturn(re); Response result = adminOrderService.updateOrder(order, headers); Assert.assertNotNull(result); } @Test public void testAddOrder1() { Order order = new Order(null, null, null, null, null, null, 0, null, "G", 0, 0, null, null, null, 0, null); HttpEntity<Order> requestEntity2 = new HttpEntity<>(order, headers); Response response = new Response(); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/admin", HttpMethod.POST, requestEntity2, Response.class)).thenReturn(re); Response result = adminOrderService.addOrder(order, headers); Assert.assertNotNull(result); } @Test public void testAddOrder2() { Order order = new Order(null, null, null, null, null, null, 0, null, "K", 0, 0, null, null, null, 0, null); HttpEntity<Order> requestEntity2 = new HttpEntity<>(order, headers); Response response = new Response(); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/admin", HttpMethod.POST, requestEntity2, Response.class)).thenReturn(re); Response result = adminOrderService.addOrder(order, headers); Assert.assertNotNull(result); } }
package admintravel.service; import admintravel.entity.AdminTrip; import admintravel.entity.TravelInfo; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; @RunWith(JUnit4.class) public class AdminTravelServiceImplTest { @InjectMocks private AdminTravelServiceImpl adminTravelServiceImpl; @Mock private RestTemplate restTemplate; private HttpHeaders headers = new HttpHeaders(); private HttpEntity requestEntity = new HttpEntity(headers); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testGetAllTravels1() { Response<ArrayList<AdminTrip>> response = new Response<>(0, null, null); ResponseEntity<Response<ArrayList<AdminTrip>>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-travel-service:12346/api/v1/travelservice/admin_trip", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<AdminTrip>>>() { })).thenReturn(re); Mockito.when(restTemplate.exchange( "http://ts-travel2-service:16346/api/v1/travel2service/admin_trip", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<AdminTrip>>>() { })).thenReturn(re); Response result = adminTravelServiceImpl.getAllTravels(headers); Assert.assertEquals(new Response<>(0, null, new ArrayList<>()), result); } @Test public void testGetAllTravels2() { ArrayList<AdminTrip> adminTrips = new ArrayList<>(); adminTrips.add(new AdminTrip()); Response<ArrayList<AdminTrip>> response = new Response<>(1, null, adminTrips); ResponseEntity<Response<ArrayList<AdminTrip>>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-travel-service:12346/api/v1/travelservice/admin_trip", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<AdminTrip>>>() { })).thenReturn(re); Mockito.when(restTemplate.exchange( "http://ts-travel2-service:16346/api/v1/travel2service/admin_trip", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<AdminTrip>>>() { })).thenReturn(re); Response result = adminTravelServiceImpl.getAllTravels(headers); Assert.assertNotNull(result); } @Test public void testAddTravel1() { TravelInfo request = new TravelInfo(null, null, "G", null, null, null, null, null, null); HttpEntity requestEntity2 = new HttpEntity<>(request, headers); Response response = new Response<>(0, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-travel-service:12346/api/v1/travelservice/trips", HttpMethod.POST, requestEntity2, Response.class)).thenReturn(re); Response result = adminTravelServiceImpl.addTravel(request, headers); Assert.assertEquals(new Response<>(0, "Admin add new travel failed", null), result); } @Test public void testAddTravel2() { TravelInfo request = new TravelInfo(null, null, "G", null, null, null, null, null, null); HttpEntity<TravelInfo> requestEntity2 = new HttpEntity<>(request, headers); Response response = new Response<>(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-travel-service:12346/api/v1/travelservice/trips", HttpMethod.POST, requestEntity2, Response.class)).thenReturn(re); Response result = adminTravelServiceImpl.addTravel(request, headers); Assert.assertEquals(new Response<>(1, "[Admin add new travel]", null), result); } @Test public void testAddTravel3() { TravelInfo request = new TravelInfo(null, null, "K", null, null, null, null, null, null); HttpEntity<TravelInfo> requestEntity2 = new HttpEntity<>(request, headers); Response response = new Response<>(0, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-travel2-service:16346/api/v1/travel2service/trips", HttpMethod.POST, requestEntity2, Response.class)).thenReturn(re); Response result = adminTravelServiceImpl.addTravel(request, headers); Assert.assertEquals(new Response<>(0, "Admin add new travel failed", null), result); } @Test public void testAddTravel4() { TravelInfo request = new TravelInfo(null, null, "K", null, null, null, null, null, null); HttpEntity<TravelInfo> requestEntity2 = new HttpEntity<>(request, headers); Response response = new Response<>(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-travel2-service:16346/api/v1/travel2service/trips", HttpMethod.POST, requestEntity2, Response.class)).thenReturn(re); Response result = adminTravelServiceImpl.addTravel(request, headers); Assert.assertEquals(new Response<>(1, "[Admin add new travel]", null), result); } @Test public void testUpdateTravel1() { TravelInfo request = new TravelInfo(null, null, "G", null, null, null, null, null, null); HttpEntity<TravelInfo> requestEntity2 = new HttpEntity<>(request, headers); Response response = new Response(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-travel-service:12346/api/v1/travelservice/trips", HttpMethod.PUT, requestEntity2, Response.class)).thenReturn(re); Response result = adminTravelServiceImpl.updateTravel(request, headers); Assert.assertEquals(new Response<>(1, null, null), result); } @Test public void testUpdateTravel2() { TravelInfo request = new TravelInfo(null, null, "K", null, null, null, null, null, null); HttpEntity<TravelInfo> requestEntity2 = new HttpEntity<>(request, headers); Response response = new Response(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-travel2-service:16346/api/v1/travel2service/trips", HttpMethod.PUT, requestEntity2, Response.class)).thenReturn(re); Response result = adminTravelServiceImpl.updateTravel(request, headers); Assert.assertEquals(new Response<>(1, null, null), result); } @Test public void testDeleteTravel1() { Response response = new Response(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-travel-service:12346/api/v1/travelservice/trips/" + "GaoTie", HttpMethod.DELETE, requestEntity, Response.class)).thenReturn(re); Response result = adminTravelServiceImpl.deleteTravel("GaoTie", headers); Assert.assertEquals(new Response<>(1, null, null), result); } @Test public void testDeleteTravel2() { Response response = new Response(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-travel2-service:16346/api/v1/travel2service/trips/" + "K1024", HttpMethod.DELETE, requestEntity, Response.class)).thenReturn(re); Response result = adminTravelServiceImpl.deleteTravel("K1024", headers); Assert.assertEquals(new Response<>(1, null, null), result); } }
package cancel.service; import cancel.entity.NotifyInfo; import cancel.entity.Order; import cancel.entity.User; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; @RunWith(JUnit4.class) public class CancelServiceImplTest { @InjectMocks private CancelServiceImpl cancelServiceImpl; @Mock private RestTemplate restTemplate; private HttpHeaders headers = new HttpHeaders(); private HttpEntity requestEntity = new HttpEntity(headers); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testCancelOrder1() { //mock getOrderByIdFromOrder() Order order = new Order(); order.setStatus(6); Response<Order> response = new Response<>(1, null, order); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); Response result = cancelServiceImpl.cancelOrder("order_id", "login_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted", null), result); } @Test public void testCancelOrder2() { //mock getOrderByIdFromOrder() Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(6); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); Response result = cancelServiceImpl.cancelOrder("order_id", "login_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted", null), result); } @Test public void testSendEmail() { NotifyInfo notifyInfo = new NotifyInfo(); HttpEntity requestEntity2 = new HttpEntity(notifyInfo, headers); ResponseEntity<Boolean> re = new ResponseEntity<>(true, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-notification-service:17853/api/v1/notifyservice/notification/order_cancel_success", HttpMethod.POST, requestEntity2, Boolean.class)).thenReturn(re); Boolean result = cancelServiceImpl.sendEmail(notifyInfo, headers); Assert.assertTrue(result); } @Test public void testCalculateRefund1() { //mock getOrderByIdFromOrder() Order order = new Order(); order.setStatus(6); Response<Order> response = new Response<>(1, null, order); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); Response result = cancelServiceImpl.calculateRefund("order_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted, Refound error", null), result); } @Test public void testCalculateRefund2() { //mock getOrderByIdFromOrder() Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(6); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); Response result = cancelServiceImpl.calculateRefund("order_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted", null), result); } @Test public void testDrawbackMoney() { Response response = new Response<>(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-inside-payment-service:18673/api/v1/inside_pay_service/inside_payment/drawback/" + "userId" + "/" + "money", HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); Boolean result = cancelServiceImpl.drawbackMoney("money", "userId", headers); Assert.assertTrue(result); } @Test public void testGetAccount() { Response<User> response = new Response<>(); ResponseEntity<Response<User>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-user-service:12342/api/v1/userservice/users/id/" + "orderId", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<User>>() { })).thenReturn(re); Response<User> result = cancelServiceImpl.getAccount("orderId", headers); Assert.assertEquals(new Response<User>(null, null, null), result); } }
package execute.service; import edu.fudan.common.util.Response; import execute.entity.Order; import execute.serivce.ExecuteServiceImpl; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; public class ExecuteServiceImplTest { @InjectMocks private ExecuteServiceImpl executeServiceImpl; @Mock private RestTemplate restTemplate; private HttpHeaders headers = new HttpHeaders(); private HttpEntity requestEntity = new HttpEntity(headers); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testTicketExecute1() { //mock getOrderByIdFromOrder() Order order = new Order(); order.setStatus(2); Response<Order> response = new Response<>(1, null, order); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock executeOrder() Response response2 = new Response(1, null, null); ResponseEntity<Response> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/status/" + "order_id" + "/" + 6, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re2); Response result = executeServiceImpl.ticketExecute("order_id", headers); Assert.assertEquals(new Response<>(1, "Success.", null), result); } @Test public void testTicketExecute2() { //mock getOrderByIdFromOrder( Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(2); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); //mock executeOrderOther() Response response3 = new Response(1, null, null); ResponseEntity<Response> re3 = new ResponseEntity<>(response3, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/status/" + "order_id" + "/" + 6, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re3); Response result = executeServiceImpl.ticketExecute("order_id", headers); Assert.assertEquals(new Response<>(1, "Success", null), result); } @Test public void testTicketCollect1() { //mock getOrderByIdFromOrder() Order order = new Order(); order.setStatus(1); Response<Order> response = new Response<>(1, null, order); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock executeOrder() Response response2 = new Response(1, null, null); ResponseEntity<Response> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/status/" + "order_id" + "/" + 2, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re2); Response result = executeServiceImpl.ticketCollect("order_id", headers); Assert.assertEquals(new Response<>(1, "Success", null), result); } @Test public void testTicketCollect2() { //mock getOrderByIdFromOrder( Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(1); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); //mock executeOrderOther() Response response3 = new Response(1, null, null); ResponseEntity<Response> re3 = new ResponseEntity<>(response3, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/status/" + "order_id" + "/" + 2, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re3); Response result = executeServiceImpl.ticketCollect("order_id", headers); Assert.assertEquals(new Response<>(1, "Success.", null), result); } }
package preserve.service; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; import preserve.entity.*; import java.util.Date; import java.util.HashMap; import java.util.UUID; @RunWith(JUnit4.class) public class PreserveServiceImplTest { @InjectMocks private PreserveServiceImpl preserveServiceImpl; @Mock private RestTemplate restTemplate; private HttpHeaders headers = new HttpHeaders(); private HttpEntity requestEntity = new HttpEntity(headers); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testPreserve() { OrderTicketsInfo oti = OrderTicketsInfo.builder() .accountId(UUID.randomUUID().toString()) .contactsId(UUID.randomUUID().toString()) .from("from_station") .to("to_station") .date(new Date()) .handleDate("handle_date") .tripId("G1255") .seatType(2) .assurance(1) .foodType(1) .foodName("food_name") .foodPrice(1.0) .stationName("station_name") .storeName("store_name") .consigneeName("consignee_name") .consigneePhone("123456789") .consigneeWeight(1.0) .isWithin(true) .build(); //response for checkSecurity()、addAssuranceForOrder()、createFoodOrder()、createConsign() Response response1 = new Response<>(1, null, null); ResponseEntity<Response> re1 = new ResponseEntity<>(response1, HttpStatus.OK); //response for sendEmail() ResponseEntity<Boolean> re10 = new ResponseEntity<>(true, HttpStatus.OK); Mockito.when(restTemplate.exchange( Mockito.anyString(), Mockito.any(HttpMethod.class), Mockito.any(HttpEntity.class), Mockito.any(Class.class))) .thenReturn(re1).thenReturn(re1).thenReturn(re1).thenReturn(re1).thenReturn(re10); //response for getContactsById() Contacts contacts = new Contacts(); contacts.setDocumentNumber("document_number"); contacts.setName("name"); contacts.setDocumentType(1); Response<Contacts> response2 = new Response<>(1, null, contacts); ResponseEntity<Response<Contacts>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); //response for getTripAllDetailInformation() TripResponse tripResponse = new TripResponse(); tripResponse.setConfortClass(1); tripResponse.setStartingTime(new Date()); TripAllDetail tripAllDetail = new TripAllDetail(true, "message", tripResponse, new Trip()); Response<TripAllDetail> response3 = new Response<>(1, null, tripAllDetail); ResponseEntity<Response<TripAllDetail>> re3 = new ResponseEntity<>(response3, HttpStatus.OK); //response for queryForStationId() Response<String> response4 = new Response<>(null, null, ""); ResponseEntity<Response<String>> re4 = new ResponseEntity<>(response4, HttpStatus.OK); //response for travel result TravelResult travelResult = new TravelResult(); travelResult.setPrices( new HashMap<String, String>(){{ put("confortClass", "1.0"); }} ); Response<TravelResult> response5 = new Response<>(null, null, travelResult); ResponseEntity<Response<TravelResult>> re5 = new ResponseEntity<>(response5, HttpStatus.OK); //response for dipatchSeat() Ticket ticket = new Ticket(); ticket.setSeatNo(1); Response<Ticket> response6 = new Response<>(null, null, ticket); ResponseEntity<Response<Ticket>> re6 = new ResponseEntity<>(response6, HttpStatus.OK); //response for createOrder() Order order = new Order(); order.setId(UUID.randomUUID()); order.setAccountId(UUID.randomUUID()); order.setTravelDate(new Date()); order.setFrom("from_station"); order.setTo("to_station"); Response<Order> response7 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re7 = new ResponseEntity<>(response7, HttpStatus.OK); //response for getAccount() User user = new User(); user.setEmail("email"); user.setUserName("user_name"); Response<User> response9 = new Response<>(1, null, user); ResponseEntity<Response<User>> re9 = new ResponseEntity<>(response9, HttpStatus.OK); Mockito.when(restTemplate.exchange( Mockito.anyString(), Mockito.any(HttpMethod.class), Mockito.any(HttpEntity.class), Mockito.any(ParameterizedTypeReference.class))) .thenReturn(re2).thenReturn(re3).thenReturn(re4).thenReturn(re4).thenReturn(re5).thenReturn(re6).thenReturn(re7).thenReturn(re9); Response result = preserveServiceImpl.preserve(oti, headers); Assert.assertEquals(new Response<>(1, "Success.", null), result); } @Test public void testDipatchSeat() { long mills = System.currentTimeMillis(); Seat seatRequest = new Seat(new Date(mills), "G1234", "start_station", "dest_station", 2); HttpEntity requestEntityTicket = new HttpEntity(seatRequest, headers); Response<Ticket> response = new Response<>(); ResponseEntity<Response<Ticket>> reTicket = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-seat-service:18898/api/v1/seatservice/seats", HttpMethod.POST, requestEntityTicket, new ParameterizedTypeReference<Response<Ticket>>() { })).thenReturn(reTicket); Ticket result = preserveServiceImpl.dipatchSeat(new Date(mills), "G1234", "start_station", "dest_station", 2, headers); Assert.assertNull(result); } @Test public void testSendEmail() { NotifyInfo notifyInfo = new NotifyInfo(); HttpEntity requestEntitySendEmail = new HttpEntity(notifyInfo, headers); ResponseEntity<Boolean> reSendEmail = new ResponseEntity<>(true, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-notification-service:17853/api/v1/notifyservice/notification/preserve_success", HttpMethod.POST, requestEntitySendEmail, Boolean.class)).thenReturn(reSendEmail); boolean result = preserveServiceImpl.sendEmail(notifyInfo, headers); Assert.assertTrue(result); } @Test public void testGetAccount() { Response<User> response = new Response<>(); ResponseEntity<Response<User>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-user-service:12342/api/v1/userservice/users/id/1", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<User>>() { })).thenReturn(re); User result = preserveServiceImpl.getAccount("1", headers); Assert.assertNull(result); } }
package rebook.service; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; import rebook.entity.*; import java.util.Date; @RunWith(JUnit4.class) public class RebookServiceImplTest { @InjectMocks private RebookServiceImpl rebookServiceImpl; @Mock private RestTemplate restTemplate; private HttpHeaders headers = new HttpHeaders(); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testRebook() { RebookInfo info = new RebookInfo(); info.setOldTripId("G"); info.setSeatType(2); //response for getOrderByRebookInfo() Order order = new Order(); order.setStatus(1); order.setFrom("from_station"); order.setTo("to_station"); order.setPrice("1.0"); Date date = new Date(System.currentTimeMillis()); order.setTravelDate(date); order.setTravelTime(date); Response<Order> response = new Response<>(1, null, order); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); //response for getTripAllDetailInformation() TripAllDetail tripAllDetail = new TripAllDetail(); TripResponse tripResponse = new TripResponse(); tripResponse.setConfortClass(1); tripResponse.setPriceForConfortClass("2.0"); tripAllDetail.setTripResponse(tripResponse); Response<TripAllDetail> response2 = new Response<>(1, null, tripAllDetail); ResponseEntity<Response<TripAllDetail>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( Mockito.anyString(), Mockito.any(HttpMethod.class), Mockito.any(HttpEntity.class), Mockito.any(ParameterizedTypeReference.class))) .thenReturn(re).thenReturn(re2); //mock queryForStationName() Response<String> response3 = new Response(null, null, ""); ResponseEntity<Response<String>> re3 = new ResponseEntity<>(response3, HttpStatus.OK); Mockito.when(restTemplate.exchange( Mockito.anyString(), Mockito.any(HttpMethod.class), Mockito.any(HttpEntity.class), Mockito.any(Class.class))) .thenReturn(re3); Response result = rebookServiceImpl.rebook(info, headers); Assert.assertEquals("Please pay the different money!", result.getMsg()); } @Test public void testPayDifference() { RebookInfo info = new RebookInfo(); info.setTripId("G"); info.setOldTripId("G"); info.setLoginId("login_id"); info.setDate(new Date()); info.setSeatType(0); //mock getOrderByRebookInfo() and getTripAllDetailInformation() Order order = new Order(); order.setFrom("from_station"); order.setTo("to_station"); order.setPrice("0"); Response<Order> response = new Response<>(1, null, order); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); TripAllDetail tripAllDetail = new TripAllDetail(); Response<TripAllDetail> response2 = new Response<>(0, null, tripAllDetail); ResponseEntity<Response<TripAllDetail>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( Mockito.anyString(), Mockito.any(HttpMethod.class), Mockito.any(HttpEntity.class), Mockito.any(ParameterizedTypeReference.class))) .thenReturn(re).thenReturn(re2); //mock queryForStationName() and updateOrder() Response response3 = new Response<>(0, null, ""); ResponseEntity<Response> re3 = new ResponseEntity<>(response3, HttpStatus.OK); Mockito.when(restTemplate.exchange( Mockito.anyString(), Mockito.any(HttpMethod.class), Mockito.any(HttpEntity.class), Mockito.any(Class.class))) .thenReturn(re3); Response result = rebookServiceImpl.payDifference(info, headers); Assert.assertEquals(new Response<>(0, "Can't pay the difference,please try again", null), result); } @Test public void testDipatchSeat() { long mills = System.currentTimeMillis(); Seat seatRequest = new Seat(new Date(mills), "G1234", "start_station", "dest_station", 2); HttpEntity requestEntityTicket = new HttpEntity<>(seatRequest, headers); Response<Ticket> response = new Response<>(); ResponseEntity<Response<Ticket>> reTicket = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-seat-service:18898/api/v1/seatservice/seats", HttpMethod.POST, requestEntityTicket, new ParameterizedTypeReference<Response<Ticket>>() { })).thenReturn(reTicket); Ticket result = rebookServiceImpl.dipatchSeat(new Date(mills), "G1234", "start_station", "dest_station", 2, headers); Assert.assertNull(result); } }
package xyz.staffjoy.account.repo; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import xyz.staffjoy.account.model.Account; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringRunner; import xyz.staffjoy.account.model.AccountSecret; import java.time.LocalDateTime; import java.time.ZoneId; import static org.junit.Assert.*; @SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.NONE) @RunWith(SpringRunner.class) public class AccountRepoTest { @Autowired private AccountRepo accountRepo; @Autowired private AccountSecretRepo accountSecretRepo; private Account newAccount; @Before public void setUp() { newAccount = Account.builder() .name("testAccount") .email("test@staffjoy.net") .memberSince(LocalDateTime.of(2019, 1, 20, 12, 50).atZone(ZoneId.systemDefault()).toInstant()) .confirmedAndActive(false) .photoUrl("https://staffjoy.xyz/photo/test.png") .phoneNumber("18001801266") .support(false) .build(); // sanity check accountRepo.deleteAll(); } @Test//(expected = DuplicateKeyException.class) public void createSampleAccount() { accountRepo.save(newAccount); assertTrue(accountRepo.existsById(newAccount.getId())); } @Test public void getAccountById() { accountRepo.save(newAccount); assertEquals(1, accountRepo.count()); Account foundAccount = accountRepo.findById(newAccount.getId()).get(); assertEquals(newAccount, foundAccount); } @Test public void findAccountByEmail() { // not existing Account foundAccount = accountRepo.findAccountByEmail("notexisting@staffjoy.net"); assertNull(foundAccount); accountRepo.save(newAccount); assertEquals(1, accountRepo.count()); foundAccount = accountRepo.findAccountByEmail(newAccount.getEmail()); assertNotNull(foundAccount); assertEquals(newAccount.getId(), foundAccount.getId()); } @Test public void findAccountByPhoneNumber() { // not existing Account foundAccount = accountRepo.findAccountByPhoneNumber("18001800180"); assertNull(foundAccount); // create new accountRepo.save(newAccount); assertEquals(1, accountRepo.count()); foundAccount = accountRepo.findAccountByPhoneNumber(newAccount.getPhoneNumber()); assertEquals(newAccount.getId(), foundAccount.getId()); } @Test public void listAccount() { Pageable pageRequest = PageRequest.of(0, 2); // test empty Page<Account> accounts = accountRepo.findAll(pageRequest); assertEquals(0, accounts.getTotalElements()); // create 1 new accountRepo.save(newAccount); assertEquals(1, accountRepo.count()); // create 2 more newAccount.setId(null); accountRepo.save(newAccount); assertEquals(2, accountRepo.count()); newAccount.setId(null); accountRepo.save(newAccount); assertEquals(3, accountRepo.count()); accounts = accountRepo.findAll(pageRequest); assertEquals(2, accounts.getNumberOfElements()); pageRequest = pageRequest.next(); accounts = accountRepo.findAll(pageRequest); assertEquals(1, accounts.getNumberOfElements()); assertEquals(2, accounts.getTotalPages()); assertEquals(3, accounts.getTotalElements()); } @Test public void updateAccount() { // create new accountRepo.save(newAccount); assertEquals(1, accountRepo.count()); Account toUpdateAccount = newAccount; toUpdateAccount.setName("update"); toUpdateAccount.setEmail("update@staffjoy.xyz"); accountRepo.save(toUpdateAccount); Account updatedAccount = accountRepo.save(toUpdateAccount); Account foundAccount = accountRepo.findById(updatedAccount.getId()).get(); assertEquals(updatedAccount, foundAccount); toUpdateAccount.setConfirmedAndActive(true); toUpdateAccount.setSupport(true); toUpdateAccount.setPhoneNumber("19001900190"); toUpdateAccount.setPhotoUrl("http://staffjoy.net/photo/update.png"); updatedAccount = accountRepo.save(toUpdateAccount); foundAccount = accountRepo.findById(updatedAccount.getId()).get(); assertEquals(updatedAccount, foundAccount); } @Test public void updateEmailAndActivateById() { // create new Account account = accountRepo.save(newAccount); assertEquals(1, accountRepo.count()); assertFalse(account.isConfirmedAndActive()); String toUpdateEmail = "update@staffjoy.xyz"; int result = accountRepo.updateEmailAndActivateById(toUpdateEmail, newAccount.getId()); assertEquals(1, result); Account updatedAccount = accountRepo.findAccountByEmail(toUpdateEmail); assertEquals(toUpdateEmail, updatedAccount.getEmail()); assertTrue(updatedAccount.isConfirmedAndActive()); } @Test public void updatePasswordById() { // create new accountRepo.save(newAccount); assertEquals(1, accountRepo.count()); String passwordHash = "testhash"; int result = accountSecretRepo.updatePasswordHashById(passwordHash, newAccount.getId()); assertEquals(1, result); AccountSecret foundAccountSecret = accountSecretRepo.findAccountSecretByEmail(newAccount.getEmail()); assertNotNull(foundAccountSecret); assertEquals(newAccount.getId(), foundAccountSecret.getId()); assertEquals(newAccount.isConfirmedAndActive(), foundAccountSecret.isConfirmedAndActive()); assertEquals(passwordHash, foundAccountSecret.getPasswordHash() ); } @After public void destroy() { accountRepo.deleteAll(); } }
package xyz.staffjoy.company.repo; import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.test.context.junit4.SpringRunner; import xyz.staffjoy.company.model.Company; import java.util.TimeZone; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.NONE) @RunWith(SpringRunner.class) @Slf4j public class CompanyRepoTest { @Autowired private CompanyRepo companyRepo; private Company newCompany; @Before public void setUp() { newCompany = Company.builder() .name("testCompany") .archived(false) .defaultTimezone(TimeZone.getDefault().getID()) .defaultDayWeekStarts("Monday") .build(); companyRepo.deleteAll(); } @Test public void testCreateCompany() { // create new Company savedCompany = companyRepo.save(newCompany); log.info(newCompany.toString()); log.info(savedCompany.toString()); assertNotNull(savedCompany); // check exists assertTrue(companyRepo.existsById(newCompany.getId())); } @Test public void testGetCompanyById() { // create new Company savedCompany = companyRepo.save(newCompany); assertNotNull(savedCompany); // find exists Company gotCompany = companyRepo.findCompanyById(newCompany.getId()); assertEquals(savedCompany, gotCompany); } @Test public void testListCompany() { Pageable pageRequest = PageRequest.of(0, 2); // test empty Page<Company> companies = companyRepo.findAll(pageRequest); assertEquals(0, companies.getTotalElements()); // create 1 new companyRepo.save(newCompany); assertEquals(1, companyRepo.count()); // create 2 more newCompany.setId(null); companyRepo.save(newCompany); assertEquals(2, companyRepo.count()); newCompany.setId(null); companyRepo.save(newCompany); assertEquals(3, companyRepo.count()); companies = companyRepo.findAll(pageRequest); assertEquals(2, companies.getNumberOfElements()); pageRequest = pageRequest.next(); companies = companyRepo.findAll(pageRequest); assertEquals(1, companies.getNumberOfElements()); assertEquals(2, companies.getTotalPages()); assertEquals(3, companies.getTotalElements()); } @Test public void testUpdateCompany() { // create new Company savedCompany = companyRepo.save(newCompany); assertNotNull(savedCompany); // update newCompany.setName("update"); newCompany.setArchived(true); Company updatedCompany = companyRepo.save(newCompany); assertEquals(newCompany, updatedCompany); Company gotCompany = companyRepo.findCompanyById(newCompany.getId()); assertEquals(newCompany, gotCompany); // update again newCompany.setDefaultTimezone("America/Cordoba"); newCompany.setDefaultDayWeekStarts("Tuesday"); updatedCompany = companyRepo.save(newCompany); assertEquals(newCompany, updatedCompany); gotCompany = companyRepo.findCompanyById(newCompany.getId()); assertEquals(newCompany, gotCompany); } @After public void destroy() { companyRepo.deleteAll(); } }